Template method to find data.
Any step (such as filtration, pagination, sorting e.t.c. can be changed in concrete class).
198097
public function getPayload()
    {
        $queryBuilder = $this->getSearchService()->query();

        $this->doFiltration($queryBuilder);
        $this->doPagination($queryBuilder);
        $this->doSorting($queryBuilder);
        $searchResult = $this->doSearch($queryBuilder);
        $result = $this->doPostProcessing($searchResult);

        return $result;
    }
251988
private final TryCatchFinally tryStatement(Data data) throws TemplateException {
	if (!data.srcCode.forwardIfCurrent("try", '{') && !data.srcCode.forwardIfCurrent("try ") && !data.srcCode.forwardIfCurrent("try", '/')) return null;
	data.srcCode.previous();

	Body body = new BodyBase(data.factory);
	TryCatchFinally tryCatchFinally = new TryCatchFinally(data.factory, body, data.srcCode.getPosition(), null);

	Body prior = data.setParent(body);
	statement(data, body, CTX_TRY);
	data.setParent(prior);
	comments(data);

	// catches
	short catchCount = 0;
	while (data.srcCode.forwardIfCurrent("catch", '(')) {
	    catchCount++;
	    comments(data);

	    // type
	    int pos = data.srcCode.getPos();
	    Position line = data.srcCode.getPosition();
	    Expression name = null, type = null;

	    StringBuffer sbType = new StringBuffer();
	    String id;
	    while (true) {
		id = identifier(data, false);
		if (id == null) break;
		sbType.append(id);
		data.srcCode.removeSpace();
		if (!data.srcCode.forwardIfCurrent('.')) break;
		sbType.append('.');
		data.srcCode.removeSpace();
	    }

	    if (sbType.length() == 0) {
		type = string(data);
		if (type == null) throw new TemplateException(data.srcCode, "a catch statement must begin with the throwing type (query, application ...).");
	    }
	    else {
		type = data.factory.createLitString(sbType.toString());
	    }

	    // name = expression();
	    comments(data);

	    // name
	    if (!data.srcCode.isCurrent(')')) {
		name = expression(data);
	    }
	    else {
		data.srcCode.setPos(pos);
		name = expression(data);
		type = data.factory.createLitString("any");
	    }
	    comments(data);

	    Body b = new BodyBase(data.factory);
	    try {
		tryCatchFinally.addCatch(type, name, b, line);
	    }
	    catch (TransformerException e) {
		throw new TemplateException(data.srcCode, e.getMessage());
	    }
	    comments(data);

	    if (!data.srcCode.forwardIfCurrent(')')) throw new TemplateException(data.srcCode, "invalid catch statement, missing closing )");

	    Body _prior = data.setParent(b);
	    statement(data, b, CTX_CATCH);
	    data.setParent(_prior);
	    comments(data);
	}

	// finally
	if (finallyStatement(data, tryCatchFinally)) {
	    comments(data);
	}
	else if (catchCount == 0) throw new TemplateException(data.srcCode, "a try statement must have at least one catch statement");

	// if(body.isEmpty()) return null;
	tryCatchFinally.setEnd(data.srcCode.getPosition());
	return tryCatchFinally;
    }
1312909
def select_data_code(options = {})
      paginate = (options.key?(:paginate) ? options[:paginate] : @table.paginate?)
      # Check order
      unless @table.options.keys.include?(:order)
        columns = @table.table_columns
        @table.options[:order] = (columns.any? ? columns.first.name.to_sym : { id: :desc })
      end

      class_name = @table.model.name
      class_name = "(controller_name != '#{class_name.tableize}' ? controller_name.to_s.classify.constantize : #{class_name})" if collection?

      # Find data
      query_code = class_name.to_s
      query_code << scope_code if scope_code
      query_code << ".select(#{select_code})" if select_code
      query_code << ".from(#{from_code})" if from_code
      query_code << ".where(#{conditions_code})" unless @table.options[:conditions].blank?
      query_code << ".joins(#{@table.options[:joins].inspect})" unless @table.options[:joins].blank?
      unless includes_reflections.empty?
        expr = includes_reflections.inspect[1..-2]
        query_code << ".includes(#{expr})"
        query_code << ".references(#{expr})"
      end

      code = ''
      code << "#{query_code}\n"

      code << if @table.options[:count].present?
                "#{var_name(:count)} = #{query_code}.count(#{@table.options[:count].inspect})\n"
              else
                "#{var_name(:count)} = #{query_code}.count\n"
              end

      query_code << ".group(#{@table.options[:group].inspect})" unless @table.options[:group].blank?
      query_code << ".reorder(#{var_name(:order)})"

      if paginate
        code << "#{var_name(:limit)}  = (#{var_name(:params)}[:per_page] || 25).to_i\n"

        code << "if params[:page]\n"
        code << "  #{var_name(:page)} = (#{var_name(:params)}[:page] || 1).to_i\n"
        code << "elsif params['#{table.name}-id'] and #{var_name(:index)} = #{query_code}.pluck(:id).index(params['#{table.name}-id'].to_i)\n"
        # Find page of request element
        code << "  #{var_name(:page)} = (#{var_name(:index)}.to_f / #{var_name(:limit)}).floor + 1\n"
        code << "else\n"
        code << "  #{var_name(:page)} = 1\n"
        code << "end\n"
        code << "#{var_name(:page)}   = 1 if #{var_name(:page)} < 1\n"

        code << "#{var_name(:offset)} = (#{var_name(:page)} - 1) * #{var_name(:limit)}\n"
        code << "#{var_name(:last)}   = (#{var_name(:count)}.to_f / #{var_name(:limit)}).ceil.to_i\n"
        code << "#{var_name(:last)}   = 1 if #{var_name(:last)} < 1\n"

        code << "return #{view_method_name}(options.merge(page: 1)) if 1 > #{var_name(:page)}\n"
        code << "return #{view_method_name}(options.merge(page: #{var_name(:last)})) if #{var_name(:page)} > #{var_name(:last)}\n"
        query_code << ".offset(#{var_name(:offset)})"
        query_code << ".limit(#{var_name(:limit)})"
      end

      code << "#{records_variable_name} = #{query_code} || {}\n"
      code
    end
1241401
def check_data(self, data):
        
        data_objs = {
            data_src: data.objects.get(data_src) for data_src in data.layer
        }
        self._is_data_loaded = all(data_objs.values())
        return data_objs
171668
def get_template(self, data=None):  # noqa (complexity)
        """"""
        with self.__lock:
            if self.__value_templates is None and self.__last_parse_ok:
                try:
                    self.__refresh()
                except RefreshException:
                    # Point has no (useable) values - don't try to refetch again
                    self.__last_parse_ok = False
                    raise
            if self.__value_templates is None:
                raise ValueError('Point has no values')
            if data is None:
                template = PointDataObject(self.__value_templates, self.__filter)
            else:
                while True:
                    try:
                        template = PointDataObject._from_dict(self.__value_templates, self.__filter, data)
                    except:
                        # parsing has failed for first time since refresh so try again
                        if self.__last_parse_ok:
                            logger.debug('Failed to parse data from for point %s, refreshing', self.__point)
                            self.__last_parse_ok = False
                            try:
                                self.__refresh()
                            except RefreshException:
                                break
                        else:
                            raise
                    else:
                        self.__last_parse_ok = True
                        break
            return template
240898
List<CtClass> findClasses(
            final ClassPool classPool,
            final String classPathElement) {

        // TODO(ville): If we ever support finding classes in other ways extract this method into a strategy.
        getLog().debug(String.format("Searching classpath element: %s", classPathElement));
        final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.{class}");
        final Path basePath = Paths.get(classPathElement);
        final List<CtClass> ctClasses = new ArrayList<>();

        try {
            Files.walkFileTree(
                    basePath,
                    new ClasspathSimpleFileVisitor(matcher, ctClasses, classPool, basePath));
        } catch (final IOException e) {
            throw new CompletionException("Unable to resolve compile classpath elements", e);
        }

        return ctClasses;
    }
946095
def search(self, template: str, first: bool = False) -> _Result:
        
        elements = [r for r in findall(template, self.xml)]

        return _get_first_or_list(elements, first)
975045
private Map<CtClass, Set<CtMethod>> find(final CtMethod declaredMethod, final int level, final Map<CtClass, Set<CtMethod>> dict) {
		if (level < 0) {
			throw new IllegalArgumentException("level < 0");
		}
		addToMap(declaredMethod.getDeclaringClass(), declaredMethod, dict);
		if (level > 0) {
			try {
				declaredMethod.instrument(new ExprEditor() {
					@Override
					public void edit(final MethodCall m) throws CannotCompileException {
						try {
							CtMethod method = m.getMethod();
							LOG.info(method.getLongName() + " / " + level);
							find(method, level - 1, dict);
						} catch (NotFoundException e) {
							e.printStackTrace(); // should not happen
						}
						super.edit(m);
					}

				});
			} catch (CannotCompileException e) {
				// cannot possibly be thrown due to the fact that we don't change anything here
				e.printStackTrace();
			}
		}
		return dict;
	}
479942
protected void findMatching(Class<? extends T> type, BiPredicate<Class<? extends T>, D> predicate)
	{
		traverseType(type, predicate, new HashSet<>());
	}
144093
def search(request, template="search_results.html", extra_context=None):
    
    query = request.GET.get("q", "")
    page = request.GET.get("page", 1)
    per_page = settings.SEARCH_PER_PAGE
    max_paging_links = settings.MAX_PAGING_LINKS
    try:
        parts = request.GET.get("type", "").split(".", 1)
        search_model = apps.get_model(*parts)
        search_model.objects.search  # Attribute check
    except (ValueError, TypeError, LookupError, AttributeError):
        search_model = Displayable
        search_type = _("Everything")
    else:
        search_type = search_model._meta.verbose_name_plural.capitalize()
    results = search_model.objects.search(query, for_user=request.user)
    paginated = paginate(results, page, per_page, max_paging_links)
    context = {"query": query, "results": paginated,
               "search_type": search_type}
    context.update(extra_context or {})
    return TemplateResponse(request, template, context)
705580
def get_template(template, relation):
    
    if isinstance(relation, Entry):
        path = relation.category.path
    elif isinstance(relation, Category):
        path = relation.path
    else:
        path = relation

    tmpl = map_template(path, template)
    return tmpl.filename if tmpl else None
906031
function find(data) {
                if (data === this.data) {
                    return this;
                }

                if (this.children) {
                    for (var i = 0, _length = this.children.length, target = null; i < _length; i++) {
                        target = this.children[i].find(data);
                        if (target) {
                            return target;
                        }
                    }
                }

                return null;
            }
1031383
def _find(api_method, query, limit, return_handler, first_page_size, **kwargs):
    ''' 
    '''
    num_results = 0

    if "limit" not in query:
        query["limit"] = first_page_size

    while True:
        resp = api_method(query, **kwargs)

        by_parent = resp.get('byParent')
        descriptions = resp.get('describe')
        def format_result(result):
            if return_handler:
                result = dxpy.get_handler(result['id'], project=result.get('project'))
            if by_parent is not None:
                return result, by_parent, descriptions
            else:
                return result

        for i in resp["results"]:
            if num_results == limit:
                return
            num_results += 1
            yield format_result(i)

        # set up next query
        if resp["next"] is not None:
            query["starting"] = resp["next"]
            query["limit"] = min(query["limit"]*2, 1000)
        else:
            return
117714
def findItems( self, cls ):
        
        return filter(lambda x: isinstance(x, cls), self.items())
1169860
def find_templates(name, prefix, partial, details, key=nil, locals=[])
      return [] if @@resolver_options[:only] && !@@resolver_options[:only].include?(prefix)

      path = build_path(name, prefix)
      conditions = {
        :path    => path,
        :locale  => [normalize_array(details[:locale]).first, nil],
        :format  => normalize_array(details[:formats]),
        :handler => normalize_array(details[:handlers]),
        :partial => partial || false
      }.merge(details[:additional_criteria].presence || {})

      @@model.find_model_templates(conditions).map do |record|
        Rails.logger.debug "Rendering template from database: #{path} (#{record.format})"
        initialize_template(record)
      end
    end
600269
def find_template_with_lookup(name, prefix = nil, partial = false)
      if prefix == controller_path
        folder = controller.find_inheritable_template_folder(name, partial)
        prefix = folder if folder
      end
      find_template_without_lookup(name, prefix, partial)
    end
255814
def search(type)
      resource_class = parse_type(type)
      client_setup
      filter = parse_hash(options['filter'])
      matches = resource_class.find_by(@client, filter)
      if matches.empty? # Search with integers & booleans converted
        filter = parse_hash(options['filter'], true)
        matches = resource_class.find_by(@client, filter) unless filter == options['filter']
      end
      if options['attribute']
        data = select_attributes_from_multiple(options['attribute'], matches)
        output data, -2 # Shift left by 2 so things look right
      else # List names only by default
        names = []
        matches.each { |m| names.push(m['name']) }
        output names
      end
    end