Replace Param File Write to File Method
558117
def _write(self, session, openFile, replaceParamFile):
        
        # Retrieve TargetParameter objects
        targets = self.targetParameters

        # Write lines
        openFile.write('%s\n' % self.numParameters)

        for target in targets:
            openFile.write('%s %s\n' % (target.targetVariable, target.varFormat))
1264961
def _write(self, session, openFile, replaceParamFile):
        
        # If the raster field is not empty, write from this field
        if self.raster is not None:
            # Configure RasterConverter
            converter = RasterConverter(session)

            # Use MapKit RasterConverter to retrieve the raster as a GRASS ASCII Grid
            grassAsciiGrid = converter.getAsGrassAsciiRaster(rasterFieldName='raster',
                                                             tableName=self.__tablename__,
                                                             rasterIdFieldName='id',
                                                             rasterId=self.id)
            # Write to file
            openFile.write(grassAsciiGrid)

        elif self.rasterText is not None:
            # Write file
            openFile.write(self.rasterText)
915042
private void replaceInFile(String oldText, String newText) {
        StringBuilder oldContent = new StringBuilder();

        try (FileReader fr = new FileReader(file); BufferedReader reader = new BufferedReader(fr)) {
            String line;
            while ((line = reader.readLine()) != null) {
                oldContent.append(line);
                oldContent.append("\r\n");
            }
        } catch (IOException e) {
            log.error(e);
        }

        // replace a word in a file
        String newContent = oldContent.toString().replaceAll(oldText, newText);

        try (FileWriter writer = new FileWriter(file)) {
            writer.write(newContent);
        } catch (IOException ioe) {
            log.error(ioe);
        }
    }
249920
def write_file(self, fileobject, skip_unknown=False):
        """"""
        self.set_metadata_version()

        for field in _version2fieldlist(self['Metadata-Version']):
            values = self.get(field)
            if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']):
                continue
            if field in _ELEMENTSFIELD:
                self._write_field(fileobject, field, ','.join(values))
                continue
            if field not in _LISTFIELDS:
                if field == 'Description':
                    if self.metadata_version in ('1.0', '1.1'):
                        values = values.replace('\n', '\n        ')
                    else:
                        values = values.replace('\n', '\n       |')
                values = [values]

            if field in _LISTTUPLEFIELDS:
                values = [','.join(value) for value in values]

            for value in values:
                self._write_field(fileobject, field, value)
1008054
def write(self, outfile='../parameters/EQcorrscan_parameters.txt',
              overwrite=False):
        
        outpath = os.sep.join(outfile.split(os.sep)[0:-1])
        if len(outpath) > 0 and not os.path.isdir(outpath):
            msg = ' '.join([os.path.join(outfile.split(os.sep)[0:-1]),
                            'does not exist, check path.'])
            raise IOError(msg)
        # Make sure that the user wants to overwrite the old parameters
        if os.path.isfile(outfile) and not overwrite:
            responding = True
            while responding:
                print(' '.join([outfile, 'exists.  Overwrite? [y/N]']))
                option = raw_input()
                if option.upper() == 'N':
                    raise IOError('File exists, will not overwrite')
                elif option.upper() == 'Y':
                    responding = False
                else:
                    print('Must respond with y or n')
        f = open(outfile, 'w')
        # Write creation info.
        header = ' '.join(['# User:', getpass.getuser(),
                           '\n# Creation date:', str(UTCDateTime()),
                           '\n# EQcorrscan version:',
                           str(eqcorrscan.__version__),
                           '\n\n\n'])
        f.write(header)
        # Write parameter info in a user readable, and parsable format.
        parameters = self.__str__().split('\n')[1:]
        f.write('[eqcorrscan_pars]\n')
        for parameter in parameters:
            f.write(parameter.lstrip() + '\n')
        f.close()
        print('Written parameter file: ' + outfile)
416164
function (params) {

            var message = translate(errors[params.caseNum])
                .replace('%n', (params.lineNum + 1).toString())
                .replace('%p', params.pattern)
                .replace('%x', params.start)
                .replace('%y', (params.endLineNum + 1).toString())
                .replace('%f', currentFile);
            if (options.testMode === true) {
                grunt.log.writeln(message);
            } else {
                grunt.warn(message);
            }
        }
1245068
def _writeXput(self, session, directory, fileCards,
                   name=None, replaceParamFile=None):
        
        for card in self.projectCards:
            if (card.name in fileCards) and self._noneOrNumValue(card.value) \
                    and fileCards[card.name]:
                fileIO = fileCards[card.name]
                filename = card.value.strip('"')

                # Check for replacement variables
                if '[' in filename or ']' in filename:
                    log.info('The file for project card {0} cannot be '
                             'written, because the path has been replaced '
                             'with replacement variable {1}.'.format(card.name, filename))
                    return

                # Determine new filename
                filename = self._replaceNewFilename(filename=filename,
                                                    name=name)

                # Invoke write method on each file
                self._invokeWrite(fileIO=fileIO,
                                  session=session,
                                  directory=directory,
                                  filename=filename,
                                  replaceParamFile=replaceParamFile)
1024809
function writeFile(filepath, data, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = {};
  }

  if (!Buffer.isBuffer(data)) {
    return callback(new TypeError('Data must be a Buffer'));
  }

  if (!options) {
    options = {};
  }

  // Default the same as node
  var mode = options.mode || constants.DEFAULT_FILE_MODE;
  var flags = options.flags || 'w';
  var position = APPEND_MODE_REGEXP.test(flags) ? null : 0;

  fs.open(filepath, flags, mode, onOpen);

  function onOpen(openErr, fd) {
    if (openErr) {
      return onComplete(openErr);
    }

    fs.write(fd, data, 0, data.length, position, onComplete);

    function onComplete(writeErr) {
      callback(writeErr, fd);
    }
  }
}
1257627
function (file, writeOptions) {
  writeOptions = writeOptions || {};
  var writeMethod = writeOptions.writeMethod || 'safeDump';
  return index[writeMethod](file, omit(writeOptions, ['writeMethod']));
}
1298561
def _write(self, session, openFile, replaceParamFile):
        
        # Retrieve the events associated with this PrecipFile
        events = self.precipEvents

        # Write each event to file
        for event in events:
            openFile.write('EVENT "%s"\nNRGAG %s\nNRPDS %s\n' % (event.description, event.nrGag, event.nrPds))

            if event.nrGag > 0:
                values = event.values

                valList = []

                # Convert PrecipValue objects into a list of dictionaries, valList,
                # so that it is compatible with the pivot function.
                for value in values:
                    valList.append({'ValueType': value.valueType,
                                    'DateTime': value.dateTime,
                                    'Gage': value.gage.id,
                                    'Value': value.value})

                # Pivot using the function found at:
                # code.activestate.com/recipes/334695
                pivotedValues = pivot.pivot(valList, ('DateTime', 'ValueType'), ('Gage',), 'Value')

                ## TODO: Create custom pivot function that can work with sqlalchemy
                ## objects explicitly without the costly conversion.

                # Create an empty set for obtaining a list of unique gages
                gages = session.query(PrecipGage). \
                    filter(PrecipGage.event == event). \
                    order_by(PrecipGage.id). \
                    all()

                for gage in gages:
                    openFile.write('COORD %s %s "%s"\n' % (gage.x, gage.y, gage.description))

                # Write the value rows out to file
                for row in pivotedValues:
                    # Extract the PrecipValues
                    valString = ''

                    # Retreive a list of sorted keys. This assumes the values are
                    # read into the database in order
                    keys = sorted([key for key in row if key != 'DateTime' and key != 'ValueType'])

                    # String all of the values together into valString
                    for key in keys:
                        if key != 'DateTime' and key != 'ValueType':
                            valString = '%s %.3f' % (valString, row[key])

                    # Write value line to file with appropriate formatting
                    openFile.write('%s %.4d %.2d %.2d %.2d %.2d%s\n' % (
                        row['ValueType'],
                        row['DateTime'].year,
                        row['DateTime'].month,
                        row['DateTime'].day,
                        row['DateTime'].hour,
                        row['DateTime'].minute,
                        valString))
168820
def writeto(self, filename, **kwargs):
        
        fits.PrimaryHDU(header=self).writeto(filename, output_verify='ignore', **kwargs)
997857
def _write_file(iface, data, folder, pattern):
    '''
    
    '''
    filename = os.path.join(folder, pattern.format(iface))
    if not os.path.exists(folder):
        msg = '{0} cannot be written. {1} does not exist'
        msg = msg.format(filename, folder)
        log.error(msg)
        raise AttributeError(msg)
    with salt.utils.files.flopen(filename, 'w') as fout:
        fout.write(salt.utils.stringutils.to_str(data))
    return filename
7453
def _replace_file(path, content):
  """"""
  if os.path.exists(path):
    with open(path, 'r') as f:
      if content == f.read():
        print("Not overwriting {} because it is unchanged".format(path), file=sys.stderr)
        return

  with open(path, 'w') as f:
    f.write(content)
938855
private String writeUpdateString(Map<String, String> param) {
        StringBuffer fieldStringBuffer = new StringBuffer();
        for(Entry<String, String> entry : param.entrySet()){
        	fieldStringBuffer.append("<field name=\"").append(entry.getKey()).append("\">")
        			.append(StringEscapeUtils.escapeXml(entry.getValue())).append("</field>");
        }
        fieldStringBuffer.insert(0,"<add><doc>").append("</doc></add>");
        
        return fieldStringBuffer.toString();
    }
394432
public void copyOutPutFilesToBucket(SubProcessConfiguration configuration, String params) {
    if (Files.exists(outFile) || Files.exists(errFile)) {
      try {
        outFileLocation = FileUtils.copyFileFromWorkerToGCS(configuration, outFile);
      } catch (Exception ex) {
        LOG.error("Error uploading log file to storage ", ex);
      }

      try {
        errFileLocation = FileUtils.copyFileFromWorkerToGCS(configuration, errFile);
      } catch (Exception ex) {
        LOG.error("Error uploading log file to storage ", ex);
      }

      LOG.info(String.format("Log Files for process: %s outFile was: %s errFile was: %s", params,
          outFileLocation, errFileLocation));
    } else {
      LOG.error(String.format("There was no output file or err file for process %s", params));
    }
  }
827719
function(param) {
  var str = param.typeExpression;
  var type = param.type;
  if (!type) {
    return escape(str);
  }

  var replaceWithLinkIfPresent = function(type) {
    if (type.name) {
      str = str.replace(type.name, toMarkdownLinkFormat(type.name));
    }
  };

  if (type.type === 'FunctionType') {
    _.each(type.params, replaceWithLinkIfPresent);
  } else if (type.type === 'TypeApplication') {
    // Is this an Array.<type>?
    var match = str.match(/Array\.<(.*)>/);
    if (match) {
      var typeInsideArray = match[1];
      str = str.replace(typeInsideArray, toMarkdownLinkFormat(typeInsideArray));
    }
  } else if (type.type === 'NameExpression') {
    replaceWithLinkIfPresent(type);
  }

  return escape(str);
}
785
function replaceInFile (filename, regex, replacement) {
    let contents = fs.readFileSync (filename, 'utf8')
    const parts = contents.split (regex)
    const newContents = parts[0] + replacement + parts[1]
    fs.truncateSync (filename)
    fs.writeFileSync (filename, newContents)
}