Find for specific query name in given file.
The file can contain multiple named queries.

Example: Given the operation named "GetUser" in file 'queries.graphql'

@Given /^the operation named "([^"]*)" in file "([^"]*)"$/
482247
public function theOperationNamedInFile($queryName, $file)
    {
        // TODO: add support for fragments
        // if a fragment is not used in some operation in the same file a error is thrown

        $this->theOperationInFile($file);
        $this->operationName = $queryName;
        if ($this->client->getGraphQL()) {
            // remove non necessary operations to avoid errors with unsettled variables
            $pattern = '/(query|mutation|subscription)\s+(?!'.$queryName.'\s*[\({])(.+\n)+}\n*/';
            $this->client->setGraphQL(preg_replace($pattern, null, $this->client->getGraphQL()));
        }

        if ($queryName) {
            if (strpos($this->client->getGraphQL(), $queryName) === false) {
                throw new \RuntimeException(sprintf('Does not exist any operation called "%s" in "%s"', $queryName, $file));
            }
        }
    }
1188926
function getQueries(req, end) {
  var urlencoded = /^application\/x-www-form-urlencoded/;
  var multipart = /^multipart\/form-data/;
  var contentType = req.headers['content-type'] || '';

  if (multipart.test(contentType)) {
    // Multipart data.
    req.form = req.form || new formidable.IncomingForm();
    req.form.multiples = true;
    req.form.parse(req, function(err, fields, files) {
      req.fields = fields;
      req.files = files;
      // Ensure that files are arrays.
      for (var key in req.files) {
        if (!(req.files[key] instanceof Array)) {
          req.files[key] = [req.files[key]];
        }
      }
      if (err == null) {
        addToQuery(req, req.fields);
        addToQuery(req, req.files);
      }
      end(err);
    });

  } else if (urlencoded.test(contentType)) {
    // URL encoded data.
    var chunks;
    var gotrequest = function (chunk) {
      if (chunk !== undefined) {
        if (chunks === undefined) {
          chunks = chunk;
        } else {
          chunks = Buffer.concat([chunks, chunk]);
        }
      }
    };
    req.on('data', gotrequest);
    req.on('end', function(err) {
      if (req.server.saveRequestChunks) {
        req.savedChunks = chunks;
      }
      var strquery = chunks? chunks.toString(): '';
      jsonFromQuery(strquery, req.query);
      end(err);
    });
  } else {
    // URL query parameters.
    var search = req.uri.search || '';
    jsonFromQuery(search.slice(1), req.query);
    end();
  }
}
964396
function withQuery(path, query) {
    var existingQuery = PathUtils.extractQuery(path);

    if (existingQuery) query = query ? assign(existingQuery, query) : existingQuery;

    var queryString = qs.stringify(query, { arrayFormat: 'brackets' });

    if (queryString) {
      return PathUtils.withoutQuery(path) + '?' + queryString;
    }return PathUtils.withoutQuery(path);
  }
1140224
function findByUsername(username, cb) {
  db.getClient(function(err, client, done) {
    client.query(SELECT_USERNAME, [username], function(err, r) {
      var result = r && r.rows[0];
      if(!err && !result) { err = new exceptions.NotFound(); }
      if(err) {
        cb(err);
        done(err);
      } else {
        cb(null, result);
        done();
      }
    });
  });
}
140757
def find_one(self, resource, req, **lookup):
        """"""

        if config.ID_FIELD in lookup:
            return self._find_by_id(resource=resource, _id=lookup[config.ID_FIELD], parent=lookup.get('parent'))
        else:
            args = self._es_args(resource)
            filters = [{'term': {key: val}} for key, val in lookup.items()]
            query = {'query': {'constant_score': {'filter': {'and': filters}}}}

            try:
                args['size'] = 1
                hits = self.elastic(resource).search(body=query, **args)
                docs = self._parse_hits(hits, resource)
                return docs.first()
            except elasticsearch.NotFoundError:
                return
275015
def get_named_queries(self):
        
        db = Database(path=self.path)
        return {k[6:]: v for k, v in db.get_configs('query.')}
67693
private static void getFilesByNameRecursive(Collection<File> filesList, File path, String name)
    {
        Optional.ofNullable(path.listFiles()).ifPresent(files -> Arrays.asList(files).forEach(content ->
        {
            if (content.isFile() && content.getName().equals(name))
            {
                filesList.add(content);
            }
            else if (content.isDirectory())
            {
                getFilesByNameRecursive(filesList, content, name);
            }
        }));
    }
1329743
def search(cls, name, lookup=[]):
        
        if os.path.isfile(name): return name
        for spath in lookup:
            fname = os.path.join(spath, name)
            if os.path.isfile(fname):
                return fname
            for ext in cls.extensions:
                if os.path.isfile('%s.%s' % (fname, ext)):
                    return '%s.%s' % (fname, ext)
85335
def find(self, pattern):
        """"""

        if not os.path.exists(environ.index_db):
            raise RuntimeError("can't find index.db")

        conn = sqlite3.connect(environ.index_db)
        cursor = conn.cursor()
        selected = cursor.execute(
            'SELECT * FROM "%s" WHERE name '
            'LIKE "%%%s%%" ORDER BY LENGTH(name)'
            % (environ.source, pattern)).fetchall()

        pat = re.compile('(%s)' % re.escape(pattern), re.I)

        if selected:
            for name, url, std in selected:
                if os.isatty(sys.stdout.fileno()):
                    print(pat.sub(r'\033[1;31m\1\033[0m', name) +
                          (' \033[1;33m[%s]\033[0m' % std if std else ''))
                else:
                    print(name + (' [%s]' % std if std else ''))
        else:
            raise RuntimeError('%s: nothing appropriate.' % pattern)
985096
public Include getDefineFromFile(String includeName, boolean useCaching) throws QueryException {
		Include include = null;
		if (useCaching) {
			include = CACHED_DEFINES.get(includeName);
		}
		if (include != null) {
			return include;
		}
		String namespaceString = includeName.substring(0, includeName.indexOf(":"));
		String singleIncludeName = includeName.substring(includeName.indexOf(":") + 1);
		URL resource;
		try {
			resource = getClass().getClassLoader().loadClass("org.bimserver.database.queries.StartFrame").getResource("json/" + namespaceString + ".json");
			if (resource == null) {
				throw new QueryException("Could not find '" + namespaceString + "' namespace in predefined queries");
			}
		} catch (ClassNotFoundException e1) {
			throw new QueryException("Could not find '" + namespaceString + "' namespace in predefined queries");
		}
		OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
		try {
			ObjectNode predefinedQuery = OBJECT_MAPPER.readValue(resource, ObjectNode.class);
			Query query = parseJson(namespaceString, predefinedQuery);
			Include define = query.getDefine(singleIncludeName);
			if (copyExternalDefines) {
				define = define.copy();
			}
			if (define == null) {
				throw new QueryException("Could not find '" + singleIncludeName + "' in defines in namespace " + query.getName());
			}
			if (useCaching) {
				CACHED_DEFINES.put(includeName, define);
			}
			return define;
		} catch (JsonParseException e) {
			throw new QueryException(e);
		} catch (JsonMappingException e) {
			throw new QueryException(e);
		} catch (IOException e) {
			throw new QueryException(e);
		}
	}
25748
private void fileNameInput(List<FileModel> vertices, GraphRewrite event, ParameterStore store)
    {
        if (this.filenamePattern != null)
        {
            Pattern filenameRegex = filenamePattern.getCompiledPattern(store);
            //in case the filename is the first operation generating result, we can use the graph regex index. That's why we distinguish that in this clause
            if (vertices.isEmpty() && StringUtils.isBlank(getInputVariablesName()))
            {
                FileService fileService = new FileService(event.getGraphContext());
                for (FileModel fileModel : fileService.findByFilenameRegex(filenameRegex.pattern()))
                {
                    vertices.add(fileModel);
                }
            }
            else
            {
                ListIterator<FileModel> fileModelIterator = vertices.listIterator();
                vertices.removeIf(fileModel -> !filenameRegex.matcher(fileModel.getFileName()).matches());
            }
        }
    }
205026
def lookahead
      @lookahead ||= begin
        ast_node = selected_operation
        root_type = warden.root_type_for_operation(ast_node.operation_type || "query")
        root_type = root_type.metadata[:type_class] || raise("Invariant: `lookahead` only works with class-based types")
        GraphQL::Execution::Lookahead.new(query: self, root_type: root_type, ast_nodes: [ast_node])
      end
    end
1201205
private Subquery<ImageFile> getImagesWithFileNameSubquery(final String filename, final FilterStringLogic searchLogic) {
        final CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
        final Subquery<ImageFile> subQuery = getCriteriaQuery().subquery(ImageFile.class);
        final Root<LanguageImage> root = subQuery.from(LanguageImage.class);
        subQuery.select(root.get("imageFile").as(ImageFile.class));

        // Create the Condition for the subquery
        final Predicate imageIdMatch = criteriaBuilder.equal(getRootPath().get("imageFileId"), root.get("imageFile").get("imageFileId"));
        final Predicate filenameMatch;
        if (searchLogic == FilterStringLogic.MATCHES) {
            filenameMatch = criteriaBuilder.equal(root.get("originalFileName"), filename);
        } else {
            filenameMatch = criteriaBuilder.like(criteriaBuilder.lower(root.get("originalFileName").as(String.class)),
                    '%' + cleanLikeCondition(filename).toLowerCase() + '%');
        }
        subQuery.where(criteriaBuilder.and(imageIdMatch, filenameMatch));

        return subQuery;
    }
909377
function getFileDetails(db, fileSelectionCriteria, fileOptions, cb) {

  defaultLogger.debug("In getFileDetails ");
  var selectionQuery = undefined;
  if (fileSelectionCriteria.groupId) {

    selectionQuery= {"metadata.groupId": fileSelectionCriteria.groupId};


  } else if (fileSelectionCriteria.hash) {
    selectionQuery= {"md5": fileSelectionCriteria.hash};
  }

  var gridStore = new GridStore(db, null, "r", {"root": constants.ROOT_COLLECTION});
  var fileOfInterest = undefined;

  gridStore.collection(function(err, collection) {
    collection.find(selectionQuery, { "sort": {"metadata.version":-1}}, function(err, files) {
      if (err) {
        defaultLogger.error(err); return cb(err);
      }

      files.toArray(function(err, filesArray) {
        if (err) {
          defaultLogger.error(err); return cb(err);
        }
        if (!(filesArray && Array.isArray(filesArray) && filesArray.length > 0)) {
          return cb(new Error("No files exist for groupId " + fileSelectionCriteria.groupId));
        }

        //If the file details are needed for all files in the groupId, then an array containing all of the file details is returned.
        if (fileOptions.allMatchingFiles == true) { // eslint-disable-line eqeqeq
          fileOfInterest = filesArray;
        } else {// Just want the details of a single file.
          //If there is no version, get the latest version

          //If no version is found or we have a hash query, just want the first entry of the array.
          if (!fileSelectionCriteria.version || fileSelectionCriteria.hash) {
            fileOfInterest = filesArray[0];
          } else {
            fileOfInterest = filesArray.filter(function(file) {
              return file.metadata.version === fileSelectionCriteria.version;
            });

            if (fileOfInterest.length === 1) {
              fileOfInterest = fileOfInterest[0];
            } else {
              return cb(new Error("Unexpected number of files returned for groupId " + fileSelectionCriteria.groupId, fileOfInterest.length));
            }
          }
        }

        if (!Array.isArray(fileOfInterest)) {
          //Actually want the thumbnail for the file, return the details for that file instead.
          if (fileOptions.thumbnail) {
            if (fileOfInterest.metadata.thumbnail) {
              getThumbnailFileDetails(db, fileOfInterest.metadata.thumbnail, function(err, thumbFileDetails) {
                if (err) {
                  defaultLogger.error(err); return cb(err);
                }

                fileOfInterest = thumbFileDetails;

                gridStore.close(function(err) {
                  return cb(err, fileOfInterest);
                });
              });
            } else {
              return cb(new Error("Thumbnail for file " + JSON.stringify(fileSelectionCriteria) + " does not exist."));
            }
          } else {
            gridStore.close(function(err) {
              return cb(err, fileOfInterest);
            });
          }
        } else {
          gridStore.close(function(err) {
            return cb(err, fileOfInterest);
          });
        }
      });
    });
  });
}
69909
def find(self, *args, **kwargs):
    " "
    return Query(*args, db=self, schema=self.schema)
456582
def query_paths(self):
        
        output = self.namespace.alias_to_query_paths.get(self.name)
        if output:
            return output
        Log.error("Can not find index {{index|quote}}", index=self.name)
533248
def _search(self, searchterm, pred, **args):
        
        # TODO: DRY with sparql_ontol_utils
        searchterm = searchterm.replace('%','.*')
        namedGraph = get_named_graph(self.handle)
        query = """
        prefix oboInOwl: <http://www.geneontology.org/formats/oboInOwl#>
        SELECT ?c WHERE {{
        GRAPH <{g}>  {{
        ?c {pred} ?l
        FILTER regex(?l,'{s}','i')
        }}
        }}
        """.format(pred=pred, s=searchterm, g=namedGraph)
        bindings = run_sparql(query)
        return [r['c']['value'] for r in bindings]