spits out the cdf for data to file
979456
def cdfout(data, file):
    
    f = open(file, "w")
    data.sort()
    for j in range(len(data)):
        y = old_div(float(j), float(len(data)))
        out = str(data[j]) + ' ' + str(y) + '\n'
        f.write(out)
    f.close()
997679
def df_to_tsv(df, tsvfile, suffix):
    
    tsvfile += suffix
    columns = ["SampleKey"] + sorted(x for x in df.columns
                                     if x.endswith(suffix))
    tf = df.reindex_axis(columns, axis='columns')
    tf.sort_values("SampleKey")
    tf.to_csv(tsvfile, sep='\t', index=False, float_format='%.4g', na_rep="na")
    print("TSV output written to `{}` (# samples={})"\
                .format(tsvfile, tf.shape[0]), file=sys.stderr)
993906
def _cdata_io(self, action, data, ctype, frames):
        """"""
        assert ctype in _ffi_types.values()
        self._check_if_closed()
        if self.seekable():
            curr = self.tell()
        func = getattr(_snd, 'sf_' + action + 'f_' + ctype)
        frames = func(self._file, data, frames)
        _error_check(self._errorcode)
        if self.seekable():
            self.seek(curr + frames, SEEK_SET)  # Update read & write position
        return frames
754842
def MakeSuiteFromCdf(cdf, name=None):
    
    if name is None:
        name = cdf.name

    suite = Suite(name=name)

    prev = 0.0
    for val, prob in cdf.Items():
        suite.Incr(val, prob - prev)
        prev = prob

    return suite
1361887
def _collect_data(directory, input_ext, target_ext):
  """"""
  # Directory from string to tuple pair of strings
  # key: the filepath to a datafile including the datafile's basename. Example,
  #   if the datafile was "/path/to/datafile.wav" then the key would be
  #   "/path/to/datafile"
  # value: a pair of strings (input_filepath, target_filepath)
  data_files = {}
  for root, _, filenames in os.walk(directory):
    input_files = [filename for filename in filenames if input_ext in filename]
    for input_filename in input_files:
      basename = input_filename.strip(input_ext)
      input_file = os.path.join(root, input_filename)
      target_file = os.path.join(root, basename + target_ext)
      key = os.path.join(root, basename)
      assert os.path.exists(target_file)
      assert key not in data_files
      data_files[key] = (input_file, target_file)
  return data_files
1003635
def prt_outfiles_flat(self, goea_results, outfiles):
        """"""
        kws = {'indent':self.args.indent, 'itemid2name':self.itemid2name}
        for outfile in outfiles:
            if outfile.endswith(".xlsx"):
                self.objgoea.wr_xlsx(outfile, goea_results, **kws)
            #elif outfile.endswith(".txt"):  # TBD
            #    pass
            else:
                self.objgoea.wr_tsv(outfile, goea_results, **kws)
1259201
def create_dat_file(self):
        
        output = "## {}\n".format(self.name)
        try:
            kwargs_items = self.kwargs.iteritems()
        except AttributeError:
            kwargs_items = self.kwargs.items()
        for key, val in kwargs_items:
            if val is "l":
                output += "#l {}=\n".format(str(key))
            elif val is "f" or True:
                output += "#f {}=\n".format(str(key))
        comment = "## " + "\t".join(["col{" + str(i) + ":d}"
                                     for i in range(self.argnum)])
        comment += "\n"
        rangeargnum = range(self.argnum)
        output += comment.format(*rangeargnum)
        if os.path.isfile(self.location_dat):
            files = glob.glob(self.location_dat + "*")
            count = 2
            while (
                    (self.location_dat + str(count) in files)
                  ) and (count <= 10):
                count += 1
            os.rename(self.location_dat, self.location_dat + str(count))
        dat_file = open(self.location_dat, "wb")
        dat_file.write(output)
        dat_file.close()
1205684
def write_gct(df, file_path):
    
    with open(file_path, 'w') as file:
        file.write('#1.2\n' + str(len(df.index)) + '\t' + str(len(df.columns)) + '\n')
        df.to_csv(file, sep='\t', mode='w+')
452102
public static void dumpStoreDefsToFile(String outputDirName,
                                           String fileName,
                                           List<StoreDefinition> storeDefs) {

        if(outputDirName != null) {
            File outputDir = new File(outputDirName);
            if(!outputDir.exists()) {
                Utils.mkdirs(outputDir);
            }

            try {
                FileUtils.writeStringToFile(new File(outputDirName, fileName),
                                            new StoreDefinitionsMapper().writeStoreList(storeDefs));
            } catch(IOException e) {
                logger.error("IOException during dumpStoreDefsToFile: " + e);
            }
        }
    }
835481
def to_file(self, path, precision='%.2g'):
        
        table_info = self.get_table_info()

        def dump_rows(rows):
            if len(rows) > 1:
                for row in rows:
                    csv_writer.writerow(row)
                csv_writer.writerow([])

        with open(path, 'wb') as _f:
            csv_writer = csv.writer(_f)

            state_rows = [['States']]
            state_rows += [['Name', 'Description', 'State', 'Number of Changes']]
            for state in self.states:
                state_rows.append([state.name, table_info[state.name]['description'], state.state, state.count])
            dump_rows(state_rows)

            stat_rows = [['Statistics']]
            stat_rows += [['Name', 'Description', 'Total', 'Average']]
            for stat in self.statistics:
                if stat.name == '__submissions__':
                    continue
                stat_rows.append([stat.name, table_info[stat.name]['description'], stat.count, stat.get_average(0)])
                dump_rows(stat_rows)

            timer_rows = [['Timers']]
            timer_rows += [['Name', 'Description', 'Average Seconds', 'Total Seconds', 'Total Minutes', 'Total Hours', 'Total Days']]
            for timer in self.timers:
                timer_rows.append([timer.name, table_info[timer.name]['description'],
                                   precision % timer.get_average(0), precision % timer.total_seconds, precision % timer.total_minutes,
                                   precision % timer.total_hours, precision % timer.total_days])
                dump_rows(timer_rows)

            sequence_rows = [['Sequences']]
            sequence_rows += [['Name', 'Description', 'Sequence', 'Number of Completions']]
            for sequence in self.sequences:
                checkpoints = '-->'.join(map(str, sequence.get_checkpoints()))
                sequence_rows.append([sequence.name, table_info[sequence.name]['description'], checkpoints, sequence.count])
                dump_rows(sequence_rows)
1123138
def sparklineData(data, filename):
    
    fd = file(filename, "w+b")
    for name in data.keys():
        action, reward = data[name]

        altName = name.lower().replace("_", "")

        fd.write("\def")
        fd.write("\REWARDDATA%s{" % altName)
        for i, r in enumerate(reward):
            fd.write("(%.2f,%.3f)" % (i / 10.0, r / 10.0)) # dimension too large
        fd.write("}\n")

        maxreward, maxindex = max(izip(reward, count()))
        minreward, minindex = min(izip(reward, count()))
        meanreward = scipy.mean(reward)
        fd.write("\def\REWARDMAX%s{%.1f}\n" % (altName, maxreward))
        fd.write("\def\REWARDMAXIDX%s{%d}\n" % (altName, maxindex))
        fd.write("\def\REWARDMIN%s{%.1f}\n" % (altName, minreward))
        fd.write("\def\REWARDMINIDX%s{%d}\n" % (altName, minindex))
        fd.write("\def\REWARDMEAN%s{%.1f}\n" % (altName, meanreward))

        fd.write("\def")
        fd.write("\ACTIONDATA%s{" % altName)
        for i, a in enumerate(action):
            fd.write("(%.2f,%.3f)" % (i / 10.0, a / 10.0))
        fd.write("}\n")

        maxaction, maxindex = max(izip(reward, count()))
        minaction, minindex = min(izip(reward, count()))
        meanaction = scipy.mean(reward)
        fd.write("\def\ACTIONMAX%s{%.1f}\n" % (altName, maxaction))
        fd.write("\def\ACTIONMAXIDX%s{%d}\n" % (altName, maxindex))
        fd.write("\def\ACTIONMIN%s{%.1f}\n" % (altName, minaction))
        fd.write("\def\ACTIONMINIDX%s{%d}\n" % (altName, minindex))
        fd.write("\def\ACTIONMEAN%s{%.1f}\n" % (altName, meanaction))
    fd.close()
205383
function (data, files, cb) {
    var outDir = data.outDir;
    var zipfilename = Mustache.render(data.template, data);
    var outfile = path.join(outDir, zipfilename);

    // store the output zip file name on the task data
    data.outfile = outfile;

    var zipfile = zip.create(outfile);

    async.each(
      files,

      function (file, next) {
        var src = file.src[0];
        var dest = file.dest || src;

        if (isFile(src)) {
          grunt.log.writeln('adding file ' + src + ' to package as ' + dest);
          zipfile.addFile(src, dest, next);
        }
        // screen out the '.' directory to avoid a spurious entry
        else if (isDirectory(src) && dest !== '.') {
          grunt.log.writeln('adding directory ' + src + ' to package as ' + dest);
          zipfile.addDirectory(dest, next);
        }
        else {
          next();
        }
      },

      function (err) {
        if (err) {
          grunt.fatal(err.message);
        }
        else {
          grunt.log.writeln('\npackage written to:\n' + outfile);
          zipfile.writeToFile(cb);
        }
      }
    );
  }
316250
def write_output(self, data, filename=None, args=None):
        """"""
        if args:
            if not args.linejson:
                return 0
        if not filename: filename = args.linejson
        entrylist = []
        for entry in data['entries']:
            entrystring = json.dumps(entry, sort_keys=True)
            entrylist.append(entrystring)
        
        with open(str(filename), 'w') as output_file:
            output_file.write('\n'.join(entrylist))
1118571
def Dump(self):
        
        prefs_file = open(self.prefs_path, 'w')
        for n in range(0,len(self.prefs)):
            if len(list(self.prefs.items())[n]) > 1:
                prefs_file.write(str(list(self.prefs.items())[n][0]) + ' = ' +
                                 str(list(self.prefs.items())[n][1]) + '\n')
        prefs_file.close()
1281453
def exporter(directory, method, datasets):
    """"""
    if method.lower() == 'json':
        # Convert json_dict to a JSON styled string
        json_string = json.dumps(datasets, indent=4)
        savefile = open('{}/exported.json'.format(directory), 'w+')
        savefile.write(json_string)
        savefile.close()

    if method.lower() == 'csv':
        with open('{}/exported.csv'.format(directory), 'w+') as csvfile:
            csv_writer = csv.writer(
                csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
            for key, values in datasets.items():
                if values is None:
                    csv_writer.writerow([key])
                else:
                    csv_writer.writerow([key] + values)
        csvfile.close()
1043989
def _cdf(self, xloc, dist, length, cache):
        
        output = evaluation.evaluate_forward(
            dist, xloc.reshape(1, -1)).reshape(length, -1)
        assert xloc.shape == output.shape
        return output
221426
def exportData(self, datfile):
        

        def ampl_set(name, values):
            def format_entry(e):
                return repr(e).replace(' ', '')

            return 'set {0} := {1};'.format(
                name, ','.join(format_entry(e) for e in values)
            )

        def ampl_param(name, values):
            def format_entry(k, v):
                k = repr(k).strip('()').replace(' ', '')
                if v == inf:
                    v = "Infinity"
                elif v == -inf:
                    v = "-Infinity"
                else:
                    v = repr(v).strip('()').replace(' ', '')
                return '[{0}]{1}'.format(k, v)

            return 'param {0} := {1};'.format(
                name, ''.join(format_entry(k, v) for k, v in values.items())
            )

        with open(datfile, 'w') as f:
            for name, entity in self.getSets():
                values = entity.getValues().toList()
                print(ampl_set(name, values), file=f)
            for name, entity in self.getParameters():
                if entity.isScalar():
                    print(
                        'param {} := {};'.format(name, entity.value()),
                        file=f
                    )
                else:
                    values = entity.getValues().toDict()
                    print(ampl_param(name, values), file=f)