Generate JSON Schema representation of a biolink model
540917
def cli(yamlfile, inline, format):
    
    print(JsonSchemaGenerator(yamlfile, format).serialize(inline=inline))
1146898
def to_dict(self):
        

        # 1. extract the schema fields
        data = self.extract_fields()

        # 2. include custom key-value pairs listed in the mapping dictionary
        for key, attr in self.attributes.iteritems():
            if key in self.ignore:
                continue  # skip ignores
            # fetch the mapped attribute
            value = getattr(self.context, attr, None)
            if value is None:
                value = getattr(self, attr, None)
            # handle function calls
            if callable(value):
                value = value()
            # map the value to the given key from the mapping
            data[key] = api.to_json_value(self.context, key, value)
        return data
918851
def schema_handler(self, schema):
        '''
        
        '''
        dict_for_render = schema.get('properties', dict()).items()
        if schema.get('$ref', None):
            def_name = schema.get('$ref').split('/')[-1]
            dict_for_render = self.definitions[def_name].get('properties', dict()).items()
        elif schema.get('properties', None) is None:
            return ''

        answer_dict = dict()
        json_dict = dict()
        for opt_name, opt_value in dict_for_render:
            var_type = opt_value.get('format', None) or opt_value.get('type', None) or 'object'
            json_name = self.indent + ':jsonparameter {} {}:'.format(var_type, opt_name)
            json_dict[json_name] = self.get_json_props_for_response(var_type, opt_value)

            answer_dict[opt_name] = self.get_response_example(opt_name, var_type, opt_value)
            if var_type == 'string':
                answer_dict[opt_name] = answer_dict[opt_name].format(opt_name)

        self.write('')
        for line in json.dumps(answer_dict, indent=4).split('\n'):
            self.write(line, self.indent_depth)

        self.write('')
        for json_param_name, json_param_value in json_dict.items():
            desc = '{}{}'.format(
                json_param_value['title'], json_param_value['props_str']
            ) or 'None'
            self.write(json_param_name + ' ' + desc)
275570
def schema_digest(self) -> str:
        
        res = self.schema._node_digest()
        res["config"] = True
        return json.dumps(res)
500323
def to_json(self):
        """"""
        return {
            'network': self.network,
            'state': self.state,
            'nodes': self.node_indices,
            'cut': self.cut,
        }
825612
function generateModelOpenApiSchema(schema, definitionName) {
    var oaSchema = {
      required: [],
      properties: {}
    };
    mergePaths(oaSchema, schema.paths, definitionName);
    mergePaths(oaSchema, schema.virtuals, definitionName);

    //remove empty arrays -> OpenAPI 3.0 validates 
    if (oaSchema.required.length === 0) {
      delete(oaSchema.required);
    }
    if (oaSchema.properties.length === 0) {
      delete(oaSchema.properties);
    }
    return oaSchema;
  }
57763
function toJSON() {
    var s = this;
    var values = Object.assign({}, s.schema);
    Object.keys(values).forEach(function (key) {
      var isFunc = iftype.isFunction(values[key]);

      if (isFunc) {
        delete values[key];
      }
    });
    return values;
  }
971237
def _build_schema(self, s):
        
        w = self._whatis(s)
        if w == self.IS_LIST:
            w0 = self._whatis(s[0])
            js = {"type": "array",
                  "items": {"type": self._jstype(w0, s[0])}}
        elif w == self.IS_DICT:
            js = {"type": "object",
                  "properties": {key: self._build_schema(val) for key, val in s.items()}}
            req = [key for key, val in s.items() if not val.is_optional]
            if req:
                js["required"] = req
        else:
            js = {"type": self._jstype(w, s)}
        for k, v in self._json_schema_keys.items():
            if k not in js:
                js[k] = v
        return js
814665
def layout_json_schema(self):
        """"""
        if self._layout_json_schema is None and self.layout_json_schema_file is not None:
            if os.path.isfile(self.layout_json_schema_file):
                with open(self.layout_json_schema_file) as fh:
                    self._layout_json_schema = json.load(fh)
        return self._layout_json_schema
1125009
function buildJsonSchema(comments) {

    // skeleton schema object
    var schema = {
        properties: {
        }
    };

    // go through each comment block
    (comments || []).forEach(function(block) {

        // we're only interested in customTags (none standard jsDoc comments i.e. @schema.)
        (block.customTags || []).forEach(function(item) {

            var tag = item.tag.replace('schema.', '');
            var value = item.value || '';

            // skip properties with no value
            if (value === '') return;

            if (block.scope === 'global') {
                schema[tag] = value;
            }
            else {

                // item is a property
                schema.properties[block.name] = schema.properties[block.name] || {};

                // jsdoc-parse lowercase tag names, so we need more case blocks to correct this
                switch (tag) {

                    /* integers */

                    case 'minimum':
                    case 'maximum': {
                        schema.properties[block.name][tag] = parseInt(value, 10);
                    } break;

                    case 'minitems': {
                        schema.properties[block.name].minItems = parseInt(value, 10);
                    } break;

                    case 'maxitems': {
                        schema.properties[block.name].maxItems = parseInt(value, 10);
                    } break;

                    case 'minlength': {
                        schema.properties[block.name].minLength = parseInt(value, 10);
                    } break;

                    case 'maxlength': {
                        schema.properties[block.name].maxLength = parseInt(value, 10);
                    } break;

                    case 'exclusiveminimum': {
                        schema.properties[block.name].exclusiveMinimum = parseInt(value, 10);
                    } break;

                    case 'exclusivemaximum': {
                        schema.properties[block.name].exclusiveMaximum = parseInt(value, 10);
                    } break;

                    case 'divisibleby': {
                        schema.properties[block.name].divisibleBy = parseInt(value, 10);
                    } break;

                    /* boolean's */

                    case 'required': {
                        schema.properties[block.name][tag] = (value === 'true');
                    } break;

                    case 'uniqueitems': {
                        schema.properties[block.name].uniqueItems = (value === 'true');
                    } break;

                    /* strings */

                    case 'extends':
                    case 'id':
                    case 'type':
                    case 'pattern':
                    case 'title':
                    case 'format':
                    case 'disallow':
                    case 'extends':
                    case 'enum':
                    case 'description':
                    case 'name':
                    case 'default':
                    default: {
                        schema.properties[block.name][tag] = value;
                    } break;
                }
            }

        });
    });

    return schema;
}
562432
function generateSchemaRaw(modelParam, opts = {}) {
  validate.notNil(modelParam, "modelParam is mandatory");

  let models;
  if (_.isArray(modelParam)) {
    models = modelParam;
  } else if (_.isObject(modelParam)) {
    models = [modelParam];
  } else {
    throw new Error("modelParam should be an object or an array of objects");
  }

  return models.map(model => {
    const processedSchema = modelTransformer.transformJsonSchemaFromModel(
      model,
      opts
    );

    return {
      name: model.name,
      schema: processedSchema
    };
  });
}
695300
def cells_from_defaults(clz, jsonobj):
        
        # convert strings to dicts
        if isinstance(jsonobj, (str, unicode)):
            jsonobj = json.loads(jsonobj)
        
        assert 'cells' in jsonobj, "No cells in object"
       
        domain = TaxonomyCell.get_domain()
        cells = []
        for num, cell_dna in enumerate(jsonobj['cells']):
            assert 'kind' in cell_dna, "No type definition"
            classgenerator = domain.node[cell_dna['kind']]['class']
            cell = classgenerator()
            cell['num'].merge(num)
            for attr, val in cell_dna.items():
                if not attr in ['kind']:
                    cell[attr].merge(val)
                    cells.append(cell)
        return cells
231757
def to_dict(self):
        """"""
        return {'schema': self.schema, 'name': self.name, 'columns': [col.to_dict() for col in self._columns],
                'foreign_keys': self.foreign_keys.to_dict(), 'ref_keys': self.ref_keys.to_dict()}
587865
def generate_bio_assembly(data_api, struct_inflator):
    """"""
    bioassembly_count = 0
    for bioassembly in data_api.bio_assembly:
        bioassembly_count += 1
        for transform in bioassembly["transformList"]:
            struct_inflator.set_bio_assembly_trans(bioassembly_count,
                                                   transform["chainIndexList"],
                                                   transform["matrix"])
1298432
def generate_schema(table, export_fields, output_format, output_fobj):
    

    if output_format in ("csv", "txt"):
        from rows import plugins

        data = [
            {
                "field_name": fieldname,
                "field_type": fieldtype.__name__.replace("Field", "").lower(),
            }
            for fieldname, fieldtype in table.fields.items()
            if fieldname in export_fields
        ]
        table = plugins.dicts.import_from_dicts(
            data, import_fields=["field_name", "field_type"]
        )
        if output_format == "txt":
            plugins.txt.export_to_txt(table, output_fobj)
        elif output_format == "csv":
            plugins.csv.export_to_csv(table, output_fobj)

    elif output_format == "sql":
        # TODO: may use dict from rows.plugins.sqlite or postgresql
        sql_fields = {
            rows.fields.BinaryField: "BLOB",
            rows.fields.BoolField: "BOOL",
            rows.fields.IntegerField: "INT",
            rows.fields.FloatField: "FLOAT",
            rows.fields.PercentField: "FLOAT",
            rows.fields.DateField: "DATE",
            rows.fields.DatetimeField: "DATETIME",
            rows.fields.TextField: "TEXT",
            rows.fields.DecimalField: "FLOAT",
            rows.fields.EmailField: "TEXT",
            rows.fields.JSONField: "TEXT",
        }
        fields = [
            "    {} {}".format(field_name, sql_fields[field_type])
            for field_name, field_type in table.fields.items()
            if field_name in export_fields
        ]
        sql = (
            dedent(
                """
                CREATE TABLE IF NOT EXISTS {name} (
                {fields}
                );
                """
            )
            .strip()
            .format(name=table.name, fields=",\n".join(fields))
            + "\n"
        )
        output_fobj.write(sql)

    elif output_format == "django":
        django_fields = {
            rows.fields.BinaryField: "BinaryField",
            rows.fields.BoolField: "BooleanField",
            rows.fields.IntegerField: "IntegerField",
            rows.fields.FloatField: "FloatField",
            rows.fields.PercentField: "DecimalField",
            rows.fields.DateField: "DateField",
            rows.fields.DatetimeField: "DateTimeField",
            rows.fields.TextField: "TextField",
            rows.fields.DecimalField: "DecimalField",
            rows.fields.EmailField: "EmailField",
            rows.fields.JSONField: "JSONField",
        }
        table_name = "".join(word.capitalize() for word in table.name.split("_"))

        lines = ["from django.db import models"]
        if rows.fields.JSONField in [
            table.fields[field_name] for field_name in export_fields
        ]:
            lines.append("from django.contrib.postgres.fields import JSONField")
        lines.append("")

        lines.append("class {}(models.Model):".format(table_name))
        for field_name, field_type in table.fields.items():
            if field_name not in export_fields:
                continue

            if field_type is not rows.fields.JSONField:
                django_type = "models.{}()".format(django_fields[field_type])
            else:
                django_type = "JSONField()"
            lines.append("    {} = {}".format(field_name, django_type))

        result = "\n".join(lines) + "\n"
        output_fobj.write(result)
324054
def to_json(self):
        
        capsule = {}
        capsule["Hierarchy"] = []
        for (
            dying,
            (persistence, surviving, saddle),
        ) in self.merge_sequence.items():
            capsule["Hierarchy"].append(
                {
                    "Dying": dying,
                    "Persistence": persistence,
                    "Surviving": surviving,
                    "Saddle": saddle,
                }
            )
        capsule["Partitions"] = []
        base = np.array([None, None] * len(self.Y)).reshape(-1, 2)
        for (min_index, max_index), items in self.base_partitions.items():
            base[items, :] = [min_index, max_index]
        capsule["Partitions"] = base.tolist()

        return json.dumps(capsule)
692747
def schema_map(schema):
    """"""
    mapper = {}
    for name in getFieldNames(schema):
        mapper[name] = name
    return mapper