A helper to export a model and all its classes in a npm module.
774769
function modelExport(m) {
  const result = _.mapValues(m.classes, _.head)
  result[m.__name] = m
  return result
}
807413
function bundleApp(codeList, ns, domload, compile, before, npmTree, o) {
  var l = []
    , usedBuiltIns = npmTree._builtIns
    , len = 0;
  delete npmTree._builtIns;

  // 1. construct the global namespace object
  l.push("window." + ns + " = {data:{}, path:{}};");

  // 2. attach path code to the namespace object so that require.js can efficiently resolve paths
  l.push('\n// include npm::path');
  var pathCode = read(join(builtInDir, 'path.posix.js'));
  l.push('(function (exports) {\n ' + pathCode + '\n}(window.' + ns + '.path));');

  // 3. pull in serialized data
  Object.keys(o.data).forEach(function (name) {
    return l.push(ns + ".data." + name + " = " + o.data[name] + ";");
  });

  // 4. attach require code
  var config = {
    namespace : ns
  , domains   : Object.keys(o.domains) // TODO: remove npm from here
  , arbiters  : o.arbiters
  , logging   : o.logLevel
  , npmTree   : npmTree
  , builtIns  : builtIns
  , slash     : '/' //TODO: figure out if different types can coexist, if so, determine in resolver, and on client
  };

  l.push(anonWrap(read(join(dir, 'require.js'))
    .replace(/VERSION/, JSON.parse(read(join(dir, '..', 'package.json'))).version)
    .replace(/REQUIRECONFIG/, JSON.stringify(config))
  ));

  // 5. include CommonJS compatible code in the order they have to be defined
  var defineWrap = function (exportName, domain, code) {
    return ns + ".define('" + exportName + "','" + domain + "',function (require, module, exports) {\n" + code + "\n});";
  };

  // 6. harvest function splits code into app and non-app code and defineWraps
  var harvest = function (onlyMain) {
    codeList.forEach(function (pair) {
      var dom = pair[0]
        , file = pair[1]
        , basename = file.split('.')[0];
      if ((dom === 'app') !== onlyMain) {
        return;
      }
      var code = before(compile(join(o.domains[dom], file)));
      l.push(defineWrap(basename, dom, code));
    });
  };

  // 7.a) include required builtIns
  l.push("\n// node builtins\n");
  len = l.length;
  usedBuiltIns.forEach(function (b) {
    if (b === 'path') { // already included
      return;
    }
    l.push(defineWrap(b, 'npm', read(join(builtInDir, b + '.js'))));
  });
  if (l.length === len) {
    l.pop();
  }

  // 7.b) include modules not on the app domain
  l.push("\n// shared code\n");
  len = l.length;
  harvest(false);
  if (l.length === len) {
    l.pop();
  }

  // 7.c) include modules on the app domain, and wait for domloader if set
  l.push("\n// app code - safety wrapped\n\n");
  domload(harvest(true));

  // 8. use a closure to encapsulate the private internal data and APIs
  return anonWrap(l.join('\n'));
}
1195356
def import_model(self, source):
        """"""
        source = self._resolve_source(source)
        self._context = FilePathContext(source)
        with self._context.open() as f:
            self._reader = self._open_reader(f)

        return self._reader.create_model()
964697
def import_model(self, source):
        """"""
        if not hasattr(source, 'read'):  # Not a File-like object
            with open(self._resolve_source(source), 'r') as f:
                return self._import(f)
        else:
            return self._import(source)
392091
def load_models(module):
    """"""
    modules = _import_submodules(module)
    return {m for module in modules for m in filter(
        _check_model, (getattr(module, name) for name in dir(module))
    )}
879727
function model(spec) {
  var schema = lodash.cloneDeep(spec);

  delete schema.id;

  schema = transform(schema, {
    removeFormats: true,
  });

  return schema;
}
702094
def model_function(self, model_name, version, func_name):
        """"""
        assert func_name in ('serializer', 'loader', 'invalidator')
        name = "%s_%s_%s" % (model_name.lower(), version, func_name)
        return getattr(self, name)
1146115
function loadModels(fpath, modelFiles) {
    try {
      fpath = path.normalize(fpath);
      if (!fs.existsSync(fpath)) throw 1;
    } catch (e) {
      return false;
    }
    if (path.extname(fpath) === '.js') {
      // we have a file.
      let itemName = path.basename(fpath);
      itemName = itemName.substr(0, itemName.lastIndexOf('.'));
      let itemCode = decamelize(itemName);
      let item = {
        fullPath: fpath,
        code: itemCode,
        name: itemName,
        path: path.basename(fpath)
      };
      modelFiles.push(item);
      return true;
    }
    const items = thorin.util.readDirectory(fpath, {
      ext: 'js',
      relative: true
    });
    if (items.length === 0) {
      return true;
    }
    for (let i = 0; i < items.length; i++) {
      let itemPath = items[i];
      let item = {
        fullPath: path.normalize(fpath + '/' + itemPath)
      };
      itemPath = itemPath.substr(0, itemPath.lastIndexOf('.'));
      let itemName = decamelize(itemPath, NAME_SEPARATOR);
      itemName = itemName.split(path.sep).join(NAME_SEPARATOR);
      item.name = itemName;
      item.code = camelcase(itemName);
      item.path = itemPath.split(path.sep).join('/');
      modelFiles.push(item);
    }
    return true;
  }
806698
def _export(self, path, variables_saver):
    
    self._saved_model_handler.export(path, variables_saver=variables_saver)

    module_def_proto = module_def_pb2.ModuleDef()
    module_def_proto.format = module_def_pb2.ModuleDef.FORMAT_V3
    module_def_filename = get_module_proto_path(path)
    tf_utils.atomic_write_string_to_file(
        module_def_filename,
        module_def_proto.SerializeToString(),
        overwrite=False)
    logging.info("Exported TF-Hub module to: %s", path)
1087114
def export_js(
            self,
            js_module_name=JS_MODULE_NAME,
            js_template=JS_ES6_IMPORT_EXPORT_TEMPLATE,
            js_indent=JS_INDENTATION):
        '''
        '''

        language = []
        refs = []
        classes = {'Grammar'}
        indent = 0
        cname = self.__class__.__name__ if 'import ' in js_template else None

        for name in self._order:
            elem = getattr(self, name, None)
            if not isinstance(elem, Element):
                continue
            if not hasattr(elem, '_export_js'):
                continue
            language.append('{indent}{var} {name} = {value};'.format(
                indent=js_indent,
                name=name,
                var='static' if cname else 'var',
                value=elem._export_js(js_indent, indent, classes, cname)))

        for name, ref in self._refs.items():
            refs.append(
                    '{pre}{name}.set({value});'
                    .format(
                        pre='{}.'.format(cname) if cname else js_indent,
                        name=name,
                        value=ref._element._export_js(
                            js_indent,
                            -1 if cname else indent,
                            classes,
                            cname)))

        if 'Rule' in classes:
            classes.remove('Rule')

        return js_template.format(
            name=self.__class__.__name__,
            indent=js_indent,
            js_module=js_module_name,
            datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
            language='\n'.join(language),
            refs='\n{}'.format('\n'.join(refs)),
            arguments=',\n'.join(map(lambda s:
                                     js_indent * 3 + s, classes)),
            re_keywords=self.RE_KEYWORDS.pattern.replace('\\', '\\\\'),
            classes=', '.join(classes),
            constructors=',\n'.join(
                map(lambda s: js_indent + s,
                    ['.'.join([
                        'window',
                        js_module_name, n]) for n in classes])))
58967
def build_model_output(cls, name='output'):
        
        return cls(name, PortDirection.OUTPUT, type=PortType.MODEL)
181184
function mapDefinitionsFromModel(model) {
  const definitionMap = [];

  /* istanbul ignore else */
  if (model && model.definitions) {
    debug('Parsing %s definitions', Object.keys(model.definitions).length);
    for (const definitionName of Object.keys(model.definitions)) {
      debug('  Reading definition for %s', definitionName);
      const definitionKey = util.format('#/definitions/%s', definitionName);
      const currentDef = model.definitions[definitionName];
      currentDef.definitionName = definitionName;
      currentDef.referencePath = definitionKey;
      definitionMap[definitionKey] = currentDef;
    }
  }

  return definitionMap;
}
182850
def export_py(
            self,
            py_module_name=PY_MODULE_NAME,
            py_template=PY_TEMPLATE,
            py_indent=PY_INDENTATION):
        ''''''

        language = []
        classes = {'Grammar'}
        indent = 0

        for name in self._order:
            elem = getattr(self, name, None)
            if not isinstance(elem, Element):
                continue
            if not hasattr(elem, '_export_py'):
                continue
            language.append('{indent}{name} = {value}'.format(
                indent=py_indent,
                name=name,
                value=elem._export_py(py_indent, indent, classes)))

        for name, ref in self._refs.items():
            language.append(
                '{indent}{name} = {value}'
                .format(
                    indent=py_indent,
                    name=name,
                    value=ref._element._export_py(
                        py_indent,
                        indent,
                        classes)))

        return py_template.format(
            name=self.__class__.__name__,
            indent=py_indent,
            py_module=py_module_name,
            datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
            language='\n'.join(language),
            re_keywords=self.RE_KEYWORDS.pattern.replace('\\', '\\\\'),
            imports='\n'.join(
                map(lambda s: s, [
                    ' '.join(['from', py_module_name, 'import', n])
                    for n in classes if n != 'Rule'])))
513865
function exported (options) {
  var exp = arrayify(options.data.root).find(where({ '!kind': 'module', id: this.id }))
  return exp || this
}
843191
def import_model(self, source):
        """"""
        model = super(StrictImporter, self).import_model(source)

        # Translate entries into dict-based entries.
        sbml.convert_model_entries(
            model, convert_id=lambda entry: entry.id,
            translate_compartment=self._translate_compartment,
            translate_compound=self._translate_compound,
            translate_reaction=self._translate_reaction)

        return model
957486
def export_fun(args):
  """"""
  # Input placeholder for inferencing
  x = tf.placeholder(tf.float32, [None, IMAGE_PIXELS * IMAGE_PIXELS], name="x")

  # Variables of the hidden layer
  hid_w = tf.Variable(tf.truncated_normal([IMAGE_PIXELS * IMAGE_PIXELS, hidden_units],
                      stddev=1.0 / IMAGE_PIXELS), name="hid_w")
  hid_b = tf.Variable(tf.zeros([hidden_units]), name="hid_b")
  tf.summary.histogram("hidden_weights", hid_w)

  # Variables of the softmax layer
  sm_w = tf.Variable(tf.truncated_normal([hidden_units, 10],
                     stddev=1.0 / math.sqrt(hidden_units)), name="sm_w")
  sm_b = tf.Variable(tf.zeros([10]), name="sm_b")

  hid_lin = tf.nn.xw_plus_b(x, hid_w, hid_b)
  hid = tf.nn.relu(hid_lin)
  y = tf.nn.softmax(tf.nn.xw_plus_b(hid, sm_w, sm_b))
  prediction = tf.argmax(y, 1, name="prediction")

  saver = tf.train.Saver()

  with tf.Session() as sess:
    # load graph from a checkpoint
    logging.info("model path: {}".format(args.model_dir))
    ckpt = tf.train.get_checkpoint_state(args.model_dir)
    logging.info("ckpt: {}".format(ckpt))
    assert ckpt and ckpt.model_checkpoint_path, "Invalid model checkpoint path: {}".format(args.model_dir)
    saver.restore(sess, ckpt.model_checkpoint_path)

    logging.info("Exporting saved_model to: {}".format(args.export_dir))
    # exported signatures defined in code
    signatures = {
      tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: {
        'inputs': {'image': x},
        'outputs': {'prediction': prediction},
        'method_name': tf.saved_model.signature_constants.PREDICT_METHOD_NAME
      },
      'featurize': {
        'inputs': {'image': x},
        'outputs': {'features': hid},
        'method_name': 'featurize'
      }
    }
    TFNode.export_saved_model(sess,
                              args.export_dir,
                              tf.saved_model.tag_constants.SERVING,
                              signatures)
    logging.info("Exported saved_model")
292297
function generate_exports (module) {
  // # 85
  // Before module factory being invoked, mark the module as `loaded`
  // so we will not execute the factory function again.

  // `mod.loaded` indicates that a module has already been `require()`d
  // When there are cyclic dependencies, neuron will not fail.
  module.loaded = true;

  // During the execution of factory,
  // the reference of `module.exports` might be changed.
  // But we still set the `module.exports` as `{}`,
  // because the module might be `require()`d during the execution of factory
  // if cyclic dependency occurs.
  var exports = module.exports = {};

  // TODO:
  // Calculate `filename` ahead of time
  var __filename
    // = module.filename
    = NEURON_CONF.resolve(module.id);
  var __dirname = dirname(__filename);

  // to keep the object mod away from the executing context of factory,
  // use `factory` instead `mod.factory`,
  // preventing user from fetching runtime data by 'this'
  var factory = module.factory;
  factory(create_require(module), exports, module, __filename, __dirname);
  return module.exports;
}