Given a list of string widths, a width of the minimum gap to place
    between them, and the maximum width of the output (such as a terminal
    width), calculate the number of columns and rows, and the width of each
    column, for the optimal layout.
967322
def get_num_columns_and_rows(widths, gap_width, term_width):
    '''

    '''
    def calc_longest_width(widths, gap_width, ncols):
        longest = 0
        rows = [widths[s:s + ncols] for s in range(0, len(widths), ncols)]
        col_widths = rows[0] # Column widths start at the first row widths
        for r in rows:
            for ii, c in enumerate(r):
                if c > col_widths[ii]:
                    col_widths[ii] = c
            length = sum(col_widths) + gap_width * (ncols - 1)
            if length > longest:
                longest = length
        return longest, col_widths

    def calc_num_rows(num_items, cols):
        div, mod = divmod(num_items, cols)
        return div + (mod != 0)

    # Start with one row
    ncols = len(widths)
    # Calculate the width of the longest row as the longest set of item widths
    # ncols long and gap widths (gap_width * ncols - 1) that fits within the
    # terminal width.
    while ncols > 0:
        longest_width, col_widths = calc_longest_width(widths, gap_width, ncols)
        if longest_width < term_width:
            # This number of columns fits
            return calc_num_rows(len(widths), ncols), ncols, col_widths
        else:
            # This number of columns doesn't fit, so try one less
            ncols -= 1
    # If got here, it all has to go in one column
    return len(widths), 1, 0
945930
def adjust_column_width(worksheet):
    
    dims = {}
    padding = 1
    for row in worksheet.rows:
        for cell in row:
            if not cell.value:
                continue
            dims[cell.column] = max(
                dims.get(cell.column, 0),
                len(str(cell.value))
            )
    for col, value in list(dims.items()):
        worksheet.column_dimensions[col].width = value + padding
304738
def calculate_bar_widths(self, size, bardata):
        
        (maxcol, _) = size

        if self.bar_width is not None:
            return [self.bar_width] * min(
                len(bardata), int(maxcol / self.bar_width))

        if len(bardata) >= maxcol:
            return [1] * maxcol

        widths = []
        grow = maxcol
        remain = len(bardata)
        for _ in bardata:
            w = int(float(grow) / remain + 0.5)
            widths.append(w)
            grow -= w
            remain -= 1
        return widths
794548
def render
      buffer = []
      _guess_col_widths
      rows = @list.size.to_s.length
      @rows = rows
      _prepare_format
      
      str = ""
      if @numbering
        str = " "*(rows+1)+@y
      end
      str <<  @fmstr % @columns
      buffer << str
      #puts "-" * str.length
      buffer << separator
      if @list
        if @numbering
          @fmstr = "%#{rows}d "+ @y + @fmstr
        end
        #@list.each { |e| puts e.join(@y) }
        count = 0
        @list.each_with_index { |r,i|  
          value = convert_value_to_text r, count
          buffer << value
          count += 1
        }
      end
      buffer
    end
1285162
def columnise(rows, padding=2):
    """"""
    strs = []
    maxwidths = {}

    for row in rows:
        for i, e in enumerate(row):
            se = str(e)
            nse = len(se)
            w = maxwidths.get(i, -1)
            if nse > w:
                maxwidths[i] = nse

    for row in rows:
        s = ''
        for i, e in enumerate(row):
            se = str(e)
            if i < len(row) - 1:
                n = maxwidths[i] + padding - len(se)
                se += ' ' * n
            s += se
        strs.append(s)
    return strs
862943
def _calculate_column_widths(self):
        """"""
        table_width = self.get_table_width()
        lpw, rpw = self._left_padding_widths, self._right_padding_widths
        pad_widths = [(lpw[i] + rpw[i]) for i in range(self._column_count)]
        max_widths = [0 for index in range(self._column_count)]
        offset = table_width - sum(self._column_widths) + sum(pad_widths)
        self._max_table_width = max(self._max_table_width,
                                    offset + self._column_count)

        for index, column in enumerate(zip(*self._table)):
            max_length = 0
            for i in column:
                for j in to_unicode(i).split('\n'):
                    output_str = get_output_str(j, self.detect_numerics,
                                                self.numeric_precision,
                                                self.sign_mode.value)
                    max_length = max(max_length, termwidth(output_str))
            for i in to_unicode(self._column_headers[index]).split('\n'):
                output_str = get_output_str(i, self.detect_numerics,
                                            self.numeric_precision,
                                            self.sign_mode.value)
                max_length = max(max_length, termwidth(output_str))
            max_widths[index] += max_length

        sum_ = sum(max_widths)
        desired_sum = self._max_table_width - offset

        # Set flag for columns who are within their fair share
        temp_sum = 0
        flag = [0] * len(max_widths)
        for i, width in enumerate(max_widths):
            if width <= int(desired_sum / self._column_count):
                temp_sum += width
                flag[i] = 1
            else:
                # Allocate atleast 1 character width to the column
                temp_sum += 1

        avail_space = desired_sum - temp_sum
        actual_space = sum_ - temp_sum
        shrinked_columns = {}

        # Columns which exceed their fair share should be shrinked based on
        # how much space is left for the table
        for i, width in enumerate(max_widths):
            self.column_widths[i] = width
            if not flag[i]:
                new_width = 1 + int((width-1) * avail_space / actual_space)
                if new_width < width:
                    self.column_widths[i] = new_width
                    shrinked_columns[new_width] = i

        # Divide any remaining space among shrinked columns
        if shrinked_columns:
            extra = (self._max_table_width
                     - offset
                     - sum(self.column_widths))
            actual_space = sum(shrinked_columns)

            if extra > 0:
                for i, width in enumerate(sorted(shrinked_columns)):
                    index = shrinked_columns[width]
                    extra_width = int(width * extra / actual_space)
                    self.column_widths[i] += extra_width
                    if i == (len(shrinked_columns) - 1):
                        extra = (self._max_table_width
                                 - offset
                                 - sum(self.column_widths))
                        self.column_widths[index] += extra

        for i in range(self.column_count):
            self.column_widths[i] += pad_widths[i]
437364
def init_width(self):
        
        self.col_width = self.c.winfo_width()/self.cols
        self.row_height = self.c.winfo_height()/self.rows
726067
def _divide_widths(self, cli, width):
        
        if not self.children:
            return []

        # Calculate widths.
        given_dimensions = self.get_dimensions(cli) if self.get_dimensions else None

        def get_dimension_for_child(c, index):
            if given_dimensions and given_dimensions[index] is not None:
                return given_dimensions[index]
            else:
                return c.preferred_width(cli, width)

        dimensions = [get_dimension_for_child(c, index) for index, c in enumerate(self.children)]

        # Sum dimensions
        sum_dimensions = sum_layout_dimensions(dimensions)

        # If there is not enough space for both.
        # Don't do anything.
        if sum_dimensions.min > width:
            return

        # Find optimal sizes. (Start with minimal size, increase until we cover
        # the whole height.)
        sizes = [d.min for d in dimensions]

        child_generator = take_using_weights(
            items=list(range(len(dimensions))),
            weights=[d.weight for d in dimensions])

        i = next(child_generator)

        while sum(sizes) < min(width, sum_dimensions.preferred):
            # Increase until we meet at least the 'preferred' size.
            if sizes[i] < dimensions[i].preferred:
                sizes[i] += 1
            i = next(child_generator)

        while sum(sizes) < min(width, sum_dimensions.max):
            # Increase until we use all the available space.
            if sizes[i] < dimensions[i].max:
                sizes[i] += 1
            i = next(child_generator)

        return sizes
610840
private String getRowFormat(List<Integer> widths) {
    StringBuilder rowFormat = new StringBuilder(spaces(this.indentation));
    for (int i=0; i< widths.size(); i++) {
      rowFormat.append("%");
      rowFormat.append(this.flags != null ? this.flags.get(i) : "");
      rowFormat.append(widths.get(i).toString());
      rowFormat.append("s");
      rowFormat.append(spaces(this.delimiterWidth));
    }
    rowFormat.append("\n");

    return rowFormat.toString();
  }
447383
protected function _calculateWidths($rows)
    {
        $widths = [];
        foreach ($rows as $line) {
            foreach (array_values($line) as $k => $v) {
                $columnLength = $this->_cellWidth($v);
                if ($columnLength >= (isset($widths[$k]) ? $widths[$k] : 0)) {
                    $widths[$k] = $columnLength;
                }
            }
        }

        return $widths;
    }
1226848
def get_terminal_width():
    
    # http://www.brandonrubin.me/2014/03/18/python-snippet-get-terminal-width/
    command = ['tput', 'cols']
    try:
        width = int(subprocess.check_output(command))
    except OSError as e:
        print(
            "Invalid Command '{0}': exit status ({1})".format(
                command[0], e.errno))
    except subprocess.CalledProcessError as e:
        print(
            "'{0}' returned non-zero exit status: ({1})".format(
                command, e.returncode))
    else:
        return width
106297
def _compute_cols_width(self):
        

        if hasattr(self, "_width"):
            return
        maxi = []
        if self._header:
            maxi = [ self._len_cell(x) for x in self._header ]
        for row in self._rows:
            for cell,i in zip(row, list(range(len(row)))):
                try:
                    maxi[i] = max(maxi[i], self._len_cell(cell))
                except (TypeError, IndexError):
                    maxi.append(self._len_cell(cell))

        ncols = len(maxi)
        content_width = sum(maxi)
        deco_width = 3*(ncols-1) + [0,4][self._has_border()]
        if self._max_width and (content_width + deco_width) > self._max_width:
            """ content too wide to fit the expected max_width
            let's recompute maximum cell width for each cell
            """
            if self._max_width < (ncols + deco_width):
                raise ValueError('max_width too low to render data')
            available_width = self._max_width - deco_width
            newmaxi = [0] * ncols
            i = 0
            while available_width > 0:
                if newmaxi[i] < maxi[i]:
                    newmaxi[i] += 1
                    available_width -= 1
                i = (i + 1) % ncols
            maxi = newmaxi
        self._width = maxi
18791
def text_justification(words, max_width):
    '''
    
    '''
    ret = []  # return value
    row_len = 0  # current length of strs in a row
    row_words = []  # current words in a row
    index = 0  # the index of current word in words
    is_first_word = True  # is current word the first in a row
    while index < len(words):
        while row_len <= max_width and index < len(words):
            if len(words[index]) > max_width:
                raise ValueError("there exists word whose length is larger than max_width")
            tmp = row_len
            row_words.append(words[index])
            tmp += len(words[index])
            if not is_first_word:
                tmp += 1  # except for the first word, each word should have at least a ' ' before it.
            if tmp > max_width:
                row_words.pop()
                break
            row_len = tmp
            index += 1
            is_first_word = False
        # here we have already got a row of str , then we should supplement enough ' ' to make sure the length is max_width.
        row = ""
        # if the row is the last
        if index == len(words):
            for word in row_words:
                row += (word + ' ')
            row = row[:-1]
            row += ' ' * (max_width - len(row))
        # not the last row and more than one word
        elif len(row_words) != 1:
            space_num = max_width - row_len
            space_num_of_each_interval = space_num // (len(row_words) - 1)
            space_num_rest = space_num - space_num_of_each_interval * (len(row_words) - 1)
            for j in range(len(row_words)):
                row += row_words[j]
                if j != len(row_words) - 1:
                    row += ' ' * (1 + space_num_of_each_interval)
                if space_num_rest > 0:
                    row += ' '
                    space_num_rest -= 1
        # row with only one word
        else:
            row += row_words[0]
            row += ' ' * (max_width - len(row))
        ret.append(row)
        # after a row , reset those value
        row_len = 0
        row_words = []
        is_first_word = True
    return ret
731930
def column_widths(self, size, focus=False):
        
        maxcol = size[0]
        self._cache_maxcol = maxcol
        widths = [width for i, (w, (t, width, b)) in enumerate(self.contents)]
        self._cache_column_widths = widths

        return widths
4765
def width_aware_splitlines(self, columns):
        # type: (int) -> Iterator[FmtStr]
        
        if columns < 2:
            raise ValueError("Column width %s is too narrow." % columns)
        if wcswidth(self.s) == -1:
            raise ValueError('bad values for width aware slicing')
        return self._width_aware_splitlines(columns)
1117621
def max_width(self):
        
        value, unit = float(self._width_str[:-1]), self._width_str[-1]

        ensure(unit in ["c", "%"], ValueError,
               "Width unit must be either 'c' or '%'")

        if unit == "c":
            ensure(value <= self.columns, ValueError,
                   "Terminal only has {} columns, cannot draw "
                   "bar of size {}.".format(self.columns, value))
            retval = value
        else:  # unit == "%"
            ensure(0 < value <= 100, ValueError,
                   "value=={} does not satisfy 0 < value <= 100".format(value))
            dec = value / 100
            retval = dec * self.columns

        return floor(retval)
919486
def suggest_column_width col
      #ret = @cw[col] || 2
      ret = get_column(col).width || 2
      ctr = 0
      @list.each_with_index { |r, i|
        #next if i < @toprow # this is also a possibility, it checks visible rows
        break if ctr > 10
        ctr += 1
        next if r == :separator
        c = r[col]
        x = c.to_s.length
        ret = x if x > ret
      }
      ret
    end