Haystack facets are returned as a two-tuple (value, count).
        The text field should contain the faceted value.
423283
def get_text(self, instance):
        
        instance = instance[0]
        if isinstance(instance, (six.text_type, six.string_types)):
            return serializers.CharField(read_only=True).to_representation(instance)
        elif isinstance(instance, datetime):
            return serializers.DateTimeField(read_only=True).to_representation(instance)
        return instance
833506
def dois2marc(self, key, value):
    """"""
    return {
        '2': 'DOI',
        '9': value.get('source'),
        'a': value.get('value'),
        'q': value.get('material'),
    }
559929
private int extractMatchingFields(Tuple<Type.Field> lhsFields, Tuple<Type.Field> rhsFields, Type.Field[] result,
			LifetimeRelation lifetimes, LinkageStack stack) {
		int index = 0;
		// Extract all matching fields first.
		for (int i = 0; i != lhsFields.size(); ++i) {
			for (int j = 0; j != rhsFields.size(); ++j) {
				Type.Field lhsField = lhsFields.get(i);
				Type.Field rhsField = rhsFields.get(j);
				Identifier lhsFieldName = lhsField.getName();
				Identifier rhsFieldName = rhsField.getName();
				if (lhsFieldName.equals(rhsFieldName)) {
					Type type = apply(lhsField.getType(), rhsField.getType(), lifetimes, stack);
					Type.Field combined = new Type.Field(lhsFieldName, type);
					result[index++] = combined;
				}
			}
		}
		return index;
	}
61146
def field_to_dict(self, field):
        """"""
        value = getattr(self, field)
        if isinstance(value, (list, tuple)):
            return [self.value_to_dict(val) for val in value]
        return self.value_to_dict(value)
945248
def count(self):
        
        if self.mode == 'spark':
            return self.tordd().count()

        if self.mode == 'local':
            return prod(self.values.values.shape)
344717
def get_search_field_values(contentitem):
    
    plugin = contentitem.plugin
    values = []
    for field_name in plugin.search_fields:
        value = getattr(contentitem, field_name)

        # Just assume all strings may contain HTML.
        # Not checking for just the PluginHtmlField here.
        if value and isinstance(value, six.string_types):
            value = get_cleaned_string(value)

        values.append(value)

    return values
1023445
public static <T> boolean containsNull(T...hayStack)
	{
		if(hayStack == null)
			return false;
		for(T hay : hayStack)
			if(hay == null)
				return true;
		return false;
	}
554978
def _fmt_fields(fld_vals, fld2fmt):
    """"""
    vals = []
    for fld, val in fld_vals:
        if fld in fld2fmt:
            val = fld2fmt[fld].format(val)
        vals.append(val)
    return vals
858430
def _validate_contains(self, expected_values, field, value):
        
        if not isinstance(value, Iterable):
            return

        if not isinstance(expected_values, Iterable) or isinstance(
            expected_values, _str_type
        ):
            expected_values = set((expected_values,))
        else:
            expected_values = set(expected_values)

        missing_values = expected_values - set(value)
        if missing_values:
            self._error(field, errors.MISSING_MEMBERS, missing_values)
1006174
def get_first_field_values_as_list(self, field):
        '''
        
        '''
        for doc in self.docs:
            if field in doc.keys():
                return doc[field]
        raise SolrResponseError("No field in result set")
96901
private String buildFacetString(List<String> facetNames, List<String>facetValues ) {
		
		StringBuilder builder = new StringBuilder();

		if( facetNames != null && facetValues != null ) 
		{
			int pairsCount = -1;
			if( facetNames.size() != facetValues.size() ) {
				pairsCount = facetNames.size() > facetValues.size() ? facetValues.size() : facetNames.size();
				log.warn( "facetNames and facetValues lists were of different sizes, your query may not be accurate" );
			} else {
				pairsCount = facetNames.size();
			}
			for( int i=0; i < pairsCount; i++ ) {
				try {
					builder.append( "&facets[").append( facetNames.get( i )).append( "][]=" )
						.append( URLEncoder.encode( facetValues.get( i ), "UTF-8" ));
				} catch (UnsupportedEncodingException ignore) {
				}
			}

		} else {
			log.error( "facetNames or facetValues was null, you are defaulting to a regular query using no facet matching" );
		}

		return builder.toString();
	}
574007
def listing_searchable_text(instance):
    
    # get all snapshots
    snapshots = get_snapshots(instance)
    # extract all snapshot values, because we are not interested in the
    # fieldnames (keys)
    values = map(lambda s: s.values(), snapshots)
    # prepare a set of unified catalog data
    catalog_data = set()
    # values to skip
    skip_values = ["None", "true", "True", "false", "False"]
    # internal uid -> title cache
    uid_title_cache = {}

    # helper function to recursively unpack the snapshot values
    def append(value):
        if isinstance(value, (list, tuple)):
            map(append, value)
        elif isinstance(value, (dict)):
            map(append, value.items())
        elif isinstance(value, basestring):
            # convert unicode to UTF8
            if isinstance(value, unicode):
                value = api.safe_unicode(value).encode("utf8")
            # skip single short values
            if len(value) < 2:
                return
            # flush non meaningful values
            if value in skip_values:
                return
            # flush ISO dates
            if re.match(DATE_RX, value):
                return
            # fetch the title
            if re.match(UID_RX, value):
                if value in uid_title_cache:
                    value = uid_title_cache[value]
                else:
                    title_or_id = get_title_or_id_from_uid(value)
                    uid_title_cache[value] = title_or_id
                    value = title_or_id
            catalog_data.add(value)

    # extract all meaningful values
    for value in itertools.chain(values):
        append(value)

    return " ".join(catalog_data)
211544
def zfind(cls, **kwargs):
        
        assert len(kwargs) == 1
        fldcond = kwargs.keys()[0].split('__')
        fld = fldcond[0]
        f = cls.__dict__[fld]
        val = kwargs.values()[0]
        if isinstance(val, tuple):
            assert len(val) == 2
            val = (f.typecast_for_write(val[0]), f.typecast_for_write(val[1]))
        else:
            val = f.typecast_for_write(val)
        if len(fldcond) == 1:
            return f.zindex.zfind(eq = val)
        else:
            cond = fldcond[1]
            return f.zindex.zfind(**{cond: val})
948299
def solr_names_and_values(field_name, field_value, index_types)
      return {} if field_value.nil?
      
      # Determine the set of index types
      index_types = Array(index_types)
      index_types.uniq!
      index_types.dup.each do |index_type|
        if index_type.to_s =~ /^not_(.*)/
          index_types.delete index_type # not_foo
          index_types.delete $1.to_sym  # foo
        end
      end
      
      # Map names and values
      
      results = {}

      # Time seems to extend enumerable, so wrap it so we don't interate over each of its elements.
      field_value = [field_value] if field_value.kind_of? Time
      
      index_types.each do |index_type|
        Array(field_value).each do |single_value|
          # Get mapping for field
          descriptor = indexer(index_type)
          data_type = extract_type(single_value)
          name, converter = descriptor.name_and_converter(field_name, type: data_type)
          next unless name

          # Is there a custom converter?
          # TODO instead of a custom converter, look for input data type and output data type. Create a few methods that can do that cast.

          value = if converter
            if converter.arity == 1
              converter.call(single_value)
            else
              converter.call(single_value, field_name)
            end
          elsif data_type == :boolean
            single_value
          else
            single_value.to_s
          end
          
          # Add mapped name & value, unless it's a duplicate
          if descriptor.evaluate_suffix(data_type).multivalued?
            values = (results[name] ||= [])
            values << value unless value.nil? || values.include?(value)
          else
            Solrizer.logger.warn "Setting #{name} to `#{value}', but it already had `#{results[name]}'" if results[name] && Solrizer.logger
            results[name] = value
          end
        end
      end
        
      results
    end
813756
def sparse_tensor_value_to_texts(value, alphabet):
    
    """
    return sparse_tuple_to_texts((value.indices, value.values, value.dense_shape), alphabet)
970853
def get_values(self, data, filter_values):
        
        values = super(ModelTermsFacet, self).get_values(data, filter_values)
        ids = [key for (key, doc_count, selected) in values]
        # Perform a model resolution: models are feched from DB
        # We use model field to cast IDs
        ids = [self.model_field.to_mongo(id) for id in ids]
        objects = self.model.objects.in_bulk(ids)

        return [
            (objects.get(self.model_field.to_mongo(key)), doc_count, selected)
            for (key, doc_count, selected) in values
        ]
1286330
def get_value_matched_by_regex(field_name, regex_matches, string):
    """"""
    try:
        value = regex_matches.group(field_name)
        if value is not None:
            return value
    except IndexError:
        pass

    raise MissingFieldError(string, field_name)