Parse the field options query string and return it as a dictionary.
5292
def parse_field_options(self, *options):
        
        defaults = {}
        for option in options:
            if isinstance(option, six.text_type):
                tokens = [token.strip() for token in option.split(self.view.lookup_sep)]

                for token in tokens:
                    if not len(token.split(":")) == 2:
                        warnings.warn("The %s token is not properly formatted. Tokens need to be "
                                      "formatted as 'token:value' pairs." % token)
                        continue

                    param, value = token.split(":", 1)

                    if any([k == param for k in ("start_date", "end_date", "gap_amount")]):

                        if param in ("start_date", "end_date"):
                            value = parser.parse(value)

                        if param == "gap_amount":
                            value = int(value)

                    defaults[param] = value

        return defaults
226718
def parse_options():
    

    parser = optparse.OptionParser(usage=USAGE, version=VERSION)

    parser.add_option("-q", "--query",
            action="store", type="string", default="", dest="query",
            help="SPARQL query string")

    parser.add_option("-f", "--format",
            action="store", type="string", default="JSON", dest="format",
            help="Results format: one of JSON, XML")

    parser.add_option("-d", "--describe",
            action="store", type="string", default="", dest="describe",
            help="Describe Query: just pass a URI")

    parser.add_option("-a", "--alltriples",
            action="store", type="string", default="", dest="alltriples",
            help="Get all available triples for a URI")

    parser.add_option("-o", "--ontology",
            action="store_true", default=False, dest="ontology",
            help="Get all entities of type owl:Class - aka the ontology")

    opts, args = parser.parse_args()

    if len(args) > 0:  #dont take no args
        parser.print_help()
        raise SystemExit, 1
    if not (opts.query or opts.describe or opts.alltriples or opts.ontology):
        parser.print_help()
        raise SystemExit, 1
    return opts, args
979578
def parse_field(setting, field_name, default):
    
    if isinstance(setting, dict):
        return setting.get(field_name, default)
    else:
        return setting
328474
def extract_options_dict(template, options):
    """"""
    for option, val in template.items():
        if options and option in options:
            yield option, options[option]
        else:
            yield option, Default(template[option]['default'](os.environ))
5418
def parse_query(query=nil, options={})
      valid_options = [:models, :lazy, :core, :results_format, :sql_options,
        :alternate_query, :boost_functions, :filter_queries, :facets, :sort,
        :scores, :operator, :latitude, :longitude, :radius, :relevance, :highlight,
        :offset, :per_page, :limit, :page,]
      query_options = {}

      return if query.nil?
      raise "Query should be a string" unless query.is_a?(String)
      raise "Invalid parameters: #{(options.keys - valid_options).join(',')}" unless (options.keys - valid_options).empty?
      begin
        Deprecation.validate_query(options)

        query_options[:filter_queries] = []
        query.strip!

        # using *:* disable index boosts, so use the type filter
        if query.blank?
          query = solr_type_condition(options)
        else
          query = sanitize_query(query)
          query_options[:filter_queries] << solr_type_condition(options)

          # put types on filtered fields
          query = replace_types([*query], ':').first
        end

        query_options[:filter_queries] += replace_types([*options[:filter_queries]], '') if options[:filter_queries]

        options[:alternate_query] ||= ''
        options[:alternate_query].strip!
        query = "#{options[:alternate_query]} #{query}" unless options[:alternate_query].blank?

        query = add_relevance query, options[:relevance]

        query_options[:query] = query

        field_list = options[:models].nil? ? solr_configuration[:primary_key_field] : "id"
        query_options[:field_list] = [field_list, 'score']

        per_page = options[:per_page] || options[:limit] || 30
        offset = options[:offset] || (((options[:page] || 1).to_i - 1) * per_page)
        query_options[:rows] = per_page
        query_options[:start] = offset

        query_options[:operator] = options[:operator]

        query_options[:boost_functions] = replace_types([*options[:boost_functions]], '').join(' ') if options[:boost_functions]

        # first steps on the facet parameter processing
        if options[:facets]
          query_options[:facets] = {}
          query_options[:facets][:limit] = -1  # TODO: make this configurable
          query_options[:facets][:sort] = :count if options[:facets][:sort]
          query_options[:facets][:mincount] = 0
          query_options[:facets][:mincount] = 1 if options[:facets][:zeros] == false
          # override the :zeros (it's deprecated anyway) if :mincount exists
          query_options[:facets][:mincount] = options[:facets][:mincount] if options[:facets][:mincount]
          query_options[:facets][:fields] = options[:facets][:fields].map{ |k| "#{k}_facet" } if options[:facets][:fields]
          query_options[:filter_queries] += replace_types([*options[:facets][:browse]]) if options[:facets][:browse]
          query_options[:facets][:queries] = replace_types([*options[:facets][:query]]) if options[:facets][:query]

          if options[:facets][:dates]
            query_options[:date_facets] = {}
            # if options[:facets][:dates][:fields] exists then :start, :end, and :gap must be there
            if options[:facets][:dates][:fields]
              [:start, :end, :gap].each { |k| raise "#{k} must be present in faceted date query" unless options[:facets][:dates].include?(k) }
              query_options[:date_facets][:fields] = []
              options[:facets][:dates][:fields].each { |f|
                if f.kind_of? Hash
                  key = f.keys[0]
                  query_options[:date_facets][:fields] << {"#{key}_d" => f[key]}
                  validate_date_facet_other_options(f[key][:other]) if f[key][:other]
                else
                  query_options[:date_facets][:fields] << "#{f}_d"
                end
              }
            end

            query_options[:date_facets][:start]   = options[:facets][:dates][:start] if options[:facets][:dates][:start]
            query_options[:date_facets][:end]     = options[:facets][:dates][:end] if options[:facets][:dates][:end]
            query_options[:date_facets][:gap]     = options[:facets][:dates][:gap] if options[:facets][:dates][:gap]
            query_options[:date_facets][:hardend] = options[:facets][:dates][:hardend] if options[:facets][:dates][:hardend]
            query_options[:date_facets][:filter]  = replace_types([*options[:facets][:dates][:filter]].collect{|k| "#{k.dup.sub!(/ *:(?!\d) */,"_d:")}"}) if options[:facets][:dates][:filter]

            if options[:facets][:dates][:other]
              validate_date_facet_other_options(options[:facets][:dates][:other])
              query_options[:date_facets][:other] = options[:facets][:dates][:other]
            end

          end
        end

        if options[:highlight]
          query_options[:highlighting] = {}
          query_options[:highlighting][:field_list] = replace_types([*options[:highlight][:fields]], '') if options[:highlight][:fields]
          query_options[:highlighting][:require_field_match] =  options[:highlight][:require_field_match] if options[:highlight][:require_field_match]
          query_options[:highlighting][:max_snippets] = options[:highlight][:max_snippets] if options[:highlight][:max_snippets]
          query_options[:highlighting][:prefix] = options[:highlight][:prefix] if options[:highlight][:prefix]
          query_options[:highlighting][:suffix] = options[:highlight][:suffix] if options[:highlight][:suffix]
        end

        query_options[:sort] = replace_types([*options[:sort]], '')[0] if options[:sort]

        if options[:radius]
          query_options[:radius] = options[:radius]
          query_options[:filter_queries] << '{!geofilt}'
        end
        query_options[:latitude] = options[:latitude]
        query_options[:longitude] = options[:longitude]

        not_dismax = query_options[:operator] == :or
        request = not_dismax ? Solr::Request::Standard.new(query_options) : Solr::Request::Dismax.new(query_options)
        ActsAsSolr::Post.execute(request, options[:core])
      rescue
        raise "#{$query} There was a problem executing your search\n#{query_options.inspect}\n: #{$!} in #{$!.backtrace.first}"
      end
    end
944410
def _parse_option(option):
    
    try:
        key, val = option.split("=", 1)
    except ValueError:
        return option, True

    try:
        val = json.loads(val)
    except json.JSONDecodeError:
        pass

    return key, val
425604
def to_dict(self):
        """"""
        d = {}
        if self.query_params_match is not None:
            d['@query_params_match'] = self.query_params_match
        if self.query_person_match is not None:
            d['@query_person_match'] = self.query_person_match
        if self.valid_since is not None:
            d['@valid_since'] = datetime_to_str(self.valid_since)
        if self.source is not None:
            d['source'] = self.source.to_dict()
        d.update(self.fields_to_dict())
        return d
822077
def parse_field(field: str) -> Tuple[str, Optional[str]]:
    
    _field = field.split('.')
    _field = [f.strip() for f in _field]
    if len(_field) == 1 and _field[0]:
        return _field[0], None
    elif len(_field) == 2 and _field[0] and _field[1]:
        return _field[0], _field[1]
    raise QueryParserException('Query field must be either a single value,'
                               'possibly with single underscores, '
                               'or a prefix double underscore field. '
                               'Received `{}`'.format(field))
966050
def parse(url):
    """"""

    config = {}

    url = urlparse.urlparse(url)

    # Remove query strings.
    path = url.path[1:]
    path = path.split('?', 2)[0]

    # Update with environment configuration.
    config.update({
        "DB": int(path or 0),
        "PASSWORD": url.password or None,
        "HOST": url.hostname or "localhost",
        "PORT": int(url.port or 6379),
    })

    return config
833712
def parse_field(self, field_data, index=0):
        """"""
        field = {
            '__index__': index,
        }

        if isinstance(field_data, str):
            field.update(self.parse_string_field(field_data))
        elif isinstance(field_data, dict):
            field.update(field_data)
        else:
            raise TypeError('Expected a str or dict get {}'.format(type(field_data)))

        if 'field' not in field:
            field['field'] = None

        if 'label' not in field and field['field']:
            try:
                field['label'] = self.object._meta.get_field(field['field']).verbose_name.capitalize()
            except Exception:
                field['label'] = field['field'].replace('_', '').capitalize()
        elif 'label' not in field:
            field['label'] = ''

        if 'format' not in field:
            field['format'] = '{0}'

        # Set default options
        for name, options in self.fields_options.items():
            if 'default' in options and name not in field:
                field[name] = options['default']

        return field
642743
def dict_to_querystring(dictionary):
    """"""
    s = u""
    for d in dictionary.keys():
        s = unicode.format(u"{0}{1}={2}&", s, d, dictionary[d])
    return s[:-1]
170743
def get_options(self):
        
        query = 'SET'
        return dict(row[:2] for row in self.con.fetchall(query))
981031
def query_to_map(text):
    '''
    '''
    dict_obj = {}

    for key, value in split_query(text, True):
        if key not in dict_obj:
            dict_obj[key] = []

        if value:
            dict_obj[key].append(value.replace('+', ' '))
        else:
            dict_obj[key].append('')

    return query_to_map(text)
797721
def get_parameters_as_dictionary(self, query_string):
        
        pairs = (x.split('=', 1) for x in query_string.split('&'))
        return dict((k, unquote(v)) for k, v in pairs)
1296068
def parse_options options = {}, request = ''
      options.each do |opt, value|
        case opt
        when :timeout, :paging, :mode
          request += "&#{opt}=#{value}"
        when :callback, :stats
          request += "&#{opt}"
        when :fields
          request += "&#{opt}=" + value.join(',') if value.is_a?(Array)
        end
      end
      request
    end
645336
def parse_querystring(msg):
    ''
    for part in msg.querystring.strip().lstrip('?').split('&'):
        key, value = part.split('=')
        yield key, value
1346147
def parse_options(cls, line, ns={}):
        
        parsed = cls.parse(line, ns=ns)
        options_list = []
        for spec in sorted(parsed.keys()):
            options = parsed[spec]
            merged = {}
            for group in options.values():
                merged = dict(group.kwargs, **merged)
            options_list.append(Options(spec, **merged))
        return options_list