Object/hash encoding serializer.
437315
function hash_serializer(result, key, value) {
  var matches = key.match(brackets);

  // Has brackets? Use the recursive assignment function to walk the keys,
  // construct any missing objects in the result tree and make the assignment
  // at the end of the chain.
  if (matches) {
    var keys = parse_keys(key);
    hash_assign(result, keys, value);
  }
  else {
    // Non bracket notation can make assignments directly.
    var existing = result[key];

    // If the value has been assigned already (for instance when a radio and
    // a checkbox have the same name attribute) convert the previous value
    // into an array before pushing into it.
    //
    // NOTE: If this requirement were removed all hash creation and
    // assignment could go through `hash_assign`.
    if (existing) {
      if (!Array.isArray(existing)) {
        result[key] = [ existing ];
      }

      result[key].push(value);
    }
    else {
      result[key] = value;
    }
  }

  return result;
}
409263
def safe_for_serialization(value):
    

    if isinstance(value, six.string_types):
        return value
    if isinstance(value, dict):
        return {
            safe_for_serialization(key): safe_for_serialization(val)
            for key, val in six.iteritems(value)
        }
    if isinstance(value, collections.Iterable):
        return list(map(safe_for_serialization, value))

    try:
        return six.text_type(value)
    except Exception:
        return '[__unicode__ failed]'
448505
def _dumps(obj, cls=pyjson.JSONEncoder):
    

    class WithBytes(cls):
        """
        JSON encoder that supports L{bytes}.
        """

        def default(self, o):
            if isinstance(o, bytes):
                warnings.warn(
                    "Eliot will soon stop supporting encoding bytes in JSON"
                    " on Python 3", DeprecationWarning
                )
                return o.decode("utf-8")
            return cls.default(self, o)

    return pyjson.dumps(obj, cls=WithBytes).encode("utf-8")
677327
def serialize(obj, **options):
    '''
    
    '''

    options.setdefault('Dumper', Dumper)
    try:
        response = yaml.dump(obj, **options)
        if response.endswith('\n...\n'):
            return response[:-5]
        if response.endswith('\n'):
            return response[:-1]
        return response
    except Exception as error:
        log.exception('Error encountered while serializing')
        raise SerializationError(error)
1147706
def _encode_request(self, request):
        """"""
        obj = request_to_dict(request, self.spider)
        return self.serializer.dumps(obj)
894105
def serialize(self, obj, method='json', beautify=False, raise_exception=False):
        """"""

        return self.helper.string.serialization.serialize(
            obj=obj, method=method, beautify=beautify, raise_exception=raise_exception)
264063
def _make_serializer(meas, schema, rm_none, extra_tags, placeholder):  # noqa: C901
    """"""
    _validate_schema(schema, placeholder)
    tags = []
    fields = []
    ts = None
    meas = meas
    for k, t in schema.items():
        if t is MEASUREMENT:
            meas = f"{{i.{k}}}"
        elif t is TIMEINT:
            ts = f"{{i.{k}}}"
        elif t is TIMESTR:
            if pd:
                ts = f"{{pd.Timestamp(i.{k} or 0).value}}"
            else:
                ts = f"{{dt_to_int(str_to_dt(i.{k}))}}"
        elif t is TIMEDT:
            if pd:
                ts = f"{{pd.Timestamp(i.{k} or 0).value}}"
            else:
                ts = f"{{dt_to_int(i.{k})}}"
        elif t is TAG:
            tags.append(f"{k}={{str(i.{k}).translate(tag_escape)}}")
        elif t is TAGENUM:
            tags.append(f"{k}={{getattr(i.{k}, 'name', i.{k} or None)}}")
        elif t in (FLOAT, BOOL):
            fields.append(f"{k}={{i.{k}}}")
        elif t is INT:
            fields.append(f"{k}={{i.{k}}}i")
        elif t is STR:
            fields.append(f"{k}=\\\"{{str(i.{k}).translate(str_escape)}}\\\"")
        elif t is ENUM:
            fields.append(f"{k}=\\\"{{getattr(i.{k}, 'name', i.{k} or None)}}\\\"")
        else:
            raise SchemaError(f"Invalid attribute type {k!r}: {t!r}")
    extra_tags = extra_tags or {}
    for k, v in extra_tags.items():
        tags.append(f"{k}={v}")
    if placeholder:
        fields.insert(0, f"_=true")

    sep = ',' if tags else ''
    ts = f' {ts}' if ts else ''
    fmt = f"{meas}{sep}{','.join(tags)} {','.join(fields)}{ts}"
    if rm_none:
        # Has substantial runtime impact. Best avoided if performance is critical.
        # First field can't be removed.
        pat = r',\w+="?None"?i?'
        f = eval('lambda i: re.sub(r\'{}\', "", f"{}").encode()'.format(pat, fmt))
    else:
        f = eval('lambda i: f"{}".encode()'.format(fmt))
    f.__doc__ = "Returns InfluxDB line protocol representation of user-defined class"
    f._args = dict(meas=meas, schema=schema, rm_none=rm_none,
                   extra_tags=extra_tags, placeholder=placeholder)
    return f
726706
def tostr(object, encoding=None):
    
    if isinstance(object, basestring):
        if encoding is None:
            return object
        else:
            return object.encode(encoding)
    if isinstance(object, tuple):
        s = ['(']
        for item in object:
            if isinstance(item, basestring):
                s.append(item)
            else:
                s.append(tostr(item))
            s.append(', ')
        s.append(')')
        return ''.join(s)
    if isinstance(object, list):
        s = ['[']
        for item in object:
            if isinstance(item, basestring):
                s.append(item)
            else:
                s.append(tostr(item))
            s.append(', ')
        s.append(']')
        return ''.join(s)
    if isinstance(object, dict):
        s = ['{']
        for item in object.items():
            if isinstance(item[0], basestring):
                s.append(item[0])
            else:
                s.append(tostr(item[0]))
            s.append(' = ')
            if isinstance(item[1], basestring):
                s.append(item[1])
            else:
                s.append(tostr(item[1]))
            s.append(', ')
        s.append('}')
        return ''.join(s)
    try:
        return unicode(object)
    except:
        return str(object)
653399
def deserialize(cls, serialized):
        ''' 
        '''
        return PublicKey(
            nacl.public.PublicKey(serialized,
                                  encoder=nacl.encoding.Base64Encoder))
243460
def to_json(object, use_alias = false)
      hash = to_hash(object, use_alias)
      JSON.dump(hash)
    end
784362
function serializeHash() {
      var hash = {}
      eachFormElement.apply(function (name, value) {
        if (name in hash) {
          hash[name] && !isArray(hash[name]) && (hash[name] = [hash[name]])
          hash[name].push(value)
        } else hash[name] = value
      }, arguments)
      return hash
    }
606012
def getStringForBytes(self, s):
        
        h = hash(s)
        u = self._unicodes.get(h, None)

        if u is not None:
            return u

        u = self._unicodes[h] = s.decode('utf-8')

        return u
820242
def encode(self, object_):
        
        if self.enforce_reversible:
            self.enforce_reversible = False
            if self.decode(self.encode(object_)) != object_:
                raise ValueError('Encoding is not reversible for "%s"' % object_)
            self.enforce_reversible = True

        return object_
562370
private String encode(Object value) {
    return BaseEncoding.base16().encode(valueSerializer.encode(value));
  }
1220499
def getBytesForString(self, u):
        
        h = hash(u)
        s = self._unicodes.get(h, None)

        if s is not None:
            return s

        s = self._unicodes[h] = u.encode('utf-8')

        return s
117988
function compositeSerializer(serializers){
  return function(vals, sliceStart){
    var i = 0, buffers = [], totalLength = 0,
        valLength = vals.length, val;

    if(!Array.isArray(vals)){
      vals = [vals];
      valLength = vals.length;
    }

    for(; i < valLength; i += 1){
      if (Array.isArray(vals[i])){
        val = [serializers[i](vals[i][0]), vals[i][1]];
        totalLength += val[0].length + 3;
      } else {
        val = serializers[i](vals[i]);
        totalLength += val.length + 3;
      }

      buffers.push(val);
    }

    var buf = new Buffer(totalLength),
        buffersLength = buffers.length,
        writtenLength = 0, eoc, inclusive;

    i = 0;
    for(; i < buffersLength; i += 1){
      val = buffers[i];
      eoc = new Buffer('00', 'hex');
      inclusive = true;

      if (Array.isArray(val)){
        inclusive = val[1];
        val = val[0];
        if(inclusive){
          if (sliceStart){
            eoc = new Buffer('ff', 'hex');
          } else if (sliceStart === false){
            eoc = new Buffer('01', 'hex');
          }
        } else {
          if (sliceStart){
            eoc = new Buffer('01', 'hex');
          } else if (sliceStart === false){
            eoc = new Buffer('ff', 'hex');
          }
        }
      } else if (i === buffersLength - 1){
      if (sliceStart){
          eoc = new Buffer('ff', 'hex');
        } else if (sliceStart === false){
          eoc = new Buffer('01', 'hex');
        }
      }

      buf.writeUInt16BE(val.length, writtenLength);
      writtenLength += 2;
      val.copy(buf, writtenLength, 0);
      writtenLength += val.length;
      eoc.copy(buf, writtenLength, 0);
      writtenLength += 1;
    }

    return buf;
  };
}
1095935
def object_to_bytes(obj):
    
    if isinstance(obj, str):
        return bytearray(obj, "UTF-8")
    elif isinstance(obj, bool):
        return bytearray()
    elif isinstance(obj, int):
        return pack("<L", obj)
    elif obj is None:
        return bytearray()
    elif isinstance(obj, bytearray):
        return obj
    else:
        return obj.get_raw()