SCHEMA mini-recompile for:

      each SEARCH then MATCH function
      each TYPE then CHOICE function
    
    given the doc, it returns a schema copy that implements the match
482007
def schema_match_up(doc, schema):
    '''
    
    '''
    copy = schema.copy(seq_prefix="", seq_suffix="")
    copy = _schema_match_up_search(doc, copy)
    copy = _schema_match_up_type_choice(doc, copy)
    return copy
232272
def _get_matching(self, reltype, target, is_external=False):
        
        def matches(rel, reltype, target, is_external):
            if rel.reltype != reltype:
                return False
            if rel.is_external != is_external:
                return False
            rel_target = rel.target_ref if rel.is_external else rel.target_part
            if rel_target != target:
                return False
            return True

        for rel in self.values():
            if matches(rel, reltype, target, is_external):
                return rel
        return None
713503
def matches(self, *args, **kwargs):
        
        request = make_prototype_request(*args, **kwargs)
        if self._prototype.opcode not in (None, request.opcode):
            return False
        if self._prototype.is_command not in (None, request.is_command):
            return False
        for name in dir(self._prototype):
            if name.startswith('_') or name in request._non_matched_attrs:
                # Ignore privates, and handle documents specially.
                continue
            prototype_value = getattr(self._prototype, name, None)
            if inspect.ismethod(prototype_value):
                continue
            actual_value = getattr(request, name, None)
            if prototype_value not in (None, actual_value):
                return False
        if len(self._prototype.docs) not in (0, len(request.docs)):
            return False

        return self._prototype._matches_docs(self._prototype.docs, request.docs)
835159
function FieldReference(typeFunction, fieldOptions = {}) {
    return function (target, key) {
        let fieldType = Reflect.getMetadata("design:type", target, key);
        let schema = MongoSchemaRegistry_1.MongoSchemaRegistry.getSchema(target.constructor.name);
        if (!schema) {
            schema = new MongoSchema_1.MongoSchema(target.constructor);
            MongoSchemaRegistry_1.MongoSchemaRegistry.register(target.constructor.name, schema);
        }
        if (!typeFunction) {
            typeFunction = type => {
                return fieldOptions.type || Reflect.getMetadata("design:type", target, key).name;
            };
        }
        fieldOptions.foreignField = fieldOptions.foreignField || "_id";
        if (!fieldType || fieldType.name != "Array") {
            fieldOptions.relationType = MongoSchema_1.ERelationType.SingleObjectId;
        }
        if (fieldType && fieldType.name == "Array") {
            fieldOptions.relationType = MongoSchema_1.ERelationType.ArrayObjectId;
        }
        schema.addField(key, typeFunction, fieldOptions);
    };
}
576768
def do_schema(self, line):
        
        args = self.getargs(line)

        if not args:
            for k in sorted(self.schema):
                print "%s\t%s" % (k, self.schema[k])
        elif args[0] == "--clear":
            self.schema.clear()
        else:
            fname = args[0]
            ftype = args[1]

            if not ftype in VALID_TYPES:
                print "invalid type: use %s" % list(VALID_TYPES)
            else:
                self.schema[fname] = ftype
139157
function instrumentSchemaForExpressGraphQL(schema) {
  addTracingToResolvers(schema);
  addSchemaLevelResolveFunction(schema, (root, args, ctx, info) => {
    const operation = print(info.operation);
    const fragments = Object.keys(info.fragments).map(k => print(info.fragments[k])).join('\n');

    ctx.tracer.log('request.query', `${operation}\n${fragments}`);
    ctx.tracer.log('request.variables', info.variableValues);
    ctx.tracer.log('request.operationName', info.operation.name);
    return root;
  });
}
483590
def export_schema(cls, recursive=True, include_parent_ref=False):
        """"""
        parent_excludes = {}
        if not include_parent_ref:
            parent_ref = cls.__mapper__.relationships.get(cls.export_parent)
            if parent_ref:
                parent_excludes = {c.name for c in parent_ref.local_columns}

        def formatter(c):
            return ('{0} Default ({1})'.format(
                str(c.type), c.default.arg) if c.default else str(c.type))

        schema = {c.name: formatter(c) for c in cls.__table__.columns
                  if (c.name in cls.export_fields and
                  c.name not in parent_excludes)}
        if recursive:
            for c in cls.export_children:
                child_class = cls.__mapper__.relationships[c].argument.class_
                schema[c] = [child_class.export_schema(recursive=recursive,
                             include_parent_ref=include_parent_ref)]
        return schema
1335190
def lexicographic_sort_schema(schema: GraphQLSchema) -> GraphQLSchema:
    """"""

    def replace_type(type_):
        if is_list_type(type_):
            return GraphQLList(replace_type(type_.of_type))
        elif is_non_null_type(type_):
            return GraphQLNonNull(replace_type(type_.of_type))
        else:
            return replace_named_type(type_)

    def replace_named_type(type_: GraphQLNamedType) -> GraphQLNamedType:
        return type_map[type_.name]

    def replace_maybe_type(maybe_type):
        return maybe_type and replace_named_type(maybe_type)

    def sort_directive(directive):
        kwargs = directive.to_kwargs()
        kwargs.update(
            locations=sorted(directive.locations, key=sort_by_name_key),
            args=sort_args(directive.args),
        )
        return GraphQLDirective(**kwargs)

    def sort_args(args_map):
        args = {}
        for name, arg in sorted(args_map.items()):
            kwargs = arg.to_kwargs()
            kwargs.update(type_=replace_type(arg.type))
            args[name] = GraphQLArgument(**kwargs)
        return args

    def sort_fields(fields_map):
        fields = {}
        for name, field in sorted(fields_map.items()):
            kwargs = field.to_kwargs()
            kwargs.update(type_=replace_type(field.type), args=sort_args(field.args))
            fields[name] = GraphQLField(**kwargs)
        return fields

    def sort_input_fields(fields_map):
        return {
            name: GraphQLInputField(
                replace_type(field.type),
                description=field.description,
                default_value=field.default_value,
                ast_node=field.ast_node,
            )
            for name, field in sorted(fields_map.items())
        }

    def sort_types(arr: List[GraphQLNamedType]) -> List[GraphQLNamedType]:
        return [
            replace_named_type(type_) for type_ in sorted(arr, key=sort_by_name_key)
        ]

    def sort_named_type(type_: GraphQLNamedType) -> GraphQLNamedType:
        if is_scalar_type(type_) or is_introspection_type(type_):
            return type_
        elif is_object_type(type_):
            kwargs = type_.to_kwargs()
            object_type = cast(GraphQLObjectType, type_)
            # noinspection PyTypeChecker
            kwargs.update(
                interfaces=lambda: sort_types(object_type.interfaces),  # type: ignore
                fields=lambda: sort_fields(object_type.fields),
            )
            return GraphQLObjectType(**kwargs)
        elif is_interface_type(type_):
            kwargs = type_.to_kwargs()
            interface_type = cast(GraphQLInterfaceType, type_)
            kwargs.update(fields=lambda: sort_fields(interface_type.fields))
            return GraphQLInterfaceType(**kwargs)
        elif is_union_type(type_):
            kwargs = type_.to_kwargs()
            union_type = cast(GraphQLUnionType, type_)
            # noinspection PyTypeChecker
            kwargs.update(types=lambda: sort_types(union_type.types))  # type: ignore
            return GraphQLUnionType(**kwargs)
        elif is_enum_type(type_):
            kwargs = type_.to_kwargs()
            enum_type = cast(GraphQLEnumType, type_)
            kwargs.update(
                values={
                    name: GraphQLEnumValue(
                        val.value,
                        description=val.description,
                        deprecation_reason=val.deprecation_reason,
                        ast_node=val.ast_node,
                    )
                    for name, val in sorted(enum_type.values.items())
                }
            )
            return GraphQLEnumType(**kwargs)
        elif is_input_object_type(type_):
            kwargs = type_.to_kwargs()
            input_object_type = cast(GraphQLInputObjectType, type_)
            kwargs.update(fields=lambda: sort_input_fields(input_object_type.fields))
            return GraphQLInputObjectType(**kwargs)

        # Not reachable. All possible types have been considered.
        raise TypeError(f"Unexpected type: '{inspect(type_)}'.")  # pragma: no cover

    type_map: Dict[str, GraphQLNamedType] = {
        type_.name: sort_named_type(type_)
        for type_ in sorted(schema.type_map.values(), key=sort_by_name_key)
    }

    return GraphQLSchema(
        types=list(type_map.values()),
        directives=[
            sort_directive(directive)
            for directive in sorted(schema.directives, key=sort_by_name_key)
        ],
        query=replace_maybe_type(schema.query_type),
        mutation=replace_maybe_type(schema.mutation_type),
        subscription=replace_maybe_type(schema.subscription_type),
        ast_node=schema.ast_node,
    )
21540
def _compile_type(self, schema):
        
        # Prepare self
        self.compiled_type = const.COMPILED_TYPE.TYPE
        self.name = get_type_name(schema)

        # Error partials
        err_type = self.Invalid(_(u'Wrong type'), self.name)

        # Type check function
        if six.PY2 and schema is basestring:
            # Relaxed rule for Python2 basestring
            typecheck = lambda v: isinstance(v, schema)
        else:
            # Strict type check for everything else
            typecheck = lambda v: type(v) == schema

        # Matcher
        if self.matcher:
            def match_type(v):
                return typecheck(v), v
            return match_type

        # Validator
        def validate_type(v):
            # Type check
            if not typecheck(v):
                # expected=<type>, provided=<type>
                raise err_type(get_type_name(type(v)))
            # Fine
            return v

        return validate_type
863725
def _compile_schema(self, schema):
        
        assert self.matcher == schema.matcher

        self.name = schema.name
        self.compiled_type = schema.compiled_type

        return schema.compiled
657654
function findReferences(schema) {
  if (schema.$ref) {
    return [schema.$ref];
  }

  let references = [];

  if (schema.allOf) {
    references = references.concat(...schema.allOf.map(findReferences));
  }

  if (schema.anyOf) {
    references = references.concat(...schema.anyOf.map(findReferences));
  }

  if (schema.oneOf) {
    references = references.concat(...schema.oneOf.map(findReferences));
  }

  if (schema.not) {
    references = references.concat(...findReferences(schema.not));
  }

  // Array

  if (schema.items) {
    if (Array.isArray(schema.items)) {
      references = references.concat(...schema.items.map(findReferences));
    } else {
      references = references.concat(findReferences(schema.items));
    }
  }

  if (schema.additionalItems && typeof schema.additionalItems === 'object') {
    references = references.concat(findReferences(schema.additionalItems));
  }

  // Object

  if (schema.properties) {
    Object.keys(schema.properties).forEach((key) => {
      references = references.concat(findReferences(schema.properties[key]));
    });
  }

  if (schema.patternProperties) {
    Object.keys(schema.patternProperties).forEach((key) => {
      references = references.concat(findReferences(schema.patternProperties[key]));
    });
  }

  if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
    references = references.concat(findReferences(schema.additionalProperties));
  }

  return references;
}
10956
def from_code(
        cls,
        schema,  # type: GraphQLSchema
        code,  # type: Union[str, Any]
        uptodate=None,  # type: Optional[bool]
        extra_namespace=None,  # type: Optional[Dict[str, Any]]
    ):
        # type: (...) -> GraphQLCompiledDocument
        
        if isinstance(code, string_types):
            filename = "<document>"
            code = compile(code, filename, "exec")
        namespace = {"__file__": code.co_filename}
        exec(code, namespace)
        if extra_namespace:
            namespace.update(extra_namespace)
        rv = cls._from_namespace(schema, namespace)
        # rv._uptodate = uptodate
        return rv
1302399
function(db) {
		function merge(a_, b_, plv8, ERROR) {

			function copy_properties(o, a) {
				Object.keys(a).forEach(function(k) {
					o[k] = a[k];
				});
				return o;
			}

			function copy(a, b) {
				return copy_properties(copy_properties({}, a), b);
			}

			try {
				return copy(a_, b_);
			} catch (e) {
				plv8.elog(ERROR, e);
				return;
			}
		}
		return db.query('CREATE SCHEMA IF NOT EXISTS nopg')
			.query('CREATE OR REPLACE FUNCTION nopg.merge(a json, b json) RETURNS json LANGUAGE plv8 STABLE AS ' + NoPg._escapeFunction(merge,
				["a", "b", "plv8", "ERROR"]) );
	}
944541
function findMatchingDocuments(type, documentIDs, modelToSearch, cb) {

    var errorTextDataType = type === models.MODELNAMES.DATA_SOURCE ? "Data Sources" : "Data Targets";

    //If the form contains no data sources, then no need to verify
    if (documentIDs.length === 0) {
      return cb(undefined, []);
    }

    var query = {_id: {
      "$in": documentIDs
    }};

    modelToSearch.find(query).exec(function(err, foundModels) {
      if (err) {
        return cb(buildErrorResponse({
          error: err,
          userDetail: "Unexpected Error Finding " + errorTextDataType
        }));
      }

      //There should be the same number of data source documents
      if (documentIDs.length !== foundModels.length) {

        var missingDocumentId = _.find(documentIDs, function(documentId) {
          return !_.findWhere(foundModels, {_id: documentId});
        });

        //If there is no missing data source, then something is wrong..
        if (!missingDocumentId) {
          return cb(buildErrorResponse({
            error: new Error("Unexpected Error When Finding " + errorTextDataType),
            systemDetail: "Expected A Missing " + errorTextDataType + " But Could Not Find It"
          }));
        }

        return cb(buildErrorResponse({
          userDetail: "A " + errorTextDataType + " Contained In The Form Could Not Be Found",
          systemDetail: "Expected " + errorTextDataType + " With ID " + missingDocumentId + " To Be Found",
          code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
        }));
      }

      //All documents found -- checking for cache if needed
      if (options.expectDataSourceCache && type === models.MODELNAMES.DATA_SOURCE) {
        var missingCache = _.find(foundModels, function(dataSource) {
          return dataSource.cache.length === 0;
        });

        if (missingCache) {
          return cb(buildErrorResponse({
            error: new Error("Expected " + errorTextDataType + " Cached Data To Be Set"),
            systemDetail: "Expected Cache For " + errorTextDataType + " ID " + missingCache._id + " To Be Set",
            code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
          }));
        }
      }

      //Checking that only one real time data target is assigned.
      if (type === models.MODELNAMES.DATA_TARGET) {
        var realTimeDataTargets = _.filter(foundModels, function(foundModel) {
          return foundModel.type === models.CONSTANTS.DATA_TARGET_TYPE_REAL_TIME;
        });

        if (realTimeDataTargets.length > 1) {
          return cb(buildErrorResponse({
            error: new Error("Only One Real Time Data Target Can Be Assigned To A Form"),
            code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
          }
                                      ));
        }
      }

      return cb(undefined, foundModels);
    });
  }
978467
def clone_schema(self, base_schema_name, new_schema_name):
        
        connection.set_schema_to_public()
        cursor = connection.cursor()

        # check if the clone_schema function already exists in the db
        try:
            cursor.execute("SELECT 'clone_schema'::regproc")
        except ProgrammingError:
            self._create_clone_schema_function()
            transaction.commit()

        sql = 'SELECT clone_schema(%(base_schema)s, %(new_schema)s, TRUE)'
        cursor.execute(
            sql,
            {'base_schema': base_schema_name, 'new_schema': new_schema_name}
        )
        cursor.close()
416540
def document_from_string(self, schema, request_string):
        # type: (GraphQLSchema, str) -> GraphQLDocument
        """"""
        key = self.get_key_for_schema_and_document_string(schema, request_string)
        if key not in self.cache_map:
            # We return from the fallback
            self.cache_map[key] = self.fallback_backend.document_from_string(
                schema, request_string
            )
            # We ensure the main backend response is in the queue
            self.get_worker().queue(self.queue_backend, key, schema, request_string)

        return self.cache_map[key]
633685
function one(schema, node, stack) {
    // console.log(node);
    var type = node && node.type
    var replacement = {type: node.type}
    var replace = true
    var definition
    var allowed
    var result
    var key

    if (!own.call(NODES, type)) {
        replace = false
    }
    else {
        definition = NODES[type]

        if (typeof definition === 'function') {
            definition = definition(schema, node)
        }

        if (!definition) {
            replace = false
        } else {
            /* old start */
            allowed = xtend(definition, NODES['*'])
            /* old end */

            /* new start */
            // allowed = xtend(definition, NODES['*'], (schema.NODES && schema.NODES['*'])?schema.NODES['*']:{})
            /* new end */

            for (key in allowed) {
                result = allowed[key](schema, node[key], node, stack)

                if (result === false) {
                    replace = false

                    /* Set the non-safe value. */
                    replacement[key] = node[key]
                } else if (result !== null && result !== undefined) {
                    replacement[key] = result
                }
            }
        }
    }

    if (!replace) {
        if (
            !replacement.children ||
            replacement.children.length === 0 ||
            schema.strip.indexOf(replacement.tagName) !== -1
        ) {
            return null
        }

        return replacement.children
    }
    // console.log(replacement);


    /* new start */
    var options = {};
    NODE_KEYS.forEach(function (key) {
        if(node.hasOwnProperty(key)) {
            options[key] = node[key];
        }
    });
    Object.assign(replacement, options);
    /* new end */



    return replacement
}