Takes a collection of variables and formats it as a table.
977181
def format_variables(variables, join_lines=True):
  """"""
  rows = []
  rows.append(("Variable", "Shape", "Type", "Collections", "Device"))
  var_to_collections = _get_vars_to_collections(variables)
  for var in sorted(variables, key=lambda var: var.op.name):
    if var.get_shape().is_fully_defined():
      shape = "x".join(str(dim) for dim in var.get_shape().as_list())
    else:
      shape = "undefined"
    dtype = repr(var.dtype.base_dtype).replace("tf.", "")
    coll = ", ".join(sorted(var_to_collections[var]))
    rows.append((var.op.name, shape, dtype, coll, _format_device(var)))
  return _format_table(rows, join_lines)
1331619
def _split_variables(variables):
    
    file_vs = []
    std_vs = []
    for v in variables:
        cur_type = v["type"]
        while isinstance(cur_type, dict):
            if "items" in cur_type:
                cur_type = cur_type["items"]
            else:
                cur_type = cur_type["type"]
        if (cur_type in ["File", "null", "record"] or
              (isinstance(cur_type, (list, tuple)) and
               ("File" in cur_type or {'items': 'File', 'type': 'array'} in cur_type))):
            file_vs.append(v)
        elif v["id"] in ALWAYS_AVAILABLE:
            std_vs.append(v)
        else:
            file_vs.append(v)
    return file_vs, std_vs
648966
def _copy_listed(self: T, names) -> T:
        
        variables = OrderedDict()  # type: OrderedDict[Any, Variable]
        coord_names = set()
        indexes = OrderedDict()  # type: OrderedDict[Any, pd.Index]

        for name in names:
            try:
                variables[name] = self._variables[name]
            except KeyError:
                ref_name, var_name, var = _get_virtual_variable(
                    self._variables, name, self._level_coords, self.dims)
                variables[var_name] = var
                if ref_name in self._coord_names or ref_name in self.dims:
                    coord_names.add(var_name)
                if (var_name,) == var.dims:
                    indexes[var_name] = var.to_index()

        needed_dims = set()  # type: set
        for v in variables.values():
            needed_dims.update(v.dims)

        dims = dict((k, self.dims[k]) for k in needed_dims)

        for k in self._coord_names:
            if set(self.variables[k].dims) <= needed_dims:
                variables[k] = self._variables[k]
                coord_names.add(k)
                if k in self.indexes:
                    indexes[k] = self.indexes[k]

        return self._replace(variables, coord_names, dims, indexes=indexes)
1125431
def format_prettytable(table):
    """"""
    for i, row in enumerate(table.rows):
        for j, item in enumerate(row):
            table.rows[i][j] = format_output(item)

    ptable = table.prettytable()
    ptable.hrules = prettytable.FRAME
    ptable.horizontal_char = '.'
    ptable.vertical_char = ':'
    ptable.junction_char = ':'
    return ptable
74806
def _read_as_table(self):
        
        rows = list()

        for row in self._rows:
            rows.append([row[i].get() for i in range(self.num_of_columns)])

        return rows
442711
def generate_table(collection, headers=nil, options={})
      return if collection.blank?
      thead = content_tag(:thead) do
        content_tag(:tr) do
          headers.map {|header| content_tag(:th, header)}
        end
      end unless headers.nil?
      tbody = content_tag(:tbody) do
        collection.map do |values|
          content_tag(:tr) do
            values.map {|value| content_tag(:td, value)}
          end
        end
      end
      content_tag(:table, [thead, tbody].compact.join("\n"), options)
    end
536055
def _at_each(self, calculator, rule, scope, block):
        
        varstring, _, valuestring = block.argument.partition(' in ')
        values = calculator.calculate(valuestring)
        if not values:
            return

        varlist = [
            normalize_var(calculator.do_glob_math(var.strip()))
            # TODO use list parsing here
            for var in varstring.split(",")
        ]

        # `@each $foo, in $bar` unpacks, but `@each $foo in $bar` does not!
        unpack = len(varlist) > 1
        if not varlist[-1]:
            varlist.pop()

        inner_rule = rule.copy()
        inner_rule.unparsed_contents = block.unparsed_contents
        if not self.should_scope_loop_in_rule(inner_rule):
            # DEVIATION: Allow not creating a new namespace
            inner_rule.namespace = rule.namespace

        for v in List.from_maybe(values):
            if unpack:
                v = List.from_maybe(v)
                for i, var in enumerate(varlist):
                    if i >= len(v):
                        value = Null()
                    else:
                        value = v[i]
                    inner_rule.namespace.set_variable(var, value)
            else:
                inner_rule.namespace.set_variable(varlist[0], v)
            self.manage_children(inner_rule, scope)
136752
def pretty_print_table(headers, rows):
    """"""
    table = make_table(headers=headers, rows=rows)
    pretty_print_table_instance(table)
1144311
def _format_dict(result):
    """"""

    table = KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    for key, value in result.items():
        value = iter_to_table(value)
        table.add_row([key, value])

    return table
411944
def _replace_variables(data, variables):
    """"""
    formatter = string.Formatter()
    return [formatter.vformat(item, [], variables) for item in data]
1322078
def _get_vars_to_collections(variables):
  """"""
  var_to_collections = collections.defaultdict(lambda: [])
  if isinstance(variables, dict):
    variables = list(v for _, v in variable_map_items(variables))
  for graph in set(v.graph for v in variables):
    for collection_name in list(graph.collections):
      entries = set(entry for entry in graph.get_collection(collection_name)
                    if isinstance(entry, tf.Variable))
      # For legacy reasons, tf.GraphKeys.GLOBAL_VARIABLES == "variables".
      # Correcting for this here, to avoid confusion.
      if collection_name == tf.GraphKeys.GLOBAL_VARIABLES:
        collection_name = "global_variables"
      for var in entries.intersection(variables):
        var_to_collections[var].append(collection_name)
  return var_to_collections
877706
def format_table(columns, rows):
    
    rows = [tuple(str(i) for i in r) for r in rows]
    columns = tuple(str(i).upper() for i in columns)
    if rows:
        widths = tuple(max(max(map(len, x)), len(c))
                       for x, c in zip(zip(*rows), columns))
    else:
        widths = tuple(map(len, columns))
    row_template = ('    '.join('%%-%ds' for _ in columns)) % widths
    header = (row_template % tuple(columns)).strip()
    if rows:
        data = '\n'.join((row_template % r).strip() for r in rows)
        return '\n'.join([header, data])
    else:
        return header
1139992
def _to_variable_type(x):
    
    var_mapping = {"string": "String", "File": "File", "null": "String",
                   "long": "Float", "int": "Int"}
    if isinstance(x, dict):
        if x["type"] == "record":
            return "Object"
        else:
            assert x["type"] == "array", x
            return "Array[%s]" % _to_variable_type(x["items"])
    elif isinstance(x, (list, tuple)):
        vars = [v for v in x if v != "null"]
        assert len(vars) == 1, vars
        return var_mapping[vars[0]]
    else:
        return var_mapping[x]
989082
def _make_data(data) -> Tuple[List[Dict], List[Dict]]:
        """"""
        jsdata = []
        for idx, row in data.iterrows():
            row.index = row.index.astype(str)
            rdict = row.to_dict()
            rdict.update(dict(key=str(idx)))
            jsdata.append(rdict)

        return jsdata, Table._make_columns(data.columns)
308724
def _with_columns(self, columns):
        """"""
        table = type(self)()
        for label, column in zip(self.labels, columns):
            self._add_column_and_format(table, label, column)
        return table
265735
def tabulate(self, format='html', syntax=''):

    '''
        
    '''

    from tabulate import tabulate as _tabulate
    
# define headers
    headers = ['Field', 'Datatype', 'Required', 'Default', 'Examples', 'Conditionals', 'Description']
    rows = []
    default_values = False
    additional_conditions = False
    field_description = False

# construct rows
    for key, value in self.keyMap.items():

        key_segments = _segment_path(key)

        if key_segments:

            row = []

        # add field column
            field_name = ''
            if len(key_segments) > 1:
                for i in range(1,len(key_segments)):
                    field_name += '&nbsp;&nbsp;&nbsp;&nbsp;'
            if key_segments[-1] == '0':
                field_name += '<i>item</i>'
            else:
                field_name += key_segments[-1]
            row.append(field_name)

        # add datatype column
            value_datatype = value['value_datatype']
            if 'integer_data' in value.keys():
                if value['integer_data'] and syntax != 'javascript':
                    value_datatype = 'integer'
            elif value['value_datatype'] == 'map':
                if syntax == 'javascript':
                    value_datatype = 'object'
            elif value['value_datatype'] == 'list':
                if syntax == 'javascript':
                    value_datatype = 'array'
            # retrieve datatype of item in list
                item_key = key + '[0]'
                item_datatype = self.keyMap[item_key]['value_datatype']
                if syntax == 'javascript':
                    if item_datatype == 'list':
                        item_datatype = 'array'
                    elif item_datatype == 'map':
                        item_datatype = 'object'
                elif 'integer_data' in self.keyMap[item_key].keys():
                    if self.keyMap[item_key]['integer_data']:
                        item_datatype = 'integer'
                value_datatype += ' of %ss' % item_datatype
            row.append(value_datatype)

        # add required column
            if value['required_field']:
                row.append('yes')
            else:
                row.append('')

        # add default column
            if 'default_value' in value.keys():
                default_values = True
                if isinstance(value['default_value'], str):
                    row.append('"%s"' % value['default_value'])
                elif isinstance(value['default_value'], bool):
                    row.append(str(value['default_value']).lower())
                else:
                    row.append(str(value['default_value']))
            else:
                row.append('')

        # define recursive example constructor
            def determine_example(k, v):
                example_value = ''
                if 'example_values' in v.keys():
                    for i in v['example_values']:
                        if example_value:
                            example_value += ', '
                        if isinstance(i, str):
                            example_value += '"%s"' % i
                        else:
                            example_value += value
                elif 'declared_value' in v.keys():
                    if isinstance(v['declared_value'], str):
                        example_value = '"%s"' % v['declared_value']
                    elif isinstance(v['declared_value'], bool):
                        example_value = str(v['declared_value']).lower()
                    else:
                        example_value = v['declared_value']
                else:
                    if v['value_datatype'] == 'map':
                        example_value = '{...}'
                    elif v['value_datatype'] == 'list':
                        example_value = '[...]'
                    elif v['value_datatype'] == 'null':
                        example_value = 'null'
                return example_value

        # add examples column
            row.append(determine_example(key, value))

        # add additional conditions
            conditions = ''
            description = ''
            for k, v in value.items():
                extra_integer = False
                if k == 'integer_data' and syntax == 'javascript':
                    extra_integer = True
                if k not in ('example_values', 'value_datatype', 'required_field', 'declared_value', 'default_value', 'field_position', 'field_metadata') or extra_integer:
                    add_extra = False
                    if k == 'extra_fields':
                        if v:
                            add_extra = True
                    if k in ('field_description', 'field_title'):
                        field_description = True
                        if k == 'field_description':
                            description = v
                        elif not description:
                            description = v
                    elif k != 'extra_fields' or add_extra:
                        additional_conditions = True
                        if conditions:
                            conditions += '<br>'
                        condition_value = v
                        if isinstance(v, str):
                            condition_value = '"%s"' % v
                        elif isinstance(v, bool):
                            condition_value = str(v).lower()
                        conditions += '%s: %s' % (k, condition_value)
            row.append(conditions)
            row.append(description)

        # add row to rows
            rows.append(row)

# add rows for top field
    top_dict = self.keyMap['.']
    if top_dict['extra_fields']:
        rows.append(['<i>**extra fields allowed</i>', '', '', '', '', '', ''])
    if 'max_bytes' in top_dict.keys():
        rows.append(['<i>**max bytes: %s</i>' % top_dict['max_bytes'], '', '', '', '', '', ''])

# eliminate unused columns
    if not field_description:
        headers.pop()
    if not additional_conditions:
        headers.pop()
    if not default_values:
        headers.pop(3)
    for row in rows:
        if not field_description:
            row.pop()
        if not additional_conditions:
            row.pop()
        if not default_values:
            row.pop(3)

# construct table html
    table_html = _tabulate(rows, headers, tablefmt='html')

# add links to urls in text
    # markdown_url = re.compile('\[(.*?)\]\((.*)\)')
    table_html = _add_links(table_html)

    return table_html
307229
def make_table(data, col_names):
    
    n_cols = len(data[0])
    assert n_cols == len(col_names)
    col_sizes = [max(len(r[i]) for r in data) for i in range(n_cols)]
    for i, cname in enumerate(col_names):
        if col_sizes[i] < len(cname):
            col_sizes[i] = len(cname)
    formatter = ' '.join('{:<%d}' % c for c in col_sizes)
    rows = '\n'.join([formatter.format(*row) for row in data])
    header = formatter.format(*col_names)
    divider = formatter.format(*['=' * c for c in col_sizes])
    output = '\n'.join((divider, header, divider, rows, divider))
    return output