Apply the changes from a csvdiff patch to an existing CSV file.
543557
def csvpatch_cmd(input_csv, input=None, output=None, strict=True):
    
    patch_stream = (sys.stdin
                    if input is None
                    else open(input))
    tocsv_stream = (sys.stdout
                    if output is None
                    else open(output, 'w'))
    fromcsv_stream = open(input_csv)

    try:
        patch_file(patch_stream, fromcsv_stream, tocsv_stream, strict=strict)

    except patch.InvalidPatchError as e:
        error.abort('reading patch, {0}'.format(e.args[0]))

    finally:
        patch_stream.close()
        fromcsv_stream.close()
        tocsv_stream.close()
245900
def patch(source, sink):
    
    sink = sink()
    for v in source():
        try:
            sink.send(v)
        except StopIteration:
            return
1153911
def patched(f):
    """"""

    def wrapped(*args, **kwargs):

        kwargs['return_response'] = False
        kwargs['prefetch'] = True

        return f(*args, **kwargs)

    return wrapped
500256
def modified_lines_from_udiff(udiff):
    """"""
    chunks = re.split('\n@@ [^\n]+\n', udiff)[1:]

    line_numbers = re.findall('@@\s[+-]\d+,\d+ \+(\d+)', udiff)
    line_numbers = list(map(int, line_numbers))

    for c, start in zip(chunks, line_numbers):
        ilines = enumerate((line for line in c.splitlines()
                            if not line.startswith('-')),
                           start=start)
        added_lines = [i for i, line in ilines if line.startswith('+')]
        if added_lines:
            yield (added_lines[0], added_lines[-1])
17943
def dicom_diff(file1, file2):
    

    datasets = compressed_dicom.read_file(file1), compressed_dicom.read_file(file2)

    rep = []

    for dataset in datasets:
        lines = (str(dataset.file_meta)+"\n"+str(dataset)).split('\n')
        lines = [line + '\n' for line in lines]  # add the newline to the end
        rep.append(lines)

    diff = difflib.Differ()
    for line in diff.compare(rep[0], rep[1]):
        if (line[0] == '+') or (line[0] == '-'):
            sys.stdout.write(line)
1362519
function filesPatch(oldFile, newFile, options) {
  let { diff, toFile } = utils;
  let opts = options || {};

  oldFile = toFile(oldFile, options);
  newFile = toFile(newFile, options);

  let nameA = oldFile.relative;
  let nameB = newFile.relative;

  let strA = oldFile.contents.toString();
  let strB = newFile.contents.toString();

  return diff.createTwoFilesPatch(nameA, nameB, strA, strB, opts.oldHeader, opts.newHeader, opts);
}
238487
def find_diff_violations(self, patch):
        
        violations = collections.defaultdict(list)
        for line in patch.changed_lines:
            file_violations = self._all_violations.get(line['file_name'])
            if not file_violations:
                continue

            line_violations = [v for v in file_violations if v.line == line['line_number']]

            for v in line_violations:
                violations[line['file_name']].append(v)

        return violations
22430
def update(self, stats):
        """"""
        # Get the stats
        all_stats = stats.getAllExportsAsDict(plugin_list=self.plugins_to_export())

        # Init data with timestamp (issue#708)
        if self.first_line:
            csv_header = ['timestamp']
        csv_data = [time.strftime('%Y-%m-%d %H:%M:%S')]

        # Loop over plugins to export
        for plugin in self.plugins_to_export():
            if isinstance(all_stats[plugin], list):
                for stat in all_stats[plugin]:
                    # First line: header
                    if self.first_line:
                        csv_header += ('{}_{}_{}'.format(
                            plugin, self.get_item_key(stat), item) for item in stat)
                    # Others lines: stats
                    csv_data += itervalues(stat)
            elif isinstance(all_stats[plugin], dict):
                # First line: header
                if self.first_line:
                    fieldnames = iterkeys(all_stats[plugin])
                    csv_header += ('{}_{}'.format(plugin, fieldname)
                                   for fieldname in fieldnames)
                # Others lines: stats
                csv_data += itervalues(all_stats[plugin])

        # Export to CSV
        if self.first_line:
            self.writer.writerow(csv_header)
            self.first_line = False
        self.writer.writerow(csv_data)
        self.csv_file.flush()
156920
def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None):
    
    with open(from_file) as from_stream:
        with open(to_file) as to_stream:
            from_records = records.load(from_stream, sep=sep)
            to_records = records.load(to_stream, sep=sep)
            return patch.create(from_records, to_records, index_columns,
                                ignore_columns=ignored_columns)
769635
def _update_with_calls(result_file, cnv_file):
    
    results = {}
    with open(result_file) as in_handle:
        in_handle.readline()  # header
        _, _, cs, ps = in_handle.readline().strip().split()
        for i, (c, p) in enumerate(zip(cs.split(":"), ps.split(","))):
            results[i] = (c, p)
    cnvs = {}
    with open(cnv_file) as in_handle:
        for line in in_handle:
            chrom, start, end, _, count = line.rstrip().split()[:5]
            cnvs[(chrom, start, end)] = count
    def update(i, line):
        parts = line.rstrip().split("\t")
        chrom, start, end = parts[1:4]
        parts += cnvs.get((chrom, start, end), ".")
        parts += list(results[i])
        return "\t".join(parts) + "\n"
    return update
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)
1106556
def _muaprocessnew(self):
        """"""
        foldername = self._foldername("new")
        files = self.filesystem.listdir(foldername)
        for filename in files:
            if filename == "":
                continue
            curfilename = self._foldername(joinpath("new", filename))
            newfilename = joinpath(
                self._cur,
                "%s:2,%s" % (filename, "")
                )
            self.filesystem.rename(curfilename, newfilename)
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')
783483
def _normalize_merge_diff(diff):
        """"""
        new_diff = []
        for line in diff.splitlines():
            # Filter blank lines and prepend +sign
            if line.strip():
                new_diff.append("+" + line)
        if new_diff:
            new_diff.insert(
                0, "! incremental-diff failed; falling back to echo of merge file"
            )
        else:
            new_diff.append("! No changes specified in merge file.")
        return "\n".join(new_diff)
1258604
def patch(filepath, debug):
    
    print("patch 'pause' in %r" % filepath)
    with open(filepath, "r") as infile:
        origin_content = infile.read()

    new_content = origin_content.replace("pause\n", """echo "'pause'"\n""")
    assert new_content!=origin_content, "not changed: %s" % origin_content

    with open(filepath, "w") as outfile:
        outfile.write(new_content)

    print("%r patched" % filepath)
    if debug:
        print("-"*79)
        print(repr(new_content))
        print("-"*79)
        print(new_content)
        print("-"*79)
404557
public static void applySuggestedFixesToFiles(Iterable<SuggestedFix> fixes)
      throws IOException {
    Set<String> filenames = new HashSet<>();
    for (SuggestedFix fix : fixes) {
      filenames.addAll(fix.getReplacements().keySet());
    }

    Map<String, String> filenameToCodeMap = new HashMap<>();
    for (String filename : filenames) {
      filenameToCodeMap.put(filename, Files.asCharSource(new File(filename), UTF_8).read());
    }

    Map<String, String> newCode = applySuggestedFixesToCode(fixes, filenameToCodeMap);
    for (Map.Entry<String, String> entry : newCode.entrySet()) {
      Files.asCharSink(new File(entry.getKey()), UTF_8).write(entry.getValue());
    }
  }
1357815
def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout,
                        sep=',', ignored_columns=None, significance=None):
    
    from_records = list(records.load(from_csv, sep=sep))
    to_records = records.load(to_csv, sep=sep)

    diff = patch.create(from_records, to_records, index_columns, ignored_columns)
    if significance is not None:
        diff = patch.filter_significance(diff, significance)

    _summarize_diff(diff, len(from_records), stream=stream)
    exit_code = (EXIT_SAME
                 if patch.is_empty(diff)
                 else EXIT_DIFFERENT)
    sys.exit(exit_code)