Esempio n. 1
0
def print_goal(goal, achieved=False, level=None, indent=2):
    """ Print a goals description with its icon. Achieved (True/False) will choose the correct icon
    from the goal. If a level is specified, a tracker line will be added under the icon showing
    the current level out of the required level for the goal. If level is > the required level,
    achieved will be set to true.
    """
    from clint.textui import puts
    from clint.textui import indent as _indent
    from clint.textui.cols import columns, console_width
    if level is not None and level >= goal['level']:
        achieved = True
    icon = (goal['icon'].achieved() if achieved else goal['icon'].unachieved()).split('\n')
    maxiw = max([len(str(_)) for _ in icon])
    descw = console_width({})-maxiw-(indent + 4)
    desc = '{0}\n{1}\n\n{2}'.format(goal['name'], '-'*len(goal['name']),
                                    columns([goal['description'], descw])).split('\n')
    if level is not None:
        if level > goal['level']:
            level = goal['level']
        maxitw = max([len(_) for _ in icon])
        icon.append(("%d/%d" % (level, goal['level'])).center(maxitw))
    with _indent(indent):
        for i, d in _zip_longest(icon, desc):
            puts("{1:{0}}    {2}".format(maxiw, str(i) if i is not None else "",
                                         d.strip() if d is not None else ""))
Esempio n. 2
0
def print_goal(goal, achieved=False, level=None, indent=2):
    """ Print a goals description with its icon. Achieved (True/False) will choose the correct icon
    from the goal. If a level is specified, a tracker line will be added under the icon showing
    the current level out of the required level for the goal. If level is > the required level,
    achieved will be set to true.
    """
    from clint.textui import puts
    from clint.textui import indent as _indent
    from clint.textui.cols import columns, console_width
    if level is not None and level >= goal['level']:
        achieved = True
    icon = (goal['icon'].achieved()
            if achieved else goal['icon'].unachieved()).split('\n')
    maxiw = max([len(str(_)) for _ in icon])
    descw = console_width({}) - maxiw - (indent + 4)
    desc = '{0}\n{1}\n\n{2}'.format(goal['name'], '-' * len(goal['name']),
                                    columns([goal['description'],
                                             descw])).split('\n')
    if level is not None:
        if level > goal['level']:
            level = goal['level']
        maxitw = max([len(_) for _ in icon])
        icon.append(("%d/%d" % (level, goal['level'])).center(maxitw))
    with _indent(indent):
        for i, d in _zip_longest(icon, desc):
            puts("{1:{0}}    {2}".format(maxiw,
                                         str(i) if i is not None else "",
                                         d.strip() if d is not None else ""))
Esempio n. 3
0
 def _parse_log(self):
     #parse the log for information, see readme for how to setup SpeedFan output so that the script
     lw.log(['started parsing log'])
     lw.log(['read the log file'])
     first, last = self._read_log_file()
     temps = []
     speeds = []
     voltages = []
     percents = []
     others = []
     if first == '' or last == '':
         return temps, speeds, voltages, percents, others
     #pair up the heading with the value
     lw.log(['pair up the heading with the value'])
     for s_item, s_value in _zip_longest(first.split('\t'),
                                         last.split('\t')):
         item_type = s_item.split('.')[-1].rstrip().lower()
         item_text = os.path.splitext(s_item)[0].rstrip()
         #round the number, drop the decimal and then covert to a string
         #skip the rounding for the voltage and other readings
         if item_type == 'voltage' or item_type == 'other':
             s_value = s_value.rstrip()
         else:
             try:
                 s_value = str(int(round(float(s_value.rstrip()))))
             except ValueError:
                 s_value = str(
                     int(round(float(s_value.rstrip().replace(',', '.')))))
         if item_type == "temp":
             lw.log(['put the information in the temperature array'])
             if self.TEMPSCALE == 'Celcius':
                 temps.append([item_text + ':', s_value + 'C'])
             else:
                 temps.append([
                     item_text + ':',
                     str(int(round((float(s_value) * 1.8) + 32))) + 'F'
                 ])
         elif item_type == "speed":
             lw.log(['put the information in the speed array'])
             speeds.append([item_text + ':', s_value + 'rpm'])
         elif item_type == "voltage":
             lw.log(['put the information in the voltage array'])
             voltages.append([item_text + ':', s_value + 'v'])
         elif item_type == "percent":
             lw.log(['put the information in the percent array'])
             percents.append([item_text, s_value + '%'])
         elif item_type == "other":
             lw.log(['put the information in the other array'])
             others.append([item_text + ":", s_value])
     lw.log([
         temps, speeds, voltages, percents, others,
         'ended parsing log, displaying results'
     ])
     return temps, speeds, voltages, percents, others
Esempio n. 4
0
File: fs.py Progetto: em-p/pithy
def path_range(start_path, end_path):
  'Yield a sequence of paths from start_path (inclusive) to end_path (exclusive).'
  # TODO: more descriptive name.
  start = path_split(start_path)
  end = path_split(end_path)
  accum = []
  for s, e in _zip_longest(start, end):
    if s:
      if s != e:
        raise ValueError('paths diverge: start {!r}; end: {!r}'.format(s, e))
    else:
      yield path_join(*accum)
    accum.append(e)
Esempio n. 5
0
def extract_data_report(filename):
    """
    @param filename: name of data report to open
    @type filename: str
    @return: headers and data from data report
    @rtype: (list[str], list[str])
    """
    with open(filename, 'r') as f:
        headers = f.readline().split(',')
        data = f.read().splitlines()

    data = _zip_longest(*map(str.split, data, _repeat(',')), fillvalue='')

    return headers, data
Esempio n. 6
0
def main(path: _t.Optional[_t.Union[str, _Path]] = None) -> None:
    """Parse README from commandline argument.

    Initialize ``Holder`` to contain expected, actual, and total values.

    Enumerate over parsed ``Readme`` and populate the three containers.

        1. Expected ``list`` from the README file directly
        2. Actual from the actual command output
        3. Total with a combination of both plus code-block headings

    Run assertions on the actual and expected commands and print output
    from the total ``list``.

    Clear and initialize base key-values on each iteration.

    If no errors are raised then print that the README is a success and
    there are no errors in testing.

    :raises OutputDocumentError: Raise if the expected ``list`` contains
        nothing even though command output was captured.
    """
    if path is None:
        parser = _Parser()
        path = parser.file

    holder = _Holder()
    _assert.syntax(path)
    readme = _Readme()
    readme.load(path)
    _assert.code_blocks(readme)
    if _exec_status.in_exec:
        print("recursive exec not implemented")
    else:
        for count, element in enumerate(readme, 1):
            code_block = f"code-block {count}"
            holder.total.append_header(code_block)
            _process(element, holder)
            for position, _ in enumerate(
                    _zip_longest(holder.actual, holder.expected)):
                actual, expected = holder.getpair(position)
                _assert.actual_expected(actual, expected, code_block)
                _assert.equality(actual, expected, code_block)

        holder.display()
Esempio n. 7
0
 def __eq__(self, other):
     if isinstance(other, OrderedDict):
         return all(p==q for p, q in  _zip_longest(self.items(), other.items()))
     return dict.__eq__(self, other)
Esempio n. 8
0
def zip_longest(fill_value, it1, it2):
    return _zip_longest(it1, it2, fillvalue=fill_value)
Esempio n. 9
0
 def __eq__(self, other):
     if isinstance(other, OrderedDict):
         return all(p == q
                    for p, q in _zip_longest(self.items(), other.items()))
     return dict.__eq__(self, other)
Esempio n. 10
0
_redirect_stdout = redirect_stdout(captured_stdout)
_redirect_stdout.__enter__()


#################################
# main # only copy this section #
#################################
def solve(a, b):
    print(a + b)
    print(a)


T = int(input())
for _ in range(T):
    a = int(input())
    b = int(input())

    solve(a, b)

######################################
# output # compare with 'output.txt' #
######################################
_redirect_stdout.__exit__(None, None, None)

with open('output.txt', 'r') as f:
    out = f.read()

for x, y in _zip_longest(captured_stdout.getvalue().splitlines(),
                         out.splitlines()):
    print('\n'.join(Differ().compare([x], [y])))
Esempio n. 11
0
def grouper(iterable, n, fillvalue=None):
    """Itertools group recipe"""
    args = [iter(iterable)] * n
    return _zip_longest(*args, fillvalue=fillvalue)