Prepare search parameters from query and config parameters.
Will add search criteria here: 'owner_id' (author), LIKE 'title'/'body'
969586
protected function prepateListSearchParams()
    {
        $groupName = basename(NewsSearchFront::className());
        $params = [];
        $params[$groupName] = Yii::$app->request->queryParams;
        if (!empty($this->module->params['titleMinLength'])) {
            $params[$groupName]['titleMinLength'] = $this->module->params['titleMinLength'];
        }
        if (!empty($this->module->params['bodyMinLength'])) {
            $params[$groupName]['bodyMinLength'] = $this->module->params['bodyMinLength' ];
        }
        return $params;
    }
308893
public function prepareQuery()
    {
        $query = $this->model->newQuery();
        $primaryTable = $this->model->getTable();
        $selects = [$primaryTable.'.*'];
        $joins = [];
        $withs = [];

        /**
         * @event backend.list.extendQueryBefore
         * Provides an opportunity to modify the `$query` object before the List widget applies its scopes to it.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQueryBefore', function($listWidget, $query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQueryBefore', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        $this->fireSystemEvent('backend.list.extendQueryBefore', [$query]);

        /*
         * Prepare searchable column names
         */
        $primarySearchable = [];
        $relationSearchable = [];

        $columnsToSearch = [];
        if (!empty($this->searchTerm) && ($searchableColumns = $this->getSearchableColumns())) {
            foreach ($searchableColumns as $column) {
                /*
                 * Related
                 */
                if ($this->isColumnRelated($column)) {
                    $table = $this->model->makeRelation($column->relation)->getTable();
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $table))
                        : $table . '.' . $column->valueFrom;

                    $relationSearchable[$column->relation][] = $columnName;
                }
                /*
                 * Primary
                 */
                else {
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $primaryTable))
                        : DbDongle::cast(Db::getTablePrefix() . $primaryTable . '.' . $column->columnName, 'TEXT');

                    $primarySearchable[] = $columnName;
                }
            }
        }

        /*
         * Prepare related eager loads (withs) and custom selects (joins)
         */
        foreach ($this->getVisibleColumns() as $column) {

            // If useRelationCount is enabled, eager load the count of the relation into $relation_count
            if ($column->relation && @$column->config['useRelationCount']) {
                $query->withCount($column->relation);
            }

            if (!$this->isColumnRelated($column) || (!isset($column->sqlSelect) && !isset($column->valueFrom))) {
                continue;
            }

            if (isset($column->valueFrom)) {
                $withs[] = $column->relation;
            }

            $joins[] = $column->relation;
        }

        /*
         * Add eager loads to the query
         */
        if ($withs) {
            $query->with(array_unique($withs));
        }

        /*
         * Apply search term
         */
        $query->where(function ($innerQuery) use ($primarySearchable, $relationSearchable, $joins) {

            /*
             * Search primary columns
             */
            if (count($primarySearchable) > 0) {
                $this->applySearchToQuery($innerQuery, $primarySearchable, 'or');
            }

            /*
             * Search relation columns
             */
            if ($joins) {
                foreach (array_unique($joins) as $join) {
                    /*
                     * Apply a supplied search term for relation columns and
                     * constrain the query only if there is something to search for
                     */
                    $columnsToSearch = array_get($relationSearchable, $join, []);

                    if (count($columnsToSearch) > 0) {
                        $innerQuery->orWhereHas($join, function ($_query) use ($columnsToSearch) {
                            $this->applySearchToQuery($_query, $columnsToSearch);
                        });
                    }
                }
            }

        });

        /*
         * Custom select queries
         */
        foreach ($this->getVisibleColumns() as $column) {
            if (!isset($column->sqlSelect)) {
                continue;
            }

            $alias = $query->getQuery()->getGrammar()->wrap($column->columnName);

            /*
             * Relation column
             */
            if (isset($column->relation)) {

                // @todo Find a way...
                $relationType = $this->model->getRelationType($column->relation);
                if ($relationType == 'morphTo') {
                    throw new ApplicationException('The relationship morphTo is not supported for list columns.');
                }

                $table =  $this->model->makeRelation($column->relation)->getTable();
                $sqlSelect = $this->parseTableName($column->sqlSelect, $table);

                /*
                 * Manipulate a count query for the sub query
                 */
                $relationObj = $this->model->{$column->relation}();
                $countQuery = $relationObj->getRelationExistenceQuery($relationObj->getRelated()->newQueryWithoutScopes(), $query);

                $joinSql = $this->isColumnRelated($column, true)
                    ? DbDongle::raw("group_concat(" . $sqlSelect . " separator ', ')")
                    : DbDongle::raw($sqlSelect);

                $joinSql = $countQuery->select($joinSql)->toSql();

                $selects[] = Db::raw("(".$joinSql.") as ".$alias);
            }
            /*
             * Primary column
             */
            else {
                $sqlSelect = $this->parseTableName($column->sqlSelect, $primaryTable);
                $selects[] = DbDongle::raw($sqlSelect . ' as '. $alias);
            }
        }

        /*
         * Apply sorting
         */
        if (($sortColumn = $this->getSortColumn()) && !$this->showTree) {
            if (($column = array_get($this->allColumns, $sortColumn)) && $column->valueFrom) {
                $sortColumn = $this->isColumnPivot($column)
                    ? 'pivot_' . $column->valueFrom
                    : $column->valueFrom;
            }

            // Set the sorting column to $relation_count if useRelationCount enabled
            if (isset($column->relation) && @$column->config['useRelationCount']) {
                $sortColumn = $column->relation . '_count';
            }

            $query->orderBy($sortColumn, $this->sortDirection);
        }

        /*
         * Apply filters
         */
        foreach ($this->filterCallbacks as $callback) {
            $callback($query);
        }

        /*
         * Add custom selects
         */
        $query->addSelect($selects);

        /**
         * @event backend.list.extendQuery
         * Provides an opportunity to modify and / or return the `$query` object after the List widget has applied its scopes to it and before it's used to get the records.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQuery', function($listWidget, $query) {
         *         $newQuery = MyModel::newQuery();
         *         return $newQuery;
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQuery', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        if ($event = $this->fireSystemEvent('backend.list.extendQuery', [$query])) {
            return $event;
        }

        return $query;
    }
445910
private void addQueryParams(final Request request) {
        if (friendlyName != null) {
            request.addQueryParam("FriendlyName", friendlyName);
        }

        if (evaluateWorkerAttributes != null) {
            request.addQueryParam("EvaluateWorkerAttributes", evaluateWorkerAttributes);
        }

        if (workerSid != null) {
            request.addQueryParam("WorkerSid", workerSid);
        }

        if (getPageSize() != null) {
            request.addQueryParam("PageSize", Integer.toString(getPageSize()));
        }
    }
1233018
def create(name, profile="splunk", **kwargs):
    '''
    
    '''
    client = _get_splunk(profile)
    search = client.saved_searches.create(name, **kwargs)

    # use the REST API to set owner and permissions
    # this is hard-coded for now; all managed searches are app scope and
    # readable by all
    config = __salt__['config.option'](profile)
    url = "https://{0}:{1}".format(config.get('host'), config.get('port'))
    auth = (config.get('username'), config.get('password'))
    data = {
        "owner": config.get("username"),
        "sharing": "app",
        "perms.read": "*",
    }
    _req_url = "{0}/servicesNS/{1}/search/saved/searches/{2}/acl".format(
        url, config.get("username"), urllib.quote(name)
    )
    requests.post(_req_url, auth=auth, verify=True, data=data)
    return _get_splunk_search_props(search)
1215238
protected function checkParameters()
    {
        if (isset($this->parameters['searchParameterName'])) {
            $this->searchParameterName = $this->parameters['searchParameterName'];
        }

        if (isset($this->parameters['searchResultsParameterName'])) {
            $this->searchParameterName = $this->parameters['searchResultsParameterName'];
        }
    }
536118
private String prepareQueryParameters(Map<J4pQueryParameter, String> pProcessingOptions) {
        if (pProcessingOptions != null && pProcessingOptions.size() > 0) {
            StringBuilder queryParams = new StringBuilder();
            for (Map.Entry<J4pQueryParameter,String> entry : pProcessingOptions.entrySet()) {
                queryParams.append(entry.getKey().getParam()).append("=").append(entry.getValue()).append("&");
            }
            return queryParams.substring(0,queryParams.length() - 1);
        } else {
            return null;
        }
    }
1192240
public static function prepareQuery($query, $params, Escaper $escaper)
    {
        // find all text parts not inside quotes or backslashed-quotes
        $apos = "'";
        $quot = '"';
        $parts = preg_split(
            "/(($apos+|$quot+|\\$apos+|\\$quot+).*?)\\2/m",
            $query,
            -1,
            PREG_SPLIT_DELIM_CAPTURE
        );

        $usedParams = array();
        // loop through the non-quoted parts (0, 3, 6, 9, etc.)
        for ($i = 0, $k = count($parts); $i <= $k; $i += 3) {
            // get the part as a reference so it can be modified in place
            $part = &$parts[$i];

            // find all :placeholder matches in the part
            preg_match_all(
                "/\W:([a-zA-Z_][a-zA-Z0-9_]*)/m",
                $part.PHP_EOL,
                $matches
            );

            // for each of the :placeholder matches ...
            foreach ($matches[1] as $key) {
                if (!array_key_exists($key, $params)) {
                    throw new ParameterNotFoundException(sprintf('The parameter "%s" not found.', $key));
                }

                $find = "/(^|\W)(:$key)(\W|$)/m";
                $repl = '${1}'.addcslashes($escaper->quote($params[$key]), '\\').'${3}';
                $part = preg_replace($find, $repl, $part);
                $usedParams[$key] = true;
            }
        }

        if (count($params) > count($usedParams)) {
            throw new ExtraParametersException(sprintf(
                'Extra parameters found: %s.',
                implode(', ', array_keys(array_diff_key($params, $usedParams)))
            ));
        }

        return implode('', $parts);
    }
297140
def _prepare_uri(self, service_name, **parameters):
        
        query_parameters = []
        for key, value in parameters.items():
            if isinstance(value, (list, tuple)):
                value = ",".join([str(member) for member in value])
            if isinstance(value, bool):
                value = "true" if value else "false"
            query_parameters.append("{}={}".format(key, value))

        if query_parameters:
            uri = "{}{}?{}".format(self.base_url, service_name,
                                   "&".join(query_parameters))
        else:
            uri = "{}{}".format(self.base_url, service_name)
        return uri
176655
private void addQueryParams(final Request request) {
        if (bindingType != null) {
            for (UserBinding.BindingType prop : bindingType) {
                request.addQueryParam("BindingType", prop.toString());
            }
        }

        if (getPageSize() != null) {
            request.addQueryParam("PageSize", Integer.toString(getPageSize()));
        }
    }
521819
def format_parameters(self, params):
        # type: (Dict[str, str]) -> None
        
        query = urlparse(self.url).query
        if query:
            self.url = self.url.partition('?')[0]
            existing_params = {
                p[0]: p[-1]
                for p in [p.partition('=') for p in query.split('&')]
            }
            params.update(existing_params)
        query_params = ["{}={}".format(k, v) for k, v in params.items()]
        query = '?' + '&'.join(query_params)
        self.url = self.url + query
20168
def prepare_params(request):
    """"""
    return request.replace(
        params={key: dump_param(val) for key, val in request.params.items()
                if val is not None})
1173496
def setup_parametrization(result, parametrize):
    """"""
    if parametrize:
        # remove parameters from title
        title = result.get("title")
        if title:
            result["title"] = TEST_PARAM_RE.sub("", title)
    else:
        # don't parametrize if not specifically configured
        if "params" in result:
            del result["params"]
278544
def search(query)
        clause = query.blank? ? nil : "%" + query.downcase + "%"
        base = ::User.where(*base_query)
        base = base.where("#{Hydra.config.user_key_field} like lower(?) OR display_name like lower(?)", clause, clause) if clause.present?
        base.registered
            .where("#{Hydra.config.user_key_field} not in (?)",
                   [::User.batch_user_key, ::User.audit_user_key])
            .references(:trophies)
            .order(sort_value)
            .page(params[:page]).per(10)
      end
158437
private CmsGallerySearchParameters prepareSearchParams(CmsGallerySearchBean searchData) {

        // create a new search parameter object
        CmsGallerySearchParameters params = new CmsGallerySearchParameters();
        CmsObject cms = getCmsObject();

        // set the selected types to the parameters
        if (searchData.getServerSearchTypes() != null) {
            params.setResourceTypes(searchData.getServerSearchTypes());
        }

        // set the selected galleries to the parameters
        if (searchData.getGalleries() != null) {
            List<String> paramGalleries = new ArrayList<String>();
            for (String gallerySitePath : searchData.getGalleries()) {
                paramGalleries.add(cms.getRequestContext().addSiteRoot(gallerySitePath));
            }
            params.setGalleries(paramGalleries);
        }

        // set the sort order for the galleries to the parameters
        CmsGallerySearchParameters.CmsGallerySortParam sortOrder;
        String temp = searchData.getSortOrder();
        try {
            sortOrder = CmsGallerySearchParameters.CmsGallerySortParam.valueOf(temp);
        } catch (Exception e) {
            sortOrder = CmsGallerySearchParameters.CmsGallerySortParam.DEFAULT;
        }
        params.setSortOrder(sortOrder);
        if (searchData.getScope() == null) {
            params.setScope(OpenCms.getWorkplaceManager().getGalleryDefaultScope());
        } else {
            params.setScope(searchData.getScope());
        }
        params.setReferencePath(searchData.getReferencePath());

        // set the selected folders to the parameters
        params.setFolders(new ArrayList<String>(searchData.getFolders()));

        // set the categories to the parameters
        if (searchData.getCategories() != null) {
            params.setCategories(searchData.getCategories());
        }

        // set the search query to the parameters
        if (!CmsStringUtil.isEmptyOrWhitespaceOnly(searchData.getQuery())) {
            params.setSearchWords(searchData.getQuery());
        }

        // set the result page to the parameters
        int page = searchData.getPage();
        params.setResultPage(page);

        // set the locale to the parameters
        String locale = searchData.getLocale();
        if (CmsStringUtil.isEmptyOrWhitespaceOnly(locale)) {
            locale = getCmsObject().getRequestContext().getLocale().toString();
        }
        params.setSearchLocale(locale);

        // set the matches per page to the parameters
        params.setMatchesPerPage(searchData.getMatchesPerPage());

        // get the date range input
        long dateCreatedStart = searchData.getDateCreatedStart();
        long dateCreatedEnd = searchData.getDateCreatedEnd();
        long dateModifiedStart = searchData.getDateModifiedStart();
        long dateModifiedEnd = searchData.getDateModifiedEnd();

        // set the date created range to the parameters
        if ((dateCreatedStart != -1L) && (dateCreatedEnd != -1L)) {
            params.setDateCreatedTimeRange(dateCreatedStart, dateCreatedEnd);
        } else if (dateCreatedStart != -1L) {
            params.setDateCreatedTimeRange(dateCreatedStart, Long.MAX_VALUE);
        } else if (dateCreatedEnd != -1L) {
            params.setDateCreatedTimeRange(Long.MIN_VALUE, dateCreatedEnd);
        }

        // set the date modified range to the parameters
        if ((dateModifiedStart != -1L) && (dateModifiedEnd != -1L)) {
            params.setDateLastModifiedTimeRange(dateModifiedStart, dateModifiedEnd);
        } else if (dateModifiedStart != -1L) {
            params.setDateLastModifiedTimeRange(dateModifiedStart, Long.MAX_VALUE);
        } else if (dateModifiedEnd != -1L) {
            params.setDateLastModifiedTimeRange(Long.MIN_VALUE, dateModifiedEnd);
        }
        params.setIgnoreSearchExclude(searchData.isIgnoreSearchExclude());
        if (GalleryMode.ade.equals(searchData.getGalleryMode())) {
            if (searchData.getTypes().isEmpty() || !Collections.disjoint(FUNCTION_TYPES, searchData.getTypes())) {
                CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(
                    cms,
                    cms.getRequestContext().addSiteRoot(searchData.getReferencePath()));
                // in case a restricted set of functions is configured, remove all other functions
                params.setAllowedFunctions(config.getDynamicFunctions());
            }
        }
        return params;
    }
36220
function (params) {
        this.query = params.q !== undefined ? String(params.q) : defaultParams.query;
        this.page = params.p !== undefined ? parseInt(params.p, 10) : defaultParams.page;
        switch (params.s) {
          case 'name':
          case 'owner':
          case 'stars':
          case 'updated':
            this.sorting = params.s;
            break;
          default:
            this.sorting = defaultParams.sorting;
        }
        switch (params.o) {
          case 'asc':
          case 'desc':
            this.order = params.o;
            break;
          default:
            this.order = defaultParams.order;
        }
      }
195249
def prepare_query(query):
    

    for name in query:
        value = query[name]

        # None is sent as an empty string.
        if value is None:
            query[name] = ""

        # Booleans are sent as 0 or 1.
        elif isinstance(value, bool):
            query[name] = int(value)

        # XXX shouldn't this just check for basestring instead?
        elif isinstance(value, dict):
            raise ValueError("Invalid query data type %r" %
                             type(value).__name__)
1094687
def _perform_custom_queries(self, conn, custom_queries, tags, instance):
        
        for query in custom_queries:
            name = query.get("name")
            if name is None:
                self.log.error("`name` field is required for custom query")
                continue
            search_base = query.get("search_base")
            if search_base is None:
                self.log.error("`search_base` field is required for custom query #%s", name)
                continue
            search_filter = query.get("search_filter")
            if search_filter is None:
                self.log.error("`search_filter` field is required for custom query #%s", name)
                continue
            attrs = query.get("attributes")
            if "username" in query:
                username = query.get("username")
                password = query.get("password")
                if not username:
                    # username is an empty string, we want anonymous bind
                    username = None
                    password = None
            else:
                # username not specified, we want to reuse the credentials for the monitor backend
                username = instance.get("username")
                password = instance.get("password")

            try:
                # Rebind with different credentials
                auth_method = ldap3.SIMPLE if username else ldap3.ANONYMOUS
                if username is None:
                    conn.user = None
                res = conn.rebind(user=username, password=password, authentication=auth_method)
                if not res:
                    raise ldap3.core.exceptions.LDAPBindError("Error binding to server: {}".format(conn.result))
            except ldap3.core.exceptions.LDAPBindError:
                self.log.exception("Could not rebind to server at %s to perform query %s", instance.get("url"), name)
                continue

            try:
                # Perform the search query
                conn.search(search_base, search_filter, attributes=attrs)
            except ldap3.core.exceptions.LDAPException:
                self.log.exception("Unable to perform search query for %s", name)
                continue

            query_tags = ['query:{}'.format(name)]
            query_tags.extend(tags)
            query_time = self._get_query_time(conn)
            results = len(conn.entries)
            self.gauge("{}.query.duration".format(self.METRIC_PREFIX), query_time, tags=query_tags)
            self.gauge("{}.query.entries".format(self.METRIC_PREFIX), results, tags=query_tags)