Format a player's result as it would appear in an SP text export file.
195504
def to_sp_text
      sp = opponent ? opponent.to_s : '0'
      sp << ':'
      if rateable
        sp << score
      else
        sp << case score
        when 'W' then '+'
        when 'L' then '-'
        else '='
        end
      end
    end
568874
def process_results(self, paragraph):
        """"""
        if 'result' in paragraph and paragraph['result']['msg']:
            msg = paragraph['result']['msg']
            self.output_options[paragraph['result']['type']](msg)
301986
def format_results(self, results):
        
        if not results:
            return None
        userdn = results[0][0]
        userobj = results[0][1]
        userobj['dn'] = userdn

        keymap = self.config.get('KEY_MAP')
        if keymap:
            return {key:scalar(userobj.get(value)) for key, value in keymap.items() if _is_utf8(scalar(userobj.get(value))) }
        else:
            return {key:scalar(value) for key, value in userobj.items() if _is_utf8(scalar(value)) }
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)
184422
def dump_results(self):
        
        system = self.system
        mu = self.mu
        partfact = self.part_fact

        if system.files.no_output:
            return

        text = []
        header = []
        rowname = []
        data = []

        neig = len(mu)
        mu_real = mu.real()
        mu_imag = mu.imag()
        npositive = sum(1 for x in mu_real if x > 0)
        nzero = sum(1 for x in mu_real if x == 0)
        nnegative = sum(1 for x in mu_real if x < 0)

        numeral = []
        for idx, item in enumerate(range(neig)):
            if mu_real[idx] == 0:
                marker = '*'
            elif mu_real[idx] > 0:
                marker = '**'
            else:
                marker = ''
            numeral.append('#' + str(idx + 1) + marker)

        # compute frequency, undamped frequency and damping
        freq = [0] * neig
        ufreq = [0] * neig
        damping = [0] * neig
        for idx, item in enumerate(mu):
            if item.imag == 0:
                freq[idx] = 0
                ufreq[idx] = 0
                damping[idx] = 0
            else:
                freq[idx] = abs(item) / 2 / pi
                ufreq[idx] = abs(item.imag / 2 / pi)
                damping[idx] = -div(item.real, abs(item)) * 100

        # obtain most associated variables
        var_assoc = []
        for prow in range(neig):
            temp_row = partfact[prow, :]
            name_idx = list(temp_row).index(max(temp_row))
            var_assoc.append(system.varname.unamex[name_idx])

        pf = []
        for prow in range(neig):
            temp_row = []
            for pcol in range(neig):
                temp_row.append(round(partfact[prow, pcol], 5))
            pf.append(temp_row)

        text.append(system.report.info)
        header.append([''])
        rowname.append(['EIGENVALUE ANALYSIS REPORT'])
        data.append('')

        text.append('STATISTICS\n')
        header.append([''])
        rowname.append(['Positives', 'Zeros', 'Negatives'])
        data.append([npositive, nzero, nnegative])

        text.append('EIGENVALUE DATA\n')
        header.append([
            'Most Associated', 'Real', 'Imag', 'Damped Freq.', 'Frequency',
            'Damping [%]'
        ])
        rowname.append(numeral)
        data.append(
            [var_assoc,
             list(mu_real),
             list(mu_imag), ufreq, freq, damping])

        cpb = 7  # columns per block
        nblock = int(ceil(neig / cpb))

        if nblock <= 100:
            for idx in range(nblock):
                start = cpb * idx
                end = cpb * (idx + 1)
                text.append('PARTICIPATION FACTORS [{}/{}]\n'.format(
                    idx + 1, nblock))
                header.append(numeral[start:end])
                rowname.append(system.varname.unamex)
                data.append(pf[start:end])

        dump_data(text, header, rowname, data, system.files.eig)
        logger.info('report saved.')
693642
def output_results(results, mvdelim = '\n', output = sys.stdout):
    """"""

    # We collect all the unique field names, as well as 
    # convert all multivalue keys to the right form
    fields = set()
    for result in results:    
        for key in result.keys():
            if(isinstance(result[key], list)):
                result['__mv_' + key] = encode_mv(result[key])
                result[key] = mvdelim.join(result[key])
        fields.update(list(result.keys()))

    # convert the fields into a list and create a CSV writer
    # to output to stdout
    fields = sorted(list(fields))

    writer = csv.DictWriter(output, fields)

    # Write out the fields, and then the actual results
    writer.writerow(dict(list(zip(fields, fields))))
    writer.writerows(results)
65337
def cli(ctx,
        amount,
        index,
        stage,
        stepresult,
        formattype,
        select,
        where,
        order,
        outputfile,
        showkeys,
        showvalues,
        showalways,
        position):
    """"""
    if not ctx.bubble:
        msg = 'There is no bubble present, will not export'
        ctx.say_yellow(msg)
        raise click.Abort()
    path = ctx.home + '/'

    if stage not in STAGES:
        ctx.say_yellow('There is no known stage:' + stage)
        raise click.Abort()
    if stepresult not in exportables:
        ctx.say_yellow('stepresult not one of: ' + ', '.join(exportables))
        raise click.Abort()

    data_gen = bubble_lod_load(ctx, stepresult, stage)

    ctx.gbc.say('data_gen:', stuff=data_gen, verbosity=20)

    part = get_gen_slice(ctx.gbc, data_gen, amount, index)
    ctx.gbc.say('selected part:', stuff=part, verbosity=20)

    aliases = get_pairs(ctx.gbc, select, missing_colon=True)
    if position or len(aliases) == 0:
        ctx.gbc.say('adding position to selection of columns:',
                    stuff=aliases, verbosity=20)
        aliases.insert(0, {'key': buts('index'), 'val': 'BUBBLE_IDX'})
        ctx.gbc.say('added position to selection of columns:',
                    stuff=aliases, verbosity=20)

    wheres = get_pairs(ctx.gbc, where)
    # TODO: use aliases as lookup for wheres

    data = tablib.Dataset()

    data.headers = [sel['val'] for sel in aliases]
    ctx.gbc.say('select wheres:' + str(wheres), verbosity=20)
    ctx.gbc.say('select aliases:' + str(aliases), verbosity=20)
    ctx.gbc.say('select data.headers:' + str(data.headers), verbosity=20)

    not_shown = True
    try:
        for ditem in part:
            row = []
            ctx.gbc.say('curr dict', stuff=ditem, verbosity=101)

            flitem = flat(ctx, ditem)
            ctx.gbc.say('curr flat dict', stuff=flitem, verbosity=101)
            row_ok = True
            for wp in wheres:
                # TODO: negative selects: k:None, k:False,k:Zero,k:Null,k:0,k:-1,k:'',k:"",
                # TODO: negative selects:
                # k:BUBBLE_NO_KEY,k:BUBBLE_NO_VAL,k:BUBBLE_NO_KEY_OR_NO_VAL

                wcheck_key=True
                if wp['key'] not in flitem:
                    row_ok = False
                    wcheck_key=False
                if wcheck_key and wp['val'] not in str(flitem[wp['key']]):
                    row_ok = False
            if not row_ok:
                continue

            for sel in aliases:
                if sel['key'] in flitem:
                    row.append(flitem[sel['key']])
                else:
                    # temporary to check, not use case for buts()
                    bnp = '____BTS_NO_PATH_'
                    tempv = get_flat_path(ctx, flitem, sel['key'] + '.*', bnp)
                    if tempv != bnp:
                        row.append(tempv)
                    else:
                        row.append('None')
                        # TODO maybe 'NONE', or just '' or something like:
                        # magic.export_format_none

            data.append(row)
            # todo: count keys, and show all keys in selection: i,a
            if not_shown and showkeys:
                if not showalways:
                    not_shown = False
                ks = list(flitem.keys())
                ks.sort()
                ctx.say(
                    'available dict path keys from first selected dict:', verbosity=0)
                for k in ks:
                    ctx.say('keypath: ' + k, verbosity=0)
                    if showvalues:
                        ctx.say('value: ' + str(flitem[k]) + '\n', verbosity=0)

    except Exception as excpt:
        ctx.say_red('Cannot export data', stuff=excpt)
        raise click.Abort()

    if not outputfile:
        outputfile = path + 'export/export_' + \
            stepresult + '_' + stage + '.' + formattype

    # todo: order key must be present in selection
    # add to selection before
    # and remove from result before output to format.
    if order:
        olast2 = order[-2:]
        ctx.gbc.say('order:' + order + ' last2:' + olast2, verbosity=100)
        if olast2 not in [':+', ':-']:
            data = data.sort(order, False)
        else:
            if olast2 == ':+':
                data = data.sort(order[:-2], False)
            if olast2 == ':-':
                data = data.sort(order[:-2], True)

    # Write `spreadsheet` to disk
    formatted = None
    if formattype == 'yaml':
        formatted = data.yaml
    if formattype == 'json':
        formatted = data.json
    if formattype == 'csv':
        formatted = data.csv

    # TODO:
    # if formattype == 'ldif':
    #    formatted = data.ldif

    if formattype == 'tab':
        # standard, output, whatever tablib makes of it, ascii table
        print(data)

    if formatted:
        enc_formatted = formatted.encode('utf-8')
        of_path = opath.Path(outputfile)
        of_dir = of_path.dirname()
        if not of_dir.exists():
            of_dir.makedirs_p()

        with open(outputfile, 'wb') as f:
            f.write(enc_formatted)
            ctx.say_green('exported: ' + outputfile)
1234859
function formatOutput (results) {
  var date = new Date()
  var commit

  try {
    commit = execSync('git rev-parse HEAD').toString().replace('\n', '')
  } catch (e) {
    commit = 'commit hash not found'
  }

  return {
    meta: {
      title: 'example benchmark',
      version: pkg.version,
      commit: commit,
      date: [
        date.toLocaleDateString(),
        date.toLocaleTimeString(),
        date.toString().match(/\(([A-Za-z\s].*)\)/)[1]
      ].join(' ')
    },
    results: results
  }
}
13458
def format_result(line, line_num, txt):
    
    
    return '&nbsp;&nbsp;' + str(line_num) + ': ' + line.replace(txt, '<span style="background-color: #FFFF00">' + txt + '</span>')
1050395
def render_file(self, context, result):
		""""""
		if __debug__:
			log.debug("Processing file-like object.", extra=dict(request=id(context), result=repr(result)))
		
		response = context.response
		response.conditional_response = True
		
		modified = mktime(gmtime(getmtime(result.name)))
		
		response.last_modified = datetime.fromtimestamp(modified)
		ct, ce = guess_type(result.name)
		if not ct: ct = 'application/octet-stream'
		response.content_type, response.content_encoding = ct, ce
		response.etag = unicode(modified)
		
		result.seek(0, 2)  # Seek to the end of the file.
		response.content_length = result.tell()
		
		result.seek(0)  # Seek back to the start of the file.
		response.body_file = result
		
		return True
483852
def format_output(instances, flag):
    """"""
    out = []
    line_format = '{0}\t{1}\t{2}\t{3}\t{4}'
    name_len = _get_max_name_len(instances) + 3
    if flag:
        line_format = '{0:<' + str(name_len) + '}{1:<16}{2:<21}{3:<16}{4:<16}'

    for i in instances:
        tag_name = get_tag_value(i.tags, 'Name')
        out.append(line_format.format(
            tag_name, i.state['Name'], i.id, i.private_ip_address, str(i.public_ip_address)))
    return out
400560
def process_results(self, paragraph):
        """"""
        if 'editorMode' in paragraph['config']:
            mode = paragraph['config']['editorMode'].split('/')[-1]
            if 'results' in paragraph and paragraph['results']['msg']:
                msg = paragraph['results']['msg'][0]
                if mode not in ('text', 'markdown'):
                    self.output_options[msg['type']](msg['data'])
1341885
def export(self, xformat='csv'):
        """"""
        if self.annot is None:  # remove if buttons are disabled
            self.parent.statusBar().showMessage('No score file loaded')
            return

        if xformat == 'csv':
            filename = splitext(self.annot.xml_file)[0] + '.csv'
            filename, _ = QFileDialog.getSaveFileName(self, 'Export stages',
                                                      filename,
                                                      'Sleep stages (*.csv)')
        if 'remlogic' in xformat:
            filename = splitext(self.annot.xml_file)[0] + '.txt'
            filename, _ = QFileDialog.getSaveFileName(self, 'Export stages',
                                                      filename,
                                                      'Sleep stages (*.txt)')
        if filename == '':
            return

        self.annot.export(filename, xformat=xformat)
807289
private String formatItem(CmsReportUpdateItem updateItem) {

        StringBuffer buf = new StringBuffer();
        CmsReportFormatType format = updateItem.getType();
        if (format == CmsReportFormatType.fmtException) {
            return formatException((Throwable)(updateItem.getMessage()));
        } else {
            String value = CmsStringUtil.escapeJavaScript((String)(updateItem.getMessage()));
            switch (format) {
                case fmtHeadline:
                    buf = new StringBuffer();
                    buf.append("aH('");
                    buf.append(value);
                    buf.append("'); ");
                    break;
                case fmtWarning:
                    buf = new StringBuffer();
                    buf.append("aW('");
                    buf.append(value);
                    buf.append("'); ");
                    break;
                case fmtError:
                    buf = new StringBuffer();
                    buf.append("aE('");
                    buf.append(value);
                    buf.append("'); ");
                    break;
                case fmtNote:
                    buf = new StringBuffer();
                    buf.append("aN('");
                    buf.append(value);
                    buf.append("'); ");
                    break;
                case fmtOk:
                    buf = new StringBuffer();
                    buf.append("aO('");
                    buf.append(value);
                    buf.append("'); ");
                    break;
                case fmtNewline:
                    buf = new StringBuffer();
                    buf.append("a('" + CmsHtmlReport.LINEBREAK + "');");
                    break;
                case fmtDefault:
                default:
                    buf = new StringBuffer();
                    buf.append("a('");
                    buf.append(value);
                    buf.append("'); ");
            }

            // the output lines get split back into single lines on the client-side.
            // thus, a separate JavaScript call has to be added here to tell the
            // client that we want a linebreak here...
            if (value.trim().endsWith(CmsHtmlReport.LINEBREAK)) {
                buf.append("aB(); ");
            }
        }
        return buf.toString();
    }
592099
def format_source(value)
      sp = value.split("\n").last[/^(\s+)/, 1]
      num = sp ? sp.size : 0
      value.gsub(/^\s{#{num}}/, '')
    end
513095
def format(self, record):
        """"""
        # XXX: idea, colorize message arguments
        s = super(ANSIFormatter, self).format(record)
        if hasattr(self.context, 'ansi'):
            s = self.context.ansi(s, **self.get_sgr(record))
        return s
283541
def output_results(cls, sprites):
        
        print(' '.join(cls.ATTRIBUTES))
        format_strs = ['{{{}!s:^{}}}'.format(x, len(x)) for x in
                       cls.ATTRIBUTES]
        print(' '.join(format_strs).format(**cls.attribute_result(sprites)))