Convert comma separated list to a mongo projection. for example f('field1,field2,field3') -> {field1:true,field2:true,field3:true}
768614
function fieldsToMongo(fields) {
    if (!fields) return null
    var hash = {}
    fields.split(',').forEach(function(field) {
        hash[field.trim()] = 1
    })
    return hash
}
736678
def tuple(data, field_name):
    
    if isinstance(data, Cube):
        Log.error("not supported yet")

    if isinstance(data, FlatList):
        Log.error("not supported yet")

    if is_data(field_name) and "value" in field_name:
        # SIMPLIFY {"value":value} AS STRING
        field_name = field_name["value"]

    # SIMPLE PYTHON ITERABLE ASSUMED
    if is_text(field_name):
        if len(split_field(field_name)) == 1:
            return [(d[field_name],) for d in data]
        else:
            path = split_field(field_name)
            output = []
            flat_list._tuple1(data, path, 0, output)
            return output
    elif is_list(field_name):
        paths = [_select_a_field(f) for f in field_name]
        output = FlatList()
        _tuple((), unwrap(data), paths, 0, output)
        return output
    else:
        paths = [_select_a_field(field_name)]
        output = FlatList()
        _tuple((), data, paths, 0, output)
        return output
623128
def map_field(field, func, dict_sequence):
    
    for item in dict_sequence:
        try:
            item[field] = func(item.get(field, None))
            yield item
        except ValueError:
            pass
1298604
function listToArray(list) {
  if(isFunction(list)) {
    return function(x) {
      const m = list(x)

      if(!isSameType(List, m)) {
        throw new TypeError('listToArray: List returning function required')
      }

      return m.toArray()
    }
  }

  if(isSameType(List, list)) {
    return list.toArray()
  }

  throw new TypeError('listToArray: List or List returning function required')
}
269441
function partition(collection, fn) {
  var result = { lhs: [], rhs: [] };
  _.forEach(collection, function(value) {
    if (fn(value)) {
      result.lhs.push(value);
    } else {
      result.rhs.push(value);
    }
  });
  return result;
}
469610
function flattenList(list) {
  // Make a copy, so the original tensor is not modified.
  list = [].concat(list);

  // Note that i must be checked against the length of the list each time through the loop, as the
  // list is modified within the iterations.
  for (let i = 0; i < list.length; i++) {
    if (Array.isArray(list[i])) {
      // Replace the item with the flattened version of the item (using the ... operator).
      // Replace with the items and backtrack 1 position
      list.splice(i, 1, ...list[i]);

      // Decrement i to look at the element again; we'll keep looking at this i index, until
      // the most deeply nested item has been flattened.
      i--;
    }
  }

  return list;
}
721052
function getFields(collection) {

    var message = 'What fields should "' + collection + '" have?\n',
        config;

    config = {
        properties: {
            fields: {
                description: message.magenta +
                '   Comma-separated fieldname:fieldtype pairs (ex: id:index, username:username)\n'.grey,
                type: 'string',
                required: true,
                pattern: FIELDS_REGEXP
            }
        }
    };

    prompt.start();
    prompt.message = '   >> ';
    prompt.delimiter = '';

    return new Promise(function(resolve, reject) {
        prompt.get(config, function(err, result) {
            if (err) return reject(err);
            return resolve(result.fields);
        });
    }).then(function(input) {
        return (input.match(FIELDS_REGEXP) || []).reduce(function(prev, curr) {
            var parts = curr.split(':');
            prev[parts[0]] = parts[1].replace(/\+/g, '}~{'); // with "+" also support name={fistName}~{lastName} concatenations
            return prev;
        }, {});
    });
}
1317195
def translate_list(cls, val):
        """"""
        escaped = ', '.join([cls.translate(v) for v in val])
        return 'Seq({})'.format(escaped)
661445
def get_convert_dict(fmt):
    """"""
    convdef = {}
    for literal_text, field_name, format_spec, conversion in formatter.parse(fmt):
        if field_name is None:
            continue
        # XXX: Do I need to include 'conversion'?
        convdef[field_name] = format_spec
    return convdef
1227101
def build_mongo_doc(self, key_list):
        
        mongo_doc = {}

        if isinstance(key_list, list) and key_list:

            for key in key_list:
                mongo_doc[key] = "$" + str(key)
        return mongo_doc
4685
def one(cls, filter=None, **kwargs):
        """"""
        from mongoframes.queries import Condition, Group, to_refs

        # Flatten the projection
        kwargs['projection'], references, subs = \
                cls._flatten_projection(
                    kwargs.get('projection', cls._default_projection)
                    )

        # Find the document
        if isinstance(filter, (Condition, Group)):
            filter = filter.to_dict()

        document = cls.get_collection().find_one(to_refs(filter), **kwargs)

        # Make sure we found a document
        if not document:
            return

        # Dereference the document (if required)
        if references:
            cls._dereference([document], references)

        # Add sub-frames to the document (if required)
        if subs:
            cls._apply_sub_frames([document], subs)

        return cls(document)
1051499
public static Projection array(String pattern,
                                   Integer from,
                                   Integer to,
                                   boolean include,
                                   Projection projection,
                                   Sort sort) {
        Projection p = new Projection(false);
        ArrayNode a = JsonNodeFactory.instance.arrayNode();
        a.add(JsonNodeFactory.instance.numberNode(from));
        if (to != null) {
            a.add(JsonNodeFactory.instance.numberNode(to));
        } else {
            a.add(JsonNodeFactory.instance.nullNode());
        }
        p.add("field", pattern).add("include", include).add("range", a);
        if (projection != null) {
            p.add("projection", projection.toJson());
        }
        if (sort != null) {
            p.add("sort", sort.toJson());
        }
        return p;
    }
546133
function groupFieldsByType(list){
    var fields = {};
    _.each(list.fields, function(v,k) {
        if (! fields.hasOwnProperty(v.type)) fields[v.type] = [];
        fields[v.type].push(v);
    });
    return fields;
}
922144
function(fieldOrSpec) {
  var fieldHash = {};
  var indexes = [];
  var keys;

  // Get all the fields accordingly
  if ('string' === typeof fieldOrSpec) {
    // 'type'
    indexes.push(fieldOrSpec + '_' + 1);
    fieldHash[fieldOrSpec] = 1;
  } else if (Array.isArray(fieldOrSpec)) {
    fieldOrSpec.forEach(function(f) {
      if ('string' === typeof f) {
        // [{location:'2d'}, 'type']
        indexes.push(f + '_' + 1);
        fieldHash[f] = 1;
      } else if (Array.isArray(f)) {
        // [['location', '2d'],['type', 1]]
        indexes.push(f[0] + '_' + (f[1] || 1));
        fieldHash[f[0]] = f[1] || 1;
      } else if (isObject(f)) {
        // [{location:'2d'}, {type:1}]
        keys = Object.keys(f);
        keys.forEach(function(k) {
          indexes.push(k + '_' + f[k]);
          fieldHash[k] = f[k];
        });
      } else {
        // undefined (ignore)
      }
    });
  } else if (isObject(fieldOrSpec)) {
    // {location:'2d', type:1}
    keys = Object.keys(fieldOrSpec);
    keys.forEach(function(key) {
      indexes.push(key + '_' + fieldOrSpec[key]);
      fieldHash[key] = fieldOrSpec[key];
    });
  }

  return {
    name: indexes.join('_'),
    keys: keys,
    fieldHash: fieldHash
  };
}
695346
def _projection_to_paths(cls, root_key, projection):
        

        # Referenced projections are handled separately so just flag the
        # reference field to true.
        if '$ref' in projection:
            return True

        inclusive = True
        sub_projection = {}
        for key, value in projection.items():
            if key in ['$sub', '$sub.']:
                continue

            if key.startswith('$'):
                sub_projection[root_key] = {key: value}
                inclusive = False
                continue

            sub_key = root_key + '.' + key

            if isinstance(value, dict):
                sub_value = cls._projection_to_paths(sub_key, value)
                if isinstance(sub_value, dict):
                    sub_projection.update(sub_value)
                else:
                    sub_projection[sub_key] = True

            else:
                sub_projection[sub_key] = True
                inclusive = False

        if inclusive:
            # No specific keys so this is inclusive
            return True

        return sub_projection
29925
def _dict_to_bson(doc, check_keys, opts, top_level=True):
    """"""
    if _raw_document_class(doc):
        return doc.raw
    try:
        elements = []
        if top_level and "_id" in doc:
            elements.append(_name_value_to_bson(b"_id\x00", doc["_id"],
                                                check_keys, opts))
        for (key, value) in iteritems(doc):
            if not top_level or key != "_id":
                elements.append(_element_to_bson(key, value,
                                                 check_keys, opts))
    except AttributeError:
        raise TypeError("encoder expected a mapping type but got: %r" % (doc,))

    encoded = b"".join(elements)
    return _PACK_INT(len(encoded) + 5) + encoded + b"\x00"
872671
def group_by(self, fields, items=None):
        
        result = defaultdict(list)
        if items is None:
            items = self.items()

        try:
            key = operator.attrgetter(fields + '')
        except TypeError:
            def key(obj, names=tuple(fields)):
                'Helper to return group key tuple'
                return tuple(getattr(obj, x) for x in names)

        for item in items:
            result[key(item)].append(item)

        return result