Serialize bucket property request and deserialize response
351861
def get_bucket_props(self, bucket):
        
        msg_code = riak.pb.messages.MSG_CODE_GET_BUCKET_REQ
        codec = self._get_codec(msg_code)
        msg = codec.encode_get_bucket_props(bucket)
        resp_code, resp = self._request(msg, codec)
        return codec.decode_bucket_props(resp.props)
737972
def _deserialize(self, value, attr, data):
        """"""
        token_builder = URLSafeTimedSerializer(
            current_app.config['SECRET_KEY'],
            salt=data['verb'],
        )
        result = token_builder.loads(value, max_age=current_app.config[
            'OAISERVER_RESUMPTION_TOKEN_EXPIRE_TIME'])
        result['token'] = value
        result['kwargs'] = self.root.load(result['kwargs'], partial=True).data
        return result
699516
private void writeObject (ObjectOutputStream out)
        throws IOException
    {
        out.defaultWriteObject();
        for (int idx = 0, pos = 0; pos < _size; idx++) {
            int value = _buckets[idx];
            if (value != _sentinel) {
                out.writeInt(value);
                pos++;
            }
        }
    }
1295516
private void getObject(WebContext ctx, Bucket bucket, String id, boolean sendFile) throws IOException {
        StoredObject object = bucket.getObject(id);
        if (!object.exists()) {
            signalObjectError(ctx, HttpResponseStatus.NOT_FOUND, "Object does not exist");
            return;
        }
        Response response = ctx.respondWith();
        Properties properties = object.getProperties();
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            response.addHeader(entry.getKey().toString(), entry.getValue().toString());
        }
        for (Map.Entry<String, String> entry : getOverridenHeaders(ctx).entrySet()) {
            response.setHeader(entry.getKey(), entry.getValue());
        }

        String etag = properties.getProperty(HTTP_HEADER_NAME_ETAG);
        if (Strings.isEmpty(etag)) {
            HashCode hash = Files.hash(object.getFile(), Hashing.md5());
            etag = BaseEncoding.base16().encode(hash.asBytes());
            Map<String, String> data = new HashMap<>();
            properties.forEach((key, value) -> data.put(key.toString(), String.valueOf(value)));
            data.put(HTTP_HEADER_NAME_ETAG, etag);
            object.storeProperties(data);
        }

        response.addHeader(HTTP_HEADER_NAME_ETAG, etag(etag));
        response.addHeader(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, HTTP_HEADER_NAME_ETAG);
        if (sendFile) {
            response.file(object.getFile());
        } else {
            String contentType = MimeHelper.guessMimeType(object.getFile().getName());
            response.addHeader(HttpHeaderNames.CONTENT_TYPE, contentType);
            response.addHeader(HttpHeaderNames.LAST_MODIFIED,
                               RFC822_INSTANT.format(Instant.ofEpochMilli(object.getFile().lastModified())));
            response.addHeader(HttpHeaderNames.CONTENT_LENGTH, object.getFile().length());
            response.status(HttpResponseStatus.OK);
        }
        signalObjectSuccess(ctx);
    }
410585
def serialize(self):
        
        if self.action == 'Create':
            payload = self.extra['index'].schema()
        else:
            payload = {
                'IndexName': self.index_name,
            }
            if self.action == 'Update':
                payload['ProvisionedThroughput'] = \
                    self.extra['throughput'].schema()
        return {
            self.action: payload
        }
610828
def getSerializedResponse(self):
        
        self._protoObject.next_page_token = pb.string(self._nextPageToken)
        s = protocol.toJson(self._protoObject)
        return s
1166023
private Entity<String> serialize(Object obj, String contentType) throws ClientErrorException {
        if (contentType.startsWith("application/json")) {
            try {
                return Entity.json(jsonMarshaller.serialize(obj));
            } catch (JsonMarshallingException e) {
                String msg = "Failed marshalling object to JSON data for sending to server: "+e.getMessage();
//                throw new ClientErrorException(Response.Status.BAD_REQUEST, e);
                throw new BadRequestServiceException(
                        new RestFaultInfo("BadRequest", Blame.CLIENT,
                                msg, ""+ ErrorCodes.Client.MARSHALLING_FAILED.getCode(),
                                null,
                                Retry.no(), Retry.no(),
                                Response.Status.BAD_REQUEST.getStatusCode(),
                                Response.Status.BAD_REQUEST.getReasonPhrase()
                        ), e
                );
            }
        } else {
            String msg = "Content type \"" + contentType + "\" is not supported.";
//            throw new NotSupportedException(msg);
            throw new BadRequestServiceException(
                    new RestFaultInfo("BadRequest", Blame.CLIENT,
                            msg, ""+ ErrorCodes.Client.UNSUPPORTED_TECHNOLOGY.getCode(),
                            null,
                            Retry.no(), Retry.no(),
                            Response.Status.BAD_REQUEST.getStatusCode(),
                            Response.Status.BAD_REQUEST.getReasonPhrase()
                    )
            );
        }
    }
174857
private void readObject(final java.io.ObjectInputStream s)  throws IOException, ClassNotFoundException {
        // Read in the threshold (ignored), and any hidden stuff
        s.defaultReadObject();

        // set other fields that need values
        keys = EMPTY;
        values = EMPTY;

        // Read in number of buckets
        final int capacity = s.readInt();
        if (capacity < 0) {
            throw new InvalidObjectException("Illegal capacity: " + capacity);
        }

        // Read number of mappings
        final int mappings = s.readInt();
        if (mappings < 0) {
            throw new InvalidObjectException("Illegal mappings count: " + mappings);
        }

        // allocate the bucket array;
        if (mappings > 0) {
            inflateTable(capacity);
        } else {
            threshold = capacity;
        }

        // Read the keys and values, and put the mappings in the arrays
        for (int i = 0; i < mappings; i++) {
            keys[i] = (String) s.readObject();
            try {
                final byte[] marshalledObject = (byte[]) s.readObject();
                values[i] = marshalledObject == null ? null : unmarshall(marshalledObject);
            } catch (final Exception | LinkageError error) {
                handleSerializationException(error, i, keys[i]);
                values[i] = null;
            }
        }
        size = mappings;
    }
136554
private Observable<ProposedBucketConfigContext> refreshAgainstNode(final String bucketName, final NetworkAddress hostname) {
        return Buffers.wrapColdWithAutoRelease(Observable.defer(new Func0<Observable<GetBucketConfigResponse>>() {
            @Override
            public Observable<GetBucketConfigResponse> call() {
                return cluster().send(new GetBucketConfigRequest(bucketName, hostname));
            }
        }))
        .doOnNext(new Action1<GetBucketConfigResponse>() {
            @Override
            public void call(GetBucketConfigResponse response) {
                if (!response.status().isSuccess()) {
                    if (response.content() != null && response.content().refCnt() > 0) {
                        response.content().release();
                    }
                    throw new ConfigurationException("Could not fetch config from node: " + response);
                }
            }
        })
        .map(new Func1<GetBucketConfigResponse, ProposedBucketConfigContext>() {
            @Override
            public ProposedBucketConfigContext call(GetBucketConfigResponse response) {
                String raw = response.content().toString(CharsetUtil.UTF_8).trim();
                if (response.content().refCnt() > 0) {
                    response.content().release();
                }

                raw = raw.replace("$HOST", response.hostname().address());
                return new ProposedBucketConfigContext(bucketName, raw, hostname);
            }
        })
        .doOnError(new Action1<Throwable>() {
            @Override
            public void call(Throwable ex) {
                LOGGER.debug("Could not fetch config from bucket \"" + bucketName + "\" against \""
                        + hostname + "\".", ex);
            }
        });
    }
378323
def _from_json(cls, response_raw, wrapper=None):
        

        json = response_raw.body_bytes.decode()
        obj = converter.json_to_class(dict, json)
        value = converter.deserialize(
            cls,
            cls._unwrap_response_single(obj, wrapper)
        )

        return client.BunqResponse(value, response_raw.headers)
1054330
def _SerializeRequest(self, request):
        
        # Construct status line
        parsed = urllib_parse.urlsplit(request.url)
        request_line = urllib_parse.urlunsplit(
            ('', '', parsed.path, parsed.query, ''))
        if not isinstance(request_line, six.text_type):
            request_line = request_line.decode('utf-8')
        status_line = u' '.join((
            request.http_method,
            request_line,
            u'HTTP/1.1\n'
        ))
        major, minor = request.headers.get(
            'content-type', 'application/json').split('/')
        msg = mime_nonmultipart.MIMENonMultipart(major, minor)

        # MIMENonMultipart adds its own Content-Type header.
        # Keep all of the other headers in `request.headers`.
        for key, value in request.headers.items():
            if key == 'content-type':
                continue
            msg[key] = value

        msg['Host'] = parsed.netloc
        msg.set_unixfrom(None)

        if request.body is not None:
            msg.set_payload(request.body)

        # Serialize the mime message.
        str_io = six.StringIO()
        # maxheaderlen=0 means don't line wrap headers.
        gen = generator.Generator(str_io, maxheaderlen=0)
        gen.flatten(msg, unixfrom=False)
        body = str_io.getvalue()

        return status_line + body
768068
def set_bucket_props(self, bucket, props):
        
        bucket_type = self._get_bucket_type(bucket.bucket_type)
        url = self.bucket_properties_path(bucket.name,
                                          bucket_type=bucket_type)
        headers = {'Content-Type': 'application/json'}
        content = json.dumps({'props': props})

        # Run the request...
        status, _, body = self._request('PUT', url, headers, content)

        if status == 401:
            raise SecurityError('Not authorized to set bucket properties.')
        elif status != 204:
            raise RiakError('Error setting bucket properties.')
        return True
452645
def from_any(cls, obj, bucket):
        
        if isinstance(obj, cls):
            return cls(obj.raw)

        return cls({
            'namespace_id': 'default',
            'keyspace_id': bucket,
            'name': obj if obj else N1QL_PRIMARY_INDEX,
            'using': 'gsi'
        })
522519
function serializeObject(obj) {
  var seen = [];

  return JSON.stringify(obj, function(key, val) {
    val = toJsonReplacer(key, val);
    if (isObject(val)) {

      if (seen.indexOf(val) >= 0) return '...';

      seen.push(val);
    }
    return val;
  });
}
950114
function serialize(queryParams) {
  return Object.keys(queryParams)
    .filter(key => queryParams[key] !== undefined)
    .map(key => arrayToStr(key, queryParams[key]))
    .join('&');
}
464052
function serialize(obj) {
  if (!isObject(obj)) return obj;
  var pairs = [];
  for (var key in obj) {
    if (null != obj[key]) {
      pushEncodedKeyValuePair(pairs, key, obj[key]);
        }
      }
  return pairs.join('&');
}
391023
function getValueBucket(val) {
  if (val === null) {
    return 'null';
  }
  var bucket = typeof val;
  if (bucket === 'object') {
    // Could be bytes, fixed, array, map, or record.
    if (Array.isArray(val)) {
      return 'array';
    } else if (Buffer.isBuffer(val)) {
      return 'buffer';
    }
  }
  return bucket;
}