Clone inference path

        For example, each side of a binary operation (BinOp)
        starts with the same context but diverge as each side is inferred
        so the InferenceContext will need be cloned
353773
def clone(self):
        """"""
        # XXX copy lookupname/callcontext ?
        clone = InferenceContext(self.path, inferred=self.inferred)
        clone.callcontext = self.callcontext
        clone.boundnode = self.boundnode
        clone.extra_context = self.extra_context
        return clone
199029
private Arguments createProgramArguments(TwillContext context, Map<String, String> configs) {
    Map<String, String> args = ImmutableMap.<String, String>builder()
      .put(ProgramOptionConstants.INSTANCE_ID, Integer.toString(context.getInstanceId()))
      .put(ProgramOptionConstants.INSTANCES, Integer.toString(context.getInstanceCount()))
      .put(ProgramOptionConstants.RUN_ID, context.getApplicationRunId().getId())
      .putAll(Maps.filterKeys(configs, Predicates.not(Predicates.in(ImmutableSet.of("hConf", "cConf")))))
      .build();

    return new BasicArguments(args);
  }
146138
NullnessPropagationTransfer setContext(@Nullable Context context) {
    // This is a best-effort check (similar to ArrayList iterators, for instance), no guarantee
    Preconditions.checkArgument(
        context == null || this.context == null,
        "Context already set: reset after use and don't use this class concurrently");
    this.context = context;
    // Clear traversed set just-in-case as this marks the beginning or end of analyzing a method
    this.traversed.clear();
    // Null out local inference results when leaving a method
    this.inferenceResults = null;
    return this;
  }
923659
function(path) {
            const { node } = path;

            // Need to be careful of side-effects.
            if (!t.isIdentifier(node.discriminant)) {
              return;
            }

            if (!node.cases.length) {
              return;
            }

            const consTestPairs = [];
            let fallThru = [];
            let defaultRet;
            for (const switchCase of node.cases) {
              if (switchCase.consequent.length > 1) {
                return;
              }

              const cons = switchCase.consequent[0];

              // default case
              if (!switchCase.test) {
                if (!t.isReturnStatement(cons)) {
                  return;
                }
                defaultRet = cons;
                continue;
              }

              if (!switchCase.consequent.length) {
                fallThru.push(switchCase.test);
                continue;
              }

              // TODO: can we void it?
              if (!t.isReturnStatement(cons)) {
                return;
              }

              let test = t.binaryExpression(
                "===",
                node.discriminant,
                switchCase.test
              );

              if (fallThru.length && !defaultRet) {
                test = fallThru.reduceRight(
                  (right, test) =>
                    t.logicalExpression(
                      "||",
                      t.binaryExpression("===", node.discriminant, test),
                      right
                    ),
                  test
                );
              }
              fallThru = [];

              consTestPairs.push([test, cons.argument || VOID_0]);
            }

            // Bail if we have any remaining fallthrough
            if (fallThru.length) {
              return;
            }

            // We need the default to be there to make sure there is an oppurtinity
            // not to return.
            if (!defaultRet) {
              if (path.inList) {
                const nextPath = path.getSibling(path.key + 1);
                if (nextPath.isReturnStatement()) {
                  defaultRet = nextPath.node;
                  nextPath.remove();
                } else if (
                  !nextPath.node &&
                  path.parentPath.parentPath.isFunction()
                ) {
                  // If this is the last statement in a function we just fake a void return.
                  defaultRet = t.returnStatement(VOID_0);
                } else {
                  return;
                }
              } else {
                return;
              }
            }

            const cond = consTestPairs.reduceRight(
              (alt, [test, cons]) => t.conditionalExpression(test, cons, alt),
              defaultRet.argument || VOID_0
            );

            path.replaceWith(t.returnStatement(cond));

            // Maybe now we can merge with some previous switch statement.
            if (path.inList) {
              const prev = path.getSibling(path.key - 1);
              if (prev.isSwitchStatement()) {
                prev.visit();
              }
            }
          }
240302
def visit_BinOp(self, node):
        
        args = [self.visit(arg) for arg in (node.left, node.right)]
        return list({frozenset.union(*x) for x in itertools.product(*args)})
545138
def read_instance(self, cls, sdmxobj, offset=None, first_only=True):
        '''
          
        '''
        if offset:
            try:
                base = self._paths[offset](sdmxobj._elem)[0]
            except IndexError:
                return None
        else:
            base = sdmxobj._elem
        result = self._paths[cls](base)
        if result:
            if first_only:
                return cls(self, result[0])
            else:
                return [cls(self, i) for i in result]
887666
RBBINode cloneTree() {
        RBBINode n;

        if (fType == RBBINode.varRef) {
            // If the current node is a variable reference, skip over it
            //   and clone the definition of the variable instead.
            n = fLeftChild.cloneTree();
        } else if (fType == RBBINode.uset) {
            n = this;
        } else {
            n = new RBBINode(this);
            if (fLeftChild != null) {
                n.fLeftChild = fLeftChild.cloneTree();
                n.fLeftChild.fParent = n;
            }
            if (fRightChild != null) {
                n.fRightChild = fRightChild.cloneTree();
                n.fRightChild.fParent = n;
            }
        }
        return n;
    }
509535
function getBinaryExpressionStarts(binaryExpression, starts) {
  function getStartsFromOneSide(side, starts) {
    starts.push(side.loc.start);
    if (side.type === 'BinaryExpression') {
      starts = getBinaryExpressionStarts(side, starts);
    }
    return starts;
  }

  starts = getStartsFromOneSide(binaryExpression.left, starts);
  starts = getStartsFromOneSide(binaryExpression.right, starts);
  return starts;
}
949380
void checkWithinBounds(InferenceContext inferenceContext,
                             Warner warn) throws InferenceException {
        MultiUndetVarListener mlistener = new MultiUndetVarListener(inferenceContext.undetvars);
        List<Type> saved_undet = inferenceContext.save();
        try {
            while (true) {
                mlistener.reset();
                if (!allowGraphInference) {
                    //in legacy mode we lack of transitivity, so bound check
                    //cannot be run in parallel with other incoprporation rounds
                    for (Type t : inferenceContext.undetvars) {
                        UndetVar uv = (UndetVar)t;
                        IncorporationStep.CHECK_BOUNDS.apply(uv, inferenceContext, warn);
                    }
                }
                for (Type t : inferenceContext.undetvars) {
                    UndetVar uv = (UndetVar)t;
                    //bound incorporation
                    EnumSet<IncorporationStep> incorporationSteps = allowGraphInference ?
                            incorporationStepsGraph : incorporationStepsLegacy;
                    for (IncorporationStep is : incorporationSteps) {
                        if (is.accepts(uv, inferenceContext)) {
                            is.apply(uv, inferenceContext, warn);
                        }
                    }
                }
                if (!mlistener.changed || !allowGraphInference) break;
            }
        }
        finally {
            mlistener.detach();
            if (incorporationCache.size() == MAX_INCORPORATION_STEPS) {
                inferenceContext.rollback(saved_undet);
            }
            incorporationCache.clear();
        }
    }
107693
private static boolean inStaticContext(TreePath path) {
    Tree prev = path.getLeaf();
    path = path.getParentPath();

    ClassSymbol enclosingClass =
        ASTHelpers.getSymbol(ASTHelpers.findEnclosingNode(path, ClassTree.class));
    ClassSymbol directSuperClass = (ClassSymbol) enclosingClass.getSuperclass().tsym;

    for (Tree tree : path) {
      switch (tree.getKind()) {
        case METHOD:
          return ASTHelpers.getSymbol(tree).isStatic();
        case BLOCK: // static initializer
          if (((BlockTree) tree).isStatic()) {
            return true;
          }
          break;
        case VARIABLE: // variable initializer of static variable
          VariableTree variableTree = (VariableTree) tree;
          VarSymbol variableSym = ASTHelpers.getSymbol(variableTree);
          if (variableSym.getKind() == ElementKind.FIELD) {
            return Objects.equals(variableTree.getInitializer(), prev) && variableSym.isStatic();
          }
          break;
        case METHOD_INVOCATION: // JLS 8.8.7.1 explicit constructor invocation
          MethodSymbol methodSym = ASTHelpers.getSymbol((MethodInvocationTree) tree);
          if (methodSym == null) {
            // sometimes javac can't resolve the symbol. In this case just assume that we are
            // in a static context - this is a safe approximation in our context (checking
            // visibility)
            return true;
          }
          if (methodSym.isConstructor()
              && (Objects.equals(methodSym.owner, enclosingClass)
                  || Objects.equals(methodSym.owner, directSuperClass))) {
            return true;
          }
          break;
        default:
          break;
      }
      prev = tree;
    }
    return false;
  }
1137164
def call_binop(self, context, operator, left, right):
        
        return self.binop_table[operator](left, right)
1361977
function deepClone(inputDict){

    if (!inputDict)
        return null;

    const clonedDict = {};

    for (let key in inputDict){

        if (typeof(inputDict[key]) == 'object'){

            clonedDict[key] = deepClone(inputDict[key]);
        
        }
        else{

            clonedDict[key] = inputDict[key];

        }

    }

    return clonedDict;

}
364588
function _createInverseContext() {
    var activeCtx = this;

    // lazily create inverse
    if(activeCtx.inverse) {
      return activeCtx.inverse;
    }
    var inverse = activeCtx.inverse = {};

    // handle default language
    var defaultLanguage = activeCtx['@language'] || '@none';

    // create term selections for each mapping in the context, ordered by
    // shortest and then lexicographically least
    var mappings = activeCtx.mappings;
    var terms = Object.keys(mappings).sort(_compareShortestLeast);
    for(var i = 0; i < terms.length; ++i) {
      var term = terms[i];
      var mapping = mappings[term];
      if(mapping === null) {
        continue;
      }

      var container = mapping['@container'] || '@none';

      // iterate over every IRI in the mapping
      var ids = mapping['@id'];
      if(!_isArray(ids)) {
        ids = [ids];
      }
      for(var ii = 0; ii < ids.length; ++ii) {
        var iri = ids[ii];
        var entry = inverse[iri];

        // initialize entry
        if(!entry) {
          inverse[iri] = entry = {};
        }

        // add new entry
        if(!entry[container]) {
          entry[container] = {
            '@language': {},
            '@type': {}
          };
        }
        entry = entry[container];

        // term is preferred for values using @reverse
        if(mapping.reverse) {
          _addPreferredTerm(mapping, term, entry['@type'], '@reverse');
        }
        // term is preferred for values using specific type
        else if('@type' in mapping) {
          _addPreferredTerm(mapping, term, entry['@type'], mapping['@type']);
        }
        // term is preferred for values using specific language
        else if('@language' in mapping) {
          var language = mapping['@language'] || '@null';
          _addPreferredTerm(mapping, term, entry['@language'], language);
        }
        // term is preferred for values w/default language or no type and
        // no language
        else {
          // add an entry for the default language
          _addPreferredTerm(mapping, term, entry['@language'], defaultLanguage);

          // add entries for no type and no language
          _addPreferredTerm(mapping, term, entry['@type'], '@none');
          _addPreferredTerm(mapping, term, entry['@language'], '@none');
        }
      }
    }

    return inverse;
  }
447498
private QueryTreeNode cloneTrunk(QueryTreeNode stop, QueryTreeNode stopClone) {
		QueryTreeNode node1 = null;
		if (n1 != null) {
			node1 = (n1 == stop ? stopClone : n1.cloneBranch());
		}
		QueryTreeNode node2 = null;
		if (n2 != null) {
			node2 = n2 == stop ? stopClone : n2.cloneBranch();
		}
		
		QueryTreeNode ret = cloneSingle(node1, t1, node2, t2);
		if (p != null) {
			p.cloneTrunk(this, ret);
		}
		ret.relateToChildren();
		return ret;
	}
854550
function _basedirWithContext (ctx) {
  let data = ctx && ctx.data
  let $$bud = data && data.root && data.root[ '$$bud' ] || {}
  return $$bud.cwd || process.cwd()
}
219284
def _get_binary_replacement(first, second, cls):
    """"""
    expr = ProtoExpr([first, second], {})
    if LOG:
        logger = logging.getLogger('QNET.create')
    for key, rule in cls._binary_rules.items():
        pat, replacement = rule
        match_dict = match_pattern(pat, expr)
        if match_dict:
            try:
                replaced = replacement(**match_dict)
                if LOG:
                    logger.debug(
                        "%sRule %s.%s: (%s, %s) -> %s", ("  " * (LEVEL)),
                        cls.__name__, key, expr.args, expr.kwargs, replaced)
                return replaced
            except CannotSimplify:
                if LOG_NO_MATCH:
                    logger.debug(
                        "%sRule %s.%s: no match: CannotSimplify",
                        ("  " * (LEVEL)), cls.__name__, key)
                continue
        else:
            if LOG_NO_MATCH:
                logger.debug(
                    "%sRule %s.%s: no match: %s", ("  " * (LEVEL)),
                    cls.__name__, key, match_dict.reason)
    return None
747617
def new_context(environment, template_name, blocks, vars=None,
                shared=None, globals=None, locals=None):
    """"""
    if vars is None:
        vars = {}
    if shared:
        parent = vars
    else:
        parent = dict(globals or (), **vars)
    if locals:
        # if the parent is shared a copy should be created because
        # we don't want to modify the dict passed
        if shared:
            parent = dict(parent)
        for key, value in iteritems(locals):
            if value is not missing:
                parent[key] = value
    return environment.context_class(environment, parent, template_name,
                                     blocks)