Get custom fields. Evaluated on 7.12
        :param search: str
        :param start: long Default: 1
        :param limit: int Default: 50
        :return:
481707
def get_custom_fields(self, search=None, start=1, limit=50):
        
        url = 'rest/api/2/customFields'
        params = {}
        if search:
            params['search'] = search
        if start:
            params['startAt'] = start
        if limit:
            params['maxResults'] = limit
        return self.get(url, params=params)
777272
def get_defaults(self):
        """"""
        defaults = self._defaults.copy()
        for field_key, default in self._default_callables.items():
            defaults[field_key] = default()
        return defaults
1222353
def _get_kind(self, limit):
        
        histo = self.fetch("custom_kind")

        if histo:
            # Parse histogram from cached field
            histo = [i.split("%_") for i in str(histo).split()]
            histo = [(int(val, 10), ext) for val, ext in histo]
            ##self._engine.LOG.debug("~~~~~~~~~~ cached histo = %r" % histo)
        else:
            # Get filetypes
            histo = traits.get_filetypes(self.fetch("files"),
                path=operator.attrgetter("path"), size=operator.attrgetter("size"))

            # Set custom cache field with value formatted like "80%_flac 20%_jpg" (sorted by percentage)
            histo_str = ' '.join(("%d%%_%s" % i).replace(' ', '_') for i in histo)
            self._make_it_so("setting kind cache %r on" % (histo_str,), ["custom.set"], "kind", histo_str)
            self._fields["custom_kind"] = histo_str

        # Return all non-empty extensions that make up at least <limit>% of total size
        return set(ext for val, ext in histo if ext and val >= limit)
408924
def get_search_results(self, request, queryset, search_term):
        
        # Apply keyword searches.
        def construct_search(field_name):
            if field_name.startswith('^'):
                return "%s__istartswith" % field_name[1:]
            elif field_name.startswith('='):
                return "%s__iexact" % field_name[1:]
            elif field_name.startswith('@'):
                return "%s__search" % field_name[1:]
            else:
                return "%s__icontains" % field_name

        use_distinct = False
        if self.search_fields and search_term:
            orm_lookups = [construct_search(str(search_field))
                           for search_field in self.search_fields]
            for bit in search_term.split():
                or_queries = [models.Q(**{orm_lookup: bit})
                              for orm_lookup in orm_lookups]
                queryset = queryset.filter(reduce(operator.or_, or_queries))
            if not use_distinct:
                for search_spec in orm_lookups:
                    if lookup_needs_distinct(self.opts, search_spec):
                        use_distinct = True
                        break

        return queryset, use_distinct
460673
def default_field_to_parameter(self, default_field):
        
        if default_field.get('type') == QVariant.Double:
            parameter = FloatParameter()
        elif default_field.get('type') in qvariant_whole_numbers:
            parameter = IntegerParameter()
        else:
            return
        default_value = default_field.get('default_value')
        if not default_value:
            message = (
                'InaSAFE default field %s does not have default value'
                % default_field.get('name'))
            LOGGER.exception(message)
            return

        parameter.guid = default_field.get('key')
        parameter.name = default_value.get('name')
        parameter.is_required = True
        parameter.precision = default_field.get('precision')
        parameter.minimum_allowed_value = default_value.get(
            'min_value', 0)
        parameter.maximum_allowed_value = default_value.get(
            'max_value', 100000000)
        parameter.help_text = default_value.get('help_text')
        parameter.description = default_value.get('description')

        # Check if user ask to restore to the most default value.
        if self.is_restore_default:
            parameter._value = default_value.get('default_value')
        else:
            # Current value
            qsetting_default_value = get_inasafe_default_value_qsetting(
                self.settings, GLOBAL, default_field['key'])

            # To avoid python error
            if qsetting_default_value > parameter.maximum_allowed_value:
                qsetting_default_value = parameter.maximum_allowed_value
            if qsetting_default_value < parameter.minimum_allowed_value:
                qsetting_default_value = parameter.minimum_allowed_value

            parameter.value = qsetting_default_value
        return parameter
136540
def all(cls, start_position="", max_results=100, qb=None):
        
        return cls.where("", start_position=start_position, max_results=max_results, qb=qb)
670343
def _search(self, limit, format):
        '''
        
        '''
        limit = min(limit, self.MAX_SEARCH_PER_QUERY)
        payload = {
          'q' : self.query,
          'count' : limit, #currently 50 is max per search.
          'offset': self.current_offset,
        }
        payload.update(self.CUSTOM_PARAMS)

        headers = { 'Ocp-Apim-Subscription-Key' : self.api_key }
        if not self.silent_fail:
            QueryChecker.check_web_params(payload, headers)
        response = requests.get(self.QUERY_URL, params=payload, headers=headers)
        json_results = self.get_json_results(response)
        packaged_results = [NewsResult(single_result_json) for single_result_json in json_results["value"]]
        self.current_offset += min(50, limit, len(packaged_results))
        return packaged_results
75564
function defaultGetDefaultFieldNames(type) {
  // If this type cannot access fields, then return an empty set.
  if (!type.getFields) {
    return [];
  }

  const fields = type.getFields();

  // Is there an `id` field?
  if (fields['id']) {
    return ['id'];
  }

  // Is there an `edges` field?
  if (fields['edges']) {
    return ['edges'];
  }

  // Is there an `node` field?
  if (fields['node']) {
    return ['node'];
  }

  // Include all leaf-type fields.
  const leafFieldNames = [];
  Object.keys(fields).forEach(fieldName => {
    if (isLeafType(fields[fieldName].type)) {
      leafFieldNames.push(fieldName);
    }
  });
  return leafFieldNames;
}
1007751
def get_list(
        self,
        search='',
        start=0,
        limit=0,
        order_by='',
        order_by_dir='ASC',
        published_only=False,
        minimal=False
    ):
        

        parameters = {}
        args = ['search', 'start', 'limit', 'minimal']
        for arg in args:
            if arg in locals() and locals()[arg]:
                parameters[arg] = locals()[arg]
        if order_by:
            parameters['orderBy'] = order_by
        if order_by_dir:
            parameters['orderByDir'] = order_by_dir
        if published_only:
            parameters['publishedOnly'] = 'true'
        response = self._client.session.get(
            self.endpoint_url, params=parameters
        )
        return self.process_response(response)
387661
def all_default_fields():
    
    default_fields = []
    for item in dir(fields):
        if not item.startswith("__"):
            var = getattr(definitions, item)
            if isinstance(var, dict):
                if var.get('replace_null', False):
                    default_fields.append(var)
    return default_fields
839885
def search(self, filter, base_dn=None, attrs=None, scope=None,
               timeout=None, limit=None):
        
        if base_dn is None:
            base_dn = self._search_defaults.get('base_dn', '')
        if attrs is None:
            attrs = self._search_defaults.get('attrs', None)
        if scope is None:
            scope = self._search_defaults.get('scope', ldap.SCOPE_SUBTREE)
        if timeout is None:
            timeout = self._search_defaults.get('timeout', -1)
        if limit is None:
            limit = self._search_defaults.get('limit', 0)

        results = self.connection.search_ext_s(
            base_dn, scope, filter, attrs, timeout=timeout, sizelimit=limit)
        return self.to_items(results)
1108523
def default_get(self, fields):
        
        if self._context is None:
            self._context = {}
        res = super(RoomReservationSummary, self).default_get(fields)
        # Added default datetime as today and date to as today + 30.
        from_dt = datetime.today()
        dt_from = from_dt.strftime(dt)
        to_dt = from_dt + relativedelta(days=30)
        dt_to = to_dt.strftime(dt)
        res.update({'date_from': dt_from, 'date_to': dt_to})

        if not self.date_from and self.date_to:
            date_today = datetime.datetime.today()
            first_day = datetime.datetime(date_today.year,
                                          date_today.month, 1, 0, 0, 0)
            first_temp_day = first_day + relativedelta(months=1)
            last_temp_day = first_temp_day - relativedelta(days=1)
            last_day = datetime.datetime(last_temp_day.year,
                                         last_temp_day.month,
                                         last_temp_day.day, 23, 59, 59)
            date_froms = first_day.strftime(dt)
            date_ends = last_day.strftime(dt)
            res.update({'date_from': date_froms, 'date_to': date_ends})
        return res
196276
def match_fields(fields, searches,
                 ignore_case=False, wholename=False, complement=False):
    
    if ignore_case:
        fields = [f.lower() for f in fields]
        searches = [s.lower() for s in searches]
    if wholename:
        match_found = _complete_match
    else:
        match_found = _partial_match

    fields = [(i, field) for i, field in enumerate(fields)]
    matched = []
    for search, (idx, field) in itertools.product(searches, fields):
        if not search:  ## don't return all fields for ''
            continue
        if match_found(search, field) and idx not in matched:
            matched.append(idx)

    if complement:
        matched = [idx for idx in list(zip(*fields))[0] if idx not in matched]

    return matched
761096
def find_users_by_email_starting_with(email_prefix=None, cursor=None, page_size=30):
    
    email_prefix = email_prefix or ''

    return ModelSearchCommand(MainUser.query_email_starts_with(email_prefix),
                              page_size, cursor, cache_begin=None)
1008803
def _custom_fields():
    
    # Import some commonly needed modules
    import os
    from pyrocore.torrent import engine, matching
    from pyrocore.util import fmt

    # PUT CUSTOM FIELD CODE HERE

    # Disk space check (as an example)
    # see https://pyrocore.readthedocs.io/en/latest/custom.html#has-room
    def has_room(obj):
        "Check disk space."
        pathname = obj.path
        if pathname and not os.path.exists(pathname):
            pathname = os.path.dirname(pathname)
        if pathname and os.path.exists(pathname):
            stats = os.statvfs(pathname)
            return (stats.f_bavail * stats.f_frsize - int(diskspace_threshold_mb) * 1024**2
                > obj.size * (1.0 - obj.done / 100.0))
        else:
            return None

    yield engine.DynamicField(engine.untyped, "has_room",
        "check whether the download will fit on its target device",
        matcher=matching.BoolFilter, accessor=has_room,
        formatter=lambda val: "OK" if val else "??" if val is None else "NO")
    globals().setdefault("diskspace_threshold_mb", "500")
607421
def filter(cls, start_position="", max_results="", qb=None, **kwargs):
        
        return cls.where(build_where_clause(**kwargs),
                         start_position=start_position, max_results=max_results, qb=qb)
717545
def apply(self, search, field, value):
        """"""
        return search.query(
            self.query_type(  # pylint: disable=not-callable
                **{
                    field: {
                        self.operator: self.get_value_query(value)
                    }
                }
            )
        )