Write out models (base + metalearner)
500600
@Override protected AutoBuffer writeAll_impl(AutoBuffer ab) {
    //Metalearner
    ab.putKey(_output._metalearner._key);
    //Base Models
    for (Key<Model> ks : _parms._base_models)
        ab.putKey(ks);
    return super.writeAll_impl(ab);
  }
80497
def _write_model_stats(self, iteration:int)->None:
        ""
        self.stats_writer.write(model=self.learn.model, iteration=iteration, tbwriter=self.tbwriter)
408140
def build_model_classes(metadata):
    """"""
    i = importlib.import_module(metadata)
    env = get_jinja_env()
    model_template = env.get_template('model.py.jinja2')
    for model in i.models:
        with open(model_path(model.name.lower()), 'w') as t:
            t.write(model_template.render(model_md=model))
141331
def _write_model(self, specification, specification_set):
        
        filename = "%s%s.py" % (self._class_prefix.lower(), specification.entity_name.lower())

        override_content = self._extract_override_content(specification.entity_name)
        constants = self._extract_constants(specification)
        superclass_name = "NURESTRootObject" if specification.rest_name == self.api_root else "NURESTObject"

        self.write(destination=self.output_directory, filename=filename, template_name="model.py.tpl",
                   specification=specification,
                   specification_set=specification_set,
                   version=self.api_version,
                   class_prefix=self._class_prefix,
                   product_accronym=self._product_accronym,
                   override_content=override_content,
                   superclass_name=superclass_name,
                   constants=constants,
                   header=self.header_content)

        self.model_filenames[filename] = specification.entity_name
931586
def add_model(self, model_type: str, model_uuid: str, meta: dict,
                  template_model: Template, update_default: bool=False):
        """"""
        if update_default or model_type not in self.meta:
            self.meta[model_type] = meta["default"]
        model_meta = meta["model"]
        self.models.setdefault(model_type, {})[model_uuid] = model_meta
        model_directory = os.path.join(self.cached_repo, model_type)
        os.makedirs(model_directory, exist_ok=True)
        model = os.path.join(model_directory, model_uuid + ".md")
        if os.path.exists(model):
            os.remove(model)
        links = {}
        for m_type, items in self.models.items():
            for uuid in items:
                if uuid in model_meta["dependencies"]:
                    links[uuid] = os.path.join("/", m_type, "%s.md" % uuid)
        with open(model, "w") as fout:
            fout.write(template_model.render(model_type=model_type, model_uuid=model_uuid,
                                             meta=model_meta, links=links))
        git.add(self.cached_repo, [model])
        self._log.info("Added %s", model)
56603
def pretty_print_model(devicemodel):
    """"""
    PRETTY_PRINT_MODEL = """Device Model ID: %(deviceModelId)s
        Project ID: %(projectId)s
        Device Type: %(deviceType)s"""
    logging.info(PRETTY_PRINT_MODEL % devicemodel)
    if 'traits' in devicemodel:
        for trait in devicemodel['traits']:
            logging.info('        Trait %s' % trait)
    else:
        logging.info('No traits')
    logging.info('')
463976
void writeInterfaces(final XMLExtendedStreamWriter writer, final ModelNode modelNode) throws XMLStreamException {
        writer.writeStartElement(Element.INTERFACES.getLocalName());
        final Set<String> interfaces = modelNode.keys();
        for (String ifaceName : interfaces) {
            final ModelNode iface = modelNode.get(ifaceName);
            writer.writeStartElement(Element.INTERFACE.getLocalName());
            writeAttribute(writer, Attribute.NAME, ifaceName);
            // <any-* /> is just handled at the root
            if (iface.get(Element.ANY_ADDRESS.getLocalName()).asBoolean(false)) {
                writer.writeEmptyElement(Element.ANY_ADDRESS.getLocalName());
            } else {
                // Write the other criteria elements
                writeInterfaceCriteria(writer, iface, false);
            }
            writer.writeEndElement();
        }
        writer.writeEndElement();
    }
570435
def base_concrete_modeladmin(self):
        
        candidates = [self.__class__]
        while candidates:
            candidate = candidates.pop()
            if ContentTypedAdmin in candidate.__bases__:
                return candidate
            candidates.extend(candidate.__bases__)

        raise Exception("Can't find base concrete ModelAdmin class.")
1148745
def main(model=None, output_dir=None, n_iter=100):
    """"""
    if model is not None:
        nlp = spacy.load(model)  # load existing spaCy model
        print("Loaded model '%s'" % model)
    else:
        nlp = spacy.blank("en")  # create blank Language class
        print("Created blank 'en' model")

    # create the built-in pipeline components and add them to the pipeline
    # nlp.create_pipe works for built-ins that are registered with spaCy
    if "ner" not in nlp.pipe_names:
        ner = nlp.create_pipe("ner")
        nlp.add_pipe(ner, last=True)
    # otherwise, get it so we can add labels
    else:
        ner = nlp.get_pipe("ner")

    # add labels
    for _, annotations in TRAIN_DATA:
        for ent in annotations.get("entities"):
            ner.add_label(ent[2])

    # get names of other pipes to disable them during training
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"]
    with nlp.disable_pipes(*other_pipes):  # only train NER
        # reset and initialize the weights randomly – but only if we're
        # training a new model
        if model is None:
            nlp.begin_training()
        for itn in range(n_iter):
            random.shuffle(TRAIN_DATA)
            losses = {}
            # batch up the examples using spaCy's minibatch
            batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))
            for batch in batches:
                texts, annotations = zip(*batch)
                nlp.update(
                    texts,  # batch of texts
                    annotations,  # batch of annotations
                    drop=0.5,  # dropout - make it harder to memorise data
                    losses=losses,
                )
            print("Losses", losses)

    # test the trained model
    for text, _ in TRAIN_DATA:
        doc = nlp(text)
        print("Entities", [(ent.text, ent.label_) for ent in doc.ents])
        print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc])

    # save model to output directory
    if output_dir is not None:
        output_dir = Path(output_dir)
        if not output_dir.exists():
            output_dir.mkdir()
        nlp.to_disk(output_dir)
        print("Saved model to", output_dir)

        # test the saved model
        print("Loading from", output_dir)
        nlp2 = spacy.load(output_dir)
        for text, _ in TRAIN_DATA:
            doc = nlp2(text)
            print("Entities", [(ent.text, ent.label_) for ent in doc.ents])
            print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc])
524141
def _check_model_types(self, models):
        
        if not hasattr(models, "__iter__"):
            models = {models}
        if not all([isinstance(model, (AbstractStateModel, StateElementModel)) for model in models]):
            raise TypeError("The selection supports only models with base class AbstractStateModel or "
                            "StateElementModel, see handed elements {0}".format(models))
        return models if isinstance(models, set) else set(models)
201058
def generate_models(args):
  """"""
  data_table = get_data_table(args.filename)
  tables = to_tables(data_table.rows_to_dicts())
  attr_indent = "\n" + args.indent * 2
  attr_sep = "," + attr_indent

  for tname, cols in tables.items():
    model_name = table_to_model_name(tname, list(cols.values())[0]["table_schema"])
    pk_cols, oth_cols = split_pks(cols)
    timestamps = get_timestamps(cols, args.created_at_col_name, args.updated_at_col_name)
    is_auto = len(pk_cols) == 1 and cols[pk_cols[0]]["is_auto"] == "t"

    attrs = OrderedDict()
    for cname in oth_cols:
      if cname not in timestamps:
        attrs[cname] = None

    print(_MODEL_SOURCE.format(
      class_name=model_name,
      base_class_name="ModelBase",
      indent=args.indent,
      table_name=repr(tname),
      pk_name=repr(pk_cols[0] if len(pk_cols) == 1 else pk_cols),
      pk_is_auto=is_auto,
      timestamps=timestamps,
      attrs="dict(" + attr_indent + attr_sep.join("{0}={1}".format(k, v) for k, v in attrs.items()) + ")"))
    print()
1319023
function ProcessBase(model) {
    if (!model)
      throw new Error('Must provide a model');
    tr.model.EventContainer.call(this);
    this.model = model;
    this.threads = {};
    this.counters = {};
    this.objects = new tr.model.ObjectCollection(this);
    this.sortIndex = 0;
  }
595797
def _cmp_models(self, m1, m2):
        """"""

        # Don't alter m1/m2 by mistake
        m1 = copy.deepcopy(m1)
        m2 = copy.deepcopy(m2)

        # Remove keys added by bravado-core
        def _cleanup(d):
            """Remove all keys in the blacklist"""
            for k in ('x-model', 'x-persist', 'x-scope'):
                if k in d:
                    del d[k]
            for v in list(d.values()):
                if isinstance(v, dict):
                    _cleanup(v)

        _cleanup(m1)
        _cleanup(m2)

        # log.debug("model1:\n" + pprint.pformat(m1))
        # log.debug("model2:\n" + pprint.pformat(m2))
        return not m1 == m2
800977
def write(models, out=None, base=None, logger=logging):
    '''
    
    '''
    assert out is not None #Output stream required
    if not isinstance(models, list): models = [models]
    for m in models:
        for link in m.match():
            s, p, o = link[:3]
            #Skip docheader statements
            if s == (base or '') + '@docheader': continue
            if p in RESOURCE_MAPPING: p = RESOURCE_MAPPING[p]
            if o in RESOURCE_MAPPING: o = RESOURCE_MAPPING[o]
            
            if p == VERSA_TYPE_REL: p = RDF_TYPE_REL
            print(strconv(s), strconv(p), strconv(o), '.', file=out)
    return
648094
def write(filename, mesh, fmt_version, write_binary=True):
    
    try:
        writer = _writers[fmt_version]
    except KeyError:
        try:
            writer = _writers[fmt_version.split(".")[0]]
        except KeyError:
            raise ValueError(
                "Need mesh format in {} (got {})".format(
                    sorted(_writers.keys()), fmt_version
                )
            )

    writer.write(filename, mesh, write_binary=write_binary)
580465
def create_manager(self, base_manager=models.Manager):
        

        _builder = self

        class CustomManager(base_manager):
            def search(self, search_data, custom_args={}):
                """
                Search inside the custom fields for this model for any match
                 of search_data and returns existing model instances

                :param search_data:
                :param custom_args:
                :return:
                """
                query = None
                lookups = (
                    '%s__%s' % ('value_text', 'icontains'),
                )
                content_type = ContentType.objects.get_for_model(self.model)
                custom_args = dict({ 'content_type': content_type, 'searchable': True }, **custom_args)
                custom_fields = dict((f.name, f) for f in _builder.fields_model_class.objects.filter(**custom_args))
                for value_lookup in lookups:
                    for key, f in custom_fields.items():
                        found = _builder.values_model_class.objects.filter(**{ 'custom_field': f,
                                                                               'content_type': content_type,
                                                                               value_lookup: search_data })
                        if found.count() > 0:
                            if query is None:
                                query = Q()
                            query = query & Q(**{ str('%s__in' % self.model._meta.pk.name):
                                                  [obj.object_id for obj in found] })
                if query is None:
                    return self.get_queryset().none()
                return self.get_queryset().filter(query)

        return CustomManager
600560
def generate
      Dir["app/models/*.rb"].each do |path|
        result = File.basename(path).scan(/^(.+)\.rb/)[0][0]
        model = eval(ActiveSupport::Inflector.camelize(result))
        next if model.respond_to?(:abstract_class) && model.abstract_class
        next unless model < ActiveRecord::Base
        @annotations[model] = generate_annotation(model) unless @annotations.keys.include?(model)
      end
    end