Serializes leases.
339314
void saveFilesUnderConstruction(SaveNamespaceContext ctx, DataOutputStream out) throws IOException {
    synchronized (leaseManager) {
      int pathsToSave = 0;
      Iterator<Lease> itrl = leaseManager.getSortedLeases().iterator();
      while (itrl.hasNext()) {
        Lease lease = itrl.next();
        for (String path : lease.getPaths()) {
          // verify that path exists in namespace
          INode node = dir.getFileINode(path);
          if (node != null && node.isUnderConstruction()) {
            pathsToSave++;
          } else if (node == null) {
            // ignore the path and continue.
            String msg = "saveLeases - counting - found path " + path
                + " but no matching entry in namespace.";
            LOG.warn(msg);
            continue;
          } else {
            throw new IOException("saveLeases found path " + path
                + " but is not under construction.");
          }
        }
      }
      
      if (pathsToSave != leaseManager.countPath()) {
        LOG.warn("Number of leases mismatch: " + pathsToSave
            + " are valid, lease manager indicated: "
            + leaseManager.countPath());
      }
      
      out.writeInt(pathsToSave); // write the size
      int pathsSaved = 0;

      LightWeightLinkedSet<Lease> sortedLeases = leaseManager.getSortedLeases();
      Iterator<Lease> itr = sortedLeases.iterator();
      while (itr.hasNext()) {
        ctx.checkCancelled();
        Lease lease = itr.next();
        for (String path : lease.getPaths()) {
          // verify that path exists in namespace
          INode node = dir.getFileINode(path);
          if (node == null) {
            // ignore the path and continue.
            String msg = "saveLeases found path " + path + " but no matching entry in namespace.";
            LOG.warn(msg);
            continue;
          }
          if (!node.isUnderConstruction()) {
            throw new IOException("saveLeases found path " + path +
              " but is not under construction.");
          }
          INodeFileUnderConstruction cons = (INodeFileUnderConstruction) node;
          FSImageSerialization.writeINodeUnderConstruction(out, cons, path);
          pathsSaved++;
        }
      }
      if (pathsSaved != pathsToSave) {
        String msg = "Saved paths: " + pathsSaved
            + " is not equal to what we thought we would save: " + pathsToSave;
        LOG.error(msg);
        throw new IOException(msg);
      }
    }
  }
1063088
def serialize_properties(properties):
    
    new_properties = properties.copy()
    for attr_name, attr_value in new_properties.items():
        if isinstance(attr_value, datetime):
            new_properties[attr_name] = attr_value.isoformat()
        elif not isinstance(attr_value, (dict, list, tuple, str, int, float, bool, type(None))):
            # Property is not JSON-serializable according to this table
            # https://docs.python.org/3.4/library/json.html#json.JSONEncoder
            # so we convert to string
            new_properties[attr_name] = str(attr_value)
    return new_properties
1199694
def SerializeExclusiveData(self, writer):
        
        writer.WriteByte(self.AssetType)
        writer.WriteVarString(self.Name)
        writer.WriteFixed8(self.Amount)
        writer.WriteByte(self.Precision)

        self.Owner.Serialize(writer)

        writer.WriteUInt160(self.Admin)
1248993
def Serialize(self, writer):
        
        super(AssetState, self).Serialize(writer)
        writer.WriteUInt256(self.AssetId)
        writer.WriteByte(self.AssetType)
        writer.WriteVarString(self.Name)

        if self.Amount.value > -1:
            writer.WriteFixed8(self.Amount, unsigned=True)
        else:
            writer.WriteFixed8(self.Amount)

        if type(self.Available) is not Fixed8:
            raise Exception("AVAILABLE IS NOT FIXED 8!")
        writer.WriteFixed8(self.Available, unsigned=True)
        writer.WriteByte(self.Precision)
        writer.WriteByte(b'\x00')
        writer.WriteFixed8(self.Fee)
        writer.WriteUInt160(self.FeeAddress)
        self.Owner.Serialize(writer)
        writer.WriteUInt160(self.Admin)
        writer.WriteUInt160(self.Issuer)
        writer.WriteUInt32(self.Expiration)
        writer.WriteBool(self.IsFrozen)
1163973
def _serialize(self):
        
        result = { a: getattr(self, a) for a in type(self).properties
            if type(self).properties[a].mutable }

        for k, v in result.items():
            if isinstance(v, Base):
                result[k] = v.id

        return result
686736
def serialize(self):
        '''
        
        '''
        serialized = {'type': self.__type__}
        for argname in self._attributes:
            if argname == 'required':
                # This is handled elsewhere
                continue
            argvalue = self._get_argname_value(argname)
            if argvalue is not None:
                if argvalue is Null:
                    argvalue = None
                # None values are not meant to be included in the
                # serialization, since this is not None...
                if self.__serialize_attr_aliases__ and argname in self.__serialize_attr_aliases__:
                    argname = self.__serialize_attr_aliases__[argname]
                serialized[argname] = argvalue
        return serialized
781123
def Serialize(self, writer):
        
        super(AccountState, self).Serialize(writer)
        writer.WriteUInt160(self.ScriptHash)
        writer.WriteBool(self.IsFrozen)
        writer.WriteVarInt(len(self.Votes))
        for vote in self.Votes:
            writer.WriteBytes(vote)

        blen = len(self.Balances)
        writer.WriteVarInt(blen)

        for key, fixed8 in self.Balances.items():
            writer.WriteUInt256(key)
            writer.WriteFixed8(fixed8)
178798
function(results) {

            function serializeToXML(results){
                var xml = "<" + results.type + " name=\"" + xmlEscape(results.name) + "\"";

                if (typeof(results.duration)=="number"){
                    xml += " duration=\"" + results.duration + "\"";
                }

                if (results.type == "test"){
                    xml += " result=\"" + results.result + "\" message=\"" + xmlEscape(results.message) + "\">";
                } else {
                    xml += " passed=\"" + results.passed + "\" failed=\"" + results.failed + "\" ignored=\"" + results.ignored + "\" total=\"" + results.total + "\">";
                    for (var prop in results){
                        if (results.hasOwnProperty(prop)){
                            if (results[prop] && typeof results[prop] == "object" && !(results[prop] instanceof Array)){
                                xml += serializeToXML(results[prop]);
                            }
                        }
                    }
                }

                xml += "</" + results.type + ">";

                return xml;
            }

            return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + serializeToXML(results);

        }
682914
def LeaseClientActionRequests(self,
                                client_id,
                                lease_time=None,
                                limit=sys.maxsize):
    """"""

    leased_requests = []

    now = rdfvalue.RDFDatetime.Now()
    expiration_time = now + lease_time
    process_id_str = utils.ProcessIdString()

    leases = self.client_action_request_leases
    # Can't use an iterator here since the dict might change when requests get
    # deleted.
    for key, request in sorted(self.client_action_requests.items()):
      if key[0] != client_id:
        continue

      existing_lease = leases.get(key)
      if not existing_lease or existing_lease[0] < now:
        if existing_lease:
          lease_count = existing_lease[-1] + 1
          if lease_count > db.Database.CLIENT_MESSAGES_TTL:
            self._DeleteClientActionRequest(*key)
            continue
        else:
          lease_count = 1

        leases[key] = (expiration_time, process_id_str, lease_count)
        request.leased_until = expiration_time
        request.leased_by = process_id_str
        request.ttl = db.Database.CLIENT_MESSAGES_TTL - lease_count
        leased_requests.append(request)
        if len(leased_requests) >= limit:
          break

    return leased_requests
1054144
public function serializeProperties()
    {
        $shift = 15;
        $flagBits = 0;
        $flags = array();
        $rawBytes = new Writer();

        foreach ($this->propertyTypes as $key => $proptype) {
            if (isset($this->properties[$key])) {
                $value = $this->properties[$key];
            } else {
                $value = null;
            }

            if ($value != null) {
                if ($shift == 0) {
                    $flags[] = $flagBits;
                    $flagBits = 0;
                    $shift = 15;
                }

                $flagBits |= (1 << $shift);
                if ($proptype != 'bit') {
                    $proptype = ucfirst($proptype);
                    $rawBytes->{'write' . $proptype}($value);
                }

            }
            $shift -= 1;
        }

        $flags[] = $flagBits;
        $result = new Writer();
        foreach ($flags as $flagBits) {
            $result->writeShort($flagBits);
        }

        $result->write($rawBytes->getvalue());

        return $result->getvalue();
    }
1128936
def serialize(self):
        """"""

        data = {self._internal_name: self.query.serialize()}
        if self.query_weight is not None:
            data['query_weight'] = self.query_weight
        if self.rescore_query_weight is not None:
            data['rescore_query_weight'] = self.rescore_query_weight

        return data
1077079
def dump(cls, filename, objects, properties, bools, encoding):
        """"""
        if encoding is None:
            encoding = cls.encoding

        source = cls.dumps(objects, properties, bools)
        if PY2:
            source = unicode(source)

        with io.open(filename, 'w', encoding=encoding) as fd:
            fd.write(source)
1226274
def serialize(self):
        """"""
        data = {'doc': self.doc}
        if isinstance(self.query, Query):
            data['query'] = self.query.serialize()
        return data
1202865
private function serializePortableProperties($properties, $ns = '', $nsUri = '', $name = null, $element = null){
        $document = null;
        $result = '';

        if ($element === null) {
            $document = new \DomDocument();
            $element = $ns ?
                $document->createElementNS($nsUri, $ns . ':properties') :
                $document->createElement('properties');

            $document->appendChild($element);
        } else {
            $newElement = $ns ?
                $element->ownerDocument->createElementNS($nsUri, $ns . ':properties') :
                $element->ownerDocument->createElement('properties');

            $element->appendChild($newElement);
            $element = $newElement;
        }

        if ($name !== null) {
            $element->setAttribute('key', $name);
        }

        foreach ($properties as $name => $value) {
            if(is_array($value)){
                $this->serializePortableProperties($value, $ns, $nsUri, $name, $element);
            } else {
                $entryElement = $ns ?
                    $element->ownerDocument->createElementNS($nsUri, $ns . ':property') :
                    $element->ownerDocument->createElement('property');

                $entryElement->setAttribute('key', $name);
                $entryElement->appendChild(new \DOMText($value));
                $element->appendChild($entryElement);
            }
        }

        if ($document !== null) {
            foreach ($document->childNodes as $node) {
                $result .= $document->saveXML($node);
            }
        }

        return $result;
    }
1164051
def _serialize_attributes(attributes):
    """"""
    result = ''
    for name, value in attributes.items():
        if not value:
            continue
        result += ' ' + _unmangle_attribute_name(name)
        result += '="' + escape(value, True) + '"'
    return result
174007
def get(self, include_backups=False):
        
        leases = []
        with open(self.filename) if not self.gzip else gzip.open(self.filename) as lease_file:
            lease_data = lease_file.read()
            if self.gzip:
                lease_data = lease_data.decode('utf-8')
            for match in self.regex_leaseblock.finditer(lease_data):
                block = match.groupdict()

                properties, options, sets = _extract_properties(block['config'])

                if 'hardware' not in properties and not include_backups:
                    # E.g. rows like {'binding': 'state abandoned', ...}
                    continue
                lease = Lease(block['ip'], properties=properties, options=options, sets=sets)
                leases.append(lease)

            for match in self.regex_leaseblock6.finditer(lease_data):
                block = match.groupdict()
                properties, options, sets = _extract_properties(block['config'])

                host_identifier = block['id']
                block_type = block['type']
                last_client_communication = parse_time(properties['cltt'])

                for address_block in self.regex_iaaddr.finditer(block['config']):
                    block = address_block.groupdict()
                    properties, options, sets = _extract_properties(block['config'])

                    lease = Lease6(block['ip'], properties, last_client_communication, host_identifier, block_type,
                                   options=options, sets=sets)
                    leases.append(lease)

        return leases
1300373
public void serialize(@Nonnull Iterable<QueryResult> results, @Nonnull OutputStream out) throws IOException {
		JsonGenerator g = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
		g.writeStartObject();
		g.writeNumberField("timestamp", System.currentTimeMillis() / 1000);
		g.writeNumberField("proto_version", STACKDRIVER_PROTOCOL_VERSION);
		g.writeArrayFieldStart("data");

		for (QueryResult metric : results) {
			g.writeStartObject();
			g.writeStringField("name", metric.getName());
			if (instanceId != null && !instanceId.isEmpty()) {
				g.writeStringField("instance", instanceId);
			}
			g.writeNumberField("collected_at", metric.getEpoch(TimeUnit.SECONDS));
			if (metric.getValue() instanceof Integer) {
				g.writeNumberField("value", (Integer) metric.getValue());
			} else if (metric.getValue() instanceof Long) {
				g.writeNumberField("value", (Long) metric.getValue());
			} else if (metric.getValue() instanceof Float) {
				g.writeNumberField("value", (Float) metric.getValue());
			} else if (metric.getValue() instanceof Double) {
				g.writeNumberField("value", (Double) metric.getValue());
			}
			g.writeEndObject();
		}

		g.writeEndArray();
		g.writeEndObject();
		g.flush();
		g.close();
	}