TODO: almost identical to ModelsHandler; refactor
775206
public static Leaderboard getFromDKV(String param_name, String key_str) {
    return getFromDKV(param_name, Key.make(key_str));
  }
305792
function(req, res, next) {
    return function(modelOrCollection) {
      this.prepareResponse(modelOrCollection, req, res, next);
    }.bind(this);
  }
869070
def convertAndMake(converter, handler):
  """"""
  def convertAction(loc, value):
    return handler(loc, converter(value))
  return convertAction
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)
516454
def mutate(self, context, handler, args, kw):
		
		def cast(arg, val):
			if arg not in annotations:
				return
			
			cast = annotations[key]
			
			try:
				val = cast(val)
			except (ValueError, TypeError) as e:
				parts = list(e.args)
				parts[0] = parts[0] + " processing argument '{}'".format(arg)
				e.args = tuple(parts)
				raise
			
			return val
			
		annotations = getattr(handler.__func__ if hasattr(handler, '__func__') else handler, '__annotations__', None)
		if not annotations:
			return
		
		argspec = getfullargspec(handler)
		arglist = list(argspec.args)
		
		if ismethod(handler):
			del arglist[0]
		
		for i, value in enumerate(list(args)):
			key = arglist[i]
			if key in annotations:
				args[i] = cast(key, value)
		
		# Convert keyword arguments
		for key, value in list(items(kw)):
			if key in annotations:
				kw[key] = cast(key, value)
844673
private List<ModelProcessorUtil.Method> getEnhancingMethods(final RuntimeResource runtimeResource) {
        final List<ModelProcessorUtil.Method> newMethods = Lists.newArrayList();

        for (final Resource resource : runtimeResource.getResources()) {
            // Handler classes.
            for (final Class<?> handlerClass : resource.getHandlerClasses()) {
                createEnhancingMethods(handlerClass, null, newMethods);
            }

            // Names - if there are no handler classes / instances.
            if (resource.getHandlerClasses().isEmpty() && resource.getHandlerInstances().isEmpty()) {
                for (String resourceName : resource.getNames()) {
                    final Class<Object> resourceClass = AccessController
                            .doPrivileged(ReflectionHelper.classForNamePA(resourceName));
                    if (resourceClass != null) {
                        createEnhancingMethods(resourceClass, null, newMethods);
                    }
                }
            }

            // Handler instances.
            Errors.process((Producer<Void>) () -> {
                for (final Object handlerInstance : resource.getHandlerInstances()) {
                    final Class<?> handlerInstanceClass = handlerInstance.getClass();

                    if (!resource.getHandlerClasses().contains(handlerInstanceClass)) {
                        createEnhancingMethods(handlerInstanceClass, handlerInstance, newMethods);
                    } else {
                        Errors.warning(resource,
                                LocalizationMessages.TEMPLATE_HANDLER_ALREADY_ENHANCED(handlerInstanceClass));
                    }
                }

                return null;
            });
        }

        return newMethods;
    }
924648
function(iteratee, instance) {
    if (_.isFunction(iteratee)) return iteratee;
    if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee);
    if (_.isString(iteratee)) return function(model) { return model.get(iteratee); };
    return iteratee;
  }
175819
def transform(self, context, handler, result):
		
		handler = handler.__func__ if hasattr(handler, '__func__') else handler
		annotation = getattr(handler, '__annotations__', {}).get('return', None)
		
		if annotation:
			return (annotation, result)
		
		return result
1308765
function(models, options) {
      var i, args, length, model, existing, needsSort;
      var at = options && options.at;
      var sort = ((options && options.sort) == null ? true : options.sort);
      models = _.isArray(models) ? models.slice() : [models];

      // Turn bare objects into model references, and prevent invalid models
      // from being added.
      for (i = models.length - 1; i >= 0; i--) {
        if(!(model = this._prepareModel(models[i], options))) {
          this.trigger("error", this, models[i], options);
          models.splice(i, 1);
          continue;
        }
        models[i] = model;

        existing = model.id != null && this._byId[model.id];
        // If a duplicate is found, prevent it from being added and
        // optionally merge it into the existing model.
        if (existing || this._byCid[model.cid]) {
          if (options && options.merge && existing) {
            existing.set(model.attributes, options);
            needsSort = sort;
          }
          models.splice(i, 1);
          continue;
        }

        // Listen to added models' events, and index models for lookup by
        // `id` and by `cid`.
        model.on('all', this._onModelEvent, this);
        this._byCid[model.cid] = model;
        if (model.id != null) this._byId[model.id] = model;
      }

      // See if sorting is needed, update `length` and splice in new models.
      if (models.length) needsSort = sort;
      this.length += models.length;
      args = [at != null ? at : this.models.length, 0];
      push.apply(args, models);
      splice.apply(this.models, args);

      // Sort the collection if appropriate.
      if (needsSort && this.comparator && at == null) this.sort({silent: true});

      if (options && options.silent) return this;

      // Trigger `add` events.
      while (model = models.shift()) {
        model.trigger('add', model, this, options);
      }

      return this;
    }
338635
function(models, out)
  {
    var target = out || this.cloneEmpty();

    for (var i = 0; i < this.length; i++)
    {
      var a = this[ i ];
      var key = a.$key();
      var exists = false;

      if ( models instanceof ModelCollection )
      {
        exists = models.has( key );
      }
      else
      {
        for (var k = 0; k < models.length && !exists; k++)
        {
          var modelKey = this.buildKeyFromInput( models[ k ] );

          exists = (key === modelKey);
        }
      }

      if (!exists)
      {
        target.push( a );
      }
    }

    return target;
  }
827066
def pre_save_full_clean_handler(sender, instance, *args, **kwargs):
    
    from django.contrib.sessions.models import Session
    if sender != Session:
        instance.full_clean()
272611
def transform_model(cls) -> None:
    
    if cls.name != "Model":
        appname = "models"
        for mcls in cls.get_children():
            if isinstance(mcls, ClassDef):
                for attr in mcls.get_children():
                    if isinstance(attr, Assign):
                        if attr.targets[0].name == "app":
                            appname = attr.value.value

        mname = "{}.{}".format(appname, cls.name)
        MODELS[mname] = cls

        for relname, relval in FUTURE_RELATIONS.get(mname, []):
            cls.locals[relname] = relval

        for attr in cls.get_children():
            if isinstance(attr, Assign):
                try:
                    attrname = attr.value.func.attrname
                except AttributeError:
                    pass
                else:
                    if attrname in ["ForeignKeyField", "ManyToManyField"]:
                        tomodel = attr.value.args[0].value
                        relname = ""
                        if attr.value.keywords:
                            for keyword in attr.value.keywords:
                                if keyword.arg == "related_name":
                                    relname = keyword.value.value

                        if not relname:
                            relname = cls.name.lower() + "s"

                        # Injected model attributes need to also have the relation manager
                        if attrname == "ManyToManyField":
                            relval = [
                                attr.value.func,
                                MANAGER.ast_from_module_name("tortoise.fields").lookup(
                                    "ManyToManyRelationManager"
                                )[1][0],
                            ]
                        else:
                            relval = [
                                attr.value.func,
                                MANAGER.ast_from_module_name("tortoise.fields").lookup(
                                    "RelationQueryContainer"
                                )[1][0],
                            ]

                        if tomodel in MODELS:
                            MODELS[tomodel].locals[relname] = relval
                        else:
                            FUTURE_RELATIONS.setdefault(tomodel, []).append((relname, relval))

    cls.locals["_meta"] = [
        MANAGER.ast_from_module_name("tortoise.models").lookup("MetaInfo")[1][0].instantiate_class()
    ]
    if "id" not in cls.locals:
        cls.locals["id"] = [nodes.ClassDef("id", None)]
268097
function (args) {
  var i;
  if (false === (this instanceof Model)) throw new Error('new operator required');
  this.attributes = [new Attribute('id', 'ID')];
  args = args || {};
  this.modelType = args.modelType || "Model";
  if (args.attributes) {
    for (i in args.attributes) {
      if (args.attributes.hasOwnProperty(i))
        this.attributes.push(args.attributes[i]);
    }
  }
  var unusedProperties = getInvalidProperties(args, ['modelType', 'attributes']);
  var errorList = this.getObjectStateErrors(); // before leaving make sure valid Model
  for (i = 0; i < unusedProperties.length; i++) errorList.push('invalid property: ' + unusedProperties[i]);
  if (errorList.length > 1) throw new Error('error creating Model: multiple errors');
  if (errorList.length) throw new Error('error creating Model: ' + errorList[0]);
  // Validations done
  this._eventListeners = [];
  this._errorConditions = {};
  for (i = 0; i < this.attributes.length; i++) {
   this.attributes[i].model = this;
  }
}
1258812
function whereHandler (obj) {
  let result = {}

  Object.keys(obj).forEach(k => {
    if (this.attributes.some(field => k.startsWith(field))) {
      _queryField2where.call(this, result, k, obj[k])
    }
    if (k === 'limit' || k === 'offset') {
      return
    }
    if (k.match(/\.\w+/)) {
      includeHandler.call(this, k, obj[k])
    }
  })

  return result
}
543669
function exampleHandlers(customHandlers) {
    return (customHandlers || []).concat([
      {
        pattern: /^(\w[\w\.\(\)\[\]'"]*)\s*===?\s*(.*)$/,
        template: 'equality',
        data: function(match) {
          return {
            left: match[1],
            right: match[2]
          };
        }
      },
      {
        pattern: /^(\w[\w\.\(\)\[\]'"]*)\s*!==?\s*(.*)$/,
        template: 'inequality',
        data: function(match) {
          return {
            left: match[1],
            right: match[2]
          };
        }
      },
      {
        pattern: /^instanceof (.*)$/,
        template: 'instanceof',
        data: function(match) {
          return { type: match[1] };
        }
      },
      {
        pattern: /^NaN$/,
        template: 'nan'
      },
      {
        pattern: /^throws$/,
        template: 'throws'
      },
      {
        pattern: /^calls\s+(\w+)\s+(\d+)(?:\s+times?)?$/,
        template: 'calls',
        data: function(match) {
          return {
            callback: match[1],
            count: getCount(match[2])
          };
        }
      },
      {
        pattern: /^calls\s+(\w+)\s+(\d+)\s+times? asynchronously$/,
        template: 'calls_async',
        data: function(match) {
          return {
            callback: match[1],
            count: getCount(match[2])
          };
        }
      },
      {
        pattern: /^=~\s+\/(.*)\/$/,
        template: 'string_proximity',
        data: function(match) {
          return { pattern: match[1] };
        }
      },
      {
        pattern: /^=~\s+\[(.*),?\s*\.\.\.\s*\]$/,
        template: 'array_inclusion',
        data: function(match) {
          return { elements: match[1] };
        }
      },
      {
        pattern: /^one of (.*)$/,
        template: 'array_membership',
        data: function(match) {
          return { values: match[1] };
        }
      },
      {
        pattern: /^=~\s+\[(.*)\]$/,
        template: 'array_proximity',
        data: function(match) {
          return { elements: match[1] };
        }
      },
      {
        pattern: /^\[(.*),?\s*\.\.\.\s*\]$/,
        template: 'array_head',
        data: function(match) {
          return { head: match[1] };
        }
      },
      {
        pattern: /^\[\s*\.\.\.,?\s*(.*)\]$/,
        template: 'array_tail',
        data: function(match) {
          return { tail: match[1] };
        }
      },
      {
        pattern: /\{([\s\S]*),?[\s\n]*\.\.\.[\s\n]*\}/,
        template: 'object_proximity',
        data: function(match) {
          return { properties: match[1] };
        }
      }
    ]);
  }
567902
function(model) {

    const modelPrev = model.collection.prev(model);
    const modelNext = model.collection.next(model);
    let mPrevSel, mNextSel;
    if ((typeof modelPrev !== "undefined" && modelPrev !== null)) { mPrevSel = this._getSelection(modelPrev); }
    if ((typeof modelNext !== "undefined" && modelNext !== null)) { mNextSel = this._getSelection(modelNext); }
    return [mPrevSel,mNextSel];
  }
166515
function (connectionName, collectionName, obj, cb) {
        if (_.isObject(obj)) {
            try {
                var modelInstance = new this._model(obj);
                return cb(null, modelInstance);
            }
            catch (err) {
                return cb(err, null);
            }
        }
    }