Fill the model with functions
434351
def model_functions(vk, model):
    """"""

    def get_vk_extension_functions():
        names = set()
        for extension in get_extensions_filtered(vk):
            for req in extension['require']:
                if 'command' not in req:
                    continue
                for command in req['command']:
                    cn = command['@name']
                    names.add(cn)
                    
                    # add alias command too
                    for alias, n in model['alias'].items():
                        if n == cn:
                            names.add(alias)
        return names

    def get_count_param(command):
        for param in command['param']:
            if param['type'] + param.get('#text', '') == 'uint32_t*':
                return param
        return None

    def member_has_str(name):
        c = next(iter([x for x in model['constructors']
                       if x['name'] == name]), None)
        if c and any(['char' in x['type'] for x in c['members']]):
            return True
        return False

    def format_member(member):
        type_name = member['type']
        if '#text' in member:
            text = member['#text'].replace('const ', '').strip()
            type_name += ' ' + text

        return {'name': member['name'],
                'type': member['type'],
                'none': member['name'] in NULL_MEMBERS,
                'force_array': True if '@len' in member else False,
                'to_create': False,
                'has_str': member_has_str(member['type'])}

    def format_return_member(member):
        t = member['type']

        static_count = None
        if '@len' in member and '::' in member['@len']:
            lens = member['@len'].split('::')
            static_count = {'key': lens[0], 'value': lens[1]}

        is_handle = t in get_handle_names(vk)
        is_enum = t in get_enum_names(vk)
        is_struct = t in get_struct_names(vk)
        return {'name': member['name'],
                'type': t,
                'handle': is_handle,
                'enum': is_enum,
                'struct': is_struct,
                'static_count': static_count,
                'has_str': member_has_str(member['type'])}

    ALLOCATE_PREFIX = ('vkCreate', 'vkGet', 'vkEnumerate', 'vkAllocate',
                       'vkMap', 'vkAcquire')
    ALLOCATE_EXCEPTION = ('vkGetFenceStatus', 'vkGetEventStatus',
                          'vkGetQueryPoolResults',
                          'vkGetPhysicalDeviceXlibPresentationSupportKHR')
    COUNT_EXCEPTION = ('vkAcquireNextImageKHR', 'vkEnumerateInstanceVersion')

    model['functions'] = []
    model['extension_functions'] = []
    functions = [f for f in vk['registry']['commands']['command']]
    extension_function_names = get_vk_extension_functions()

    for function in functions:
        if '@alias' in function:
            continue

        fname = function['proto']['name']
        ftype = function['proto']['type']

        if fname in CUSTOM_FUNCTIONS:
            continue

        if type(function['param']) is not list:
            function['param'] = [function['param']]

        count_param = get_count_param(function)
        if fname in COUNT_EXCEPTION:
            count_param = None
        is_allocate = any([fname.startswith(a) for a in ALLOCATE_PREFIX])
        is_count = is_allocate and count_param is not None

        if fname in ALLOCATE_EXCEPTION or ftype == 'VkBool32':
            is_allocate = is_count = False

        members = []
        for member in function['param']:
            members.append(format_member(member))

        return_member = None
        if is_allocate:
            return_member = format_return_member(function['param'][-1])
            members[-1]['to_create'] = True
        if is_count:
            members[-2]['to_create'] = True

        f = {
            'name': fname,
            'members': members,
            'allocate': is_allocate,
            'count': is_count,
            'return_boolean': True if ftype == 'VkBool32' else False,
            'return_result': True if ftype == 'VkResult' else False,
            'return_member': return_member,
            'is_extension': fname in extension_function_names
        }

        model['functions'].append(f)
98866
function init (model) {
    if (model.__ttl) return;

    var distinct_ = model.distinct;
    model.distinct = function distinct (field, cond, cb) {
      applyTTL(cond);
      return distinct_.call(model, field, cond, cb);
    }

    'findOne find count'.split(' ').forEach(function (method) {
      var fn = model[method];

      model[method] = function (cond, fields, opts, cb) {
        if (!cond) {
          cond = {};
        } else if ('function' == typeof cond) {
          cb = cond;
          cond = {};
        }

        applyTTL(cond);
        return fn.call(model, cond, fields, opts, cb);
      }
    });

    'where $where'.split(' ').forEach(function (method) {
      var fn = model[method];
      model[method] = function () {
        var query = fn.apply(this, arguments)
          , cond = {};
        applyTTL(cond);
        return query.find(cond);
      }
    });

    if (reap) {
      model.startTTLReaper();
    }
  }
1199470
function Models(ml, base_url) {
  this.ml = ml;
  this.base_url = base_url;

  if (includes(base_url, 'classifiers')) {
    this.run_action = 'classify';
  } else if (includes(base_url, 'extractors')) {
    this.run_action = 'extract';
  } else {
    this.run_action = undefined;
  }
}
323235
def flatten_models(models):
        "  "
        if isinstance(models, MultiFitterModel):
            ans = [models]
        else:
            tasklist = MultiFitter._compile_models(models)
            ans = MultiFitter._flatten_models(tasklist)
        return ans
648112
def model_ext_functions(vk, model):
    """"""
    model['ext_functions'] = {'instance': {}, 'device': {}}

    # invert the alias to better lookup
    alias = {v: k for k, v in model['alias'].items()}

    for extension in get_extensions_filtered(vk):
        for req in extension['require']:
            if not req.get('command'):
                continue

            ext_type = extension['@type']
            for x in req['command']:
                name = x['@name']
                if name in alias.keys():
                    model['ext_functions'][ext_type][name] = alias[name]
                else:
                    model['ext_functions'][ext_type][name] = name
223317
@Override
  public Models fillImpl(Models m) {
    super.fillImpl(m);

    if (null != models) {
      m.models = new Model[models.length];

      int i = 0;
      for (ModelSchemaBaseV3 model : this.models) {
        m.models[i++] = (Model)model.createImpl();
      }
    }
    return m;
  }
499206
function loadModels() {
  const modelSpecsPath = path.join(process.cwd(), plugin.config.modelsPath);

  return plugin.myrmex.fire('beforeModelsLoad')
  .spread(() => {
    return Promise.promisify(fs.readdir)(modelSpecsPath);
  })
  .then(fileNames => {
    // Load all the model specifications
    return Promise.map(fileNames, fileName => {
      const modelSpecPath = path.join(modelSpecsPath, fileName);
      const modelName = path.parse(fileName).name;
      return loadModel(modelSpecPath, modelName);
    });
  })
  .then(models => {
    return plugin.myrmex.fire('afterModelsLoad', models);
  })
  .spread(models => {
    return Promise.resolve(models);
  })
  .catch(e => {
    if (e.code === 'ENOENT' && path.basename(e.path) === path.basename(plugin.config.modelsPath)) {
      return Promise.resolve([]);
    }
    Promise.reject(e);
  });
}
354053
def build_model(self):
        """"""
        with tf.variable_scope(
                "model", reuse=None, initializer=self.initializer):
            self._create_placeholders()
            self._create_rnn_cells()
            self._create_initstate_and_embeddings()
            self._create_rnn_architecture()
            self._create_optimizer_node()
947206
function (model) {

                var ret = [];

                function getSubModel(obj) {

                    if (obj === model) {
                        return;
                    }

                    if (_.indexOf(ret, obj) !== -1) {
                        // already in list
                        return;
                    }

                    if (obj instanceof Model) {
                        ret.push(obj);
                        return;
                    }

                    for (var key in obj) {
                        if (obj.hasOwnProperty(key)) {
                            var value = obj[key];

                            if (value instanceof Array) {
                                for (var i = 0; i < value.length; i++) {
                                    getSubModel(value[i]);
                                }
                            } else if (value instanceof List) {
                                value.each(getSubModel);
                            } else if (value instanceof Object) {
                                getSubModel(value);
                            }
                        }
                    }
                }

                getSubModel(model.$);

                return ret;

            }
970016
function initModels(seqObj, modelFiles, models, tablePrefix) {
    modelFiles.forEach((item) => {
      var modelFn;
      try {
        modelFn = require(item.fullPath);
      } catch (e) {
        console.error('Thorin.sql: could not require model: ' + item.fullPath + '\n', e.stack);
        return;
      }
      if (modelFn == null) return;  // we skip it
      if (typeof modelFn !== 'function') {
        console.error(thorin.error('SQL.INVALID_MODEL', 'SQL Model: ' + item.fullPath + ' must export a function(modelObj){}'));
        return;
      }
      if (modelFn.name === 'extend') {
        if (typeof extendModels[item.code] === 'undefined') extendModels[item.code] = [];
        extendModels[item.code].push(modelFn);
        return;
      }
      let modelObj = loader.buildModel(seqObj, modelFn, item, tablePrefix);
      if (modelObj) {
        if (typeof models[modelObj.code] !== 'undefined') {
          console.error(thorin.error('SQL.ADD_MODEL', 'SQL Store: model ' + modelObj.code + ' was already declared.'));
          return;
        }
        models[modelObj.code] = modelObj;
      }
    });
  }
1253345
def modelstandardfunctions(self):
        """"""
        lines = Lines()
        lines.extend(self.doit)
        lines.extend(self.iofunctions)
        lines.extend(self.new2old)
        lines.extend(self.run)
        lines.extend(self.update_inlets)
        lines.extend(self.update_outlets)
        lines.extend(self.update_receivers)
        lines.extend(self.update_senders)
        return lines
1090121
function update(item, model, data, funcParams) {
    var working = [];
    var definedByData = [];

    _.forEach(data, function(value, key) {
        if (_.isFunction(value)) {
            working.push(Promise.resolve(value()).then(function(val) {
                item[key] = val;
            }));
        } else item[key] = value;
        definedByData.push(value);
    });

    _.forEach(model.itemDef, function(value, key) {
        if (value && value.__precalc) {
            var func = value.__precalc, previousVal = data[key];
            working.push(Promise.resolve(func.call(item, previousVal, funcParams || {})).then(function(val) {
                item[key] = (val && val._stWrapped) ? val.val : val;
            }));
        } // if the property has not been set from the itemDef yet. This allows item def properties to be changed
        else if (!_.has(item, key) || definedByData.indexOf(key) !== -1) item[key] = value;
    });

    return Promise.all(working);
}
886334
def _fill_function(*args):
    
    if len(args) == 2:
        func = args[0]
        state = args[1]
    elif len(args) == 5:
        # Backwards compat for cloudpickle v0.4.0, after which the `module`
        # argument was introduced
        func = args[0]
        keys = ['globals', 'defaults', 'dict', 'closure_values']
        state = dict(zip(keys, args[1:]))
    elif len(args) == 6:
        # Backwards compat for cloudpickle v0.4.1, after which the function
        # state was passed as a dict to the _fill_function it-self.
        func = args[0]
        keys = ['globals', 'defaults', 'dict', 'module', 'closure_values']
        state = dict(zip(keys, args[1:]))
    else:
        raise ValueError('Unexpected _fill_value arguments: %r' % (args,))

    # - At pickling time, any dynamic global variable used by func is
    #   serialized by value (in state['globals']).
    # - At unpickling time, func's __globals__ attribute is initialized by
    #   first retrieving an empty isolated namespace that will be shared
    #   with other functions pickled from the same original module
    #   by the same CloudPickler instance and then updated with the
    #   content of state['globals'] to populate the shared isolated
    #   namespace with all the global variables that are specifically
    #   referenced for this function.
    func.__globals__.update(state['globals'])

    func.__defaults__ = state['defaults']
    func.__dict__ = state['dict']
    if 'annotations' in state:
        func.__annotations__ = state['annotations']
    if 'doc' in state:
        func.__doc__  = state['doc']
    if 'name' in state:
        func.__name__ = state['name']
    if 'module' in state:
        func.__module__ = state['module']
    if 'qualname' in state:
        func.__qualname__ = state['qualname']

    cells = func.__closure__
    if cells is not None:
        for cell, value in zip(cells, state['closure_values']):
            if value is not _empty_cell_value:
                cell_set(cell, value)

    return func
1298244
def set_functions(self, functions):
        """"""
        for func in functions:
            try:
                self.append_function(func)
            except (ValueError, AttributeError) as ex:
                log.error("'%s' is not a callable function: %s", func, ex)
                raise
1303045
def fill(*args, &block)
      ary = self.to_a
      ary.fill *args, &block
      self.replace ary
    end
174481
function ModelIndices(model) {
    // For now the only indices we construct are for flowEvents
    this.flowEventsById_ = {};
    model.flowEvents.forEach(function(fe) {
      if (fe.id !== undefined) {
        if (!this.flowEventsById_.hasOwnProperty(fe.id)) {
          this.flowEventsById_[fe.id] = new Array();
        }
        this.flowEventsById_[fe.id].push(fe);
      }
    }, this);
  }
4660
function expandModel (model, view) {
  const modelPath = new BunsenModelPath(model)
  const modelExpansions = aggregateModels(view, modelPath)
  let newModel = model
  _.forEach(modelExpansions, (propertyModel, path) => {
    newModel = addBunsenModelProperty(newModel, propertyModel, path)
  })
  return newModel
}