Routine to page text or determine window size via command line.
358973
def main(argv=None):
  """"""

  if argv is None:
    argv = sys.argv

  try:
    opts, args = getopt.getopt(argv[1:], 'dhs', ['nodelay', 'help', 'size'])
  except getopt.error as msg:
    raise Usage(msg)

  # Print usage and return, regardless of presence of other args.
  for opt, _ in opts:
    if opt in ('-h', '--help'):
      print(__doc__)
      print(help_msg)
      return 0

  isdelay = False
  for opt, _ in opts:
    # Prints the size of the terminal and returns.
    # Mutually exclusive to the paging of text and overrides that behaviour.
    if opt in ('-s', '--size'):
      print('Length: %d, Width: %d' % TerminalSize())
      return 0
    elif opt in ('-d', '--delay'):
      isdelay = True
    else:
      raise Usage('Invalid arguments.')

  # Page text supplied in either specified file or stdin.

  if len(args) == 1:
    with open(args[0]) as f:
      fd = f.read()
  else:
    fd = sys.stdin.read()
  Pager(fd, delay=isdelay).Page()
310197
def hrule(width=None, char=None):
    """"""
    width = width or HRWIDTH
    char = char or HRCHAR
    return echo(getline(char, width))
983484
def opt_pagesize(self, pagesize):
        
        if pagesize != "auto":
            pagesize = int(pagesize)
        self.conf["pagesize"] = pagesize
398039
def interactive_mode(self):
        
        if PLATFORM == 'win32':
            # Defaulting to 80 on windows, better ideas are welcome, but the
            # solutions I found online are rather bulky
            height = 20
            width = 80
        else:
            height, width = os.popen('stty size', 'r').read().split()
            width = int(width)
            height = int(height)

        message_no = 0
        page_no = 0
        action = None
        while action != 'q':
            page_no = self.__update_window(width, height, message_no, page_no)
            action = getch()
            if action == 's':
                # Coerce in range
                message_no = \
                    max(min(len(self.messages) - 1, message_no + 1), 0)
                page_no = 0
            elif action == 'w':
                # Coerce in range
                message_no = \
                    max(min(len(self.messages) - 1, message_no - 1), 0)
                page_no = 0
            elif action == 'a':
                page_no -= 1
            elif action == 'd':
                page_no += 1
            elif action == 'b':
                self.__to_browser(message_no)
            elif action == 'f':
                self.__to_file(message_no)
1374002
def main(opts):
    """"""
    term = Terminal()
    style = Style()

    # if the terminal supports colors, use a Style instance with some
    # standout colors (magenta, cyan).
    if term.number_of_colors:
        style = Style(attr_major=term.magenta,
                      attr_minor=term.bright_cyan,
                      alignment=opts['--alignment'])
    style.name_len = term.width - 15

    screen = Screen(term, style, wide=opts['--wide'])
    pager = Pager(term, screen, opts['character_factory'])

    with term.location(), term.cbreak(), \
            term.fullscreen(), term.hidden_cursor():
        pager.run(writer=echo, reader=term.inkey)
    return 0
487578
def fill_pager(self, page):
        
        tty_size = os.popen("stty size", "r").read().split()
        rows = int(tty_size[0]) - 1
        lines = sum(1 for line in page.splitlines())
        diff = rows - lines
        fill = "\n" * diff
        if diff > 0:
            return fill
        else:
            return ""
136519
def parse_page(page):
    """"""
    colors = get_config()['colors']
    with io.open(page, encoding='utf-8') as f:
        lines = f.readlines()
    output_lines = []
    for line in lines[1:]:
        if is_headline(line):
            continue
        elif is_description(line):
            output_lines.append(click.style(line.replace('>', ' '),
                                            fg=colors['description']))
        elif is_old_usage(line):
            output_lines.append(click.style(line, fg=colors['usage']))
        elif is_code_example(line):
            line = '  ' + line if line.startswith('`') else line[2:]
            output_lines.append(click.style(line.replace('`', ''),
                                            fg=colors['command']))
        elif is_line_break(line):
            output_lines.append(click.style(line))
        else:
            output_lines.append(click.style('- ' + line, fg=colors['usage']))
    return output_lines
407856
def prompt(pagenum):
    
    prompt = "Page -%s-. Press any key to continue . . . " % pagenum
    echo(prompt)
    if getch() in [ESC_, CTRL_C_, 'q', 'Q']:
        return False
    echo('\r' + ' '*(len(prompt)-1) + '\r')
296980
def lvresize(size=None, lvpath=None, extents=None):
    '''
    

    '''
    if size and extents:
        log.error('Error: Please specify only one of size or extents')
        return {}

    cmd = ['lvresize']

    if size:
        cmd.extend(['-L', '{0}'.format(size)])
    elif extents:
        cmd.extend(['-l', '{0}'.format(extents)])
    else:
        log.error('Error: Either size or extents must be specified')
        return {}

    cmd.append(lvpath)
    cmd_ret = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
    return {'Output from lvresize': cmd_ret[0].strip()}
1083613
public static void printCommandInfo(Command command, PrintWriter pw) {
    String description =
        String.format("%s: %s", command.getCommandName(), command.getDescription());
    int width = 80;
    try {
      width = TerminalFactory.get().getWidth();
    } catch (Exception e) {
      // In case the terminal factory failed to decide terminal type, use default width
    }

    HELP_FORMATTER.printWrapped(pw, width, description);
    HELP_FORMATTER.printUsage(pw, width, command.getUsage());
    if (command.getOptions().getOptions().size() > 0) {
      HELP_FORMATTER.printOptions(pw, width, command.getOptions(), HELP_FORMATTER.getLeftPadding(),
          HELP_FORMATTER.getDescPadding());
    }
  }
1353602
def term_width():
    
    if fcntl and termios:
        try:
            winsize = fcntl.ioctl(0, termios.TIOCGWINSZ, '    ')
            _, width = struct.unpack('hh', winsize)
            return width
        except IOError:
            pass
    elif windll and create_string_buffer:  # pragma: no cover (windows)
        stderr_handle, struct_size = -12, 22
        handle = windll.kernel32.GetStdHandle(stderr_handle)
        csbi = create_string_buffer(struct_size)
        res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
        if res:
            (_, _, _, _, _, left, _, right, _,
             _, _) = struct.unpack('hhhhHhhhhhh', csbi.raw)
            return right - left + 1
        else:
            return 0
396688
def get_terminal_width():
    
    # Let's first try using the official API
    # (Python 3.3+)
    if not six.PY2:
        import shutil
        sizex = shutil.get_terminal_size(fallback=(0, 0))[0]
        if sizex != 0:
            return sizex
    # Backups / Python 2.7
    if WINDOWS:
        from ctypes import windll, create_string_buffer
        # http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/
        h = windll.kernel32.GetStdHandle(-12)
        csbi = create_string_buffer(22)
        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
        if res:
            (bufx, bufy, curx, cury, wattr,
             left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)  # noqa: E501
            sizex = right - left + 1
            # sizey = bottom - top + 1
            return sizex
        return None
    else:
        # We have various methods
        sizex = None
        # COLUMNS is set on some terminals
        try:
            sizex = int(os.environ['COLUMNS'])
        except Exception:
            pass
        if sizex:
            return sizex
        # We can query TIOCGWINSZ
        try:
            import fcntl
            import termios
            s = struct.pack('HHHH', 0, 0, 0, 0)
            x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
            sizex = struct.unpack('HHHH', x)[1]
        except IOError:
            pass
        return sizex
970159
void setPageSizeAsString(String pageSize) {

        if (CmsStringUtil.isEmpty(pageSize)) {
            return;
        }

        try {
            m_pageSize = Integer.parseInt(pageSize);
        } catch (NumberFormatException e) {
            // intentionally left blank
        }
    }
755595
def terminal_width():
    """"""
    try:
        if os.name == 'nt':
            _WindowsCSBI.initialize()
            return _WindowsCSBI.get_info(_WindowsCSBI.HANDLE_STDOUT)['terminal_width']
        return struct.unpack('hhhh', fcntl.ioctl(0, termios.TIOCGWINSZ, '\000' * 8))[1]
    except IOError:
        return 80
658296
def get_terminal_size():
    ''''''
    def read_terminal_size_by_ioctl(fd):
        try:
            import struct, fcntl, termios
            cr = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ,
                                                            '0000'))
        except ImportError:
            return None
        except IOError as e:
            return None
        return cr[1], cr[0]

    cr = read_terminal_size_by_ioctl(0) or \
            read_terminal_size_by_ioctl(1) or \
            read_terminal_size_by_ioctl(2)
    if not cr:
        try:
            import os
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = read_terminal_size_by_ioctl(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        import os
        cr = [80, 25] # 25 rows, 80 columns is the default value
        if os.getenv('ROWS'):
            cr[1] = int(os.getenv('ROWS'))
        if os.getenv('COLUMNS'):
            cr[0] = int(os.getenv('COLUMNS'))

    return cr[1], cr[0]
997016
def _get_windows_console_width() -> int:
    
    from ctypes import byref, windll
    import pyreadline

    out = windll.kernel32.GetStdHandle(-11)
    info = pyreadline.console.CONSOLE_SCREEN_BUFFER_INFO()
    windll.kernel32.GetConsoleScreenBufferInfo(out, byref(info))
    return info.dwSize.X
1228563
def size(args):
    
    from jcvi.utils.cbook import human_size

    p = OptionParser(size.__doc__)
    fp = sys.stdin

    results = []
    for link_name in fp:
        link_name = link_name.strip()
        if not op.islink(link_name):
            continue

        source = get_abs_path(link_name)

        link_name = op.basename(link_name)
        filesize = op.getsize(source)
        results.append((filesize, link_name))

    # sort by descending file size
    for filesize, link_name in sorted(results, reverse=True):
        filesize = human_size(filesize, a_kilobyte_is_1024_bytes=True)
        print("%10s\t%s" % (filesize, link_name), file=sys.stderr)