Show a table of some expt-wide numeric measurement.
508102
public void table(String what) throws NoSuchMethodException,IllegalAccessException,InvocationTargetException
	{
		PrintfFormat dfmt = new PrintfFormat("Dataset %2d:");
		PrintfFormat fmt = new PrintfFormat(" %9.5f  ");
		PrintfFormat nfmt = new PrintfFormat(" %11s");
		if (expt==null) compute();
		for (int i=0; i<blockerNames.size(); i++) {
			System.out.println("\nblocker: "+blockerNames.get(i)+"\n");
			System.out.print("           ");
			for (int j=0;  j<learnerNames.size(); j++) {
				String s = (String)learnerNames.get(j);
				if (s.length()>11) s = s.substring(0,11);
				System.out.print( nfmt.sprintf(s) );
			}
			System.out.println();
			double[] average = new double[learnerNames.size()];
			for (int k=0; k<datasetNames.size(); k++) {
				System.out.print( dfmt.sprintf(k+1));
				for (int j=0; j<learnerNames.size(); j++) {
					Method m = MatchExpt.class.getMethod(what, new Class[] {});
					Double d = (Double)m.invoke(expt[i][j][k], new Object[]{});
					System.out.print( fmt.sprintf(d) );
					average[j] += d.doubleValue();
				}
				System.out.print("\n");
			}
			System.out.print( "   Average:");
			for (int j=0; j<learnerNames.size(); j++) {
				System.out.print( fmt.sprintf( average[j]/datasetNames.size() ) );
			}
			System.out.print("\n\n");
		}
	}
1244247
def submit_statsd_measurements(self):
        """"""
        for key, value in self.measurement.counters.items():
            self.statsd.incr(key, value)
        for key, values in self.measurement.durations.items():
            for value in values:
                self.statsd.add_timing(key, value)
        for key, value in self.measurement.values.items():
            self.statsd.set_gauge(key, value)
        for key, value in self.measurement.tags.items():
            if isinstance(value, bool):
                if value:
                    self.statsd.incr(key)
            elif isinstance(value, str):
                if value:
                    self.statsd.incr('{}.{}'.format(key, value))
            elif isinstance(value, int):
                self.statsd.incr(key, value)
            else:
                LOGGER.warning('The %s value type of %s is unsupported',
                               key, type(value))
878857
def size(ctx, dataset, kwargs):
    ""

    kwargs = parse_kwargs(kwargs)
    (print)(data(dataset, **ctx.obj).get(**kwargs).complete_set.size)
1150347
def auto_display_limits(self):
        """"""
        display_data_and_metadata = self.get_calculated_display_values(True).display_data_and_metadata
        data = display_data_and_metadata.data if display_data_and_metadata else None
        if data is not None:
            # The old algorithm was a problem during EELS where the signal data
            # is a small percentage of the overall data and was falling outside
            # the included range. This is the new simplified algorithm. Future
            # feature may allow user to select more complex algorithms.
            mn, mx = numpy.nanmin(data), numpy.nanmax(data)
            self.display_limits = mn, mx
684413
def table_measure(self, columns, content):
        
        dimensions = {}
        for row in content:
            i = 0
            for cell in row:
                # Calculate maximum from:
                dimensions[i] = max(
                        dimensions.get(i, 0),              # current column max width
                        len(cell),                         # current cell value width
                        len(columns[i].get('label', '')),  # column label width
                        columns[i].get('width_min', 0),    # configured column minimal width
                    )
                i += 1
        return dimensions
327542
def propagate_measurement_info(self):
        
        meas_df = self.tables['measurements'].df
        names_list = ['specimen', 'sample', 'site', 'location']
        # add in any tables that you can
        for num, name in enumerate(names_list):
            # don't replace tables that already exist
            if (name + "s") in self.tables:
                continue
            elif name in meas_df.columns:
                items = meas_df[name].unique()
                df = pd.DataFrame(columns=[name], index=items)
                df[name] = df.index
                # add in parent name if possible
                # (i.e., sample name to specimens table)
                if num < (len(names_list) - 1):
                    parent = names_list[num+1]
                    if parent in meas_df.columns:
                        meas_df = meas_df.where(meas_df.notnull(), "")
                        df[parent] = meas_df.drop_duplicates(subset=[name])[parent].values.astype(str)
                df = df.where(df != "", np.nan)
                df = df.dropna(how='all', axis='rows')
                if len(df):
                    self.tables[name + "s"] = MagicDataFrame(dtype=name + "s", df=df)
                    self.write_table_to_file(name + "s")
323422
def stats_table(self, data):
        """"""
        headers = OrderedDict()
        headers['combopairs'] = {
            'title': 'Combined pairs',
            'description': 'Num read pairs combined',
            'shared_key': 'read_count',
            'hidden': True,
            'scale': False
        }
        headers['perccombo'] = {
            'title': '% Combined',
            'description': '% read pairs combined',
            'max': 100,
            'min': 0,
            'suffix': '%',
            'scale': 'PiYG'
        }
        self.general_stats_addcols(data, headers)
226966
def show_hbonds(self):
        """"""
        hbonds = self.plcomplex.hbonds
        for group in [['HBondDonor-P', hbonds.prot_don_id],
                      ['HBondAccept-P', hbonds.prot_acc_id]]:
            if not len(group[1]) == 0:
                self.select_by_ids(group[0], group[1], restrict=self.protname)
        for group in [['HBondDonor-L', hbonds.lig_don_id],
                      ['HBondAccept-L', hbonds.lig_acc_id]]:
            if not len(group[1]) == 0:
                self.select_by_ids(group[0], group[1], restrict=self.ligname)
        for i in hbonds.ldon_id:
            cmd.select('tmp_bs', 'id %i & %s' % (i[0], self.protname))
            cmd.select('tmp_lig', 'id %i & %s' % (i[1], self.ligname))
            cmd.distance('HBonds', 'tmp_bs', 'tmp_lig')
        for i in hbonds.pdon_id:
            cmd.select('tmp_bs', 'id %i & %s' % (i[1], self.protname))
            cmd.select('tmp_lig', 'id %i & %s' % (i[0], self.ligname))
            cmd.distance('HBonds', 'tmp_bs', 'tmp_lig')
        if self.object_exists('HBonds'):
            cmd.set('dash_color', 'blue', 'HBonds')
629379
def num_elements(self):
        """"""
        if self.is_fully_defined():
            size = 1
            for dim in self._dims:
                size *= dim.value
            return size
        else:
            return None
136752
def pretty_print_table(headers, rows):
    """"""
    table = make_table(headers=headers, rows=rows)
    pretty_print_table_instance(table)
919138
def numeric_value(self):
        """"""
        numeric_value = self._element_dict.get("numeric_value")
        return np.nan if numeric_value is None else numeric_value
1367911
def _table_info(self, buf=None):
    
    metrics = [self.count().name('nrows')]
    for col in self.columns:
        metrics.append(self[col].count().name(col))

    metrics = self.aggregate(metrics).execute().loc[0]

    names = ['Column', '------'] + self.columns
    types = ['Type', '----'] + [repr(x) for x in self.schema().types]
    counts = ['Non-null #', '----------'] + [str(x) for x in metrics[1:]]
    col_metrics = util.adjoin(2, names, types, counts)
    result = 'Table rows: {}\n\n{}'.format(metrics[0], col_metrics)

    print(result, file=buf)
858691
def measures(self):
        """"""
        from ambry.valuetype.core import ROLE

        return [c for c in self.columns if c.role == ROLE.MEASURE]
21353
def show(db, encoding, no_limit, zip, case_insensitive):
    """"""

    limit = 15

    if no_limit:
        limit = float('inf')

    with open_db(db, zip, encoding=encoding, case_sensitive=not case_insensitive) as dbf:
        for idx, row in enumerate(dbf, 1):
            click.secho('')

            for key, val in row._asdict().items():
                click.secho('  %s: %s' % (key, val))

            if idx == limit:
                click.secho(
                    'Note: Output is limited to %s rows. Use --no-limit option to bypass.' % limit, fg='red')
                break
306958
def _displaystr2num(st):
    """"""
    num = None
    for s, n in [('DFP-', 16), ('TV-', 8), ('CRT-', 0)]:
        if st.startswith(s):
            try:
                curnum = int(st[len(s):])
                if 0 <= curnum <= 7:
                    num = n + curnum
                    break
            except Exception:
                pass
    if num is not None:
        return num
    else:
        raise ValueError('Unrecognised display name: ' + st)
15917
def stats_mouse(events, table):
    """"""
    if not events: return [], [], []
    distance, last, deltas = 0, None, []
    HS = conf.MouseHeatmapSize
    SC = dict(("xy"[i], conf.DefaultScreenSize[i] / float(HS[i])) for i in [0, 1])
    xymap = collections.defaultdict(int)
    sizes = db.fetch("screen_sizes", order=("dt",))
    sizeidx, sizelen = -1, len(sizes) # Scale by desktop size at event time
    for e in events:
        if last:
            deltas.append(e["dt"] - last["dt"])
            distance += math.sqrt(sum(abs(e[k] - last[k])**2 for k in "xy"))
        last = dict(e) # Copy, as we modify coordinates
        if sizeidx < 0: # Find latest size from before event
            for i, size in reversed(list(enumerate(sizes))):
                if e["dt"] >= size["dt"]:
                    SC = dict((k, size[k] / float(HS["y" == k])) for k in "xy")
                    sizeidx = i
                    break # for i, size
        else: # Find next size from before event
            while sizeidx < sizelen - 2 and e["dt"] >= sizes[sizeidx + 1]["dt"]:
                sizeidx += 1
            if sizeidx < sizelen - 1 and e["dt"] >= sizes[sizeidx]["dt"]:
                SC = dict((k, sizes[sizeidx][k] / float(HS["y" == k])) for k in "xy")
        e["x"], e["y"] = tuple(min(int(e[k] / SC[k]), HS["y" == k]) for k in "xy")
        xymap[(e["x"], e["y"])] += 1

    stats, positions = [], [dict(x=x, y=y, count=v) for (x, y), v in xymap.items()]
    if "moves" == table:
        px = re.sub(r"(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % math.ceil(distance))
        seconds = timedelta_seconds(events[-1]["dt"] - events[0]["dt"])
        stats = [("Total distance", "%s pixels " % px),
                 ("", "%.1f meters (if pixel is %smm)" %
                  (distance * conf.PixelLength, conf.PixelLength * 1000)),
                 ("Average speed", "%.1f pixels per second" % (distance / (seconds or 1))),
                 ("", "%.4f meters per second" %
                  (distance * conf.PixelLength / (seconds or 1))), ]
    elif "scrolls" == table:
        counts = collections.Counter(e["wheel"] for e in events)
        stats = [("Scrolls per hour", 
                  int(len(events) / (timedelta_seconds(events[-1]["dt"] - events[0]["dt"]) / 3600 or 1))),
                 ("Average interval", sum(deltas, datetime.timedelta()) / (len(deltas) or 1)),
                 ("Scrolls down", counts[-1]),
                 ("Scrolls up", counts[1]), ]
    elif "clicks" == table:
        counts = collections.Counter(e["button"] for e in events)
        NAMES = {1: "Left", 2: "Right", 3: "Middle"}
        stats = [("Clicks per hour", 
                  int(len(events) / (timedelta_seconds(events[-1]["dt"] - events[0]["dt"]) / 3600 or 1))),
                 ("Average interval between clicks",
                  sum(deltas, datetime.timedelta()) / (len(deltas) or 1)),
                 ("Average distance between clicks",
                  "%.1f pixels" % (distance / (len(events) or 1))), ]
        for k, v in sorted(counts.items()):
            stats += [("%s button clicks" % NAMES.get(k, "%s." % k), v)]
    return stats, positions, events
1323534
def format_table(self, width=None,
                     min_label_width=10, min_progress_width=10):
        
        # handle the special case of an empty table.
        if len(self._lines) == 0:
            return []

        if width is None:  # pragma: no cover
            width = shutil.get_terminal_size()[0]

        labelw, progw, summaryw = self.calculate_field_widths(
            width=width,
            min_label_width=min_label_width,
            min_progress_width=min_progress_width
        )
        output = [
            sb.format_status(
                label_width=labelw,
                progress_width=progw,
                summary_width=summaryw
            )
            for sb in self._lines
        ]

        return output