Patch the file system
325186
function patch(fs) {
    if (fs[NS])
        return;

    const virtualFS = {
        files: {},
        add(options) {
            const file = path.resolve(options.path);
            if (virtualFS.files[file] && virtualFS.files[file].content.equals(options.content)) {
                return;
            }
            virtualFS.files[file] = {
                path: file,
                content: options.content,
            };
        },
    };
    fs[NS] = virtualFS;

    createPatchFn(fs, 'readFile', function (orig, args, file, encoding, cb) {
        const rfile = path.resolve(file);
        const vfile = virtualFS.files[rfile];
        if (vfile) {
            if (typeof encoding === 'function') {
                cb = encoding;
                encoding = null;
            }

            let content = vfile.content;
            if (encoding !== null)
                content = content.toString(encoding);

            cb(null, content);
            return;
        }
        return orig.apply(this, args);
    });
    createPatchFn(fs, 'readFileSync', function (orig, args, file, encoding) {
        const rfile = path.resolve(file);
        const vfile = virtualFS.files[rfile];
        if (vfile) {
            let content = vfile.content;
            if (encoding !== null)
                content = content.toString(encoding);
            return content;
        }
        return orig.apply(this, args);
    });

    createPatchFn(fs, 'stat', function (orig, args, p, cb) {
        const rp = path.resolve(p);
        const vfile = virtualFS.files[rp];
        if (vfile) {
            const vstat = {
                dev: 8675309,
                nlink: 1,
                uid: 501,
                gid: 20,
                rdev: 0,
                blksize: 4096,
                ino: 44700000,
                mode: 33188,
                size: vfile.content.length,
                isFile: function isFile() {
                    return true;
                },
                isDirectory: function isDirectory() {
                    return false;
                },
                isBlockDevice: function isBlockDevice() {
                    return false;
                },
                isCharacterDevice: function isCharacterDevice() {
                    return false;
                },
                isSymbolicLink: function isSymbolicLink() {
                    return false;
                },
                isFIFO: function isFIFO() {
                    return false;
                },
                isSocket: function isSocket() {
                    return false;
                },
            };
            cb(null, vstat);
            return;
        }
        return orig.apply(this, args);
    });
    createPatchFn(fs, 'statSync', function (orig, args, p) {
        const rp = path.resolve(p);
        const vfile = virtualFS.files[rp];
        if (vfile) {
            const vstat = {
                dev: 8675309,
                nlink: 1,
                uid: 501,
                gid: 20,
                rdev: 0,
                blksize: 4096,
                ino: 44700000,
                mode: 33188,
                size: vfile.content.length,
                isFile: function isFile() {
                    return true;
                },
                isDirectory: function isDirectory() {
                    return false;
                },
                isBlockDevice: function isBlockDevice() {
                    return false;
                },
                isCharacterDevice: function isCharacterDevice() {
                    return false;
                },
                isSymbolicLink: function isSymbolicLink() {
                    return false;
                },
                isFIFO: function isFIFO() {
                    return false;
                },
                isSocket: function isSocket() {
                    return false;
                },
            };
            return vstat;
        }
        return orig.apply(this, args);
    });
}
335988
def patch(path, headers: {}, query: {}, payload: {})
      @parent.patch("/#{@segment}/#{path}".gsub(%r{/+}, '/'),
                    heades: @default_headers.merge(headers), query: query, payload: payload)
    end
323742
def patch_sys(self, inherit_path):
    """"""
    def patch_dict(old_value, new_value):
      old_value.clear()
      old_value.update(new_value)

    def patch_all(path, path_importer_cache, modules):
      sys.path[:] = path
      patch_dict(sys.path_importer_cache, path_importer_cache)
      patch_dict(sys.modules, modules)

    new_sys_path, new_sys_path_importer_cache, new_sys_modules = self.minimum_sys(inherit_path)

    new_sys_path.extend(merge_split(self._pex_info.pex_path, self._vars.PEX_PATH))

    patch_all(new_sys_path, new_sys_path_importer_cache, new_sys_modules)
104573
def CleanUp(self, path):
    """"""
    try:
      if os.path.exists(path):
        os.remove(path)
    except (OSError, IOError) as e:
      logging.info("Failed to remove temporary file %s. Err: %s", path, e)
713893
def teardown(self):
        """"""

        for proxy in self._proxies.values():
            proxy.restore_original_object()

        for patch in self._patches.values():
            patch.restore_original_object()
723851
def fileupdate(self, data):
        """"""

        self.name = data["name"]
        add = self.__additional
        add["filetype"] = "other"
        for filetype in ("book", "image", "video", "audio", "archive"):
            if filetype in data:
                add["filetype"] = filetype
                break
        if add["filetype"] in ("image", "video", "audio"):
            add["thumb"] = data.get("thumb", dict())
        # checksum is md5
        add["checksum"] = data["checksum"]
        add["expire_time"] = data["expires"] / 1000
        add["size"] = data["size"]
        add["info"] = data.get(add["filetype"], dict())
        add["uploader"] = data["user"]
        if self.room.admin:
            add["info"].update({"room": data.get("room")})
            add["info"].update({"uploader_ip": data.get("uploader_ip")})
        self.updated = True
960254
def patch(cls):
        
        orig = distutils.core.Distribution
        distutils.core.Distribution = cls
        try:
            yield
        finally:
            distutils.core.Distribution = orig
765902
def patch(self, patch):
        """"""
        # explicitly pick out the parts to update so we don't inadvertently
        # step on the model name or anything
        self._contents.update({
            'patch_path': patch.original_file_path,
            'description': patch.description,
            'columns': patch.columns,
            'docrefs': patch.docrefs,
        })
        # patches always trigger re-validation
        self.validate()
453277
function _monkeypatch(filePath, monkeyPatched, processor, complete) {
  async.waterfall(
    [
      function read(next) {
        fs.readFile(filePath, 'utf8', next);
      },

      // TODO - need to parse gyp file - this is a bit hacker
      function monkeypatch(content, next) {
        if (monkeyPatched(content)) return complete();

        _log('monkey patch %s', filePath);
        processor(content, next);
      },

      function write(content, next) {
        fs.writeFile(filePath, content, 'utf8', function(err) {
          return next(err);
        });
      },
    ],
    complete,
  );
}
88639
def patchFile(filename, replacements):
		
		patched = Utility.readFile(filename)
		
		# Perform each of the replacements in the supplied dictionary
		for key in replacements:
			patched = patched.replace(key, replacements[key])
		
		Utility.writeFile(filename, patched)
926773
def freeze_archive(tmp_dir, dest_prefix):
    """"""
    zip_filename = "%s/aomi-blah.zip" % tmp_dir
    archive = zipfile.ZipFile(zip_filename, 'w')
    for root, _dirnames, filenames in os.walk(dest_prefix):
        for filename in filenames:
            relative_path = subdir_path(root, dest_prefix).split(os.sep)[1:]
            relative_path = os.sep.join(relative_path)
            archive.write("%s/%s" % (root, filename),
                          "%s/%s" % (relative_path, filename))

    archive.close()
    return zip_filename
770980
def can_patch(self, filename):
    
    filename = abspath(filename)
    for p in self.items:
      if filename == abspath(p.source):
        return self._match_file_hunks(filename, p.hunks)
    return None
5311
def apply_fixes(args, tmpdir):
  """"""
  invocation = [args.clang_apply_replacements_binary]
  if args.format:
    invocation.append('-format')
  if args.style:
    invocation.append('-style=' + args.style)
  invocation.append(tmpdir)
  subprocess.call(invocation)
121688
def _repair(self):
        
        self.files = list(filter(self._safe_path, self.files))
1138964
def patch_xml(files, root_file=None, float_precision=3):
    
    if float_precision < 0:
        raise ValueError("precision must be greater than 0")

    def fix_path(match):
        path = match.group(1)
        if path:
            head, tail = os.path.split(path)
            new_path = os.path.join(os.path.basename(head), tail)
        else:
            new_path = ''
        return '<Input>{0}</Input>'.format(new_path)

    for xmlfilename in files:
        xmlfilename = os.path.abspath(os.path.normpath(xmlfilename))
        patched_xmlfilename = '{0}.tmp'.format(xmlfilename)
        log.info("patching {0} ...".format(xmlfilename))
        fin = open(xmlfilename, 'r')
        fout = open(patched_xmlfilename, 'w')
        for line in fin:
            if root_file is not None:
                line = re.sub(
                    'InputFile="[^"]*"',
                    'InputFile="{0}"'.format(root_file), line)
            line = line.replace(
                '<StatError Activate="True"  InputFile=""  '
                'HistoName=""  HistoPath=""  />',
                '<StatError Activate="True" />')
            line = re.sub(
                '<Combination OutputFilePrefix="(\S*)" >',
                '<Combination OutputFilePrefix="hist2workspace" >', line)
            line = re.sub('\w+=""', '', line)
            line = re.sub('\s+/>', ' />', line)
            line = re.sub('(\S)\s+</', r'\1</', line)
            # HistFactory bug:
            line = re.sub('InputFileHigh="\S+"', '', line)
            line = re.sub('InputFileLow="\S+"', '', line)
            # HistFactory bug:
            line = line.replace(
                '<ParamSetting Const="True"></ParamSetting>', '')
            # chop off floats to desired precision
            line = re.sub(
                r'"(\d*\.\d{{{0:d},}})"'.format(float_precision + 1),
                lambda x: '"{0}"'.format(
                    str(round(float(x.group(1)), float_precision))),
                line)
            line = re.sub('"\s\s+(\S)', r'" \1', line)
            line = re.sub('<Input>(.*)</Input>', fix_path, line)
            fout.write(line)
        fin.close()
        fout.close()
        shutil.move(patched_xmlfilename, xmlfilename)
        if not os.path.isfile(os.path.join(
                              os.path.dirname(xmlfilename),
                              'HistFactorySchema.dtd')):
            rootsys = os.getenv('ROOTSYS', None)
            if rootsys is not None:
                dtdfile = os.path.join(rootsys, 'etc/HistFactorySchema.dtd')
                target = os.path.dirname(xmlfilename)
                if os.path.isfile(dtdfile):
                    log.info("copying {0} to {1} ...".format(dtdfile, target))
                    shutil.copy(dtdfile, target)
                else:
                    log.warning("{0} does not exist".format(dtdfile))
            else:
                log.warning(
                    "$ROOTSYS is not set so cannot find HistFactorySchema.dtd")
799037
def update(connection, force_download):
    """"""
    manager.database.update(
        connection=connection,
        force_download=force_download
    )
154521
def fixpath(path):
    """"""
    return os.path.normpath(os.path.realpath(os.path.expanduser(path)))