Update a file's copyright statement to include the given year
960094
def update_copyright(path, year):
    
    with open(path, "r") as fobj:
        text = fobj.read().rstrip()
    match = COPYRIGHT_REGEX.search(text)
    x = match.start("years")
    y = match.end("years")
    if text[y-1] == " ":  # don't strip trailing whitespace
        y -= 1
    yearstr = match.group("years")
    years = set(_parse_years(yearstr)) | {year}
    with open(path, "w") as fobj:
        print(text[:x] + _format_years(years) + text[y:], file=fobj)
343292
def Copy(self,
           old_urn,
           new_urn,
           age=NEWEST_TIME,
           limit=None,
           update_timestamps=False):
    """"""
    new_urn = rdfvalue.RDFURN(new_urn)

    if update_timestamps and age != NEWEST_TIME:
      raise ValueError(
          "Can't update timestamps unless reading the latest version.")

    values = {}
    for predicate, value, ts in data_store.DB.ResolvePrefix(
        old_urn,
        AFF4_PREFIXES,
        timestamp=self.ParseAgeSpecification(age),
        limit=limit):
      if update_timestamps:
        values.setdefault(predicate, []).append((value, None))
      else:
        values.setdefault(predicate, []).append((value, ts))

    if values:
      with data_store.DB.GetMutationPool() as pool:
        pool.MultiSet(new_urn, values, replace=False)
        self._UpdateChildIndex(new_urn, pool)
966183
def replace_if_changed(localfile, jottapath, JFS):
    """"""
    jf = JFS.getObject(jottapath)
    lf_hash = getxattrhash(localfile) # try to read previous hash, stored in xattr
    if lf_hash is None:               # no valid hash found in xattr,
        with open(localfile) as lf:
            lf_hash = calculate_md5(lf) # (re)calculate it
    if type(jf) == JFSIncompleteFile:
        log.debug("Local file %s is incompletely uploaded, continue", localfile)
        return resume(localfile, jf, JFS)
    elif jf.md5 == lf_hash: # hashes are the same
        log.debug("hash match (%s), file contents haven't changed", lf_hash)
        setxattrhash(localfile, lf_hash)
        return jf         # return the version from jottaclouds
    else:
        setxattrhash(localfile, lf_hash)
        return new(localfile, jottapath, JFS)
175123
def copyright2marc(self, key, value):
    """"""
    E_MAP = {
        'publication': 'Article',
    }

    e_value = value.get('material')

    return {
        'd': value.get('holder'),
        'e': E_MAP.get(e_value),
        'f': value.get('statement'),
        'g': value.get('year'),
        'u': value.get('url'),
    }
283478
def last_modified_date(filename):
    """"""
    mtime = os.path.getmtime(filename)
    dt = datetime.datetime.utcfromtimestamp(mtime)
    return dt.replace(tzinfo=pytz.utc)
594559
function updateExistingFile(db, fileName, fileReadStream, options, cb) {
  defaultLogger.debug("In updateExistingFile");

  getFileDetails(db, {"groupId": options.groupId}, {}, function(err, fileInfo) {
    if (err) {
      defaultLogger.error(err); return cb(err);
    }
    var latestFileVersion = fileInfo.metadata.version;
    incrementFileVersion(latestFileVersion, function(newFileVersion) {
      if (!newFileVersion) {
        return cb(new Error("File version was not incremented for file " + fileName));
      }
      defaultLogger.debug("New File Version ", newFileVersion);
      createFileWithVersion(db, fileName, fileReadStream, newFileVersion, options, cb);
    });
  });
}
813715
def update(self, of):
        """"""

        # The other values should be set when the file object is created with dataset.bsfile()
        for p in ('mime_type', 'preference', 'state', 'hash', 'modified', 'size', 'contents', 'source_hash', 'data'):
            setattr(self, p, getattr(of, p))

        return self
167688
def load_version_as_string():
    """"""
    with open(VERSION_PATH, 'r') as rfile:
        contents = rfile.read().strip()

    _, version = contents.split('=')
    version = version.strip()

    # Remove quotes
    return version.strip('"\'')
1237062
function updateFilesList(adds, removes, prefix, name, currentVersion) {
    let configuration = loadConfiguration();
    let filesList = configuration.filesList;
    let modified = false;

    // manage custom prefix
    if (prefix) {
        configuration.versionPrefix = prefix;
        modified = true;
        print('new custom version prefix: ' + prefix, 'completed', 'spaced22');
    }

    // manage custom name and currentVersion
    if (name) {
        configuration.name = name;
        modified = true;
        print('new project name: ' + name, 'completed', 'spaced22');
    }
    if (currentVersion) {
        configuration.currentVersion = currentVersion;
        modified = true;
        print('new project currentVersion: ' + currentVersion, 'completed', 'spaced22');
    }

    function findFileInList(fileName) {
        for(i = 0; i < configuration.filesList.length; i++) {
            if (configuration.filesList[i].indexOf(fileName) === 0) {
                return i;
            }
        }
        return -1;
    }

    // manage additions
    if (adds) {
        let addArray = adds.split(',');

        addArray.forEach(function(a, index) {
            let fileData = a.split(':');
            let fileName = fileData[0];
            let fileType = fileData[1];

            let fileString;
            let fileTypeString;

            if (fileType) {
                fileString = a;
                fileTypeString = fileType;
            }
            else {
                // autodetect file type
                let ext = fileName.split('.');
                    ext = ext[ext.length - 1];

                for (let key in fileTypeExtensions) {
                    if (fileTypeExtensions.hasOwnProperty(key)) {
                        let extList = fileTypeExtensions[key];

                        if (extList.indexOf(ext) >= 0) {
                            fileType = key;
                            break;
                        }
                    }
                }

                if (fileType) {
                    fileString = fileName + ':' + fileType;
                    fileTypeString = fileType;
                }
                else {
                    fileString = fileName;
                    fileTypeString = 'normal';
                }
            }

            if (fileTypeString !== 'normal' && supportedVersioningTypes.indexOf(fileTypeString) < 0) {
                print('The versioning type: ' + fileTypeString + 'is unknown -> file skipped', 'strongWarning', 'date');
            }
            else {
                if (fs.existsSync(fileName)) {
                    let isInFileList = findFileInList(fileName);

                    if (isInFileList < 0) {
                        if (!modified) {
                            modified = true;
                        }

                        filesList.push(fileString);
                        print('file ' + fileName + ' added to list, type of file: ' + fileTypeString, 'completed', 'date');
                    }
                    else {
                        let oldFileType = configuration.filesList[isInFileList].split(':')[1];

                        if (oldFileType !== fileType) {
                            if (!modified) {
                                modified = true;
                            }

                            filesList[isInFileList] = fileString;
                            print('file ' + fileName + ' is already in list but the type has been changed to: ' + fileTypeString, 'completed', 'date');
                        }
                        else {
                            print('file ' + fileName + ' is already in versionFilesList.json with same type -> discarded', 'msgWarning', 'date');
                        }
                    }
                }
                else {
                    print('file ' + a[0] + ' does not exists -> discarded', 'msgWarning', 'date');
                }
            }
        });
    }

    //manage removals
    if (removes) {
        console.log('');
        let remArray = removes.split(',');

        remArray.forEach(function(r, index) {
            let isInFileList = findFileInList(r);

            if (isInFileList >= 0) {
                if (!modified) {
                    modified = true;
                }

                filesList.splice(isInFileList, 1);
                print('file ' + r + ' removed from list', 'completed', 'date');
            }
            else {
                print('file ' + r + ' is not in list -> nothing to remove', 'msgWarning', 'date');
            }
        });
    }

    if (modified) {
        configuration.filesList = filesList;

        fs.writeFileSync('./.versionFilesList.json', JSON.stringify(configuration, null, 2));
        print('.versionFilesList.json updated', 'completed', 'date');
    }

    process.exit(0);
}
782734
def do_file_update_metadata(client, args):
    """"""
    client.update_file_metadata(args.uri, filename=args.filename,
                                description=args.description, mtime=args.mtime,
                                privacy=args.privacy)
    return True
19281
def require_compatible_version(compatible_version, word="File"):
    """"""
    if isinstance(compatible_version, str):
        compatible_version = parse_version(compatible_version)
    elif not isinstance(compatible_version, Version):
        raise ValueError("Type of `compatible_version` not understood.")
    
    current_version = parse_version(CURRENT_VERSION)
    if current_version < compatible_version:
        raise VersionError("{0} written for version >= {1}, this is {2}.".format(
            word, str(compatible_version), CURRENT_VERSION
        ))
53467
def fix_header_comment(filename, timestamp):
    """"""
    # Fix input file.
    name = os.path.basename( filename )
    for line in fileinput.input( filename, inplace=1, mode="rU" ):
        # If header-comment already contains anything for '$Id$', remove it.
        line = re.sub(r'\$Id:[^$]+\$', r'$Id$', line.rstrip())
        # Replace '$Id$' by a string containing the file's name (and a timestamp)!
        line = re.sub(re.escape(r'$Id$'), r'$Id: ' + name + r' ' + timestamp.isoformat() + r' $', line.rstrip())
        print(line)
374241
def patch_file(actions, tree):
    """"""
    tree = etree.parse(tree)

    if isinstance(actions, six.string_types):
        # It's a string, so it's a filename
        with open(actions) as f:
            actions = f.read()
    else:
        # We assume it's a stream
        actions = actions.read()

    actions = patch.DiffParser().parse(actions)
    tree = patch_tree(actions, tree)
    return etree.tounicode(tree)
447184
def update_stampfile_hook(self, dependencies):  # suppress(no-self-use)
        """"""
        hashes = {d: _sha1_for_file(d) for d in dependencies
                  if os.path.exists(d)}
        with open(self._stamp_file_hashes_path, "wb") as hashes_file:
            hashes_file.write(json.dumps(hashes).encode("utf-8"))
477306
def touch(filename, timestamp):
    """"""
    if timestamp is not None:
        timestamp = (timestamp, timestamp)  # atime, mtime

    from os import utime
    utime(filename, timestamp)
44225
function uglifyWithCopyrights() {
    const preserveComments = (f) => {
        return (_node, comment) => {
            const text = comment.value;
            const type = comment.type;
            if (/@minifier_do_not_preserve/.test(text)) {
                return false;
            }
            const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
            if (isOurCopyright) {
                if (f.__hasOurCopyright) {
                    return false;
                }
                f.__hasOurCopyright = true;
                return true;
            }
            if ('comment2' === type) {
                // check for /*!. Note that text doesn't contain leading /*
                return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
            }
            else if ('comment1' === type) {
                return /license|copyright/i.test(text);
            }
            return false;
        };
    };
    const minify = composer(uglifyes);
    const input = es.through();
    const output = input
        .pipe(flatmap((stream, f) => {
        return stream.pipe(minify({
            output: {
                comments: preserveComments(f),
                max_line_len: 1024
            }
        }));
    }));
    return es.duplex(input, output);
}
355526
def generate_version_file(self, schema_filename, binding_filename):
        """"""
        version_filename = binding_filename + '_version.txt'
        version_path = os.path.join(self.binding_dir, version_filename)
        schema_path = os.path.join(self.schema_dir, schema_filename)
        try:
            tstamp, svnpath, svnrev, version = self.get_version_info_from_svn(
                schema_path
            )
        except TypeError:
            pass
        else:
            self.write_version_file(version_path, tstamp, svnpath, svnrev, version)