used by other refactorings
359486
def replace(code, pattern, goal):
    """"""
    finder = similarfinder.RawSimilarFinder(code)
    matches = list(finder.get_matches(pattern))
    ast = patchedast.get_patched_ast(code)
    lines = codeanalyze.SourceLinesAdapter(code)
    template = similarfinder.CodeTemplate(goal)
    computer = _ChangeComputer(code, ast, lines, template, matches)
    result = computer.get_changed()
    if result is None:
        return code
    return result
308405
protected void processReferencesAndOutput(List<Ref> refList) {
                List<String> refNames = new ArrayList<String>(refList.size());

                for (Ref ref : refList) {
                        refNames.add(GitTaskUtils.sanitizeRefName(ref.getName()));
                }

                if (!namesToCheck.isEmpty()) {
                        if (!refNames.containsAll(namesToCheck)) {
                                List<String> namesCopy = new ArrayList<String>(namesToCheck);
                                namesCopy.removeAll(refNames);

                                throw new GitBuildException(String.format(MISSING_REFS_TEMPLATE, namesCopy.toString()));
                        }
                }

                if (!GitTaskUtils.isNullOrBlankString(outputFilename)) {
                        FileUtils fileUtils = FileUtils.getFileUtils();

                        Echo echo = new Echo();
                        echo.setProject(getProject());
                        echo.setFile(fileUtils.resolveFile(getProject().getBaseDir(), outputFilename));

                        for (int i = 0; i < refNames.size(); i++) {
                                String refName = refNames.get(i);
                                echo.addText(String.format(REF_NAME_TEMPLATE, refName));
                        }

                        echo.perform();
                }
        }
848492
@Override
    public void sawOpcode(int seen) {
        try {
            switch (state) {
                case SAW_NOTHING:
                    if (seen == Const.RETURN) {
                        bugReporter.reportBug(new BugInstance(this, BugType.ACEM_ABSTRACT_CLASS_EMPTY_METHODS.name(), NORMAL_PRIORITY).addClass(this)
                                .addMethod(this).addSourceLine(this));
                        state = State.SAW_DONE;
                    } else if (seen == Const.NEW) {
                        String newClass = getClassConstantOperand();
                        JavaClass exCls = Repository.lookupClass(newClass);
                        if ((exceptionClass != null) && exCls.instanceOf(exceptionClass)) {
                            state = State.SAW_NEW;
                        } else {
                            state = State.SAW_DONE;
                        }
                    } else {
                        state = State.SAW_DONE;
                    }
                break;

                case SAW_NEW:
                    if (seen == Const.DUP) {
                        state = State.SAW_DUP;
                    } else {
                        state = State.SAW_DONE;
                    }
                break;

                case SAW_DUP:
                    if (((seen == Const.LDC) || (seen == Const.LDC_W)) && (getConstantRefOperand() instanceof ConstantString)) {
                        state = State.SAW_LDC;
                    } else {
                        state = State.SAW_DONE;
                    }
                break;

                case SAW_LDC:
                    if ((seen == Const.INVOKESPECIAL) && Values.CONSTRUCTOR.equals(getNameConstantOperand())) {
                        state = State.SAW_INVOKESPECIAL;
                    } else {
                        state = State.SAW_DONE;
                    }
                break;

                case SAW_INVOKESPECIAL:
                    if (seen == Const.ATHROW) {
                        bugReporter.reportBug(new BugInstance(this, BugType.ACEM_ABSTRACT_CLASS_EMPTY_METHODS.name(), NORMAL_PRIORITY).addClass(this)
                                .addMethod(this).addSourceLine(this));
                    }
                    state = State.SAW_DONE;
                break;

                case SAW_DONE:
                break;
            }
        } catch (ClassNotFoundException cnfe) {
            bugReporter.reportMissingClass(cnfe);
            state = State.SAW_DONE;
        }
    }
936971
function handleExtractToVariable() {
        var editor = EditorManager.getActiveEditor();

        if (editor.getSelections().length > 1) {
            editor.displayErrorMessageAtCursor(Strings.ERROR_EXTRACTTO_VARIABLE_MULTICURSORS);
            return;
        }

        initializeSession(editor);

        var selection = editor.getSelection(),
            doc       = editor.document,
            retObj    = RefactoringUtils.normalizeText(editor.getSelectedText(), editor.indexFromPos(selection.start),
                        editor.indexFromPos(selection.end), true),
            text      = retObj.text,
            start     = retObj.start,
            end       = retObj.end,
            ast,
            scopes,
            expns,
            inlineMenu;

        function callExtractToVariable(startPos, endPos, value) {
            RefactoringUtils.getScopeData(session, editor.posFromIndex(startPos))
                .done(function(expnscope) {
                    scopes = RefactoringUtils.getAllScopes(ast, expnscope, doc.getText());
                    extractToVariable(ast, startPos, endPos, value, scopes);
                }).fail(function() {
                    editor.displayErrorMessageAtCursor(Strings.ERROR_TERN_FAILED);
                });
        }

        RefactoringUtils.getScopeData(session, editor.posFromIndex(start)).done(function(scope) {
            ast = RefactoringUtils.getAST(doc.getText());
            scopes = RefactoringUtils.getAllScopes(ast, scope, doc.getText());

            if (editor.hasSelection()) {
                extractToVariable(ast, start, end, text, scopes);
            } else {
                expns = getExpressions(ast, start, end);

                expns.forEach(function(expn, index) {
                    expn.value = doc.getText().substr(expn.start, expn.end - expn.start);
                });

                // Sort expressions by their length
                expns.sort(function(a, b) {
                    return a.value.length - b.value.length;
                });

                if (!expns || !expns.length) {
                    session.editor.displayErrorMessageAtCursor(Strings.ERROR_EXTRACTTO_VARIABLE_NOT_VALID);
                    return;
                }

                // Filter expns based on length of first surrounding expression
                var firstExpnLength = RefactoringUtils.numLines(expns[0].value);
                expns = expns.filter(function(expn) {
                    return RefactoringUtils.numLines(expn.value) === firstExpnLength;
                });

                // Add name for the expression based on its value
                expns.forEach(function(expn, index) {
                    // If expn name is multi-line, display only first line
                    if (RefactoringUtils.numLines(expn.value) > 1) {
                        expn.name = expn.value.substr(0, expn.value.indexOf("\n")) + "...";
                    } else {
                        expn.name = expn.value;
                    }
                });

                // If only one surround expression, extract
                if (expns.length === 1) {
                    callExtractToVariable(expns[0].start, expns[0].end, expns[0].value);
                    return;
                }

                expns.forEach(function(expn, index) {
                    expn.id = index;
                });

                // UI for extract to variable
                inlineMenu = new InlineMenu(session.editor, Strings.EXTRACTTO_VARIABLE_SELECT_EXPRESSION);

                inlineMenu.onHover(function (expnId) {
                    // Remove the scroll Handlers If already Attached.
                    editor.off("scroll.inlinemenu");
                    // Add a scroll handler If Selection Range is not View.
                    // This is Added for a Bug, where Menu used not to open for the first Time
                    if(!editor.isLineVisible(editor.posFromIndex(expns[expnId].end).line)) {
                        editor.on("scroll.inlinemenu", function() {
                            // Remove the Handlers so that If scroll event is triggerd again by any other operation
                            // Menu should not be reopened.
                            // Menu Should be reopened only if Scroll event is triggered by onHover.
                            editor.off("scroll.inlinemenu");
                            inlineMenu.openRemovedMenu();
                        });
                    }
                    editor.setSelection(editor.posFromIndex(expns[expnId].start), editor.posFromIndex(expns[expnId].end));
                });

                inlineMenu.open(expns);

                inlineMenu.onSelect(function (expnId) {
                    callExtractToVariable(expns[expnId].start, expns[expnId].end, expns[expnId].value);
                    inlineMenu.close();
                });

                inlineMenu.onClose(function () {
                    inlineMenu.close();
                });
            }
        }).fail(function() {
            editor.displayErrorMessageAtCursor(Strings.ERROR_TERN_FAILED);
        });
    }
328554
@Override
    public void sawOpcode(int seen) {
        if (seen == Const.INVOKEVIRTUAL) {
            String className = getClassConstantOperand();
            String methodName = getNameConstantOperand();
            String methodSig = getSigConstantOperand();

            FQMethod methodInfo = new FQMethod(className, methodName, methodSig);
            if (oldMethods.contains(methodInfo)) {
                bugReporter.reportBug(new BugInstance(this, BugType.NCMU_NON_COLLECTION_METHOD_USE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
                        .addSourceLine(this));
            }
        }
    }
966309
def __store_other(self, o, method_name, member):
        
        self.__store__[ method_name ] = eval( "o." + method_name )
        self.__store__[ method_name[0].lower() + method_name[1:] ] = eval( "o." + method_name )
347776
def write_other_members(self, f, catch_all=False):
    
    if catch_all:
      names = self._members.items()
    else:
      names = inspect.getmembers(self._module)
    leftovers = []
    for name, _ in names:
      if name in self._members and name not in self._documented:
        leftovers.append(name)
    if leftovers:
      print("%s: undocumented members: %d" % (self._title, len(leftovers)))
      print("\n## Other Functions and Classes", file=f)
      for name in sorted(leftovers):
        print("  %s" % name)
        self._documented.add(name)
        self._mentioned.add(name)
        self._write_member_markdown_to_file(f, "###", *self._members[name])
321942
function ReferenceIterator(iterable) {
            _classCallCheck(this, ReferenceIterator);

            this.iterator = null;
            var artifacts = new IterationArtifacts(iterable);
            this.artifacts = artifacts;
        }
1106125
private void rewriteAliasReferences(Name aliasingName, Ref aliasingRef, Set<AstChange> newNodes) {
    List<Ref> refs = new ArrayList<>(aliasingName.getRefs());
    for (Ref ref : refs) {
      switch (ref.type) {
        case SET_FROM_GLOBAL:
          continue;
        case DIRECT_GET:
        case ALIASING_GET:
        case PROTOTYPE_GET:
        case CALL_GET:
        case SUBCLASSING_GET:
          if (ref.getTwin() != null) {
            // The reference is the left-hand side of a nested assignment. This means we store two
            // separate 'twin' Refs with the same node of types ALIASING_GET and SET_FROM_GLOBAL.
            // For example, the read of `c.d` has a twin reference in
            //   a.b = c.d = e.f;
            // We handle this case later.
            checkState(ref.type == Type.ALIASING_GET, ref);
            break;
          }
          if (ref.getNode().isStringKey()) {
            // e.g. `y` in `const {y} = x;`
            DestructuringGlobalNameExtractor.reassignDestructringLvalue(
                ref.getNode(), aliasingRef.getNode().cloneTree(), newNodes, ref, compiler);
          } else {
            // e.g. `x.y`
            checkState(ref.getNode().isGetProp() || ref.getNode().isName());
            Node newNode = aliasingRef.getNode().cloneTree();
            Node node = ref.getNode();
            node.replaceWith(newNode);
            compiler.reportChangeToEnclosingScope(newNode);
            newNodes.add(new AstChange(ref.module, ref.scope, newNode));
          }
          aliasingName.removeRef(ref);
          break;
        default:
          throw new IllegalStateException();
      }
    }
  }
1117729
function(str, methodDec, methodName, method, methodsMap, options){
    var methodValue = getMethodValue(methodDec, methodName, method, methodsMap, options);
    if(str === methodDec) return methodValue;
    return str.replace(methodDec, function(){ return methodValue; });
  }
17120
function(methodName, sinceVersion, removeVersion, replacementCall) {
      if(window.console && console.log){
        console.log(methodName + ' has been deprecated since ' + sinceVersion +
          ' and will be removed in version ' + removeVersion + '.' +
          ' Use ' + replacementCall + ' instead.');
      }
    }
168780
public static void checkUnusedParameters(SQLiteModelMethod method, Set<String> usedMethodParameters, TypeName excludedClasses) {
		int paramsCount = method.getParameters().size();
		int usedCount = usedMethodParameters.size();

		if (paramsCount > usedCount) {
			StringBuilder sb = new StringBuilder();
			String separator = "";
			for (Pair<String, TypeName> item : method.getParameters()) {
				if (excludedClasses != null && item.value1.equals(excludedClasses)) {
					usedCount++;
				} else {
					if (!usedMethodParameters.contains(item.value0)) {
						sb.append(separator + "'" + item.value0 + "'");
						separator = ", ";
					}
				}
			}

			if (paramsCount > usedCount) {
				throw (new InvalidMethodSignException(method, "unused parameter(s) " + sb.toString()));
			}
		}
	}
792533
public final void expurge() {
		Reference<? extends E> obj;

		final Iterator<R> iter = this.theSet.iterator();
		R reference;
		while (iter.hasNext()) {
			reference = iter.next();
			if (reference != null
					&& ((reference.isEnqueued()) || (reference.get() == null))) {
				reference.enqueue();
				reference.clear();
			}
		}
		while ((obj = this.queue.poll()) != null) {
			obj.clear();
			if (this.referenceType.isInstance(obj)) {
				this.theSet.remove(this.referenceType.cast(obj));
			}
		}
	}
1073818
private void traverseAndRemoveUnusedReferences(Node root) {
    // Create scope from parent of root node, which also has externs as a child, so we'll
    // have extern definitions in scope.
    Scope scope = scopeCreator.createScope(root.getParent(), null);
    if (!scope.hasSlot(NodeUtil.JSC_PROPERTY_NAME_FN)) {
      // TODO(b/70730762): Passes that add references to this should ensure it is declared.
      // NOTE: null input makes this an extern var.
      scope.declare(
          NodeUtil.JSC_PROPERTY_NAME_FN, /* no declaration node */ null, /* no input */ null);
    }
    worklist.add(new Continuation(root, scope));
    while (!worklist.isEmpty()) {
      Continuation continuation = worklist.remove();
      continuation.apply();
    }

    removeUnreferencedVarsAndPolyfills();
    removeIndependentlyRemovableProperties();
    for (Scope fparamScope : allFunctionParamScopes) {
      removeUnreferencedFunctionArgs(fparamScope);
    }
  }
1132247
function (filter) {
    var obj = {}
    var val = this.__input

    this.each(function (property, key) {
      obj[key] = property.flatten ? property.flatten(filter) : property
    }, wrapFilter(filter))

    if (val !== void 0) {
      if (val instanceof Base) {
        val = {
          reference: val.path
        }
      }
      obj.val = val
    }

    // refactoring non standard keys
    var flattened = flatten(obj)
    for (var key in flattened) {
      if (key.indexOf('.val') > 0) {
        var newKey = key.split('.val')[0]
        flattened[newKey] = flattened[key]
        delete flattened[key]
      }
    }
    return flattened
  }
1267906
def apply_refactor(self, call_id, payload):
        """"""
        supported_refactorings = ["Rename", "InlineLocal", "AddImport", "OrganizeImports"]

        if payload["refactorType"]["typehint"] in supported_refactorings:
            diff_filepath = payload["diff"]
            path = self.editor.path()
            bname = os.path.basename(path)
            target = os.path.join(self.tmp_diff_folder, bname)
            reject_arg = "--reject-file={}.rej".format(target)
            backup_pref = "--prefix={}".format(self.tmp_diff_folder)
            # Patch utility is prepackaged or installed with vim
            cmd = ["patch", reject_arg, backup_pref, path, diff_filepath]
            failed = Popen(cmd, stdout=PIPE, stderr=PIPE).wait()
            if failed:
                self.editor.message("failed_refactoring")
            # Update file and reload highlighting
            self.editor.edit(self.editor.path())
            self.editor.doautocmd('BufReadPre', 'BufRead', 'BufEnter')
1085889
def refactor(module, name, repl):
        
        name = nstr(name)

        # import a module when refactoring based on a string
        if isinstance(module, basestring):
            try:
                module = __import__(module)
            except ImportError:
                logger.exception('Could not import module: %s' % module)
                return False

        try:
            glbls = module.__dict__
        except AttributeError:
            err = '%s cannot support refactoring.' % module.__name__
            logger.exception(err)
            return False

        if name in glbls:
            # refactor the value
            glbls[name] = repl

            return True
        else:
            err = '%s is not a member of %s.' % (name, module.__name__)
            logger.warning(err)
            return False