Encodes an iterable of a given field into a database-compatible format.
480920
def list_encoder(values, instance, field: Field):
    """"""
    return [field.to_db_value(element, instance) for element in values]
763946
def encode(self, o):
        
        # This doesn't pass the iterator directly to ''.join() because it
        # sucks at reporting exceptions.  It's going to do this internally
        # anyway because it uses PySequence_Fast or similar.
        chunks = list(self.iterencode(o))
        return ''.join(chunks)
4810
def encode_list(key, list_):
    # type: (str, Iterable) -> Dict[str, str]
    
    if not list_:
        return {}
    return {key: " ".join(str(i) for i in list_)}
1318777
def encode_field(self, field, value):
        
        for encoder in _GetFieldCodecs(field, 'encoder'):
            result = encoder(field, value)
            value = result.value
            if result.complete:
                return value
        if isinstance(field, messages.EnumField):
            if field.repeated:
                remapped_value = [GetCustomJsonEnumMapping(
                    field.type, python_name=e.name) or e.name for e in value]
            else:
                remapped_value = GetCustomJsonEnumMapping(
                    field.type, python_name=value.name)
            if remapped_value:
                return remapped_value
        if (isinstance(field, messages.MessageField) and
                not isinstance(field, message_types.DateTimeField)):
            value = json.loads(self.encode_message(value))
        return super(_ProtoJsonApiTools, self).encode_field(field, value)
1247144
def encode(self, entity):
        
        possible_results = []
        entity_dict = self.get_entity_dict(entity)
        record_field_encoders = self.get_record_fields_encoders()
        for field_encoders in record_field_encoders:
            result = self.try_encode(field_encoders, entity_dict)
            if result:
                possible_results.append({'result': result, 'len': len(field_encoders)})
        cwr = self.head(entity) + self._get_best_result(possible_results) + "\r\n"
        return cwr
423821
def iterdecode(iterable, codec):
    
    decoder = codec.incrementaldecoder()
    for chunk in iterable:
        yield decoder.decode(chunk)
    yield decoder.decode(b'', True)
975850
def encode_list(data, encoding=None, errors='strict', keep=False,
                preserve_dict_class=False, preserve_tuples=False):
    '''
    
    '''
    rv = []
    for item in data:
        if isinstance(item, list):
            item = encode_list(item, encoding, errors, keep,
                               preserve_dict_class, preserve_tuples)
        elif isinstance(item, tuple):
            item = encode_tuple(item, encoding, errors, keep, preserve_dict_class) \
                if preserve_tuples \
                else encode_list(item, encoding, errors, keep,
                                 preserve_dict_class, preserve_tuples)
        elif isinstance(item, Mapping):
            item = encode_dict(item, encoding, errors, keep,
                               preserve_dict_class, preserve_tuples)
        else:
            try:
                item = salt.utils.stringutils.to_bytes(item, encoding, errors)
            except TypeError:
                # to_bytes raises a TypeError when input is not a
                # string/bytestring/bytearray. This is expected and simply
                # means we are going to leave the value as-is.
                pass
            except UnicodeEncodeError:
                if not keep:
                    raise

        rv.append(item)
    return rv
1269162
def _encode_list(self, obj):# do
        """"""

        self._increment_nested_level()

        buffer = []
        for element in obj:
            buffer.append(self._encode(element))

        self._decrement_nested_level()

        return '['+ ','.join(buffer) + ']'
831886
private void encodeAttributes(List attributes, PrintStream out,
                                  Indenter indenter) {
        Iterator it = attributes.iterator();
        while (it.hasNext()) {
            Attribute attr = (Attribute)(it.next());
            attr.encode(out, indenter);
        }
    }
60023
def encode_field(self, field, value):
    
    # Override the handling of 64-bit integers, so they're always encoded
    # as strings.
    if (isinstance(field, messages.IntegerField) and
        field.variant in (messages.Variant.INT64,
                          messages.Variant.UINT64,
                          messages.Variant.SINT64)):
      if value not in (None, [], ()):
        # Convert and replace the value.
        if isinstance(value, list):
          value = [str(subvalue) for subvalue in value]
        else:
          value = str(value)
        return value

    return super(EndpointsProtoJson, self).encode_field(field, value)
1179184
def encode_list(cls, value):
        
        encoded = base64.b64encode(six.b(" ".join(str(v) for v in value) or "-"))
        return encoded.decode("utf-8") if six.PY3 else encoded
1341617
def encode(self, obj):
        
        if isinstance(obj, int_like_types):
            self.result.append("i%de" % obj)
        elif isinstance(obj, string_types):
            self.result.extend([str(len(obj)), ':', str(obj)])
        elif hasattr(obj, "__bencode__"):
            self.encode(obj.__bencode__())
        elif hasattr(obj, "items"):
            # Dictionary
            self.result.append('d')
            for key, val in sorted(obj.items()):
                key = str(key)
                self.result.extend([str(len(key)), ':', key])
                self.encode(val)
            self.result.append('e')
        else:
            # Treat as iterable
            try:
                items = iter(obj)
            except TypeError as exc:
                raise BencodeError("Unsupported non-iterable object %r of type %s (%s)" % (
                    obj, type(obj), exc
                ))
            else:
                self.result.append('l')
                for item in items:
                    self.encode(item)
                self.result.append('e')

        return self.result
19960
def value_to_db(self, value):
        
        if isinstance(value, six.string_types):
            value = value.encode("utf_8")
        return value
720018
def StringEncoder(field_number, is_repeated, is_packed):
  """"""

  tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  local_EncodeVarint = _EncodeVarint
  local_len = len
  assert not is_packed
  if is_repeated:
    def EncodeRepeatedField(write, value):
      for element in value:
        encoded = element.encode('utf-8')
        write(tag)
        local_EncodeVarint(write, local_len(encoded))
        write(encoded)
    return EncodeRepeatedField
  else:
    def EncodeField(write, value):
      encoded = value.encode('utf-8')
      write(tag)
      local_EncodeVarint(write, local_len(encoded))
      return write(encoded)
    return EncodeField
936236
def convertfields(key_comm, obj, inblock=None):
    """"""
    # f_ stands for field_
    convinidd = ConvInIDD()
    if not inblock:
        inblock = ['does not start with N'] * len(obj)
    for i, (f_comm, f_val, f_iddname) in enumerate(zip(key_comm, obj, inblock)):
        if i == 0:
            # inblock[0] is the iddobject key. No conversion here
            pass
        else:
            obj[i] = convertafield(f_comm, f_val, f_iddname)
    return obj
514473
def encode_network(root):
    """"""
    def fix_values(obj):
        if isinstance(obj, Container):
            obj.update((k, get_ref(v)) for (k, v) in obj.items()
                                       if k != 'class_name')
            fixed_obj = obj

        elif isinstance(obj, Dictionary):
            fixed_obj = obj.__class__(dict(
                (get_ref(field), get_ref(value))
                for (field, value) in obj.value.items()
            ))

        elif isinstance(obj, dict):
            fixed_obj = dict(
                (get_ref(field), get_ref(value))
                for (field, value) in obj.items()
            )

        elif isinstance(obj, list):
            fixed_obj = [get_ref(field) for field in obj]

        elif isinstance(obj, Form):
            fixed_obj = obj.__class__(**dict(
                (field, get_ref(value))
                for (field, value) in obj.value.items()
            ))

        elif isinstance(obj, ContainsRefs):
            fixed_obj = obj.__class__([get_ref(field)
                                       for field in obj.value])

        else:
            return obj

        fixed_obj._made_from = obj
        return fixed_obj

    objects = []

    def get_ref(obj, objects=objects):
        obj = PythonicAdapter(Pass)._encode(obj, None)

        if isinstance(obj, (FixedObject, Container)):
            if getattr(obj, '_index', None):
                index = obj._index
            else:
                objects.append(None)
                obj._index = index = len(objects)
                objects[index - 1] = fix_values(obj)
            return Ref(index)
        else:
            return obj # Inline value

    get_ref(root)

    for obj in objects:
        if getattr(obj, '_index', None):
            del obj._index
    return objects
429515
def make_serializable(data):
    """"""
    if is_serializable(data):
        return data

    # if numpy array convert to list
    try:
        return data.tolist()
    except AttributeError:
        pass
    except Exception as e:
        logger.debug('{} exception ({}): {}'.format(type(e).__name__, e, data))

    # try serializing each child element
    if isinstance(data, dict):
        return {key: make_serializable(value) for key, value in data.items()}
    try:
        return [make_serializable(element) for element in data]
    except TypeError:  # not iterable
        pass
    except Exception:
        logger.debug('Could not serialize {}; converting to string'.format(data))

    # last resort: convert to string
    return str(data)