Write the parameter file in the format that elaxtix likes.
163081
def _write_parameter_file(params):
    
    
    # Get path
    path = os.path.join(get_tempdir(), 'params.txt')
    
    # Define helper function
    def valToStr(val):
        if val in [True, False]:
            return '"%s"' % str(val).lower()
        elif isinstance(val, int):
            return str(val)
        elif isinstance(val, float):
            tmp = str(val)
            if not '.' in tmp:
                tmp += '.0'
            return tmp
        elif isinstance(val, str):
            return '"%s"' % val
    
    # Compile text
    text = ''
    for key in params:
        val = params[key]
        # Make a string of the values
        if isinstance(val, (list, tuple)):
            vals = [valToStr(v) for v in val]
            val_ = ' '.join(vals)
        else:
            val_ = valToStr(val)
        # Create line and add
        line = '(%s %s)' % (key, val_)
        text += line + '\n'
    
    # Write text
    f = open(path, 'wb')
    try:
        f.write(text.encode('utf-8'))
    finally:
        f.close()
    
    # Done
    return path
270242
def write(file, system):
    

    # TODO: Check for bugs!!!

    out = list()
    out.append('# DOME format version 1.0')
    ppl = 7  # parameter per line
    retval = True
    dev_list = sorted(system.devman.devices)
    for dev in dev_list:
        model = system.__dict__[dev]
        if not model.n:
            continue

        out.append('')
        header = dev + ', '
        space = ' ' * (len(dev) + 2)
        keys = list(model._data.keys())
        keys.extend(['name', 'idx'])
        keys = sorted(keys)

        # remove non-existent keys
        for key in keys:
            if key not in model.__dict__.keys():
                keys.pop(key)

        nline = int(ceil(len(keys) / ppl))
        nelement = model.n
        vals = [''] * len(keys)

        # for each element, read values
        for elem in range(nelement):
            for idx, key in enumerate(keys):
                if model._flags['sysbase'] and key in model._store.keys():
                    val = model._store[key][elem]
                else:
                    val = model.__dict__[key][elem]

                if isinstance(val, float):
                    val = round(val, 5)
                elif isinstance(val, str):
                    val = '"{}"'.format(val)
                elif isinstance(val, list):
                    val = list(val)
                    val = '; '.join(str(i) for i in val)
                    val = '[{}]'.format(val)
                elif val is None:
                    val = 0
                vals[idx] = val

            pair = []
            for key, val in zip(keys, vals):
                pair.append('{} = {}'.format(key, val))

            for line in range(nline):
                string = ', '.join(pair[ppl * line:ppl * (line + 1)])
                if line == 0:  # append header or space
                    string = header + string
                else:
                    string = space + string
                if not line == nline - 1:  # add comma except for last line
                    string += ','

                out.append(string)

    fid = open(file, 'w')
    for line in out:
        fid.write(line + '\n')

    fid.close()
    return retval
15956
def write_Composition(file, composition, bpm=120, repeat=0, verbose=False):
    """"""
    m = MidiFile()
    t = []
    for x in range(len(composition.tracks)):
        t += [MidiTrack(bpm)]
    m.tracks = t
    while repeat >= 0:
        for i in range(len(composition.tracks)):
            m.tracks[i].play_Track(composition.tracks[i])
        repeat -= 1
    return m.write_file(file, verbose)
627005
def pyxwriter(self):
        """"""
        model = self.Model()
        if hasattr(self, 'Parameters'):
            model.parameters = self.Parameters(vars(self))
        else:
            model.parameters = parametertools.Parameters(vars(self))
        if hasattr(self, 'Sequences'):
            model.sequences = self.Sequences(model=model, **vars(self))
        else:
            model.sequences = sequencetools.Sequences(model=model,
                                                      **vars(self))
        return PyxWriter(self, model, self.pyxfilepath)
455370
def _fast_write(self, outfile, value):
        """"""
        outfile.truncate(0)
        outfile.write(str(int(value)))
        outfile.flush()
1166857
def fastaAlignmentWrite(columnAlignment, names, seqNo, fastaFile,
                        filter=lambda x : True):
    
    fastaFile = open(fastaFile, 'w')
    columnAlignment = [ i for i in columnAlignment if filter(i) ]
    for seq in xrange(0, seqNo):
        fastaFile.write(">%s\n" % names[seq])
        for column in columnAlignment:
            fastaFile.write(column[seq])
        fastaFile.write("\n")
    fastaFile.close()
102531
private void writeLegacyFormatting(List<Object> list, Object paramExtractor) {
        if (paramExtractor != null) {
            list.add("{\"params\":");
            list.add(paramExtractor);
            list.add(",");
        }
        else {
            list.add("{");
        }

        if (HAS_SCRIPT) {
            /*
             * {
             *   "params": ...,
             *   "lang": "...",
             *   "script": "...",
             *   "upsert": {...}
             * }
             */
            if (HAS_LANG) {
                list.add(SCRIPT_LANG_1X);
            }
            list.add(SCRIPT_1X);
            if (UPSERT) {
                list.add(",\"upsert\":");
            }
        }
        else {
            /*
             * {
             *   "doc_as_upsert": true,
             *   "doc": {...}
             * }
             */
            if (UPSERT) {
                list.add("\"doc_as_upsert\":true,");
            }
            list.add("\"doc\":");
        }
    }
1138550
def write_template_file(source, target, content):
    """"""

    # print(formatTemplateFile(source, content))
    print(target)
    data = format_template_file(source, content)
    with open(target, 'w') as f:
        for line in data:
            if type(line) != str:
                line = line.encode('utf-8')
            f.write(line)
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)
1010416
def write(self, x):
        """"""
        if self._new_lines:
            if not self._first_write:
                self.stream.write('\n' * self._new_lines)
                self.code_lineno += self._new_lines
                if self._write_debug_info is not None:
                    self.debug_info.append((self._write_debug_info,
                                            self.code_lineno))
                    self._write_debug_info = None
            self._first_write = False
            self.stream.write('    ' * self._indentation)
            self._new_lines = 0
        self.stream.write(x)
696342
public void writeFile(TileDao tileDao) {
		try {
			PrintWriter pw = new PrintWriter(propertiesFile);

			TileMatrixSet tileMatrixSet = tileDao.getTileMatrixSet();
			pw.println(GEOPACKAGE_PROPERTIES_EPSG + "="
					+ tileMatrixSet.getSrs().getOrganizationCoordsysId());
			pw.println(GEOPACKAGE_PROPERTIES_MIN_X + "="
					+ tileMatrixSet.getMinX());
			pw.println(GEOPACKAGE_PROPERTIES_MAX_X + "="
					+ tileMatrixSet.getMaxX());
			pw.println(GEOPACKAGE_PROPERTIES_MIN_Y + "="
					+ tileMatrixSet.getMinY());
			pw.println(GEOPACKAGE_PROPERTIES_MAX_Y + "="
					+ tileMatrixSet.getMaxY());

			for (TileMatrix tileMatrix : tileDao.getTileMatrices()) {
				long zoom = tileMatrix.getZoomLevel();
				pw.println(getMatrixWidthProperty(zoom) + "="
						+ tileMatrix.getMatrixWidth());
				pw.println(getMatrixHeightProperty(zoom) + "="
						+ tileMatrix.getMatrixHeight());
			}

			pw.close();

		} catch (FileNotFoundException e) {
			throw new GeoPackageException(
					"GeoPackage file format properties file could not be created: "
							+ propertiesFile, e);
		}
	}
1212870
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
    """"""
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position(yticks_position)
    ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
                             pad=tick_padding, length=2, width=0.5)
    ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
                             pad=tick_padding, length=2, width=0.5)
    ax.xaxis.labelpad = label_padding
    ax.yaxis.labelpad = label_padding
    ax.xaxis.label.set_size(fontsize)
    ax.yaxis.label.set_size(fontsize)
412909
private void writeOutRequestParams(List<String> elements, Writer out) throws IOException {
		if (elements != null && elements.size() > 0) {
			for (String param : elements) {
				out.write("\n\t\t\"" + param + "\": ");
				if (param.equalsIgnoreCase("boolean")) {
					addImports = true;
					out.write("strconv.FormatBool(boolean)");
				} else if (param.equalsIgnoreCase("integer")) {
					addImports = true;
					out.write("strconv.Itoa(i)");
				} else if (param.equalsIgnoreCase("string")) {
					out.write("str");
				} else if (param.equalsIgnoreCase("type")) {
					out.write("t");
				} else {
					out.write(param.toLowerCase());
				}
				out.write(",");
			}
		}
	}
588369
def simple_write(filename, group, times, features,
                 properties=None, item='item', mode='a'):
    """"""
    write(filename, group, [item], [times], [features], mode=mode,
          properties=[properties] if properties is not None else None)
1166401
def _par_write(self, dirname):
        
        filename = dirname + '/' + 'template_parameters.csv'
        with open(filename, 'w') as parfile:
            for template in self.templates:
                for key in template.__dict__.keys():
                    if key not in ['st', 'event']:
                        parfile.write(key + ': ' +
                                      str(template.__dict__[key]) + ', ')
                parfile.write('\n')
        return self
713204
def writeToFile(self, filename, saveOpts=False):
        '''
        
        '''
        try:
            if not filename.endswith('.%s' % self.ftype):
                filename += '.%s' % self.ftype
            s = {'coeffs': self.coeffs}
            if saveOpts:
                s['opts'] = self.opts
#             else:
#                 s['opts':{}]
            np.savez(filename, **s)
            return filename
        except AttributeError:
            raise Exception(
                'need to calibrate camera before calibration can be saved to file')
11674
def Write(self, outpath):
    ""
    out = zipfile.ZipFile(outpath, mode="w", compression=zipfile.ZIP_DEFLATED)
    for filename, func in [('agency.txt', self.WriteAgency),
                           ('calendar.txt', self.WriteCalendar),
                           ('calendar_dates.txt', self.WriteCalendarDates),
                           ('routes.txt', self.WriteRoutes),
                           ('trips.txt', self.WriteTrips),
                           ('stops.txt', self.WriteStations),
                           ('stop_times.txt', self.WriteStopTimes)]:
      s = cStringIO.StringIO()
      func(s)
      out.writestr(filename, s.getvalue())
    out.close()