Write Optional Cross Section Cards to File Method
356975
def _writeOptionalXsecCards(self, fileObject, xSec, replaceParamFile):
        
        if xSec.erode:
            fileObject.write('ERODE\n')

        if xSec.maxErosion != None:
            fileObject.write('MAX_EROSION    %.6f\n' % xSec.maxErosion)

        if xSec.subsurface:
            fileObject.write('SUBSURFACE\n')

        if xSec.mRiver != None:
            mRiver = vwp(xSec.mRiver, replaceParamFile)
            try:
                fileObject.write('M_RIVER        %.6f\n' % mRiver)
            except:
                fileObject.write('M_RIVER        %s\n' % mRiver)

        if xSec.kRiver != None:
            kRiver = vwp(xSec.kRiver, replaceParamFile)
            try:
                fileObject.write('K_RIVER        %.6f\n' % kRiver)
            except:
                fileObject.write('K_RIVER        %s\n' % kRiver)
336228
def _cellChunk(self, lines):
        
        KEYWORDS = ('CELLIJ',
                    'NUMPIPES',
                    'SPIPE')

        result = {'i': None,
                  'j': None,
                  'numPipes': None,
                  'spipes': []}

        chunks = pt.chunk(KEYWORDS, lines)

        # Parse chunks associated with each key
        for card, chunkList in iteritems(chunks):
            # Parse each chunk in the chunk list
            for chunk in chunkList:
                schunk = chunk[0].strip().split()

                # Cases
                if card == 'CELLIJ':
                    # CELLIJ handler
                    result['i'] = schunk[1]
                    result['j'] = schunk[2]

                elif card == 'NUMPIPES':
                    # NUMPIPES handler
                    result['numPipes'] = schunk[1]

                elif card == 'SPIPE':
                    # SPIPE handler
                    pipe = {'linkNumber': schunk[1],
                            'nodeNumber': schunk[2],
                            'fraction': schunk[3]}

                    result['spipes'].append(pipe)

        return result
1028206
def write_tables_to_fits(filepath, tablelist, clobber=False,
                         namelist=None, cardslist=None, hdu_list=None):
    
    outhdulist = [fits.PrimaryHDU()]
    rmlist = []
    for i, table in enumerate(tablelist):
        ft_name = "%s._%i" % (filepath, i)
        rmlist.append(ft_name)
        try:
            os.unlink(ft_name)
        except:
            pass
        table.write(ft_name, format="fits")
        ft_in = fits.open(ft_name)
        if namelist:
            ft_in[1].name = namelist[i]
        if cardslist:
            for k, v in cardslist[i].items():
                ft_in[1].header[k] = v
        ft_in[1].update()
        outhdulist += [ft_in[1]]

    if hdu_list is not None:
        for h in hdu_list:
            outhdulist.append(h)

    fits.HDUList(outhdulist).writeto(filepath, overwrite=clobber)
    for rm in rmlist:
        os.unlink(rm)
838636
def _write_remaining_pages(self):
        """"""
        if not self._tags or self._truncate:
            return

        pageno = self._shape[0] * self._datashape[0] - 1
        if pageno < 1:
            self._tags = None
            self._datadtype = None
            self._dataoffset = None
            self._databytecounts = None
            return

        fh = self._fh
        fhpos = fh.tell()
        if fhpos % 2:
            fh.write(b'\0')
            fhpos += 1

        pack = struct.pack
        offsetformat = self._byteorder + self._offsetformat
        offsetsize = self._offsetsize
        tagnoformat = self._byteorder + self._tagnoformat
        tagsize = self._tagsize
        dataoffset = self._dataoffset
        pagedatasize = sum(self._databytecounts)

        # construct template IFD in memory
        # need to patch offsets to next IFD and data before writing to file
        ifd = io.BytesIO()
        ifd.write(pack(tagnoformat, len(self._tags)))
        tagoffset = ifd.tell()
        ifd.write(b''.join(t[1] for t in self._tags))
        ifdoffset = ifd.tell()
        ifd.write(pack(offsetformat, 0))  # offset to next IFD
        # tag values
        for tagindex, tag in enumerate(self._tags):
            offset = tagoffset + tagindex * tagsize + offsetsize + 4
            code = tag[0]
            value = tag[2]
            if value:
                pos = ifd.tell()
                if pos % 2:
                    # tag value is expected to begin on word boundary
                    ifd.write(b'\0')
                    pos += 1
                ifd.seek(offset)
                try:
                    ifd.write(pack(offsetformat, fhpos + pos))
                except Exception:  # struct.error
                    if self._imagej:
                        warnings.warn('truncating ImageJ file')
                        self._truncate = True
                        return
                    raise ValueError('data too large for non-BigTIFF file')
                ifd.seek(pos)
                ifd.write(value)
                if code == self._tagoffsets:
                    # save strip/tile offsets for later updates
                    dataoffsetsoffset = offset, pos
            elif code == self._tagoffsets:
                dataoffsetsoffset = offset, None

        ifdsize = ifd.tell()
        if ifdsize % 2:
            ifd.write(b'\0')
            ifdsize += 1

        # check if all IFDs fit in file
        if not self._bigtiff and fhpos + ifdsize * pageno > 2**32 - 32:
            if self._imagej:
                warnings.warn('truncating ImageJ file')
                self._truncate = True
                return
            raise ValueError('data too large for non-BigTIFF file')

        # assemble IFD chain in memory from IFD template
        ifds = io.BytesIO(bytes(ifdsize * pageno))
        ifdpos = fhpos
        for _ in range(pageno):
            # update strip/tile offsets in IFD
            dataoffset += pagedatasize  # offset to image data
            offset, pos = dataoffsetsoffset
            ifd.seek(offset)
            if pos:
                ifd.write(pack(offsetformat, ifdpos + pos))
                ifd.seek(pos)
                offset = dataoffset
                for size in self._databytecounts:
                    ifd.write(pack(offsetformat, offset))
                    offset += size
            else:
                ifd.write(pack(offsetformat, dataoffset))
            # update pointer at ifdoffset to point to next IFD in file
            ifdpos += ifdsize
            ifd.seek(ifdoffset)
            ifd.write(pack(offsetformat, ifdpos))
            # write IFD entry
            ifds.write(iogetbuffer(ifd))

        # terminate IFD chain
        ifdoffset += ifdsize * (pageno - 1)
        ifds.seek(ifdoffset)
        ifds.write(pack(offsetformat, 0))
        # write IFD chain to file
        fh.write(iogetbuffer(ifds))
        # update file to point to new IFD chain
        pos = fh.tell()
        fh.seek(self._ifdoffset)
        fh.write(pack(offsetformat, fhpos))
        fh.flush()
        fh.seek(pos)

        self._ifdoffset = fhpos + ifdoffset
        self._tags = None
        self._datadtype = None
        self._dataoffset = None
        self._databytecounts = None
1202635
async function exportCustomSelectorsToMjsFile(to, customSelectors) {
	const mjsContents = Object.keys(customSelectors).reduce((mjsLines, name) => {
		mjsLines.push(`\t'${escapeForJS(name)}': '${escapeForJS(customSelectors[name])}'`);

		return mjsLines;
	}, []).join(',\n');
	const mjs = `export const customSelectors = {\n${mjsContents}\n};\n`;

	await writeFile(to, mjs);
}
1187989
private function _writeMsoDrawing()
	{
		// write the Escher stream if necessary
		if (isset($this->_escher)) {
			$writer = new PHPExcel_Writer_Excel5_Escher($this->_escher);
			$data = $writer->close();
			$spOffsets = $writer->getSpOffsets();
			$spTypes = $writer->getSpTypes();
			// write the neccesary MSODRAWING, OBJ records

			// split the Escher stream
			$spOffsets[0] = 0;
			$nm = count($spOffsets) - 1; // number of shapes excluding first shape
			for ($i = 1; $i <= $nm; ++$i) {
				// MSODRAWING record
				$record = 0x00EC;			// Record identifier

				// chunk of Escher stream for one shape
				$dataChunk = substr($data, $spOffsets[$i -1], $spOffsets[$i] - $spOffsets[$i - 1]);

				$length = strlen($dataChunk);
				$header = pack("vv", $record, $length);

				$this->_append($header . $dataChunk);

				// OBJ record
				$record = 0x005D; // record identifier
				$objData = '';

				// ftCmo
				if($spTypes[$i] == 0x00C9){
					// Add ftCmo (common object data) subobject
					$objData .=
						pack('vvvvvVVV'
								, 0x0015	// 0x0015 = ftCmo
								, 0x0012	// length of ftCmo data
								, 0x0014	// object type, 0x0014 = filter
								, $i		// object id number, Excel seems to use 1-based index, local for the sheet
								, 0x2101	// option flags, 0x2001 is what OpenOffice.org uses
								, 0			// reserved
								, 0			// reserved
								, 0			// reserved
						);

					// Add ftSbs Scroll bar subobject
					$objData .= pack('vv', 0x00C, 0x0014);
					$objData .= pack('H*', '0000000000000000640001000A00000010000100');
					// Add ftLbsData (List box data) subobject
					$objData .= pack('vv', 0x0013, 0x1FEE);
					$objData .= pack('H*', '00000000010001030000020008005700');
				}
				else {
					// Add ftCmo (common object data) subobject
					$objData .=
						pack('vvvvvVVV'
							, 0x0015	// 0x0015 = ftCmo
							, 0x0012	// length of ftCmo data
							, 0x0008	// object type, 0x0008 = picture
							, $i		// object id number, Excel seems to use 1-based index, local for the sheet
							, 0x6011	// option flags, 0x6011 is what OpenOffice.org uses
							, 0			// reserved
							, 0			// reserved
							, 0			// reserved
						);
				}

				// ftEnd
				$objData .=
					pack('vv'
						, 0x0000	// 0x0000 = ftEnd
						, 0x0000	// length of ftEnd data
					);

				$length = strlen($objData);
				$header = pack('vv', $record, $length);
				$this->_append($header . $objData);
			}
		}
	}
513242
def save_as outfile
      _t = "(all rows)"
      if @selected_indices.size > 0
        _t = "(selected rows)"
      end
      unless outfile
        outfile = get_string "Enter file name to save #{_t} as "
        return unless outfile
      end

      # if there is a selection, then write only selected rows
      l = nil
      if @selected_indices.size > 0
        l = []
        @list.each_with_index { |v,i| l << v if @selected_indices.include? i }
      else
        l = @list
      end

      File.open(outfile, 'w') {|f|
        l.each {|r|
          line = r.join "\t"
          f.puts line
        }
      }
    end
1359277
def _write_section(self, fp, section_name, section_items, delimiter):
        """"""
        fp.write("[{0}]\n".format(section_name))
        for key, value in section_items:
            value = self._interpolation.before_write(self, section_name, key,
                                                     value)
            if value is not None or not self._allow_no_value:
                value = delimiter + str(value).replace('\n', '\n\t')
            else:
                value = ""
            fp.write("{0}{1}\n".format(key, value))
        fp.write("\n")
940804
function renderTemplateFiles (skipInterpolation) {
  skipInterpolation = typeof skipInterpolation === 'string'
    ? [skipInterpolation]
    : skipInterpolation
  return (files, metalsmith, done) => {
    const keys = Object.keys(files)
    const metalsmithMetadata = metalsmith.metadata()
    async.each(keys, (file, next) => {
      // skipping files with skipInterpolation option
      if (skipInterpolation && multimatch([file], skipInterpolation, { dot: true }).length) {
        return next()
      }
      const str = files[file].contents.toString()
      // do not attempt to render files that do not have mustaches
      if (!/{{([^{}]+)}}/g.test(str)) {
        return next()
      }
      render(str, metalsmithMetadata, (err, res) => {
        if (err) {
          err.message = `[${file}] ${err.message}`
          return next(err)
        }
        files[file].contents = Buffer.from(res)
        next()
      })
    }, done)
  }
}
308960
def to_vcards(self):
        """"""
        self._update()
        return [self._to_vcard(self._book[entry]) for entry in self._book.sections()]
786593
def _eval_card(source, card):
	
	if isinstance(card, LazyValue):
		card = card.evaluate(source)

	if isinstance(card, Action):
		card = card.trigger(source)[0]

	if not isinstance(card, list):
		cards = [card]
	else:
		cards = card

	ret = []
	for card in cards:
		if isinstance(card, str):
			ret.append(source.controller.card(card, source))
		else:
			ret.append(card)

	return ret
588468
function writeApplicationFileForMultipleApplications(application) {
  const applicationBaseName = application[GENERATOR_NAME].baseName;
  checkPath(applicationBaseName);
  createFolderIfNeeded(applicationBaseName);
  writeConfigFile(application, path.join(applicationBaseName, '.yo-rc.json'));
}
751962
def write(filename, mesh, file_format=None, **kwargs):
    
    if not file_format:
        # deduce file format from extension
        file_format = _filetype_from_filename(filename)

    # check cells for sanity
    for key, value in mesh.cells.items():
        if key[:7] == "polygon":
            assert value.shape[1] == int(key[7:])
        else:
            assert value.shape[1] == num_nodes_per_cell[key]

    try:
        interface, args, default_kwargs = _writer_map[file_format]
    except KeyError:
        raise KeyError(
            "Unknown format '{}'. Pick one of {}".format(
                file_format, sorted(list(_writer_map.keys()))
            )
        )

    # Build kwargs
    _kwargs = default_kwargs.copy()
    _kwargs.update(kwargs)

    # Write
    return interface.write(filename, mesh, *args, **_kwargs)
849088
def to_abook(card, section, book, bookfile=None):
        """"""
        book[section] = {}
        book[section]['name'] = card.fn.value

        if hasattr(card, 'email'):
            book[section]['email'] = ','.join([e.value for e in card.email_list])

        if hasattr(card, 'adr'):
            Abook._conv_adr(card.adr, book[section])

        if hasattr(card, 'tel_list'):
            Abook._conv_tel_list(card.tel_list, book[section])

        if hasattr(card, 'nickname') and card.nickname.value:
            book[section]['nick'] = card.nickname.value

        if hasattr(card, 'url') and card.url.value:
            book[section]['url'] = card.url.value

        if hasattr(card, 'note') and card.note.value:
            book[section]['notes'] = card.note.value

        if hasattr(card, 'photo') and bookfile:
            try:
                photo_file = join(dirname(bookfile), 'photo/%s.%s' % (card.fn.value, card.photo.TYPE_param))
                open(photo_file, 'wb').write(card.photo.value)
            except IOError:
                pass
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)
171466
function wrap(elements, options) {
    elements = toArray(elements);
    /* Don't wrap only a container in a container */
    if (elements.length === 1 && isContainer(elements[0])) {
        return elements[0];
    }
    var container = {
        type: cardTypes.container,
        items: elements
    };
    setOptions(container, options);
    return container;
}
225179
def _write_vxr(self, f, numEntries=None):
        '''
        
        '''

        f.seek(0, 2)
        byte_loc = f.tell()
        section_type = CDF.VXR_
        nextVXR = 0
        if (numEntries == None):
            nEntries = CDF.NUM_VXR_ENTRIES
        else:
            nEntries = int(numEntries)
        block_size = CDF.VXR_BASE_SIZE64 + (4 + 4 + 8) * nEntries
        nUsedEntries = 0
        firsts = [-1] * nEntries
        lasts = [-1] * nEntries
        offsets = [-1] * nEntries

        vxr = bytearray(block_size)
        vxr[0:8] = struct.pack('>q', block_size)
        vxr[8:12] = struct.pack('>i', section_type)
        vxr[12:20] = struct.pack('>q', nextVXR)
        vxr[20:24] = struct.pack('>i', nEntries)
        vxr[24:28] = struct.pack('>i', nUsedEntries)
        estart = 28 + 4*nEntries
        vxr[28:estart] = struct.pack('>%si' % nEntries, *firsts)
        eend = estart + 4*nEntries
        vxr[estart:eend] = struct.pack('>%si' % nEntries, *lasts)
        vxr[eend:block_size] = struct.pack('>%sq' % nEntries, *offsets)
        f.write(vxr)
        return byte_loc