text:
'use strict';

var GraphQL = require('GraphQL');
var RelayConnectionInterface = require('RelayConnectionInterface');
var RelayFragmentReference = require('RelayFragmentReference');
import type {Call}  from 'RelayInternalTypes';
var RelayMetaRoute = require('RelayMetaRoute');
var RelayRouteFragment = require('RelayRouteFragment');
import type {Variables} from 'RelayTypes';

var areEqual = require('areEqual');
var callsFromGraphQL = require('callsFromGraphQL');
var callsToGraphQL = require('callsToGraphQL');
var generateRQLFieldAlias = require('generateRQLFieldAlias');
var getWeakIdForObject = require('getWeakIdForObject');
var invariant = require('invariant');
var printRelayQueryCall = require('printRelayQueryCall');
var shallowEqual = require('shallowEqual');
var stableStringify = require('stableStringify');

type BatchCall = {
  refParamName: string;
  sourceQueryID: string;
  sourceQueryPath: string;
};
type ConcreteQueryObject = any;
type FragmentMetadata = {
  isDeferred: boolean;
  isReferenceFragment: boolean;
  isTypeConditional: boolean;
};
type FragmentNames = {[key: string]: string};
type RootCallValue = string | GraphQL.BatchCallVariable;
// TODO: replace once #6525923 is resolved
type NextChildren = Array<any>;

// conditional field calls/values
var IF = 'if';
var UNLESS = 'unless';
var TRUE = 'true';
var FALSE = 'false';

var QUERY_ID_PREFIX = 'q';
var REF_PARAM_PREFIX = 'ref_';

var _nextQueryID = 0;

var DEFAULT_FRAGMENT_METADATA = {
  isDeferred: false,
  isReferenceFragment: false,
  isTypeConditional: false,
};

/**
 * @internal
 *
 * Queries in Relay are represented as trees. Possible nodes include the root,
 * fields, and fragments. Fields can have children, or they can be leaf nodes.
 * Root and fragment nodes must always have children.
 *
 * `RelayQueryNode` provides access to information such as the field name,
 * generated alias, sub-fields, and call values.
 *
 * Nodes are immutable; query modification is supported via `clone`:
 *
 * ```
 * var next = prev.clone(prev.getChildren().filter(f => ...));
 * ```
 *
 * Note: Mediating access to actual query nodes is necessary so that we can
 * replace the current mutable GraphQL nodes with an immutable query
 * representation. This class *must not* mutate the underlying `concreteNode`.
 * Instead, use an instance variable (see `clone()`).
 *
 * TODO (#6937314): RelayQueryNode support for toJSON/fromJSON
 */
class RelayQueryNode {
  constructor: Function; // for flow
  __calls__: ?Array<Call>;
  __children__: ?Array<RelayQueryNode>;
  __concreteNode__: ConcreteQueryObject;
  __fieldMap__: ?{[key: string]: RelayQueryField};
  __hasDeferredDescendant__: ?boolean;
  __hasValidatedConnectionCalls__: ?boolean;
  __route__: RelayMetaRoute;
  __serializationKey__: ?string;
  __storageKey__: ?string;
  __variables__: Variables;

  // TODO(#7161070) Remove this once `toGraphQL` is no longer needed.
  __isConcreteNodeCached__: boolean;

  static create(
    concreteNode: ConcreteQueryObject,
    route: RelayMetaRoute,
    variables: Variables
  ): RelayQueryNode {
    var node = createNode(concreteNode, route, variables);
    invariant(
      node instanceof RelayQueryNode,
      'RelayQueryNode.create(): Expected a node.'
    );
    return node;
  }

  /**
   * Helper to construct a new root query with the given attributes and 'empty'
   * route/variables.
   */
  static buildRoot(
    rootCall: string,
    rootCallValue?: ?Array<RootCallValue> | ?RootCallValue,
    children?: ?Array<RelayQueryNode>,
    metadata?: ?{[key: string]: mixed},
    name?: ?string
  ): RelayQueryRoot {
    var nextChildren = children ? children.filter(child => !!child) : [];
    var concreteRoot = new GraphQL.Query(
      rootCall,
      rootCallValue || null,
      null,
      null,
      metadata,
      name
    );
    var root = new RelayQueryRoot(
      concreteRoot,
      RelayMetaRoute.get('$RelayQuery'),
      {}
    );
    root.__children__ = nextChildren;
    return root;
  }

  /**
   * Helper to construct a new fragment with the given attributes and 'empty'
   * route/variables.
   */
  static buildFragment(
    name: string,
    type: string,
    children?: ?Array<RelayQueryNode>,
    metadata?: ?{[key: string]: mixed}
  ): RelayQueryFragment {
    var nextChildren = children ? children.filter(child => !!child) : [];
    var concreteFragment = new GraphQL.QueryFragment(
      name,
      type,
      null,
      null,
      metadata
    );
    var fragment = new RelayQueryFragment(
      concreteFragment,
      RelayMetaRoute.get('$RelayQuery'),
      {},
      {
        isDeferred: !!(metadata && metadata.isDeferred),
        isReferenceFragment: !!(metadata && metadata.isReferenceFragment),
        isTypeConditional: !!(metadata && metadata.isTypeConditional),
      }
    );
    fragment.__children__ = nextChildren;
    return fragment;
  }

  /**
   * Helper to construct a new field with the given attributes and 'empty'
   * route/variables.
   */
  static buildField(
    fieldName: string,
    calls?: ?Array<Call>,
    children?: ?NextChildren,
    metadata?: ?{[key: string]: mixed},
    alias?: ?string
  ): RelayQueryField {
    var nextChildren = children ? children.filter(child => !!child) : [];
    var concreteField = new GraphQL.Field(
      fieldName,
      null,
      null,
      calls ? callsToGraphQL(calls) : null,
      alias,
      null,
      metadata
    );
    var field = new RelayQueryField(
      concreteField,
      RelayMetaRoute.get('$RelayQuery'),
      {}
    );
    field.__children__ = nextChildren;
    return field;
  }

  /**
   * Helper to construct a new mutation with the given attributes and 'empty'
   * route/variables.
   */
  static buildMutation(
    mutationName: string,
    responseType: string,
    callName: string,
    callValue?: ?mixed,
    children?: ?Array<RelayQueryNode>,
    metadata?: ?{[key: string]: mixed}
  ): RelayQueryMutation {
    var nextChildren = children ? children.filter(child => !!child) : [];
    var concreteMutation = new GraphQL.Mutation(
      mutationName,
      responseType,
      new GraphQL.Callv(callName, new GraphQL.CallVariable('input')),
      null,
      null,
      metadata
    );
    var mutation = new RelayQueryMutation(
      concreteMutation,
      RelayMetaRoute.get('$RelayQuery'),
      {input: callValue || ''}
    );
    mutation.__children__ = nextChildren;
    return mutation;
  }

  static createFragment(
    concreteNode: ConcreteQueryObject,
    route: RelayMetaRoute,
    variables: Variables,
    metadata?: ?FragmentMetadata
  ): RelayQueryFragment {
    invariant(
      GraphQL.isFragment(concreteNode),
      'RelayQuery.createQuery(): Expected a concrete query fragment, got: %s',
      concreteNode
    );
    return createMemoizedFragment(
      concreteNode,
      route,
      variables,
      metadata || DEFAULT_FRAGMENT_METADATA
    );
  }

  static createQuery(
    concreteNode: ConcreteQueryObject,
    route: RelayMetaRoute,
    variables: Variables
  ): RelayQueryRoot {
    invariant(
      GraphQL.isQuery(concreteNode),
      'RelayQuery.createQuery(): Expected a concrete query, got: %s',
      concreteNode
    );
    return new RelayQueryRoot(
      concreteNode,
      route,
      variables
    );
  }

  /**
   * @private
   *
   * Base class for all node types, must not be directly instantiated.
   */
  constructor(
    concreteNode: ConcreteQueryObject,
    route: RelayMetaRoute,
    variables: Variables
  ) {
    invariant(
      this.constructor.name !== 'RelayQueryNode',
      'RelayQueryNode: Abstract class cannot be instantiated.'
    );
    this.__concreteNode__ = concreteNode;
    this.__route__ = route;
    this.__variables__ = variables;

    // lazily computed properties
    this.__calls__ = null;
    this.__children__ = null;
    this.__fieldMap__ = null;
    this.__hasDeferredDescendant__ = null;
    this.__hasValidatedConnectionCalls__ = null;
    this.__serializationKey__ = null;
    this.__storageKey__ = null;

    // TODO(#7161070) Remove this once `toGraphQL` is no longer needed.
    this.__isConcreteNodeCached__ = false;
  }

  isGenerated(): boolean {
    return false;
  }

  isRefQueryDependency(): boolean {
    return false;
  }

  isScalar(): boolean {
    return false;
  }

  clone(children: NextChildren): ?RelayQueryNode {
    if (this.isScalar()) {
      // Compact new children *after* this check, for consistency.
      invariant(
        children.length === 0,
        'RelayQueryNode: Cannot add children to scalar fields.'
      );
      return this;
    }

    var prevChildren = this.getChildren();
    var nextChildren = cloneChildren(prevChildren, children);

    if (!nextChildren.length) {
      return null;
    } else if (nextChildren === prevChildren) {
      return this;
    }

    var clone = RelayQueryNode.create(
      this.__concreteNode__,
      this.__route__,
      this.__variables__
    );
    clone.__children__ = nextChildren;
    clone.__calls__ = this.__calls__;
    clone.__serializationKey__ = this.__serializationKey__;
    clone.__storageKey__ = this.__storageKey__;

    return clone;
  }

  getChildren(): Array<RelayQueryNode> {
    var children = this.__children__;
    if (!children) {
      var nextChildren = [];
      this.__concreteNode__.children.forEach(concreteChild => {
        var node = createNode(
          concreteChild,
          this.__route__,
          this.__variables__
        );
        if (node) {
          nextChildren.push(node);
        }
      });
      this.__children__ = nextChildren;
      children = nextChildren;
    }
    return children;
  }

  getField(field: RelayQueryField): ?RelayQueryField {
    return this.getFieldByStorageKey(field.getStorageKey());
  }

  getFieldByStorageKey(storageKey: string): ?RelayQueryField {
    var fieldMap = this.__fieldMap__;
    if (!fieldMap) {
      fieldMap = {};
      var child;
      var children = this.getChildren();
      for (var ii = 0; ii < children.length; ii++) {
        child = children[ii];
        if (child instanceof RelayQueryField) {
          fieldMap[child.getStorageKey()] = child;
        }
      }
      this.__fieldMap__ = fieldMap;
    }
    return fieldMap[storageKey];
  }

  getRoute(): RelayMetaRoute {
    return this.__route__;
  }

  getVariables(): Variables {
    return this.__variables__;
  }

  hasDeferredDescendant(): boolean {
    var hasDeferredDescendant = this.__hasDeferredDescendant__;
    if (hasDeferredDescendant == null) {
      hasDeferredDescendant =
        !this.isScalar() &&
        this.getChildren().some(child => child.hasDeferredDescendant());
      this.__hasDeferredDescendant__ = hasDeferredDescendant;
    }
    return hasDeferredDescendant;
  }

  isRequisite(): boolean {
    return false;
  }

  /**
   * Determine if `this` and `that` are deeply equal.
   */
  equals(that: RelayQueryNode): boolean {
    var thisChildren = this.getChildren();
    var thatChildren = that.getChildren();

    return thisChildren === thatChildren || (
      thisChildren.length === thatChildren.length &&
      thisChildren.every((c, ii) => c.equals(thatChildren[ii]))
    );
  }

  /**
   * Performs a fast comparison of whether `this` and `that` represent identical
   * query nodes. Returns true only if the concrete nodes, routes, and variables
   * are all the same.
   *
   * Note that it is possible that this method can return false in cases where
   * `equals` would return true. This can happen when the concrete nodes are
   * different but structurally identical, or when the route/variables are
   * different but do not have an effect on the structure of the query.
   */
  isEquivalent(that: RelayQueryNode): boolean {
    return (
      this.__concreteNode__ === that.__concreteNode__ &&
      this.__route__ === that.__route__ &&
      shallowEqual(this.__variables__, that.__variables__)
    );
  }

  createNode(concreteNode: ConcreteQueryObject): RelayQueryNode {
    return RelayQueryNode.create(
      concreteNode,
      this.__route__,
      this.__variables__
    );
  }

  getConcreteQueryNode(
    onCacheMiss: () => ConcreteQueryObject
  ): ConcreteQueryObject {
    if (!this.__isConcreteNodeCached__) {
      this.__concreteNode__ = onCacheMiss();
      this.__isConcreteNodeCached__ = true;
    }
    return this.__concreteNode__;
  }
}

/**
 * @internal
 *
 * Wraps access to query root nodes.
 */
class RelayQueryRoot extends RelayQueryNode {
  __batchCall__: ?BatchCall;
  __deferredFragmentNames__: ?FragmentNames;
  __id__: ?string;

  constructor(
    concreteNode: ConcreteQueryObject,
    route: RelayMetaRoute,
    variables: Variables
  ) {
    super(concreteNode, route, variables);
    this.__batchCall__ = undefined;
    this.__deferredFragmentNames__ = undefined;
    this.__id__ = undefined;

    // Ensure IDs are generated in the order that queries are created
    this.getID();
  }

  getName(): string {
    var name = this.__concreteNode__.name;
    if (!name) {
      name = this.getID();
      this.__concreteNode__.name = name;
    }
    return name;
  }

  getID(): string {
    var id = this.__id__;
    if (id == null) {
      id = QUERY_ID_PREFIX + _nextQueryID++;
      this.__id__ = id;
    }
    return id;
  }

  getBatchCall(): ?BatchCall {
    var batchCall = this.__batchCall__;
    if (batchCall === undefined) {
      var concreteCalls = this.__concreteNode__.calls;
      var callArg = concreteCalls[0].value;
      if (GraphQL.isBatchCallVariable(callArg)) {
        batchCall = {
          refParamName: REF_PARAM_PREFIX + callArg.sourceQueryID,
          sourceQueryID: callArg.sourceQueryID,
          sourceQueryPath: callArg.jsonPath,
        };
      } else {
        batchCall = null;
      }
      this.__batchCall__ = batchCall;
    }
    return batchCall;
  }

  getRootCall(): Call {
    var calls = this.__calls__;
    if (!calls) {
      var concreteCalls = this.__concreteNode__.calls;
      calls = callsFromGraphQL(concreteCalls, this.__variables__);
      this.__calls__ = calls;
    }
    return calls[0];
  }

  getCallType(): ?string {
    if (this.__concreteNode__.calls.length > 0) {
      return this.__concreteNode__.metadata.rootCallType;
    }
  }

  getRootCallArgument(): ?string {
    return this.__concreteNode__.metadata.rootArg;
  }

  hasDeferredDescendant(): boolean {
    return this.isDeferred() || super.hasDeferredDescendant();
  }

  isDeferred(): boolean {
    return this.__concreteNode__.isDeferred;
  }

  getDeferredFragmentNames(): FragmentNames {
    var fragmentNames = this.__deferredFragmentNames__;
    if (!fragmentNames) {
      fragmentNames = {};
      getDeferredFragmentNamesForField(this, fragmentNames);
      this.__deferredFragmentNames__ = fragmentNames;
    }
    return fragmentNames;
  }

  equals(that: RelayQueryNode): boolean {
    if (this === that) {
      return true;
    }
    if (!(that instanceof RelayQueryRoot)) {
      return false;
    }
    if (!areEqual(this.getRootCall(), that.getRootCall())) {
      return false;
    }
    if (!areEqual(this.getBatchCall(), that.getBatchCall())) {
      return false;
    }
    if (this.getRootCallArgument() !== that.getRootCallArgument()) {
      return false;
    }
    return super.equals(that);
  }
}

/**
 * @internal
 *
 * Abstract base class for mutations and subscriptions.
 */
class RelayQueryOperation extends RelayQueryNode {
  __callVariableName__: string;

  constructor(
    concreteNode: ConcreteQueryObject,
    route: RelayMetaRoute,
    variables: Variables
  ) {
    super(concreteNode, route, variables);
    invariant(
      this.constructor.name !== 'RelayQueryOperation',
      'RelayQueryOperation: Abstract class cannot be instantiated.'
    );
  }

  getName(): string {
    return this.__concreteNode__.name;
  }

  getResponseType(): string {
    return this.__concreteNode__.responseType;
  }

  getInputType(): string {
    var inputType = this.__concreteNode__.metadata.inputType;
    invariant(
      inputType,
      'RelayQuery: Expected operation `%s` to be annotated with the type of ' +
      'its argument. Either the babel transform was configured incorrectly, ' +
      'or the schema failed to define an argument for this mutation.',
      this.getCall().name
    );
    return inputType;
  }

  getCall(): Call {
    var calls = this.__calls__;
    if (!calls) {
      var concreteCalls = this.__concreteNode__.calls;
      calls = callsFromGraphQL(concreteCalls, this.__variables__);
      this.__calls__ = calls;
    }
    return calls[0];
  }

  getCallVariableName(): string {
    if (!this.__callVariableName__) {
      var concreteCalls = this.__concreteNode__.calls;
      var callArg = concreteCalls[0].value;
      invariant(
        GraphQL.isCallVariable(callArg),
        'RelayQuery: Expected mutation to have a single argument.'
      );
      this.__callVariableName__ = callArg.callVariableName;
    }
    return this.__callVariableName__;
  }
}

/**
 * @internal
 *
 * Represents a GraphQL mutation.
 */
class RelayQueryMutation extends RelayQueryOperation {
  equals(that: RelayQueryNode): boolean {
    if (this === that) {
      return true;
    }
    if (!(that instanceof RelayQueryMutation)) {
      return false;
    }
    if (!areEqual(this.getResponseType(), that.getResponseType())) {
      return false;
    }
    if (!areEqual(this.getCall(), that.getCall())) {
      return false;
    }
    return super.equals(that);
  }
}

/**
 * @internal
 *
 * Represents a GraphQL subscription.
 */
class RelayQuerySubscription extends RelayQueryOperation {
  getPublishedPayloadType(): string {
    return this.getResponseType();
  }

  equals(that: RelayQueryNode): boolean {
    if (this === that) {
      return true;
    }
    if (!(that instanceof RelayQuerySubscription)) {
      return false;
    }
    if (
      !areEqual(this.getPublishedPayloadType(), that.getPublishedPayloadType())
    ) {
      return false;
    }
    if (!areEqual(this.getCall(), that.getCall())) {
      return false;
    }
    return super.equals(that);
  }
}

/**
 * @internal
 *
 * Wraps access to query fragments.
 *
 * Note: place proxy methods for `GraphQL.QueryFragment` here.
 */
class RelayQueryFragment extends RelayQueryNode {
  __fragmentID__: ?string;
  __metadata__: FragmentMetadata;

  constructor(
    concreteNode: ConcreteQueryObject,
    route: RelayMetaRoute,
    variables: Variables,
    metadata?: FragmentMetadata
  ) {
    super(concreteNode, route, variables);
    this.__fragmentID__ = null;
    this.__metadata__ = metadata || DEFAULT_FRAGMENT_METADATA;
  }

  getDebugName(): string {
    return this.__concreteNode__.name;
  }

  /**
   * Returns the weak ID for the concrete fragment. Unlike `getFragmentID`,
   * this value is identical for any `RelayQueryFragment` with the same concrete
   * fragment, regardless of params/route.
   */
  getConcreteFragmentID(): string {
    return '_RelayQueryFragment' + getWeakIdForObject(this.__concreteNode__);
  }

  /**
   * Returns an identifier for a fragment that is unique for any combination of
   * concrete fragment, route name, and variables.
   */
  getFragmentID(): string {
    var fragmentID = this.__fragmentID__;
    if (!fragmentID) {
      fragmentID = generateRQLFieldAlias(
        this.getConcreteFragmentID() + '.' +
        this.__route__.name + '.' +
        stableStringify(this.__variables__)
      );
      this.__fragmentID__ = fragmentID;
    }
    return fragmentID;
  }

  getType(): string {
    return this.__concreteNode__.type;
  }

  isDeferred(): boolean {
    return this.__metadata__.isDeferred;
  }

  isPlural(): boolean {
    return !!(
      (this.__concreteNode__.isPlural || // RQLPrinter
      this.__concreteNode__.metadata.plural) // GraphQLPrinter
    );
  }

  isReferenceFragment(): boolean {
    return this.__metadata__.isReferenceFragment;
  }

  isTypeConditional(): boolean {
    return this.__metadata__.isTypeConditional;
  }

  hasDeferredDescendant(): boolean {
    return this.isDeferred() || super.hasDeferredDescendant();
  }

  clone(children: NextChildren): ?RelayQueryNode {
    var clone = super.clone(children);
    if (clone instanceof RelayQueryFragment) {
      clone.__metadata__ = {
        ...this.__metadata__
      };
    }
    return clone;
  }

  equals(that: RelayQueryNode): boolean {
    if (this === that) {
      return true;
    }
    if (!(that instanceof RelayQueryFragment)) {
      return false;
    }
    if (this.getType() !== that.getType()) {
      return false;
    }
    return super.equals(that);
  }
}

/**
 * @internal
 *
 * Wraps access to query fields.
 *
 * Note: place proxy methods for `GraphQL.Field` here.
 */
class RelayQueryField extends RelayQueryNode {
  __isRefQueryDependency__: boolean;

  constructor(
    concreteNode: ConcreteQueryObject,
    route: RelayMetaRoute,
    variables: Variables
  ) {
    super(concreteNode, route, variables);
    this.__isRefQueryDependency__ = false;
  }

  isRequisite(): boolean {
    return this.__concreteNode__.metadata.isRequisite;
  }

  isFindable(): boolean {
    return this.__concreteNode__.metadata.isFindable;
  }

  isGenerated(): boolean {
    return this.__concreteNode__.metadata.isGenerated;
  }

  isConnection(): boolean {
    return this.__concreteNode__.metadata.isConnection;
  }

  isPlural(): boolean {
    return this.__concreteNode__.metadata.isPlural;
  }

  isRefQueryDependency(): boolean {
    return this.__isRefQueryDependency__;
  }

  isScalar(): boolean {
    return (
      (!this.__children__ || this.__children__.length === 0) &&
      this.__concreteNode__.children.length === 0
    );
  }

  isUnionOrInterface(): boolean {
    return this.__concreteNode__.metadata.isUnionOrInterface;
  }

  getParentType(): string {
    var parentType = this.__concreteNode__.metadata.parentType;
    invariant(
      parentType,
      'RelayQueryField(): Expected field `%s` to be annotated with the ' +
      'type of the parent field.',
      this.getSchemaName()
    );
    return parentType;
  }

  /**
   * The canonical name for the referenced field in the schema.
   */
  getSchemaName(): string {
    return this.__concreteNode__.fieldName;
  }

  /**
   * The name for the field when serializing the query or interpreting query
   * responses from the server. The serialization key is derived from
   * all calls/values and hashed for compactness.
   *
   * Given the graphql
   * `news_feed.first(10).orderby(TOP_STORIES)`
   *
   * the serialization key is
   * `generateRQLFieldAlias('news_feed.first(10).orderby(TOP_STORIES')`
   */
  getSerializationKey(): string {
    var serializationKey = this.__serializationKey__;
    if (!serializationKey) {
      serializationKey = this.getSchemaName();
      var calls = this.getCallsWithValues();
      for (var ii = 0; ii < calls.length; ii++) {
        serializationKey += printRelayQueryCall(calls[ii]);
      }
      serializationKey = generateRQLFieldAlias(serializationKey);
      this.__serializationKey__ = serializationKey;
    }
    return serializationKey;
  }

  /**
   * The name which Relay internals can use to reference this field, without
   * collisions. The storage key is derived from arguments with the following
   * exclusions:
   *
   *  - Range calls such as `first` or `find` on connections.
   *  - Conditionals when the field is present.
   *
   * Given the graphql
   * `news_feed.first(10).orderby(TOP_STORIES).if(true)`
   *
   * the storage key is
   * `'news_feed.orderby(TOP_STORIES)'`
   */
  getStorageKey(): string {
    var storageKey = this.__storageKey__;
    if (!storageKey) {
      var isConnection = this.isConnection();
      storageKey = this.getSchemaName();
      var calls = this.getCallsWithValues();
      for (var ii = 0; ii < calls.length; ii++) {
        var call = calls[ii];
        if (isConnection && RelayConnectionInterface.isConnectionCall(call)) {
          continue;
        } else if (
          (call.name === IF && (String(call.value) === TRUE)) ||
          (call.name === UNLESS && (String(call.value) === FALSE))
        ) {
          // `name.if(true)`, `name.unless(false)`, and `name` are all
          // equivalent fields.
          continue;
        }
        storageKey += printRelayQueryCall(call);
      }
      this.__storageKey__ = storageKey;
    }
    return storageKey;
  }

  /**
   * The name by which this field's results should be made available to the
   * application.
   */
  getApplicationName(): string {
    return this.__concreteNode__.alias || this.__concreteNode__.fieldName;
  }

  getInferredRootCallName(): ?string {
    return this.__concreteNode__.metadata.inferredRootCallName;
  }

  getInferredPrimaryKey(): ?string {
    return this.__concreteNode__.metadata.inferredPrimaryKey;
  }

  getCallsWithValues(): Array<Call> {
    var calls = this.__calls__;
    if (!calls) {
      var concreteCalls = this.__concreteNode__.calls;
      calls = callsFromGraphQL(concreteCalls, this.__variables__);
      this.__calls__ = calls;
    }
    return calls;
  }

  getCallType(callName: string): ?string {
    var concreteCall = this.__concreteNode__.calls.filter(
      call => call.name === callName
    )[0];
    if (concreteCall) {
      return concreteCall.metadata.type;
    }
  }

  equals(that: RelayQueryNode): boolean {
    if (this === that) {
      return true;
    }
    if (!(that instanceof RelayQueryField)) {
      return false;
    }
    if (
      this.getSchemaName() !== that.getSchemaName() ||
      this.getApplicationName() !== that.getApplicationName() ||
      !areEqual(this.getCallsWithValues(), that.getCallsWithValues())
    ) {
      return false;
    }
    return super.equals(that);
  }

  cloneAsRefQueryDependency(): RelayQueryField {
    var field = new RelayQueryField(
      this.__concreteNode__,
      this.__route__,
      this.__variables__
    );
    field.__children__ = [];
    field.__isRefQueryDependency__ = true;
    return field;
  }

  cloneFieldWithCalls(
    children: NextChildren,
    calls: Array<Call>
  ): ?RelayQueryField {
    if (this.isScalar()) {
      // Compact new children *after* this check, for consistency.
      invariant(
        children.length === 0,
        'RelayQueryField: Cannot add children to scalar fields.'
      );
    }

    // use `clone()` if call values do not change
    if (areEqual(this.getCallsWithValues(), calls)) {
      var clone: RelayQueryField = (this.clone(children): any);
      return clone;
    }

    var nextChildren = cloneChildren(this.getChildren(), children);
    if (!nextChildren.length) {
      return null;
    }

    var field = new RelayQueryField(
      this.__concreteNode__,
      this.__route__,
      this.__variables__
    );
    field.__children__ = nextChildren;
    field.__calls__ = calls;

    return field;
  }
}

function createNode(
  concreteNode: ConcreteQueryObject,
  route: RelayMetaRoute,
  variables: Variables
): ?RelayQueryNode {
  // unused default value keeps flow happy
  var type = RelayQueryNode;
  if (GraphQL.isField(concreteNode)) {
    type = RelayQueryField;
  } else if (GraphQL.isFragment(concreteNode)) {
    type = RelayQueryFragment;
  } else if (GraphQL.isQuery(concreteNode)) {
    type = RelayQueryRoot;
  } else if (GraphQL.isQueryWithValues(concreteNode)) {
    concreteNode = (concreteNode: $FlowIssue).query;
    type = RelayQueryRoot;
  } else if (GraphQL.isMutation(concreteNode)) {
    type = RelayQueryMutation;
  } else if (GraphQL.isSubscription(concreteNode)) {
    type = RelayQuerySubscription;
  } else if (concreteNode instanceof RelayRouteFragment) {
    var routeFragment = concreteNode.getFragmentForRoute(route);
    if (routeFragment) {
      // may be null if no value was defined for this route.
      return createNode(
        routeFragment,
        route,
        variables
      );
    }
    return null;
  } else if (concreteNode instanceof RelayFragmentReference) {
    var fragment = concreteNode.getFragment(variables);
    var fragmentVariables = concreteNode.getVariables(route, variables);
    if (fragment) {
      // the fragment may be null when `if` or `unless` conditions are not met.
      invariant(
        GraphQL.isFragment(fragment),
        'RelayQuery: Invalid fragment reference, expected query fragment.'
      );
      return createMemoizedFragment(
        fragment,
        route,
        fragmentVariables,
        {
          isDeferred: concreteNode.isDeferred(),
          isReferenceFragment: true,
          isTypeConditional: concreteNode.isTypeConditional(),
        }
      );
    }
    return null;
  } else {
    invariant(false, 'RelayQueryNode: Invalid concrete node.');
  }
  return new type(
    concreteNode,
    route,
    variables
  );
}

/**
 * Memoizes the `RelayQueryFragment` equivalent of a given `GraphQL` fragment
 * for the given route, variables, and deferred status.
 */
function createMemoizedFragment(
  concreteFragment: GraphQL.QueryFragment,
  route: RelayMetaRoute,
  variables: Variables,
  metadata: FragmentMetadata
): RelayQueryFragment {
  var cacheKey = route.name + ':' + stableStringify(variables) + ':' +
    stableStringify(metadata);
  var fragment = concreteFragment.__cachedFragment__;
  var fragmentCacheKey = concreteFragment.__cacheKey__;
  if (!fragment || fragmentCacheKey !== cacheKey) {
    fragment = new RelayQueryFragment(
      concreteFragment,
      route,
      variables,
      metadata
    );
    concreteFragment.__cachedFragment__ = fragment;
    concreteFragment.__cacheKey__ = cacheKey;
  }
  return fragment;
}

/**
 * Compacts new children and compares them to the previous children.
 * - If all items are equal, returns previous array
 * - If any items differ, returns new array
 */
function cloneChildren(
  prevChildren: Array<RelayQueryNode>,
  nextChildren: NextChildren
): Array<RelayQueryNode> {
  var children = [];
  var isSameChildren = true;

  var prevIndex = 0;
  for (var ii = 0; ii < nextChildren.length; ii++) {
    var child = nextChildren[ii];
    if (child) {
      children.push(child);
      isSameChildren = isSameChildren && child === prevChildren[prevIndex++];
    }
  }

  if (isSameChildren && children.length === prevChildren.length) {
    return prevChildren;
  } else {
    return children;
  }
}

/**
 * Returns the names of the deferred fragments in the query. Does not return
 * nested deferred fragment names.
 */
function getDeferredFragmentNamesForField(
  node: RelayQueryNode,
  fragmentNames: FragmentNames
): void {
  if (node instanceof RelayQueryFragment && node.isDeferred()) {
    var fragmentID = node.getFragmentID();
    fragmentNames[fragmentID] = fragmentID;
    return;
  }
  node.getChildren().forEach(
    child => getDeferredFragmentNamesForField(child, fragmentNames)
  );
}

module.exports = {
  Field: RelayQueryField,
  Fragment: RelayQueryFragment,
  Mutation: RelayQueryMutation,
  Node: RelayQueryNode,
  Operation: RelayQueryOperation,
  Root: RelayQueryRoot,
  Subscription: RelayQuerySubscription,
};


text:
<!DOCTYPE html>

    <title>Mad Libs</title>

Noun: <input type="text" name="noun1-input" id="noun1-input">

Adjective: <input type="text" name="adj1-input" id="adj1-input">

      <button id="fillButton" onclick="fill()">Fill</button>

On his 11th birthday, Harry Potter found out that he was a .  things had been happening to him his entire life and now he knew why.

redpajama_set_name: RedPajamaGithub


text:
require "spec_helper"
require "json-pointer"

describe JsonPointer do
  let(:hash) do
    {
      :water => ["river", "lake", "ocean", "pond", "everything else"],
      :fire => {
        :water => {
          :wind => "earth"
        },
        :dirt => [
          { :foo => "bar", :hello => "world" },
          { :baz => "biz" }
        ]
      }
    }
  end

  let(:path) { "" }
  let(:path_fragments) { path.split('/') }
  let(:pointer) { described_class.new(hash, path, :symbolize_keys => true) }
  let(:parent_pointer) {
    described_class.new(hash, path_fragments[0..-2].join('/'), :symbolize_keys => true)
  }
  let(:expected_parent_value) {}

  describe "#exists?" do
    shared_examples "a checker method" do
      context "when member exists" do
        it "returns true" do
          expect(pointer.exists?).to be_true
        end
      end

      context "when member exists and is nil" do
        it "returns true" do
          pointer.value = nil
          expect(pointer.exists?).to be_true
        end
      end

      context "when member doesn't exist" do
        let(:hash) { Hash.new }

        it "returns false" do
          expect(pointer.exists?).to be_false
          expect(hash).to eq(Hash.new)
        end
      end
    end

    context "when array index" do
      let(:path) { %(/water/2) }

      it_behaves_like "a checker method"
    end

    context "when in member of array index" do
      let(:path) { %(/fire/dirt/0/hello) }

      it_behaves_like "a checker method"
    end

    context "when wildcard array index" do
      let(:path) { %(/water/~) }

      context "when any member exists" do
        it "returns true" do
          expect(pointer.exists?).to be_true
        end
      end

      context "when no members exist" do
        it "returns false" do
          array_pointer = described_class.new(hash, %(/water), :symbolize_keys => true)
          array_pointer.value = []
          expect(pointer.exists?).to be_false
        end
      end
    end

    context "when in member of array wildcard" do
      context "when any matching member exists" do
        let(:path) { %(/fire/dirt/~/hello) }

        it "returns true" do
          expect(pointer.exists?).to be_true
        end
      end

      context "when no matching members" do
        let(:path) { %(/fire/dirt/~/fictitious) }

        it "returns false" do
          expect(pointer.exists?).to be_false
        end
      end
    end

    context "when object member" do
      let(:path) { %(/fire/water/wind) }

      it_behaves_like "a checker method"

      context "when not existant" do
        let(:path) { %(/foo) }

        it "returns false" do
          expect(pointer.exists?).to be_false
        end
      end
    end
  end

  describe "#value" do
    shared_examples "a getter method" do
      context "when member exists" do
        it "returns value of referenced member" do
          expect(pointer.value).to eql(expected_value)
        end
      end

      context "when member doesn't exist" do
        let(:hash) { Hash.new }

        it "returns nil" do
          expect(pointer.value).to be_nil
        end
      end
    end

    context "when array index" do
      let(:path) { %(/water/2) }
      let(:expected_value) { hash[:water][2] }

      it_behaves_like "a getter method"
    end

    context "when in member of array index" do
      let(:path) { %(/fire/dirt/0/hello) }
      let(:expected_value) { hash[:fire][:dirt][0][:hello] }

      it_behaves_like "a getter method"
    end

    context "when array wildcard" do
      let(:path) { %(/fire/dirt/~) }
      let(:expected_value) { hash[:fire][:dirt] }

      it_behaves_like "a getter method"
    end

    context "when in member of array wildcard" do
      let(:path) { %(/fire/dirt/~/hello) }
      let(:expected_value) { ["world", nil] }

      it_behaves_like "a getter method"
    end

    context "when object member" do
      let(:path) { %(/fire/water/wind) }
      let(:expected_value) { hash[:fire][:water][:wind] }

      it_behaves_like "a getter method"
    end
  end

  describe "#value=" do
    let(:asymmetric) { false }

    shared_examples "a setter method" do
      context "when parent member exists" do
        it "sets referenced member value" do
          pointer.value = value

          unless asymmetric
            expect(pointer.value).to eql(value)
          end

          if expected_parent_value
            expect(parent_pointer.value).to eql(expected_parent_value)
          end
        end
      end

      context "when parent member doesn't exist" do
        let(:hash) { Hash.new }

        it "sets referenced member value" do
          pointer.value = value
          expect(pointer.value).to eql(value)
        end
      end
    end

    context "when array index" do
      let(:path) { %(/water/2) }
      let(:value) { "swamp" }
      let(:expected_parent_value) { ["river", "lake", value, "ocean", "pond", "everything else"] }

      it_behaves_like "a setter method"

      context "when appending to array" do
        let(:path) { %(/water/-) }
        let(:expected_parent_value) { ["river", "lake", "ocean", "pond", "everything else", value] }
      end

      context "when array doesn't exist" do
        let(:path) { %(/water/-) }
        let(:hash) { Hash.new }
        let(:expected_parent_value) { [value] }

        it_behaves_like "a setter method"
      end
    end

    context "when in member of array index" do
      let(:path) { %(/fire/dirt/0/biz) }
      let(:value) { "baz" }
      let(:expected_parent_value) { { :foo => "bar", :hello => "world", :biz => value } }

      it_behaves_like "a setter method"
    end

    context "when array wildcard" do
      let(:path) { %(/water/~) }
      let(:value) { "baz" }
      let(:asymmetric) { true }
      let(:expected_parent_value) { hash[:water].concat([value]) }

      it_behaves_like "a setter method"
    end

    context "when in member of array wildcard" do
      let(:path) { %(/fire/dirt/~/gash) }
      let(:value) { "very deep!" }
      let(:asymmetric) { true }
      let(:expected_parent_value) {
        [
          { :foo => "bar", :hello => "world" },
          { :baz => "biz" },
          { :gash => value }
        ]
      }

      context "when parent member exists" do
        it "sets referenced member value" do
          pointer.value = value

          unless asymmetric
            expect(pointer.value).to eql(value)
          end

          if expected_parent_value
            expect(parent_pointer.value).to eql(expected_parent_value)
          end
        end
      end
    end

    context "when object member" do
      let(:path) { %(fire/water/foo) }
      let(:value) { "Foo Bar!" }

      it_behaves_like "a setter method"
    end
  end

  describe "#delete" do
    let(:asymmetric) { false }

    shared_examples "a delete method" do
      context "when parent member exists" do
        it "deletes referenced member" do
          pointer.delete

          unless asymmetric
            expect(pointer.value).to be_nil
          end

          if expected_parent_value
            expect(parent_pointer.value).to eql(expected_parent_value)
          end
        end
      end

      context "when parent member doesn't exist" do
        let(:hash) { Hash.new }

        it "does nothing" do
          pointer.delete
          expect(pointer.value).to be_nil
        end
      end
    end

    context "when array index" do
      let(:path) { %(/water/2) }
      let(:asymmetric) { true }
      let(:expected_parent_value) { ["river", "lake", "pond", "everything else"] }

      it_behaves_like "a delete method"
    end

    context "when in member of array index" do
      let(:path) { %(/fire/dirt/0/foo) }
      let(:expected_parent_value) { { :hello => "world" } }

      it_behaves_like "a delete method"
    end

    context "when array wildcard" do
      let(:path) { %(/water/~) }
      let(:asymmetric) { true }
      let(:expected_parent_value) { [] }

      it_behaves_like "a delete method"
    end

    context "when in member of array wildcard" do
      let(:path) { %(/fire/dirt/~/foo) }
      let(:asymmetric) { true }
      let(:expected_parent_value) {
        [
          { :hello => "world" },
          { :baz => "biz" }
        ]
      }

      it_behaves_like "a delete method"
    end

    context "when object member" do
      let(:path) { %(fire/water/foo) }

      it_behaves_like "a delete method"
    end
  end
end


text:
<?php

class ReportsController extends AppController {

	function index() {
		HTML::Redirect('reports', 'search');
	}

	function latest() {
		Model::Load('report');
		Model::Load('user');

		$this->pageTitle = 'Latest Reports';
		$this->setData('selectednavi', $ref = 'Latest');
		$this->includeJavascript('js/searchforms.js');

		// Validated page.
		V::Set($_GET['page'], $_GET['page'], 'posinteger', 1);
		V::Set($_GET['sortcol'], $_GET['sortcol'], 'table:reports', 'reporttime');
		V::Set($_GET['sortdir'], $_GET['sortdir'], 'sortdir', preg_match('/^(reporttime|errors)$/', $_GET['sortcol']) ? 'desc' : 'asc');
		V::Set($_GET['filters'], $_GET['filters'], 'array', array());

		// Remove a filter.
		if (isset($_GET['removefilter'])) {
			if (V::Check('latestsearch', $_GET['filters'][intval($_GET['removefilter'])])) {
				$parts = explode('-', $_GET['filters'][intval($_GET['removefilter'])]);
				$this->setData('initialSearchValues', $tmp = array(
					'column' => $parts[0],
					'flag' => $parts[1],
					'text' => $parts[2]
				));
			}
			unset($_GET['filters'][intval($_GET['removefilter'])]);
			unset($_GET['removefilter']);
		}

		// Add a new search filter.
		if (isset($_GET['search']) && is_array($_GET['search'])) {
			array_push($_GET['filters'], $_GET['search']['field'] . '-' . $_GET['search']['filter'] . '-' . $_GET['search']['text']);
			unset($_GET['search']);
		}

		// Validate the filters and reformat for mReport::Search().
		$searchFilters = array();
		foreach ($_GET['filters'] as $key => $filter) {
			if (V::Check('latestsearch', $filter)) {
				$parts = explode('-', $filter, 3);
				array_push($searchFilters, array(
					'column' => $parts[0],
					'flag' => $parts[1],
					'text' => $parts[2]
				));
			}
			else {
				// Removed invalid filters.
				unset($_GET['filters'][$key]);
			}
		}

		// Clean up the indexes for the filters, in case some where removed.
		$_GET['filters'] = array_values($_GET['filters']);

		$this->setData('latest', $latest =& mReport::Search(array(
			'latest' => true,
			'filters' => $searchFilters,
			'userid' => AC::InGroup('admin') || AC::InGroup('viewall_reports') ? null : AC::GetLoggedInUser(),
			'page' => intval($_GET['page']),
			'limit' => 50,
			'order' => array(
				array('column' => $_GET['sortcol'], 'direction' => $_GET['sortdir']),
				array('column' => 'clientid', 'direction' => 'asc'),
				array('column' => 'job', 'direction' => 'asc')
			)
		)));

		if (is_string($latest)) {
			Controller::ShowError('db_error', array('errorin' => 'reports/latest', 'errormessage' => $latest));
		}
	}

	function search() {

		$this->setData('selectednavi', $ref = 'Reports');
		$this->includeJavascript('js/searchforms.js');
		$this->includeJavascript('js/jquery.button.js');
		$this->includeCSS('css/buttons.css');

		// Validated page.
		V::Set($_GET['page'], $_GET['page'], 'posinteger', 1);
		V::Set($_GET['sortcol'], $_GET['sortcol'], 'table:reports', 'reporttime');
		V::Set($_GET['sortdir'], $_GET['sortdir'], 'sortdir', preg_match('/^(reporttime|duration|uploadsize|changedfiles|errors)$/', $_GET['sortcol']) ? 'desc' : 'asc');
		V::Set($_GET['filters'], $_GET['filters'], 'stringarray', array());
		V::Set($_GET['purge'], $_GET['purge'], 'table:clients:clientid', null);

		// Remove a filter.
		if (isset($_GET['removefilter'])) {
			if (V::Check('reportssearch', $_GET['filters'][intval($_GET['removefilter'])])) {
				$parts = explode('-', $_GET['filters'][intval($_GET['removefilter'])]);
				$this->setData('initialSearchValues', $tmp = array(
					'column' => $parts[0],
					'flag' => $parts[1],
					'text' => $parts[2]
				));
			}
			unset($_GET['filters'][intval($_GET['removefilter'])]);
			unset($_GET['removefilter']);
		}

		// Add a new search filter.
		if (isset($_GET['search']) && is_array($_GET['search'])) {
			array_push($_GET['filters'], $_GET['search']['field'] . '-' . $_GET['search']['filter'] . '-' . $_GET['search']['text']);
			unset($_GET['search']);
		}

		// Validate the filters and reformat for mReport::Search().
		$searchFilters = array();
		$foundPurge = FALSE;
		foreach ($_GET['filters'] as $key => $filter) {
			if (V::Check('reportssearch', $filter)) {
				$parts = explode('-', $filter, 3);
				array_push($searchFilters, array(
					'column' => $parts[0],
					'flag' => $parts[1],
					'text' => $parts[2]
				));
			}
			else {
				// Removed invalid filters.
				unset($_GET['filters'][$key]);
			}
		}

		if (!is_null($_GET['purge'])) {

			$this->pageTitle = 'Purge Reports for ' . $_GET['purge'];

			// Add an additional filter if purge is specified.
			array_push($searchFilters, array(
				'column' => 'clientid',
				'flag' => 'x',
				'text' => $_GET['purge']
			));
		}

		// Clean up the filter indexes (in case some were removed) and remove duplicates.
		$_GET['filters'] = array_keys(array_flip($_GET['filters']));

		$this->setData('results', $results =& mReport::Search(array(
			'filters' => $searchFilters,
			'userid' => AC::InGroup('admin') || AC::InGroup('viewall_reports') ? null : AC::GetLoggedInUser(),
			'page' => intval($_GET['page']),
			'limit' => 50,
			'order' => array(
				array('column' => $_GET['sortcol'], 'direction' => $_GET['sortdir']),
				array('column' => 'clientid', 'direction' => 'asc'),
				array('column' => 'job', 'direction' => 'asc')
			)
		)));

		if (is_string($results)) {
			Controller::ShowError('db_error', array('errorin' => 'reports/search', 'errormessage' => $results));
		}
	}

	function purge($clientid = NULL) {
		if (!V::Check('table:clients:clientid', $clientid)) {
			Controller::ShowError('missing_arguments', array('value' => $clientid, 'variable' => 'clientid'));
		}

		V::Set($_GET['filters'], $_GET['filters'], 'array', array());
		V::Set($_GET['verify'], $_GET['verify'], 'boolean');
		$this->setData('clientid', $clientid);

		$this->pageTitle = 'Purge Reports';

		// Validate the filters and reformat for mReport::Purge().
		$searchFilters = array();
		foreach ($_GET['filters'] as $key => $filter) {
			if (V::Check('reportssearch', $filter)) {
				$parts = explode('-', $filter, 3);
				array_push($searchFilters, array(
					'column' => $parts[0],
					'flag' => $parts[1],
					'text' => $parts[2]
				));
			}
		}

		if (isset($_GET['verify']) && $_GET['verify'] == '1') {
			$result = mReport::Purge($clientid, $searchFilters, AC::InGroup('admin') || AC::InGroup('viewall_reports') ? null : AC::GetLoggedInUser());

			if (is_string($result)) {
				Controller::ShowError('db_error', array('errorin' => 'reports/purge', 'errormessage' => $result));
			}

			HTML::Redirect('clients', 'show', array($clientid));
		}
	}

	function show($clientid = NULL, $job = NULL, $reporttime = NULL) {

		Model::Load('item');
		$this->pageTitle = 'Report Detail';

		$this->setData('selectednavi', $ref = 'Reports');
		$this->includeJavascript('js/searchforms.js');

		// Validated page.
		V::Set($_GET['page'], $_GET['page'], 'posinteger', 1);
		V::Set($_GET['sortcol'], $_GET['sortcol'], 'table:items', 'logorder');
		V::Set($_GET['sortdir'], $_GET['sortdir'], 'sortdir', preg_match('/^(duration|size2)$/', $_GET['sortcol']) ? 'desc' : 'asc');
		V::Set($_GET['filters'], $_GET['filters'], 'array', array());

		// Validate arguments.
		if (($msg = V::Check('table:clients:clientid', $clientid, TRUE)) !== TRUE) {
			Controller::ShowError('invalid_value', array('value' => $clientid, 'variable' => 'first argument', 'message' => $msg));
		}
		if (($msg = V::Check('table:reports:job', $job, TRUE)) !== TRUE) {
			Controller::ShowError('invalid_value', array('value' => $job, 'variable' => 'second argument', 'message' => $msg));
		}
		if (($msg = V::Check('table:reports:reporttime', $reporttime, TRUE)) !== TRUE) {
			Controller::ShowError('invalid_value', array('value' => $reporttime, 'variable' => 'third argument', 'message' => $msg));
		}

		// Remove a filter.
		if (isset($_GET['removefilter'])) {
			if (V::Check('itemssearch', $_GET['filters'][intval($_GET['removefilter'])])) {
				$parts = explode('-', $_GET['filters'][intval($_GET['removefilter'])]);
				$this->setData('initialSearchValues', $tmp = array(
					'column' => $parts[0],
					'flag' => $parts[1],
					'text' => $parts[2]
				));
			}
			unset($_GET['filters'][intval($_GET['removefilter'])]);
			unset($_GET['removefilter']);
		}

		// Add a new search filter.
		if (isset($_GET['search']) && is_array($_GET['search'])) {
			array_push($_GET['filters'], $_GET['search']['field'] . '-' . $_GET['search']['filter'] . '-' . $_GET['search']['text']);
			unset($_GET['search']);
		}

		// Validate the filters and reformat for mItem::Search().
		$searchFilters = array();
		foreach ($_GET['filters'] as $key => $filter) {
			if (V::Check('itemssearch', $filter)) {
				$parts = explode('-', $filter, 3);
				array_push($searchFilters, array(
					'column' => $parts[0],
					'flag' => $parts[1],
					'text' => $parts[2]
				));
			}
			else {
				// Removed invalid filters.
				unset($_GET['filters'][$key]);
			}
		}

		// Clean up the indexes for the filters, in case some where removed.
		$_GET['filters'] = array_values($_GET['filters']);

		$this->setData('report', $report =& mReport::Search(array(
			'filters' => array(
				array('column' => 'clientid', 'flag' => 'x', 'text' => $clientid),
				array('column' => 'job', 'flag' => 'x', 'text' => $job),
				array('column' => 'reporttime', 'flag' => 'x', 'text' => $reporttime)
			),
			'userid' => AC::InGroup('admin') || AC::InGroup('viewall_reports') ? null : AC::GetLoggedInUser()
			)));

		if (is_string($report)) {
			Controller::ShowError('db_error', array('errorin' => 'reports/search', 'errormessage' => $report));
		}
		elseif (count($report) > 0) {
			$this->setData('items', $items =& mItem::Search(array(
				'filters' => array_merge($searchFilters, array(
					array('column' => 'clientid', 'flag' => 'x', 'text' => $clientid),
					array('column' => 'job', 'flag' => 'x', 'text' => $job),
					array('column' => 'reporttime', 'flag' => 'x', 'text' => $reporttime)
				)),
				'page' => intval($_GET['page']),
				'limit' => 100,
				'order' =>
					$_GET['sortcol'] == 'path1' ? array(
						array('column' => 'path1', 'direction' => $_GET['sortdir']),
						array('column' => 'path2', 'direction' => $_GET['sortdir']),
						array('column' => 'path3', 'direction' => $_GET['sortdir']),
						array('column' => 'logorder', 'direction' => 'asc')
					) :
					array(
						array('column' => $_GET['sortcol'], 'direction' => $_GET['sortdir']),
						array('column' => 'logorder', 'direction' => 'asc')
					)
			)));

			if (is_string($items)) {
				Controller::ShowError('db_error', array('errorin' => 'reports/search', 'errormessage' => $items));
			}

		}
	}

}
?>


text:
@interface RotatedAngleView ()
/// 默认旋转值
@property (nonatomic,assign) CGAffineTransform defaultTransform;
@end

@implementation RotatedAngleView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.defaultTransform = self.transform;
    }
    return self;
}

- (void)roateAngle:(CGFloat)angle duration:(CGFloat)duration{
    [UIView animateWithDuration:duration animations:^{
        self.transform = CGAffineTransformRotate(self.defaultTransform, RADIAN(angle));
    }];
}

/// 旋转角度
- (void)roateAngle:(CGFloat)angle{
    self.transform = CGAffineTransformRotate(_defaultTransform, RADIAN(angle));
}
/// 恢复动画的效果
- (void)recoverDuration:(CGFloat)duration{
    [UIView animateWithDuration:duration animations:^{
        self.transform = CGAffineTransformRotate(self.defaultTransform, 0);
    }];
}

@end


text:
#include "dsp/channel_converter.h"

#include <vector>

#include "third_party/googletest/googletest/include/gtest/gtest.h"
#include "base/constants_and_types.h"

namespace vraudio {

namespace {

// Number of frames for test buffers.
const size_t kNumFrames = 5;

// Tests that the correct stereo output buffer is obtained from the converter
// given an arbitrary mono input buffer.
TEST(ChannelConverterTest, ConvertStereoFromMonoTest) {
  const std::vector<std::vector<float>> kMonoInput = {
      {1.0f, 2.0f, 3.0f, 4.0f, 5.0f}};
  const std::vector<std::vector<float>> kExpectedStereoOutput = {
      {0.707107f, 1.414214f, 2.121320f, 2.828427f, 3.535534f},
      {0.707107f, 1.414214f, 2.121320f, 2.828427f, 3.535534f}};

  // Initialize the test buffers.
  AudioBuffer mono_input(kNumMonoChannels, kNumFrames);
  mono_input = kMonoInput;
  AudioBuffer stereo_output(kNumStereoChannels, kNumFrames);
  // Process the input buffer.
  ConvertStereoFromMono(mono_input, &stereo_output);
  // Compare the output buffer against the expected output.
  for (size_t channel = 0; channel < kNumStereoChannels; ++channel) {
    for (size_t frame = 0; frame < kNumFrames; ++frame) {
      EXPECT_NEAR(stereo_output[channel][frame],
                  kExpectedStereoOutput[channel][frame], kEpsilonFloat);
    }
  }
}

// Tests that the correct mono output buffer is obtained from the converter
// given an arbitrary stereo input buffer.
TEST(ChannelConverterTest, ConvertMonoFromStereoTest) {
  const std::vector<std::vector<float>> kStereoInput = {
      {0.707107f, 1.414214f, 2.121320f, 2.828427f, 3.535534f},
      {0.707107f, 1.414214f, 2.121320f, 2.828427f, 3.535534f}};

  const std::vector<std::vector<float>> kExpectedMonoOutput = {
      {1.0f, 2.0f, 3.0f, 4.0f, 5.0f}};

  // Initialize the test buffers.
  AudioBuffer stereo_input(kNumStereoChannels, kNumFrames);
  stereo_input = kStereoInput;
  AudioBuffer mono_output(kNumMonoChannels, kNumFrames);
  // Process the input buffer.
  ConvertMonoFromStereo(stereo_input, &mono_output);
  // Compare the output buffer against the expected output.
  for (size_t frame = 0; frame < kNumFrames; ++frame) {
    EXPECT_NEAR(mono_output[0][frame], kExpectedMonoOutput[0][frame],
                kEpsilonFloat);
  }
}

}  // namespace

}  // namespace vraudio


text:
<?xml version="1.0" encoding="UTF-8"?>
<module codename="org.netbeans.modules.spellchecker.bindings.properties">
    <module_version install_time="1370464698308" last="true" origin="installer" specification_version="1.12.1">
        <file crc="1082921001" name="config/Modules/org-netbeans-modules-spellchecker-bindings-properties.xml"/>
        <file crc="1334823774" name="modules/locale/org-netbeans-modules-spellchecker-bindings-properties_ja.jar"/>
        <file crc="2930118869" name="modules/locale/org-netbeans-modules-spellchecker-bindings-properties_pt_BR.jar"/>
        <file crc="3809572238" name="modules/locale/org-netbeans-modules-spellchecker-bindings-properties_ru.jar"/>
        <file crc="2479333813" name="modules/locale/org-netbeans-modules-spellchecker-bindings-properties_zh_CN.jar"/>
        <file crc="3910707030" name="modules/org-netbeans-modules-spellchecker-bindings-properties.jar"/>
    </module_version>
</module>


text:
package com.nordnetab.chcp.main.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Nikolay Demyankov on 21.07.15.
 * <p/>
 * Helper class to work with file system.
 */
public class FilesUtility {

    /**
     * Delete object at the given location.
     * If it is a folder - it will be deleted recursively will all content.
     *
     * @param pathToFileOrDirectory absolute path to the file/directory.
     */
    public static void delete(String pathToFileOrDirectory) {
        delete(new File(pathToFileOrDirectory));
    }

    /**
     * Delete file object.
     * If it is a folder - it will be deleted recursively will all content.
     *
     * @param fileOrDirectory file/directory to delete
     */
    public static void delete(File fileOrDirectory) {
        if (!fileOrDirectory.exists()) {
            return;
        }

        if (fileOrDirectory.isDirectory()) {
            File[] filesList = fileOrDirectory.listFiles();
            for (File child : filesList) {
                delete(child);
            }
        }

        final File to = new File(fileOrDirectory.getAbsolutePath() + System.currentTimeMillis());
        fileOrDirectory.renameTo(to);
        to.delete();

        //fileOrDirectory.delete();
    }

    /**
     * Check if folder exists at the given path.
     * If not - it will be created with with all subdirectories.
     *
     * @param dirPath absolute path to the directory
     */
    public static void ensureDirectoryExists(String dirPath) {
        ensureDirectoryExists(new File(dirPath));
    }

    /**
     * Check if folder exists.
     * If not - it will be created with with all subdirectories.
     *
     * @param dir file object
     */
    public static void ensureDirectoryExists(File dir) {
        if (dir != null && (!dir.exists() || !dir.isDirectory())) {
            dir.mkdirs();
        }
    }

    /**
     * Copy object from one place to another.
     * Can be used to copy file to file, or folder to folder.
     *
     * @param src absolute path to source object
     * @param dst absolute path to destination object
     * @throws IOException
     */
    public static void copy(String src, String dst) throws IOException {
        copy(new File(src), new File(dst));
    }

    /**
     * Copy file object from one place to another.
     * Can be used to copy file to file, or folder to folder.
     *
     * @param src source file
     * @param dst destination file
     * @throws IOException
     */
    public static void copy(File src, File dst) throws IOException {
        if (src.isDirectory()) {
            ensureDirectoryExists(dst);

            String[] filesList = src.list();
            for (String file : filesList) {
                File srcFile = new File(src, file);
                File destFile = new File(dst, file);

                copy(srcFile, destFile);
            }
        } else {
            copyFile(src, dst);
        }
    }

    private static void copyFile(File fromFile, File toFile) throws IOException {
        InputStream in = new BufferedInputStream(new FileInputStream(fromFile));
        OutputStream out = new BufferedOutputStream(new FileOutputStream(toFile));

        // Transfer bytes from in to out
        byte[] buf = new byte[8192];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        in.close();
        out.close();
    }

    /**
     * Read data as string from the provided file.
     *
     * @param filePath absolute path to the file
     * @return data from file
     * @throws IOException
     */
    public static String readFromFile(String filePath) throws IOException {
        return readFromFile(new File(filePath));
    }

    /**
     * Read data as string from the provided file.
     *
     * @param file file to read from
     * @return data from file
     * @throws IOException
     */
    public static String readFromFile(File file) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

        StringBuilder content = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line).append("\n");
        }

        bufferedReader.close();

        return content.toString().trim();
    }

    /**
     * Save string into the file
     *
     * @param content  data to store
     * @param filePath absolute path to file
     * @throws IOException
     */
    public static void writeToFile(String content, String filePath) throws IOException {
        writeToFile(content, new File(filePath));
    }

    /**
     * Save string into the file
     *
     * @param content data to store
     * @param dstFile where to save
     * @throws IOException
     */
    public static void writeToFile(String content, File dstFile) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(dstFile, false));

        bufferedWriter.write(content);

        bufferedWriter.close();
    }

    /**
     * Calculate MD5 hash of the file at the given path
     *
     * @param filePath absolute path to the file
     * @return calculated hash
     * @throws Exception
     * @see MD5
     */
    public static String calculateFileHash(String filePath) throws Exception {
        return calculateFileHash(new File(filePath));
    }

    /**
     * Calculate MD5 hash of the file
     *
     * @param file file whose hash we need
     * @return calculated hash
     * @throws Exception
     * @see MD5
     */
    public static String calculateFileHash(File file) throws Exception {
        MD5 md5 = new MD5();
        InputStream in = new BufferedInputStream(new FileInputStream(file));

        int len;
        byte[] buff = new byte[8192];
        while ((len = in.read(buff)) > 0) {
            md5.write(buff, len);
        }

        return md5.calculateHash();
    }
}


text:
import axios from 'axios'
import * as Qs from 'querystring'
import * as fs from 'fs'
import moment from 'moment'

export function AuthUrl(client_id: string, scope: string) {
    const open = [
        "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?",
        `client_id=${client_id}&`,
        `scope=${encodeURIComponent(scope)}&`,
        "response_type=code&",
        `redirect_uri=${encodeURIComponent(redirect_uri)}`,
    ].join('')
    console.log('open', open)
    return open
}

export interface Info {
    access_token: string
    refresh_token: string
    expires_in: number
    expires_at: number
    client_id: string
    client_secret: string
}

const INFO_PATH = process.env['HOME'] + '/.odInfo.json'
const redirect_uri = 'http://localhost:44321'

export async function exToken(code: string, client_id: string, client_secret: string) {
    const params = {
        code, client_secret, client_id, redirect_uri,
        grant_type: 'authorization_code',
    }
    const resp = await axios.post<Info>('https://login.microsoftonline.com/common/oauth2/v2.0/token', Qs.stringify(params))
    resp.data.client_id = client_id
    resp.data.client_secret = client_secret
    resp.data.expires_at = resp.data.expires_in + moment().unix()
    console.log(resp.data, INFO_PATH)
    fs.writeFile(INFO_PATH, JSON.stringify(resp.data), err => err)
    return resp.data
}

export async function getToken() {
    const bf: Buffer = fs.readFileSync(INFO_PATH)
    const info: Info = JSON.parse(bf.toString())
    if (info.expires_at > moment().unix()) {
        return info
    }
    const params = {
        client_id: info.client_id,
        client_secret: info.client_secret,
        grant_type: 'refresh_token',
        redirect_uri: redirect_uri,
        refresh_token: info.refresh_token,
    }
    const resp = await axios.post<Info>('https://login.microsoftonline.com/common/oauth2/v2.0/token', Qs.stringify(params))
    resp.data.expires_at = resp.data.expires_in + moment().unix()
    Object.assign(info, resp.data)
    fs.writeFile(INFO_PATH, JSON.stringify(info), err => err)
    return info
}

export function fsStat(path: string): Promise<fs.Stats | undefined> {
    return new Promise<fs.Stats>((res, rej) => {
        fs.access(path, (err) => {
            if (err) {
                return res()
            }
            fs.stat(path, (err, st) => {
                err ? rej(err) : res(st)
            })
        })
    })
}


text:
small go cmd for converting csv, xlsx to sql

| go run main.go examples\test1
| go run main.go examples\test2


text:
require 'digest'

class MembersController < ApplicationController
  before_action :load_internal_style_sheet!

  def index
    set_site_title(I18n.t('members.login'))

    referer = request.headers['X-XHR-Referer']
    render file: 'public/403.html', status: :forbidden, layout: false and return if referer.nil?

    if @access > 0
      redirect_to root_path and return if referer.nil?
      response.headers['X-TOP-Redirected-To'] = root_url
      render nothing: true
    end
  end

  def login
    set_site_title(I18n.t('members.login'))

    @username = request.POST[:username]
    password = request.POST[:password]
    referer = request.headers['X-XHR-Referer']
    encrypted = Digest::SHA1.hexdigest Digest::MD5.hexdigest password
    members = Member.where(username: @username, password: encrypted).limit(1)
    identity = nil

    members.each do |member|
      session[:identity] = identity = member.identity
      session[:nickname] = member.nickname
      session[:access] = member.access
    end

    if identity.nil?
      flash.now[:error] = I18n.t('members.login_failed')
      render action: 'index'
      return
    end

    redirect_to root_path and return if referer.nil?
    response.headers['X-TOP-Redirected-To'] = root_url
    render nothing: true
  end

  def logout
    set_site_title(I18n.t('members.logout'))

    referer = request.headers['X-XHR-Referer']
    session.delete(:identity)
    session.delete(:nickname)
    session.delete(:access)

    redirect_to root_path and return if referer.nil?
    response.headers['X-TOP-Redirected-To'] = root_url
    render nothing: true
  end
end


text:
<?php

namespace Pool\LinkmotorBundle\Service;

use Pool\LinkmotorBundle\Entity\Competitor;
use Pool\LinkmotorBundle\Entity\Keyword;

class Pages
{
    /**
     * @var \Doctrine\Bundle\DoctrineBundle\Registry
     */
    private $doctrine;

    /**
     * @var PageCreator
     */
    private $pageCreator;

    /**
     * @var
     */
    private $seoServices;

    /**
     * Maximale Anzahl von Seiten, die vom Service angefragt werden, damit eine Endlosschleife ausgeschlossen wird.
     *
     * @var int $maxPages
     */
    private $maxPages;

    public function __construct($doctrine, PageCreator $pageCreator, SeoServices $seoServices)
    {
        $this->doctrine = $doctrine;
        $this->pageCreator = $pageCreator;
        $this->seoServices = $seoServices;

        $this->maxPages = 25;
    }

    /**
     * @param Competitor $competitor
     * @return int
     */
    public function importFromCompetitor(Competitor $competitor)
    {
        return $this->importFromKeywordOrCompetitor($competitor);
    }

    /**
     * @param Keyword $keyword
     * @return int
     */
    public function importFromKeyword(Keyword $keyword)
    {
        return $this->importFromKeywordOrCompetitor($keyword);
    }

    /**
     * // @todo interface einführen
     *
     * @param $object
     * @return int
     */
    private function importFromKeywordOrCompetitor($object)
    {
        if (get_class($object) == 'Pool\LinkmotorBundle\Entity\Competitor') {
            $which = 'competitor';
            $modus = 'new';
        } elseif (get_class($object) == 'Pool\LinkmotorBundle\Entity\Keyword') {
            $which = 'keyword';
            $modus = 'top';
        } else {
            return 0;
        }

        $em = $this->doctrine->getManager();
        if (!$object->getAssignedTo()) {
            $users = $this->doctrine->getRepository('PoolLinkmotorBundle:User')->getAllActiveNonSupportUsers();
        }

        $numReceived = 0;
        for ($page = 1; $page <= $this->maxPages; $page++) {
            if ($which == 'keyword') {
                $result = $this->seoServices->getUrlsByKeyword(
                    $object->getKeyword(),
                    $object->getMarket()->getIsoCode(),
                    $page
                );
            } elseif ($which == 'competitor') {
                $result = $this->seoServices->getUrlsByDomain($object->getDomain(), $page);
            } else {
                $result = array('data' => null);
            }

            $urls = $result['data'];
            if ($urls) {
                $project = $object->getProject();

                $selectedUserIndex = 0;
                foreach ($urls as $url) {
                    if ($modus == 'top') {
                        $numReceived++;
                    }
                    if ($numReceived >= $object->getImportLimit()) {
                        break;
                    }
                    if ($this->pageCreator->checkIfPageExists($project, $url) == true) {
                        continue;
                    }
                    $result = $this->pageCreator->checkIfSubdomainHasPages($project, $url);
                    if ($result['subdomain'] && $result['hasPages']) {
                        continue;
                    }
                    $user = $object->getAssignedTo();
                    if (!$user) {
                        $user = $users[$selectedUserIndex];
                        $selectedUserIndex++;
                        if ($selectedUserIndex >= count($users)) {
                            $selectedUserIndex = 0;
                        }
                    }
                    $createdPage = $this->pageCreator->addPage($project, $url, $user);
                    if ($createdPage) { // Domain could be blacklisted
                        if ($which == 'keyword') {
                            $createdPage->setSourceKeyword($object);
                        } else {
                            $createdPage->setSourceCompetitor($object);
                        }
                        $em->persist($createdPage);
                        $em->flush();

                        if ($modus == 'new') {
                            $numReceived++;
                        }
                    }
                }
            }

            if (!$urls || $numReceived >= $object->getImportLimit()) {
                break;
            }
        }

        $object->setLastImportAt(new \DateTime());

        $em->persist($object);
        $em->flush();

        return $numReceived;
    }
}


text:
\input{header.tex}

\title{Inverser Faraday-Effekt an Mottisolatoren}
\date{
  Durchführung: DATUM
  \hspace{3em}
  Abgabe: DATUM
}

\begin{document}

\maketitle
\thispagestyle{empty}
\tableofcontents
\newpage

\input{content/theorie.tex}
\input{content/durchfuehrung.tex}
\input{content/auswertung.tex}
\input{content/diskussion.tex}

\printbibliography

\end{document}


text:
'use strict';
const assert = require('assert');

module.exports.hasOnlyDigits = (str, id) => {
    assert.ok(/^\d+$/.test(str), `${id}: string should contain only digits`);
}

const propExists = (obj, id, propString) => {
    assert.ok(obj.hasOwnProperty(propString), `${id}: ${propString} is missing`);
    // assert.ok(typeof obj[propString] === 'string', `${id} ${propString} is no string`);
}

const isMandatoryString = (obj, id, propString) => {
    assert.ok(obj[propString].length > 0, `${id}: ${propString} is mandatory`);
}

const isFixedLengthString = (obj, id, propString, len) => {
    assert.equal(obj[propString].length, len, `${id}: ${propString} should have fixed size of ${len}`);
}

module.exports.childPropExists = (child, propString) => propExists(child, child.ds_childnumber, propString);

module.exports.siblingPropExists = (sibling, propString) => propExists(sibling, sibling.record1id, propString);

module.exports.housePropExists = (house, propString) => propExists(house, house.ds_key, propString);

module.exports.visitPropExists = (visit, propString) => propExists(visit, visit.ds_contactid, propString);

module.exports.letterPropExists = (letter, propString) => propExists(letter, letter.ds_childid, propString);

module.exports.progressPropExists = (progress, propString) => propExists(progress, progress.ds_childid, propString);

module.exports.childIsMandatoryString = (child, propString) => isMandatoryString(child, child.ds_childnumber, propString);

module.exports.siblingIsMandatoryString = (sibling, propString) => isMandatoryString(sibling, sibling.record1id, propString);

module.exports.houseIsMandatoryString = (house, propString) => isMandatoryString(house, house.ds_key, propString);

module.exports.visitIsMandatoryString = (visit, propString) => isMandatoryString(visit, visit.ds_contactid, propString);

module.exports.letterIsMandatoryString = (letter, propString) => isMandatoryString(letter, letter.ds_childid, propString);

module.exports.progressIsMandatoryString = (progress, propString) => isMandatoryString(progress, progress.ds_childid, propString);

module.exports.childIsFixedLengthString = (child, propString, len) => isFixedLengthString(child, child.ds_childnumber, propString, len);

module.exports.testDateFormat = (dateStr, id) => {
    const m = dateStr.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);
    assert.ok(Array.isArray(m), `${id}: can not parse dateString`);
    assert.ok(m.length >= 3, `${id}: date should contain 3 - separated day month year tokens`);
    assert.ok(m[1] > 0, `${id}: day token has to be greater 0`);
    assert.ok(m[1] < 32, `${id}: day token has to be not greater than 31`);
    assert.ok(m[2] > 0, `${id}: month token has to be greater 0`);
    assert.ok(m[2] < 13, `${id}: month token has to be not greater than 12`);
    assert.ok(m[3] > 1949, `${id}: year token has to be greate than 1949`);
    assert.ok(m[3] < 2019, `${id}: year token can not be in the future`);
}


text:
 * Open terminal
 * Navigate to ```project_1```
 * Run ```python entertainment_center.py```


text:
using System;
using System.Collections.Generic;

namespace Lucene.Net.Support
{

    public static class ListExtensions
    {
        public static void AddRange<T>(this IList<T> list, IEnumerable<T> values)
        {
            var lt = list as List<T>;

            if (lt != null)
                lt.AddRange(values);
            else
            {
                foreach (var item in values)
                {
                    list.Add(item);
                }
            }
        }

        public static IList<T> SubList<T>(this IList<T> list, int fromIndex, int toIndex)
        {
            // .NET Port: This is to mimic Java's List.subList method, which has a different usage
            // than .NETs' List.GetRange. subList's parameters are indices, GetRange's parameters are a
            // starting index and a count. So we would need to do some light index math to translate this into
            // GetRange. This will be a safer extension method to use when translating java code
            // as there will be no question as to how to change it into GetRange. Also, subList returns
            // a list instance that, when modified, modifies the original list. So we're duplicating
            // that behavior as well.

            return new SubList<T>(list, fromIndex, toIndex);
        }

        public static void Swap<T>(this IList<T> list, int indexA, int indexB)
        {
            T tmp = list[indexA];
            list[indexA] = list[indexB];
            list[indexB] = tmp;
        }

        /// <summary>
        /// If the underlying type is <see cref="List{T}"/>,
        /// calls <see cref="List{T}.Sort()"/>. If not,
        /// uses <see cref="Util.CollectionUtil.TimSort{T}(IList{T})"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">this <see cref="IList{T}"/></param>
        public static void Sort<T>(this IList<T> list)
        {
            if (list is List<T>)
            {
                ((List<T>)list).Sort();
            }
            else
            {
                Util.CollectionUtil.TimSort(list);
            }
        }

        /// <summary>
        /// If the underlying type is <see cref="List{T}"/>,
        /// calls <see cref="List{T}.Sort(IComparer{T})"/>. If not,
        /// uses <see cref="Util.CollectionUtil.TimSort{T}(IList{T}, IComparer{T})"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">this <see cref="IList{T}"/></param>
        /// <param name="comparer">the comparer to use for the sort</param>
        public static void Sort<T>(this IList<T> list, IComparer<T> comparer)
        {
            if (list is List<T>)
            {
                ((List<T>)list).Sort(comparer);
            }
            else
            {
                Util.CollectionUtil.TimSort(list, comparer);
            }
        }

        /// <summary>
        /// If the underlying type is <see cref="List{T}"/>,
        /// calls <see cref="List{T}.Sort(IComparer{T})"/>. If not,
        /// uses <see cref="Util.CollectionUtil.TimSort{T}(IList{T}, IComparer{T})"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">this <see cref="IList{T}"/></param>
        /// <param name="comparison">the comparison function to use for the sort</param>
        public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
        {
            IComparer<T> comparer = new FunctorComparer<T>(comparison);
            Sort(list, comparer);
        }

        /// <summary>
        /// Sorts the given <see cref="IList{T}"/> using the <see cref="IComparer{T}"/>.
        /// This method uses the Tim sort
        /// algorithm, but falls back to binary sort for small lists.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">this <see cref="IList{T}"/></param>
        public static void TimSort<T>(this IList<T> list)
        {
            Util.CollectionUtil.TimSort(list);
        }

        /// <summary>
        /// Sorts the given <see cref="IList{T}"/> using the <see cref="IComparer{T}"/>.
        /// This method uses the Tim sort
        /// algorithm, but falls back to binary sort for small lists.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">this <see cref="IList{T}"/></param>
        /// <param name="comparer">The <see cref="IComparer{T}"/> to use for the sort.</param>
        public static void TimSort<T>(this IList<T> list, IComparer<T> comparer)
        {
            Util.CollectionUtil.TimSort(list, comparer);
        }

        /// <summary>
        /// Sorts the given <see cref="IList{T}"/> using the <see cref="IComparer{T}"/>.
        /// This method uses the intro sort
        /// algorithm, but falls back to insertion sort for small lists.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">this <see cref="IList{T}"/></param>
        public static void IntroSort<T>(this IList<T> list)
        {
            Util.CollectionUtil.IntroSort(list);
        }

        /// <summary>
        /// Sorts the given <see cref="IList{T}"/> using the <see cref="IComparer{T}"/>.
        /// This method uses the intro sort
        /// algorithm, but falls back to insertion sort for small lists.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">this <see cref="IList{T}"/></param>
        /// <param name="comparer">The <see cref="IComparer{T}"/> to use for the sort.</param>
        public static void IntroSort<T>(this IList<T> list, IComparer<T> comparer)
        {
            Util.CollectionUtil.IntroSort(list, comparer);
        }

        #region Nested Type: FunctorComparer<T>

        private sealed class FunctorComparer<T> : IComparer<T>
        {
            private Comparison<T> comparison;

            public FunctorComparer(Comparison<T> comparison)
            {
                this.comparison = comparison;
            }

            public int Compare(T x, T y)
            {
                return this.comparison(x, y);
            }
        }

        #endregion Nested Type: FunctorComparer<T>
    }

    #region SubList<T>

    internal sealed class SubList<T> : IList<T>
    {
        private readonly IList<T> list;
        private readonly int fromIndex;
        private int toIndex;

        /// <summary>
        /// Creates a ranged view of the given <paramref name="list"/>.
        /// </summary>
        /// <param name="list">The original list to view.</param>
        /// <param name="fromIndex">The inclusive starting index.</param>
        /// <param name="toIndex">The exclusive ending index.</param>
        public SubList(IList<T> list, int fromIndex, int toIndex)
        {
            if (fromIndex < 0)
                throw new ArgumentOutOfRangeException("fromIndex");

            if (toIndex > list.Count)
                throw new ArgumentOutOfRangeException("toIndex");

            if (toIndex < fromIndex)
                throw new ArgumentOutOfRangeException("toIndex");

            if (list == null)
                throw new ArgumentNullException("list");

            this.list = list;
            this.fromIndex = fromIndex;
            this.toIndex = toIndex;
        }

        public int IndexOf(T item)
        {
            for (int i = fromIndex, fakeIndex = 0; i < toIndex; i++, fakeIndex++)
            {
                var current = list[i];

                if (current == null && item == null)
                    return fakeIndex;

                if (current.Equals(item))
                {
                    return fakeIndex;
                }
            }

            return -1;
        }

        public void Insert(int index, T item)
        {
            throw new NotSupportedException();
        }

        public void RemoveAt(int index)
        {
            // TODO: is this the right behavior?
            list.RemoveAt(fromIndex + index);
            toIndex--;
        }

        public T this[int index]
        {
            get
            {
                return list[fromIndex + index];
            }
            set
            {
                list[fromIndex + index] = value;
            }
        }

        public void Add(T item)
        {
            throw new NotSupportedException();
        }

        public void Clear()
        {
            // TODO: is this the correct behavior?

            for (int i = toIndex - 1; i >= fromIndex; i--)
            {
                list.RemoveAt(i);
            }

            toIndex = fromIndex; // can't move further
        }

        public bool Contains(T item)
        {
            return IndexOf(item) >= 0;
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            int count = array.Length - arrayIndex;

            for (int i = fromIndex, arrayi = arrayIndex; i <= Math.Min(toIndex - 1, fromIndex + count - 1); i++, arrayi++)
            {
                array[arrayi] = list[i];
            }
        }

        public int Count
        {
            get { return Math.Max(toIndex - fromIndex, 0); }
        }

        public bool IsReadOnly
        {
            get { return list.IsReadOnly; }
        }

        public bool Remove(T item)
        {
            var index = this.IndexOf(item); // get fake index

            if (index < 0)
                return false;

            list.RemoveAt(fromIndex + index);
            toIndex--;

            return true;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return YieldItems().GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        private IEnumerable<T> YieldItems()
        {
            for (int i = fromIndex; i <= Math.Min(toIndex - 1, list.Count - 1); i++)
            {
                yield return list[i];
            }
        }
    }

    #endregion SubList<T>
}


text:
/**
 * @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield`
 * @author Teddy Katz
 * @author Toru Nagashima
 */
"use strict";

/**
 * Make the map from identifiers to each reference.
 * @param {escope.Scope} scope The scope to get references.
 * @param {Map<Identifier, escope.Reference>} [outReferenceMap] The map from identifier nodes to each reference object.
 * @returns {Map<Identifier, escope.Reference>} `referenceMap`.
 */
function createReferenceMap(scope, outReferenceMap = new Map()) {
    for (const reference of scope.references) {
        outReferenceMap.set(reference.identifier, reference);
    }
    for (const childScope of scope.childScopes) {
        if (childScope.type !== "function") {
            createReferenceMap(childScope, outReferenceMap);
        }
    }

    return outReferenceMap;
}

/**
 * Checks if an expression is a variable that can only be observed within the given function.
 * @param {escope.Variable} variable The variable to check
 * @returns {boolean} `true` if the variable is local to the given function, and is never referenced in a closure.
 */
function isLocalVariableWithoutEscape(variable) {
    const functionScope = variable.scope.variableScope;

    return variable.references.every(reference =>
        reference.from.variableScope === functionScope);
}

class SegmentInfo {
    constructor() {
        this.info = new WeakMap();
    }

    /**
     * Initialize the segment information.
     * @param {PathSegment} segment The segment to initialize.
     * @returns {void}
     */
    initialize(segment) {
        const outdatedReadVariables = new Set();
        const freshReadVariables = new Set();

        for (const prevSegment of segment.prevSegments) {
            const info = this.info.get(prevSegment);

            if (info) {
                info.outdatedReadVariables.forEach(Set.prototype.add, outdatedReadVariables);
                info.freshReadVariables.forEach(Set.prototype.add, freshReadVariables);
            }
        }

        this.info.set(segment, { outdatedReadVariables, freshReadVariables });
    }

    /**
     * Mark a given variable as read on given segments.
     * @param {PathSegment[]} segments The segments that it read the variable on.
     * @param {escope.Variable} variable The variable to be read.
     * @returns {void}
     */
    markAsRead(segments, variable) {
        for (const segment of segments) {
            const info = this.info.get(segment);

            if (info) {
                info.freshReadVariables.add(variable);
            }
        }
    }

    /**
     * Move `freshReadVariables` to `outdatedReadVariables`.
     * @param {PathSegment[]} segments The segments to process.
     * @returns {void}
     */
    makeOutdated(segments) {
        const vars = new Set();

        for (const segment of segments) {
            const info = this.info.get(segment);

            if (info) {
                info.freshReadVariables.forEach(Set.prototype.add, info.outdatedReadVariables);
                info.freshReadVariables.forEach(Set.prototype.add, vars);
                info.freshReadVariables.clear();
            }
        }
    }

    /**
     * Check if a given variable is outdated on the current segments.
     * @param {PathSegment[]} segments The current segments.
     * @param {escope.Variable} variable The variable to check.
     * @returns {boolean} `true` if the variable is outdated on the segments.
     */
    isOutdated(segments, variable) {
        for (const segment of segments) {
            const info = this.info.get(segment);

            if (info && info.outdatedReadVariables.has(variable)) {
                return true;
            }
        }
        return false;
    }
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        type: "problem",

        docs: {
            description: "disallow assignments that can lead to race conditions due to usage of `await` or `yield`",
            category: "Possible Errors",
            recommended: true,
            url: "https://eslint.org/docs/rules/require-atomic-updates"
        },

        fixable: null,
        schema: [],

        messages: {
            nonAtomicUpdate: "Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`."
        }
    },

    create(context) {
        const sourceCode = context.getSourceCode();
        const globalScope = context.getScope();
        const dummyVariables = new Map();
        const assignmentReferences = new Map();
        const segmentInfo = new SegmentInfo();
        let stack = null;

        /**
         * Get the variable of a given reference.
         * If it's not defined, returns a dummy object.
         * @param {escope.Reference} reference The reference to get.
         * @returns {escope.Variable} The variable of the reference.
         */
        function getVariable(reference) {
            if (reference.resolved) {
                return reference.resolved;
            }

            // Get or create a dummy.
            const name = reference.identifier.name;
            let variable = dummyVariables.get(name);

            if (!variable) {
                variable = {
                    name,
                    scope: globalScope,
                    references: []
                };
                dummyVariables.set(name, variable);
            }
            variable.references.push(reference);

            return variable;
        }

        /**
         * Get `reference.writeExpr` of a given reference.
         * If it's the read reference of MemberExpression in LHS, returns RHS in order to address `a.b = await a`
         * @param {escope.Reference} reference The reference to get.
         * @returns {Expression|null} The `reference.writeExpr`.
         */
        function getWriteExpr(reference) {
            if (reference.writeExpr) {
                return reference.writeExpr;
            }
            let node = reference.identifier;

            while (node) {
                const t = node.parent.type;

                if (t === "AssignmentExpression" && node.parent.left === node) {
                    return node.parent.right;
                }
                if (t === "MemberExpression" && node.parent.object === node) {
                    node = node.parent;
                    continue;
                }

                break;
            }

            return null;
        }

        return {
            onCodePathStart(codePath) {
                const scope = context.getScope();
                const shouldVerify =
                    scope.type === "function" &&
                    (scope.block.async || scope.block.generator);

                stack = {
                    upper: stack,
                    codePath,
                    referenceMap: shouldVerify ? createReferenceMap(scope) : null
                };
            },
            onCodePathEnd() {
                stack = stack.upper;
            },

            // Initialize the segment information.
            onCodePathSegmentStart(segment) {
                segmentInfo.initialize(segment);
            },

            // Handle references to prepare verification.
            Identifier(node) {
                const { codePath, referenceMap } = stack;
                const reference = referenceMap && referenceMap.get(node);

                // Ignore if this is not a valid variable reference.
                if (!reference) {
                    return;
                }
                const variable = getVariable(reference);
                const writeExpr = getWriteExpr(reference);

                // Add a fresh read variable.
                if (reference.isRead() && !(writeExpr && writeExpr.parent.operator === "=")) {
                    segmentInfo.markAsRead(codePath.currentSegments, variable);
                }

                /*
                 * Register the variable to verify after ESLint traversed the `writeExpr` node
                 * if this reference is an assignment to a variable which is referred from other clausure.
                 */
                if (writeExpr &&
                    writeExpr.parent.right === writeExpr && // ← exclude variable declarations.
                    !isLocalVariableWithoutEscape(variable)
                ) {
                    let refs = assignmentReferences.get(writeExpr);

                    if (!refs) {
                        refs = [];
                        assignmentReferences.set(writeExpr, refs);
                    }

                    refs.push(reference);
                }
            },

            /*
             * Verify assignments.
             * If the reference exists in `outdatedReadVariables` list, report it.
             */
            ":expression:exit"(node) {
                const { codePath, referenceMap } = stack;

                // referenceMap exists if this is in a resumable function scope.
                if (!referenceMap) {
                    return;
                }

                // Mark the read variables on this code path as outdated.
                if (node.type === "AwaitExpression" || node.type === "YieldExpression") {
                    segmentInfo.makeOutdated(codePath.currentSegments);
                }

                // Verify.
                const references = assignmentReferences.get(node);

                if (references) {
                    assignmentReferences.delete(node);

                    for (const reference of references) {
                        const variable = getVariable(reference);

                        if (segmentInfo.isOutdated(codePath.currentSegments, variable)) {
                            context.report({
                                node: node.parent,
                                messageId: "nonAtomicUpdate",
                                data: {
                                    value: sourceCode.getText(node.parent.left)
                                }
                            });
                        }
                    }
                }
            }
        };
    }
};


text:
class ContractItemPurchase < ActiveRecord::Base

   has_ancestor :named => :item_purchase

   def close_item_purchase
     self.cost = self.length * self.unit_count * self.unit_cost
     self.closed = 1
   end

end


text:
package p_Avatar.benders;

public class WaterBender extends Bender {
    private double waterClarity;

    public WaterBender(String name, int power, double waterClarity) {
        super(name, power);
        this.waterClarity = waterClarity;
    }

    @Override
    public double getTotalPower() {
        return super.getPower() * this.waterClarity;
    }

    @Override
    public String toString() {
        return String.format("###Water Bender: %s, Power: %d, Water Clarity: %.2f", super.getName(), super.getPower(),
                this.waterClarity);
    }
}