Replace shortcuts in imported files
492051
function(filepath, source) {
            var parser = parsers.get(path.extname(filepath));
            var type = parser? parser.name : null;

            return  that.applyShortcuts(type, source);
        }
368790
def _init_code_edit(self, backend):
        
        from pyqode.core import panels, modes
        self.modes.append(_LinkHighlighter(self.document()))
        self.background = self._formatter.color_scheme.background
        self.foreground = self._formatter.color_scheme.foreground
        self._reset_stylesheet()
        self.setCenterOnScroll(False)
        self.setMouseTracking(True)
        self.setUndoRedoEnabled(False)
        search_panel = panels.SearchAndReplacePanel()
        self.panels.append(search_panel, search_panel.Position.TOP)
        self.action_copy.setShortcut('Ctrl+Shift+C')
        self.action_paste.setShortcut('Ctrl+Shift+V')
        self.remove_action(self.action_undo, sub_menu=None)
        self.remove_action(self.action_redo, sub_menu=None)
        self.remove_action(self.action_cut, sub_menu=None)
        self.remove_action(self.action_duplicate_line, sub_menu=None)
        self.remove_action(self.action_indent)
        self.remove_action(self.action_un_indent)
        self.remove_action(self.action_goto_line)
        self.remove_action(search_panel.menu.menuAction())
        self.remove_menu(self._sub_menus['Advanced'])
        self.add_action(search_panel.actionSearch, sub_menu=None)
        self.modes.append(modes.ZoomMode())
        self.backend.start(backend)
1314053
def fix_e401(self, result):
        """"""
        line_index = result['line'] - 1
        target = self.source[line_index]
        offset = result['column'] - 1

        if not target.lstrip().startswith('import'):
            return []

        indentation = re.split(pattern=r'\bimport\b',
                               string=target, maxsplit=1)[0]
        fixed = (target[:offset].rstrip('\t ,') + '\n' +
                 indentation + 'import ' + target[offset:].lstrip('\t ,'))
        self.source[line_index] = fixed
218180
def fix_builtins(override_debug=False):
    """"""
    override_dict = {}
    orig_print = None
    used_print = None

    if(__builtins__.__class__ is dict):
        builtins_dict = __builtins__
    else:
        try:
            import builtins
        except ImportError:
            import __builtin__ as builtins
        builtins_dict = builtins.__dict__

    def _deprecated(*args, **kwargs):
        """Report the fact that the called function is deprecated."""
        import traceback
        raise DeprecationWarning("the called function is deprecated => " +
                                 traceback.extract_stack(None, 2)[0][3])

    def _print_wrapper(*args, **kwargs):
        flush = kwargs.get("flush", False)
        if "flush" in kwargs:
            del kwargs["flush"]
        orig_print(*args, **kwargs)
        if flush:
            kwargs.get("file", sys.stdout).flush()

    def _print_full(*args, **kwargs):
        opt = {"sep": " ", "end": "\n", "file": sys.stdout, "flush": False}
        for key in kwargs:
            if(key in opt):
                opt[key] = kwargs[key]
            else:
                raise TypeError("'"+key+"' is an invalid keyword argument "
                                "for this function")
        opt["file"].write(opt["sep"].join(str(val) for val in args)+opt["end"])
        if opt["flush"]:
            opt["file"].flush()

    def _sorted(my_list):
        my_list = list(my_list)
        my_list.sort()
        return my_list

    def _format(value, format_spec):
        return value.__format__(format_spec)

    if builtins_dict.get(__name__, False):
        raise RuntimeError(__name__+" already loaded")

    # Exceptions
    if builtins_dict.get("BaseException") is None:
        override_dict["BaseException"] = Exception

    # basestring
    if builtins_dict.get("basestring") is None:
        if builtins_dict.get("bytes") is None:
            import types
            override_dict["basestring"] = types.StringType
        else:
            override_dict["basestring"] = (str, bytes)  # It works only when used in isinstance
    # IntType
    if getattr(int, "__str__", None) is None:
        import types
        override_dict["IntType"] = types.IntType
    else:
        override_dict["IntType"] = int  # Python >= 2.2

    if 'format' not in str.__dict__:
        override_dict["str"] = _Internal.ExtStr
    # Function 'input'
    if builtins_dict.get("raw_input") is not None:
        override_dict["input"] = builtins_dict.get("raw_input")
    override_dict["raw_input"] = _deprecated
    # Function 'print' (also aliased as print_)
    if sys.version_info >= (3, 3):
        used_print = builtins_dict.get("print")
    else:
        orig_print = builtins_dict.get("print")
        if orig_print is not None:
            used_print = _print_wrapper
        else:
            used_print = _print_full
        override_dict["print"] = used_print
    override_dict["print_"] = used_print
    # Function 'sorted'
    if builtins_dict.get("sorted") is None:
        override_dict["sorted"] = _sorted
    # Function 'format'
    if builtins_dict.get("format") is None:
        override_dict["format"] = _format

    override_dict[__name__] = True
    builtins_dict.update(override_dict)
    del override_dict
623286
function replaceMacro(code) {
		if (!re) return getKeys(code);
		var match = code.match(re);
		if (!match) return getKeys(code);

		var includeFile = match[1];
		includeFile = path.relative(self.config.root, path.join(path.dirname(fileName), includeFile));

		self._parse(includeFile, function (err, includeCode) {
			if (err) return callback(err);
			includeCode = '\n\r-- ' + macro + ' ' + match[1] + ':\n'
				+ includeCode
				+ '\n\r-- End of ' + match[1];
			code = code.replace(match[0], includeCode);
			replaceMacro(code);
		});
	}
942831
function applyShortcut(content, shortcut) {
    var start = shortcut.getStart();
    var end = shortcut.getEnd();

    var tagStart = shortcut.getStartTag();
    var tagEnd = shortcut.getEndTag();

    var regex = new RegExp(
        escapeStringRegexp(start) + '([\\s\\S]*?[^\\$])' + escapeStringRegexp(end),
       'g'
    );
    return content.replace(regex, function(all, match) {
        return '{% ' + tagStart + ' %}' + match + '{% ' + tagEnd + ' %}';
    });
}
399476
def refactor_organize_imports(self):
        """"""
        refactor = ImportOrganizer(self.project)
        changes = refactor.organize_imports(self.resource)
        return translate_changes(changes)
128628
def copy_and_replace(file_in, file_out, mapping, **kwargs):
    '''
    
    '''
    separator = '@@'
    if 'separator' in kwargs:
        separator = kwargs['separator']
    file_in = open(file_in, 'r')
    file_out = open(file_out, 'w')
    s = file_in.read()
    for find, replace in mapping:
        find = separator + find + separator
        print(u'Replacing {0} with {1}'.format(find, replace))
        s = s.replace(find, replace)
    file_out.write(s)
958192
def handle_aliases_in_init_files(name, import_alias_mapping):
    
    for key, val in import_alias_mapping.items():
        # e.g. Foo == Foo
        # e.g. Foo.Bar startswith Foo.
        if name == val or \
                name.startswith(val + '.'):

            # Replace val with key in name
            # e.g. StarbucksVisitor.Tea -> Eataly.Tea because
            #   "from .nested_folder import StarbucksVisitor as Eataly"
            return name.replace(val, key)
    return None
1200654
def _clone_file_everywhere(self, finfo):
        """"""
        for editorstack in self.editorstacks[1:]:
            editor = editorstack.clone_editor_from(finfo, set_current=False)
            self.register_widget_shortcuts(editor)
518476
def _get_shortcut_string(shortcut):
    """"""
    if shortcut is None:
        return ''
    if isinstance(shortcut, (tuple, list)):
        return ', '.join([_get_shortcut_string(s) for s in shortcut])
    if isinstance(shortcut, string_types):
        if hasattr(QKeySequence, shortcut):
            shortcut = QKeySequence(getattr(QKeySequence, shortcut))
        else:
            return shortcut.lower()
    assert isinstance(shortcut, QKeySequence)
    s = shortcut.toString() or ''
    return str(s).lower()
1251429
def _replace_match(m, env):
    """"""
    # ditch the curly braces
    s = m.group()[1:-1].strip()

    try:
        # get the env attributes e.g. envpython or toxinidir.
        # Note: if you ask for a env methodname this will raise
        # later on... so don't do that.
        return getattr(env, s)
    except AttributeError:
        pass

    for r in [_replace_envvar, _replace_config, _replace_posargs]:
        try:
            return r(s, env)
        except ValueError:
            pass

    raise NotImplementedError("{%s} not understood in tox.ini file." % s)
429010
function replace(file, options) {
  var contents = file.contents;
  var copied = 0;

  var processed = translate(options, contents, copied, file.path);

  var files = [];
  for (var lang in processed) {
    var params = {};
    params.ext = path.extname(file.path).substr(1);
    params.name = path.basename(file.path, path.extname(file.path));
    params.path = file.path.substring(file.base.length, file.path.lastIndexOf(path.sep));
    params.lang = lang;

    var filePath = options.filename;
    for (var param in params) {
      filePath = filePath.replace('${' + param + '}', params[param]);
    }
    filePath = path.join(file.base,filePath);

    var newFile = new gutil.File({
      base: file.base,
      cwd: file.cwd,
      path: filePath,
      contents: new Buffer(processed[lang], 'utf8')
    });
    files.push(newFile);
  }

	return files;
}
943000
def fixchars(self):
        """"""
        for key in Config.CHARFIXES:
            self.project.set_search_string(key)
            self.project.set_search_replacement(Config.CHARFIXES[key])
            self.project.replace_all()
495381
function replaceInFile (filename, regex, replacement) {
    log.bright.cyan ('Exporting exchanges →', filename.yellow)
    let contents = fs.readFileSync (filename, 'utf8')
    const newContents = contents.replace (regex, replacement)
    fs.truncateSync (filename)
    fs.writeFileSync (filename, newContents)
}
844953
def transform_import(self, node, results):
        
        import_mod = results.get("module")
        pref = import_mod.prefix

        names = []

        # create a Node list of the replacement modules
        for name in MAPPING[import_mod.value][:-1]:
            names.extend([Name(name[0], prefix=pref), Comma()])
        names.append(Name(MAPPING[import_mod.value][-1][0], prefix=pref))
        import_mod.replace(names)
676359
function replacePlaceholders(src, options) {
	return Object.keys(placeholders).reduce((out, placeholder) => {
		return out.replace(new RegExp(`${placeholder}`, 'g'), placeholders[placeholder]);
	}, src);
}