Serialize provenance graph in the specified format
349611
def serialize(self, format):
        
        if PY3:
            return self.prov_g.serialize(format=format).decode('utf-8')
        else:
            return self.prov_g.serialize(format=format)
194941
function serialize(){
    var serialized = {
      nodes: nodes().map(function (id){
        return { id: id };
      }),
      links: []
    };

    serialized.nodes.forEach(function (node){
      var source = node.id;
      adjacent(source).forEach(function (target){
        serialized.links.push({
          source: source,
          target: target,
          weight: getEdgeWeight(source, target)
        });
      });
    });

    return serialized;
  }
325940
def serialize_to_bundle(self, transformer, path, model_name, serialize_node=True):
        

        # Define attributes
        attributes = list()
        attributes.append(('num_features', transformer.n_features_))
        if isinstance(transformer, DecisionTreeClassifier):
            attributes.append(('num_classes', int(transformer.n_classes_)))

        inputs = []
        outputs = []
        if serialize_node:
            # define node inputs and outputs
            inputs = [{
                      "name": transformer.input_features,
                      "port": "features"
                    }]

            outputs = [{
                      "name": transformer.prediction_column,
                      "port": "prediction"
                    }]

        self.serialize(transformer, path, model_name, attributes, inputs, outputs, node=serialize_node)

        # Serialize tree.json
        tree_path = "{}/{}.node/tree.json".format(path, model_name)
        if not serialize_node:
            tree_path = "{}/{}/tree.json".format(path, model_name)
        with open(tree_path, 'w') as outfile:
            self.serialize_tree(transformer, transformer.feature_names, outfile)
913873
def to_json(self, schema_info=True):
        
        genomes = set()
        result = {}
        result["edges"] = []
        for bgedge in self.edges():
            genomes |= bgedge.multicolor.colors
            result["edges"].append(bgedge.to_json(schema_info=schema_info))
        result["vertices"] = [bgvertex.to_json(schema_info=schema_info) for bgvertex in self.nodes()]
        result["genomes"] = [bggenome.to_json(schema_info=schema_info) for bggenome in genomes]
        return result
378590
def serialize_relations(pid):
    """"""
    data = {}
    relations = PIDRelation.get_child_relations(pid).all()
    for relation in relations:
        rel_cfg = resolve_relation_type_config(relation.relation_type)
        dump_relation(rel_cfg.api(relation.parent),
                      rel_cfg, pid, data)
    parent_relations = PIDRelation.get_parent_relations(pid).all()
    rel_cfgs = set([resolve_relation_type_config(p) for p in parent_relations])
    for rel_cfg in rel_cfgs:
        dump_relation(rel_cfg.api(pid), rel_cfg, pid, data)
    return data
945457
function saveGraphSON(graph, filename, callback) {
        var FileOutputStream = Tinkerpop.autoImport('FileOutputStream');
        var stream = new FileOutputStream(filename);
        return Tinkerpop.GraphSONWriter.buildP()
            .then(function (builder) {
            return _newGraphSONMapper()
                .then(function (mapper) { return builder.mapperP(mapper); });
        })
            .then(function (builder) { return builder.createP(); })
            .then(function (writer) { return writer.writeGraphP(stream, graph); })
            .then(function () { return graph; })
            .nodeify(callback);
    }
1150609
def save_graph(graphdef):
    ''''''
    if graphdef.filename is None:
        if 'HOME' in os.environ:
            dname = os.path.join(os.environ['HOME'], '.mavproxy')
            mp_util.mkdir_p(dname)
            graphdef.filename = os.path.join(dname, 'mavgraphs.xml')
        else:
            graphdef.filename = 'mavgraphs.xml'
    if graphdef.filename is None:
        mestate.console.writeln("No file to save graph to", fg='red')
        return
    graphs = load_graph_xml(open(graphdef.filename).read(), graphdef.filename, load_all=True)
    found_name = False
    for i in range(len(graphs)):
        if graphs[i].name == graphdef.name:
            graphs[i] = graphdef
            found_name = True
            break
    if not found_name:
        graphs.append(graphdef)
    mestate.console.writeln("Saving %u graphs to %s" % (len(graphs), graphdef.filename))
    f = open(graphdef.filename, "w")
    f.write("<graphs>\n\n")
    for g in graphs:
        f.write(" <graph name='%s'>\n" % g.name.strip())
        if g.description is None:
            g.description = ''
        f.write("  <description>%s</description>\n" % g.description.strip())
        for e in g.expressions:
            f.write("  <expression>%s</expression>\n" % e.strip())
        f.write(" </graph>\n\n")
    f.write("</graphs>\n")
    f.close()
92514
def to_json(self, indent=None):
        """"""

        inputs = ParameterCollection(self.inputs)

        d = {
            'meta': {
                'name': self.name,
                'description': self.description
            },
            'inputs': [],
            'workflow': [],
            'outputs': [{'name': k, 'node': v} for k, v in six.iteritems(self.output_mapping)]
        }

        for parameter in self.inputs:
            input_info = {
                'name': parameter.name,
                'type': parameter.id
            }

            args, kwargs = parameter.serialize_args()
            args = list(args)
            args.pop(0)  # 'name' is already taken care of
            kwargs.pop('required', None)  # 'required' is assumed True for workflow inputs
            if args or kwargs:
                input_info['args'] = [args, kwargs]

            d['inputs'].append(input_info)

        for node in sorted(six.itervalues(self.nodes_by_id), key=lambda x: x.id):
            task_name = node.task.name
            if not task_name:
                raise ValueError('The task {0} does not have a name and therefore cannot be serialized.'.format(
                    node.task.__class__.__name__)
                )

            node_inputs = {}
            for input_name, (source, value) in six.iteritems(node.inputs):
                input_info = {'source': source}

                if source == 'input':
                    input_info['input'] = inputs.by_name[value].name
                else:
                    input_info['node'] = value

                node_inputs[input_name] = input_info

            d['workflow'].append({
                'id': node.id,
                'task': task_name,
                'inputs': node_inputs
            })

        return json.dumps(d, indent=indent)
1162739
def rdf_source(self, format="turtle"):
        
        s = self.rdflib_graph.serialize(format=format)
        if isinstance(s, bytes):
            s = s.decode('utf-8')
        return s
114162
def dump_tf_graph(tfgraph, tfgraphdef):
    
    print("Nodes ({})".format(len(tfgraphdef.node)))
    f = "{:15} {:59} {:20} {}"
    print(f.format("kind", "scopeName", "shape", "inputs"))
    for node in tfgraphdef.node:
        scopename = node.name
        kind = node.op
        inputs = node.input
        shape = tf.graph_util.tensor_shape_from_node_def_name(tfgraph, scopename)
        print(f.format(kind, scopename, str(shape), inputs))
270946
def serialize(data, measurement=None, tag_columns=None, **extra_tags):
    """"""
    if isinstance(data, bytes):
        return data
    elif isinstance(data, str):
        return data.encode('utf-8')
    elif hasattr(data, 'to_lineprotocol'):
        return data.to_lineprotocol()
    elif pd is not None and isinstance(data, pd.DataFrame):
        return dataframe.serialize(data, measurement, tag_columns, **extra_tags)
    elif isinstance(data, dict):
        return mapping.serialize(data, measurement, **extra_tags)
    elif hasattr(data, '__iter__'):
        return b'\n'.join([serialize(i, measurement, tag_columns, **extra_tags) for i in data])
    else:
        raise ValueError('Invalid input', data)
250911
def _serialize(self, include_run_logs=False, strict_json=False):
        
        result = {'dagobah_id': self.dagobah_id,
                  'created_jobs': self.created_jobs,
                  'jobs': [job._serialize(include_run_logs=include_run_logs,
                                          strict_json=strict_json)
                           for job in self.jobs]}
        if strict_json:
            result = json.loads(json.dumps(result, cls=StrictJSONEncoder))
        return result
162367
def serialize(self):
        """"""
        res = {}
        if self.query:
            if isinstance(self.query, dict):
                res["query"] = self.query
            elif isinstance(self.query, Query):
                res["query"] = self.query.serialize()
            else:
                raise InvalidQuery("Invalid query")
        if self.filter:
            res['filter'] = self.filter.serialize()
        if self.facet.facets:
            res['facets'] = self.facet.serialize()
        if self.agg.aggs:
            res['aggs'] = self.agg.serialize()
        if self.rescore:
            res['rescore'] = self.rescore.serialize()
        if self.window_size:
            res['window_size'] = self.window_size
        if self.fields is not None: #Deal properly with self.fields = []
            res['fields'] = self.fields
        if self.size is not None:
            res['size'] = self.size
        if self.start is not None:
            res['from'] = self.start
        if self._highlight:
            res['highlight'] = self._highlight.serialize()
        if self.sort:
            if isinstance(self.sort, SortFactory):
                sort = self.sort.serialize()
                if sort:
                    res['sort'] = sort
            else:
                res['sort'] = self.sort
        if self.explain:
            res['explain'] = self.explain
        if self.version:
            res['version'] = self.version
        if self.track_scores:
            res['track_scores'] = self.track_scores
        if self._script_fields:
            if isinstance(self.script_fields, ScriptFields):
                res['script_fields'] = self.script_fields.serialize()
            elif isinstance(self.script_fields, dict):
                res['script_fields'] = self.script_fields
            else:
                raise ScriptFieldsError("Parameter script_fields should of type ScriptFields or dict")
        if self.index_boost:
            res['indices_boost'] = self.index_boost
        if self.min_score:
            res['min_score'] = self.min_score
        if self.stats:
            res['stats'] = self.stats
        if self.partial_fields:
            res['partial_fields'] = self.partial_fields
        if self._source:
            res['_source'] = self._source
        if self.timeout:
            res['timeout'] = self.timeout
        return res
1192850
def to_csv_path(graph: BELGraph, path: str, sep: Optional[str] = None) -> None:
    """"""
    with open(path, 'w') as file:
        to_csv(graph, file, sep=sep)
1084813
def generatemetadata(self, parameters, parentfile, relevantinputfiles, provenancedata = None):
        """"""
        assert isinstance(provenancedata,CLAMProvenanceData) or provenancedata is None

        data = {}

        if self.copymetadata:
            #Copy parent metadata
            for key, value in parentfile.metadata.items():
                data[key] = value

        for metafield in self.metafields:
            if isinstance(metafield, ParameterCondition):
                metafield = metafield.evaluate(parameters)
                if not metafield:
                    continue
            assert isinstance(metafield, AbstractMetaField)
            metafield.resolve(data, parameters, parentfile, relevantinputfiles)

        if provenancedata:
            data['provenance'] = provenancedata

        return self.formatclass(None, **data)
322531
def nodes_dump(self):
        """"""
        self._flush_nodes()
        for (graph, node, branch, turn,tick, extant) in self.sql('nodes_dump'):
            yield (
                self.unpack(graph),
                self.unpack(node),
                branch,
                turn,
                tick,
                bool(extant)
            )
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)