call 'patch -p[level] [--posix] < arg1'

    posix mode is sometimes necessary. It keeps empty files so that
    dpkg-source removes their contents.
494857
def apply_patch(patchfile,cwd=None,posix=False,level=0):
    
    if not os.path.exists(patchfile):
        raise RuntimeError('patchfile "%s" does not exist'%patchfile)
    fd = open(patchfile,mode='r')

    level_str = '-p%d'%level
    args = ['/usr/bin/patch',level_str]
    if posix:
        args.append('--posix')

    log.info('PATCH COMMAND: %s < %s', ' '.join(args), patchfile)
    log.info('  PATCHING in dir: %s', cwd)
#    print >> sys.stderr, 'PATCH COMMAND:',' '.join(args),'<',patchfile
#    print >> sys.stderr, '  PATCHING in dir:',cwd
    res = subprocess.Popen(
        args, cwd=cwd,
        stdin=fd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True
        )
    returncode=None
    while returncode is None:
        returncode = res.poll()
        ready = select.select( [res.stdout,res.stderr],[],[],0.1)
        # XXX figure out how to do this without reading byte-by-byte
        if res.stdout in ready[0]:
            sys.stdout.write(res.stdout.read(1))
            sys.stdout.flush()
        if res.stderr in ready[0]:
            sys.stderr.write(res.stderr.read(1))
            sys.stderr.flush()
    # finish outputting file
    sys.stdout.write(res.stdout.read())
    sys.stdout.flush()
    sys.stderr.write(res.stderr.read())
    sys.stderr.flush()

    if returncode:
        log.error('ERROR running: %s', ' '.join(args))
        log.error('ERROR in %s', cwd)
#        print >> sys.stderr, 'ERROR running: %s'%(' '.join(args),)
#        print >> sys.stderr, 'ERROR in',cwd
        raise RuntimeError('returncode %d'%returncode)
1105670
def apply(self, strip=0, root=None):
    
    if root:
      prevdir = os.getcwd()
      os.chdir(root)

    total = len(self.items)
    errors = 0
    if strip:
      # [ ] test strip level exceeds nesting level
      #   [ ] test the same only for selected files
      #     [ ] test if files end up being on the same level
      try:
        strip = int(strip)
      except ValueError:
        errors += 1
        warning("error: strip parameter '%s' must be an integer" % strip)
        strip = 0

    #for fileno, filename in enumerate(self.source):
    for i,p in enumerate(self.items):
      if strip:
        debug("stripping %s leading component(s) from:" % strip)
        debug("   %s" % p.source)
        debug("   %s" % p.target)
        old = pathstrip(p.source, strip)
        new = pathstrip(p.target, strip)
      else:
        old, new = p.source, p.target

      filename = self.findfile(old, new)

      if not filename:
          warning("source/target file does not exist:\n  --- %s\n  +++ %s" % (old, new))
          errors += 1
          continue
      if not isfile(filename):
        warning("not a file - %s" % filename)
        errors += 1
        continue

      # [ ] check absolute paths security here
      debug("processing %d/%d:\t %s" % (i+1, total, filename))

      # validate before patching
      f2fp = open(filename, 'rb')
      hunkno = 0
      hunk = p.hunks[hunkno]
      hunkfind = []
      hunkreplace = []
      validhunks = 0
      canpatch = False
      for lineno, line in enumerate(f2fp):
        if lineno+1 < hunk.startsrc:
          continue
        elif lineno+1 == hunk.startsrc:
          hunkfind = [x[1:].rstrip(b"\r\n") for x in hunk.text if x[0] in b" -"]
          hunkreplace = [x[1:].rstrip(b"\r\n") for x in hunk.text if x[0] in b" +"]
          #pprint(hunkreplace)
          hunklineno = 0

          # todo \ No newline at end of file

        # check hunks in source file
        if lineno+1 < hunk.startsrc+len(hunkfind)-1:
          if line.rstrip(b"\r\n") == hunkfind[hunklineno]:
            hunklineno+=1
          else:
            info("file %d/%d:\t %s" % (i+1, total, filename))
            info(" hunk no.%d doesn't match source file at line %d" % (hunkno+1, lineno+1))
            info("  expected: %s" % hunkfind[hunklineno])
            info("  actual  : %s" % line.rstrip(b"\r\n"))
            # not counting this as error, because file may already be patched.
            # check if file is already patched is done after the number of
            # invalid hunks if found
            # TODO: check hunks against source/target file in one pass
            #   API - check(stream, srchunks, tgthunks)
            #           return tuple (srcerrs, tgterrs)

            # continue to check other hunks for completeness
            hunkno += 1
            if hunkno < len(p.hunks):
              hunk = p.hunks[hunkno]
              continue
            else:
              break

        # check if processed line is the last line
        if lineno+1 == hunk.startsrc+len(hunkfind)-1:
          debug(" hunk no.%d for file %s  -- is ready to be patched" % (hunkno+1, filename))
          hunkno+=1
          validhunks+=1
          if hunkno < len(p.hunks):
            hunk = p.hunks[hunkno]
          else:
            if validhunks == len(p.hunks):
              # patch file
              canpatch = True
              break
      else:
        if hunkno < len(p.hunks):
          warning("premature end of source file %s at hunk %d" % (filename, hunkno+1))
          errors += 1

      f2fp.close()

      if validhunks < len(p.hunks):
        if self._match_file_hunks(filename, p.hunks):
          warning("already patched  %s" % filename)
        else:
          warning("source file is different - %s" % filename)
          errors += 1
      if canpatch:
        backupname = filename+b".orig"
        if exists(backupname):
          warning("can't backup original file to %s - aborting" % backupname)
        else:
          import shutil
          shutil.move(filename, backupname)
          if self.write_hunks(backupname, filename, p.hunks):
            info("successfully patched %d/%d:\t %s" % (i+1, total, filename))
            os.unlink(backupname)
          else:
            errors += 1
            warning("error patching file %s" % filename)
            shutil.copy(filename, filename+".invalid")
            warning("invalid version is saved to %s" % filename+".invalid")
            # todo: proper rejects
            shutil.move(backupname, filename)

    if root:
      os.chdir(prevdir)

    # todo: check for premature eof
    return (errors == 0)
71969
def clean(args):
    
    p = OptionParser(clean.__doc__)
    opts, args = p.parse_args(args)

    for link_name in os.listdir(os.getcwd()):
        if not op.islink(link_name):
            continue
        logging.debug("remove symlink `{0}`".format(link_name))
        os.unlink(link_name)
204260
def destroy_decompress(dinfo):
    """"""
    argtypes = [ctypes.POINTER(DecompressionInfoType)]
    OPENJPEG.opj_destroy_decompress.argtypes = argtypes
    OPENJPEG.opj_destroy_decompress(dinfo)
1013001
def fix_pdf_with_ghostscript_to_tmp_file(input_doc_fname):
    """"""

    if not gs_executable: init_and_test_gs_executable(exit_on_fail=True)
    temp_file_name = get_temporary_filename(extension=".pdf")
    gs_run_command = [gs_executable, "-dSAFER", "-o", temp_file_name,
                    "-dPDFSETTINGS=/prepress", "-sDEVICE=pdfwrite", input_doc_fname]
    try:
        gs_output = get_external_subprocess_output(gs_run_command, print_output=True,
                                             indent_string="   ", env=gs_environment)
    except subprocess.CalledProcessError:
        print("\nError in pdfCropMargins:  Ghostscript returned a non-zero exit"
              "\nstatus when attempting to fix the file:\n   ", input_doc_fname,
              file=sys.stderr)
        cleanup_and_exit(1)
    except UnicodeDecodeError:
        print("\nWarning in pdfCropMargins:  In attempting to repair the PDF file"
              "\nGhostscript produced a message containing characters which cannot"
              "\nbe decoded by the 'utf-8' codec.  Ignoring and hoping for the best.",
              file=sys.stderr)
    return temp_file_name
1359964
function fixImportedSourceMap(file, state, callback) {
  if (!state.map) {
    return callback();
  }

  state.map.sourcesContent = state.map.sourcesContent || [];

  nal.map(state.map.sources, normalizeSourcesAndContent, callback);

  function assignSourcesContent(sourceContent, idx) {
    state.map.sourcesContent[idx] = sourceContent;
  }

  function normalizeSourcesAndContent(sourcePath, idx, cb) {
    var sourceRoot = state.map.sourceRoot || '';
    var sourceContent = state.map.sourcesContent[idx] || null;

    if (isRemoteSource(sourcePath)) {
      assignSourcesContent(sourceContent, idx);
      return cb();
    }

    if (state.map.sourcesContent[idx]) {
      return cb();
    }

    if (sourceRoot && isRemoteSource(sourceRoot)) {
      assignSourcesContent(sourceContent, idx);
      return cb();
    }

    var basePath = path.resolve(file.base, sourceRoot);
    var absPath = path.resolve(state.path, sourceRoot, sourcePath);
    var relPath = path.relative(basePath, absPath);
    var unixRelPath = normalizePath(relPath);

    state.map.sources[idx] = unixRelPath;

    if (absPath !== file.path) {
      // Load content from file async
      return fs.readFile(absPath, onRead);
    }

    // If current file: use content
    assignSourcesContent(state.content, idx);
    cb();

    function onRead(err, data) {
      if (err) {
        assignSourcesContent(null, idx);
        return cb();
      }
      assignSourcesContent(removeBOM(data).toString('utf8'), idx);
      cb();
    }
  }
}
770576
def apply_patch(self, filename, arch, build_dir=None):
        
        info("Applying patch {}".format(filename))
        build_dir = build_dir if build_dir else self.get_build_dir(arch)
        filename = join(self.get_recipe_dir(), filename)
        shprint(sh.patch, "-t", "-d", build_dir, "-p1",
                "-i", filename, _tail=10)
851658
def dedup(args):
    
    from jcvi.formats.fasta import gaps
    from jcvi.apps.cdhit import deduplicate, ids

    p = OptionParser(dedup.__doc__)
    p.set_align(pctid=GoodPct)
    p.set_mingap(default=10)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    scaffolds, = args
    mingap = opts.mingap
    splitfile, oagpfile, cagpfile = gaps([scaffolds, "--split", "--mingap={0}".format(mingap)])

    dd = splitfile + ".cdhit"
    clstrfile = dd + ".clstr"
    idsfile = dd + ".ids"
    if need_update(splitfile, clstrfile):
        deduplicate([splitfile, "--pctid={0}".format(opts.pctid)])
    if need_update(clstrfile, idsfile):
        ids([clstrfile])

    agp = AGP(cagpfile)
    reps = set(x.split()[-1] for x in open(idsfile))
    pf = scaffolds.rsplit(".", 1)[0]
    dedupagp = pf + ".dedup.agp"
    fw = open(dedupagp, "w")

    ndropped = ndroppedbases = 0
    for a in agp:
        if not a.is_gap and a.component_id not in reps:
            span = a.component_span
            logging.debug("Drop component {0} ({1})".\
                          format(a.component_id, span))
            ndropped += 1
            ndroppedbases += span
            continue
        print(a, file=fw)
    fw.close()

    logging.debug("Dropped components: {0}, Dropped bases: {1}".\
                  format(ndropped, ndroppedbases))
    logging.debug("Deduplicated file written to `{0}`.".format(dedupagp))

    tidyagp = tidy([dedupagp, splitfile])
    dedupfasta = pf + ".dedup.fasta"
    build([tidyagp, dd, dedupfasta])

    return dedupfasta
1304529
def patch_init_py(base_dir, name, version):
    """"""
    # Ensure main package dir is there (may be absent in script-only packages)
    package_dir = os.path.join(base_dir, name)
    if not os.path.isdir(package_dir):
        os.makedirs(package_dir)
    # Open top-level __init__.py and read whole file
    init_py = os.path.join(package_dir, '__init__.py')
    log.info("patching %s to bake in version '%s'" % (init_py, version))
    with open(init_py, 'r+') as init_file:
        lines = init_file.readlines()
        # Search for sentinels indicating version checking block
        try:
            begin = lines.index("# BEGIN VERSION CHECK\n")
            end = lines.index("# END VERSION CHECK\n")
        except ValueError:
            begin = end = len(lines)
        # Delete existing repo version checking block in file
        init_file.seek(0)
        init_file.writelines(lines[:begin] + lines[end+1:])
        # Append new version attribute to ensure it is authoritative, but only
        # if it is not already there (this happens in pip sdist installs)
        version_cmd = "__version__ = '{0}'\n".format(version)
        if not lines or lines[-1] != version_cmd:
            init_file.write("\n# Automatically added by katversion\n")
            init_file.write(version_cmd)
        init_file.truncate()
1286027
function pkgdir() {
	var parts,
		len,
		str,
		i;

	parts = cwd().split( path.sep );
	len = parts.length;
	for ( i = 0; i < len; i++ ) {
		str = parts.join( path.sep );
		if ( exists( path.join( str, 'package.json' ) ) ) {
			return str;
		}
		parts.pop();
	}
	return null;
}
376591
def dpkg_source(b_or_x,arg1,cwd=None):
    ""
    assert b_or_x in ['-b','-x']
    args = ['/usr/bin/dpkg-source',b_or_x,arg1]
    process_command(args, cwd=cwd)
900785
def add_patchs_to_build_without_pkg_config(self, lib_dir, include_dir):
        
        additional_patches = [
            {
                'src': r"pkgconfig\('--libs-only-L'\)",
                'dest': "['{0}']".format(lib_dir),
            },
            # Considering -libs-only-l and -libs-only-L
            # https://github.com/rpm-software-management/rpm/pull/327
            {
                'src': r"pkgconfig\('--libs(-only-l)?'\)",
                'dest': "['rpm', 'rpmio']",
                'required': True,
            },
            {
                'src': r"pkgconfig\('--cflags'\)",
                'dest': "['{0}']".format(include_dir),
                'required': True,
            },
        ]
        self.patches.extend(additional_patches)
1307511
def fix(args):
    
    p = OptionParser(fix.__doc__)
    p.add_option("--ignore_sym_pat", default=False, action="store_true",
        help="Do not fix names matching symbol patterns i.e." + \
        " names beginning or ending with gene symbols or a series of numbers." + \
        " e.g. `ARM repeat superfamily protein`, `beta-hexosaminidase 3`," + \
        " `CYCLIN A3;4`, `WALL ASSOCIATED KINASE (WAK)-LIKE 10`")
    p.set_outfile()
    opts, args = p.parse_args(args)

    if len(args) < 1:
        sys.exit(not p.print_help())

    csvfile, = args
    fp = open(csvfile)
    fw = must_open(opts.outfile, "w")
    for row in fp:
        if row[0] == '#':
            continue
        if row.strip() == "":
            continue
        atoms = row.rstrip("\r\n").split("\t")
        name, hit, ahrd_code, desc = atoms[:4] \
                if len(atoms) > 2 else \
                (atoms[0], None, None, atoms[-1])

        newdesc = fix_text(desc, ignore_sym_pat=opts.ignore_sym_pat)
        if hit and hit.strip() != "" and newdesc == Hypothetical:
            newdesc = "conserved " + newdesc
        print("\t".join(atoms[:4] + [newdesc] + atoms[4:]), file=fw)
522994
def pkg_install(self):
        
        flag = []
        options = [
            "-s",
            "--sync"
        ]
        additional_options = [
            "--resolve-off",
            "--download-only",
            "--directory-prefix=",
            "--case-ins",
            "--rebuild",
            "--reinstall",
            "--patches"
        ]
        for arg in self.args:
            if arg.startswith(additional_options[2]):
                flag.append(arg)
                arg = ""
            if arg in additional_options:
                flag.append(arg)
        # clean from flags
        for ar in flag:
            if ar in self.args:
                self.args.remove(ar)
        if len(self.args) >= 3 and self.args[0] in options:
            if (self.args[1] in self.meta.repositories and
                    self.args[1] not in ["sbo"]):
                BinaryInstall(self.args[2:], self.args[1], flag).start(
                    is_upgrade=False)
            elif (self.args[1] == "sbo" and
                    self.args[1] in self.meta.repositories):
                SBoInstall(self.args[2:], flag).start(is_upgrade=False)
            else:
                usage(self.args[1])
        else:
            usage("")
53318
def cleanup(config_dir):
    """"""
    stdout_path = os.path.join(config_dir, 'pueue.stdout')
    stderr_path = os.path.join(config_dir, 'pueue.stderr')
    if os._exists(stdout_path):
        os.remove(stdout_path)
    if os._exists(stderr_path):
        os.remove(stderr_path)

    socketPath = os.path.join(config_dir, 'pueue.sock')
    if os.path.exists(socketPath):
        os.remove(socketPath)
1100463
function entrifyFromPkg(dir, options) {

  // Find package.json files.
  const pkgPaths = glob.sync('**/package.json', { cwd: dir, nodir: true, absolute: true })

  pkgPaths.forEach((pkgPath) => {
    console.log('[entrify]', 'Found:', pkgPath)
    const pkg = require(pkgPath)

    // A package.json file should have a main entry.
    if (!pkg.main) {
      console.warn('[entrify]', pkgPath, 'does not have a main entry.')
      return
    }

    // The main entry should not point to an index.js file.
    if (pkg.main === 'index.js' || pkg.main === './index.js') {
      console.warn('[entrify]', pkgPath, 'main entry is index.js.')
      return
    }

    // Ensure the index.js file to create doesn't already exist.
    const pkgDir = path.dirname(pkgPath)
    const indexPath = `${pkgDir}/index.js`

    if (fs.existsSync(indexPath)) {
      console.warn('[entrify]', indexPath, 'already exists.')
      return
    }

    // Create an index.js file alongside the package.json.
    const name = camelize(path.basename(pkgDir))
    const main = pkg.main.startsWith('./') ? pkg.main : `./${pkg.main}`

    fs.writeFileSync(indexPath, indexTemplate(options.format, { name, main }))
    console.log('[entrify]', indexPath, 'created!')

    // Delete the package.json file.
    fs.unlinkSync(pkgPath)
    console.log('[entrify]', pkgPath, 'deleted!')
  })
}
790349
def strip_files(files, argv_max=(256 * 1024)):
    
    tostrip = [(fn, flipwritable(fn)) for fn in files]
    while tostrip:
        cmd = list(STRIPCMD)
        flips = []
        pathlen = reduce(operator.add, [len(s) + 1 for s in cmd])
        while pathlen < argv_max:
            if not tostrip:
                break
            added, flip = tostrip.pop()
            pathlen += len(added) + 1
            cmd.append(added)
            flips.append((added, flip))
        else:
            cmd.pop()
            tostrip.append(flips.pop())
        os.spawnv(os.P_WAIT, cmd[0], cmd)
        for args in flips:
            flipwritable(*args)