示例#1
0
def main():
    print("Begining test:")
    wids = utils.get_terminal_height()
    hits = utils.get_terminal_width()
    print("Screen width: {}\nScreen height :{}".format(wids, hits))
    print("-" * 80)
    print("Testing get_box_size function (this WILL end in an exception):")
    screens = [140, 120, 80, 60, 59, 40, 0]
    days = [10, 12, 15, 5]
    try:
        for size in screens:
            for day in days:
                mc, bw = get_box_size(day, size)
                print("{}: {:>5} {}: {:>3} {}: {:>3} {}: {:>4} {}: {}".format(
                    "Window width:",
                    size,
                    "Days in forcast",
                    day,
                    "max_cols",
                    mc,
                    "box_width",
                    bw,
                    "Columns used",
                    mc * bw))
    except IndexError as e:
        print("Exception correctly caught: \n\t{}".format(e))
        print("-" * 80)
        raise e
示例#2
0
def print_forecast(weat_db, frmt='lines', screen_width=None):
    if screen_width is None:
        screen_width = utils.get_terminal_width()
    if frmt == 'lines':
        res = lines_forecast(weat_db)
    elif frmt == 'grid':
        import printers.forecast_grid as fg
        res = fg.grid_forecast(weat_db, screen_width)
    elif frmt == 'week':
        import printers.forecast_week as fw
        res = fw.week_forecast(weat_db, screen_width)
    else:
        res = lines_forecast(weat_db)
    return res
示例#3
0
def newer_cols_formatter(l, l2, start, func_obj, COLOR,
                         col_height=19, col_width=6):
    # important screen info!
    import sys
    home_dir = '/usr/self/weather/'
    if home_dir not in sys.path:
        sys.path.append(home_dir)
    import utils.utilities as utils
    screen_width = utils.get_terminal_width()
    screen_height = utils.get_terminal_height()

    # massage the func_obj into shape:
    if isinstance(func_obj, dict):
        func_obj = dict_to_obj(func_obj)
    func_obj_defaults = {'scale_format':        lambda x: str(x),
                         'right_string':        '| ',
                         'fargs':               [],
                         'label_fargs':         [],
                         'color_func':          '',
                         'label_color_func':    ''}
    for key in func_obj_defaults:
        if not hasattr(func_obj, key):
            setattr(func_obj, key, func_obj_defaults[key])

    if start is None:
        ind = 0
        while l[ind] is None:
            ind += 1
        start = l[ind]
    if hasattr(func_obj, 'scale_max') and hasattr(func_obj, 'scale_min'):
        mx = func_obj.scale_max(max(list(z for z in l if z is not None)))
        mn = func_obj.scale_min(min(list(z for z in l if z is not None)))
    else:
        mx = max(list(z for z in l if z is not None))
        mn = min(list(z for z in l if z is not None))

    col_height = min(col_height, screen_height - 4)
    if hasattr(func_obj, 'height_func'):
        old_col_height = col_height
        col_height = func_obj.height_func(mn, mx, col_height)
        if old_col_height != col_height:
            print("Changed {} to {}".format(old_col_height, col_height))

    zindexer = indexer_maker(mn, mx, col_height)
    # TODO:     get screen width and height (utils.get_terminal_width etc)
    #           limit l and l2 depending on col_width into screen width
    cols = column_maker(l[:((screen_width//col_width) - 2)],
                        start, zindexer, col_height, col_width,
                        func_obj, func_obj.color_func, COLOR)
    scale = scale_formatter(mx, mn, col_height, col_width,
                            func_obj.scale_format,
                            func_obj.right_string,
                            *func_obj.fargs)
    labels = func_obj.label_formatter(l2[:((screen_width//col_width) - 2)], 
                                      col_width,
                                      func_obj.label_func,
                                      func_obj.label_color_func,
                                      func_obj.label_test_func,
                                      COLOR,
                                      *func_obj.label_fargs)
    res = join_all(cols, scale, labels)
    return res
示例#4
0
def day_temps_formatter(temps, times):
    import sys
    import datetime as dt
    home_dir = '/usr/self/weather/'
    if home_dir not in sys.path:
        sys.path.append(home_dir)
    import utils.utilities as utils
    import printers.colorfuncs as cf
    width = utils.get_terminal_width()

    # make the passed-in objects
    col_width = min(5, width // 25)
    col_height = 21
    COLOR = utils.get_colors()

    def date_func(zed):
        if isinstance(zed, dt.datetime) or isinstance(zed, dt.time):
            temp = zed
        else:
            temp = dt.datetime.fromtimestamp(int(zed))
        return temp.strftime('%H:%M')

    def scale_min(x):
        return int(x - (x % 10))
        #  return int(x - (x % 5))

    def scale_max(x):
        #  return int(x + (10 - (x % 5)))
        return int(x + (10 - (x % 10)))

    def height_func(mn, mx, col_height):
        scales = [1, 2.5, 5, 10, 20]
        ind = 0
        while ind < len(scales) and (mx - mn) / scales[ind] > (col_height - 1):
            ind += 1
        return min(mx - mn // scales[ind - 1], col_height)

    funcs = {}
    funcs['above'] = lambda x, y: "{}{}{}".format(' ', '+' * (y - 2), ' ')
    funcs['equal'] = lambda x, y: str(x)[:y]
    funcs['below'] = lambda x, y: "{}{}{}".format(' ', '-' * (y - 2), ' ')
    funcs['color_func'] = cf.bar_temp_color
    funcs['label_func'] = date_func
    funcs['label_color_func'] = cf.new_alternating_bg
    funcs['label_test_func'] = lambda x: x % 2 == 0
    funcs['label_formatter'] = label_formatter
    funcs['scale_format'] = lambda x: str(round(x, 1))
    funcs['scale_max'] = scale_max
    funcs['scale_min'] = scale_min
    funcs['height_func'] = height_func

    # clean the input lists
    zepochs = list(map(lambda x: dt.datetime.fromtimestamp(int(x)), times))
    #  cleaned = clean_by_hours(opened[target_keys[0]], zepochs)
    cleaned = clean_by_hours(temps, zepochs)
    full = list(z[0] for z in cleaned)
    epochs = list(z[1] for z in cleaned)

    # call the wrapped func
    return newer_cols_formatter(full, epochs, None, funcs, COLOR,
                                col_height=col_height,
                                col_width=col_width)
示例#5
0
def main():
    """ Hooray, a giant if-elif-else tree!
    """
    # TODO:     1. move ALL this junk to main(), call from here
    #           2. open shelve file here
    #           3. check to see if there IS a current response key
    #           4. put open/close shelve in update so it can be called
    #              seperately
    # -------------------------------------------------------------------------
    # init variables
    # -------------------------------------------------------------------------
    home_dir = '/usr/self/weather'
    # here we make sure the package imports can go through:
    if home_dir not in sys.path:
        sys.path.append(home_dir)
    import config.loaders
    import logging
    import utils.utilities as utils
    config_file = config.loaders.config_file_name()
    weather_db_name = config.loaders.day_file_name()
    log_file = config.loaders.log_file_name()
    logging.basicConfig(filename=log_file, level=logging.DEBUG,
        format="%(levelname)s:%(name)s:%(asctime)s -- %(message)s")

    args = parse_arguments()
    logging.debug("Loaded args object. {} attrs in args.__dict__".format(
        len(args.__dict__)))

    configs = config.loaders.parse_config()
    loop_flag = True
    while loop_flag is True:
        try:
            if args.update:
                args.verbose = True
                update(verbose=args.verbose, check_time=True)
                loop_flag = False
            elif args.options:
                temp = config.loaders.load_vars(config_file)
                res = config.loaders.key_formatter(temp)
                for r in res:
                    print(r)
                loop_flag = False
            else:
                # only get current response object if we need it
                import returner
                current = returner.main()

                if args.width:
                    screen_width = min(utils.get_terminal_width(), args.width)
                else:
                    screen_width = utils.get_terminal_width()
                if args.logging:
                    logging.info("Sending test message -- all is well!")
                    loop_flag = False
                elif args.debug in ['current', 'c']:
                    res = config.loaders.key_formatter(
                        current['current_observation'])
                    for r in res:
                        print(r)
                    loop_flag = False
                elif args.debug in ['hourly', 'h']:
                    res = config.loaders.key_formatter(
                        current['hourly_forecast'][0])
                    for r in res:
                        print(r)
                    loop_flag = False
                elif args.debug in ['forecast', 'f']:
                    res = config.loaders.key_formatter(
                        current['forecast']
                               ['simpleforecast']
                               ['forecastday'][0])
                    for r in res:
                        print(r)
                    loop_flag = False
                elif args.files:
                    raise NotImplementedError
                elif args.yesterday:
                    import printers.prinutils as pu
                    import utils.file_utils as fu
                    import datetime as dt
                    tim = dt.date.today() - dt.timedelta(days=1)
                    target = config.loaders.day_file_name(tim)
                    target_keys = []
                    target_keys.append(('current_observation', 'temp_f'))
                    target_keys.append(('current_observation',
                                        'observation_epoch'))

                    opened = fu.parse_database(target, target_keys)
                    res = pu.day_temps_formatter(opened[target_keys[0]],
                                                 opened[target_keys[1]])
                    print("Queried Temperatures for {}".format(
                        tim.strftime('%b %d %y')))
                    for lin in res:
                        print(lin)
                elif args.moon:
                    import printers.moon
                    printers.moon.print_moon(current['moon_phase'])
                    loop_flag = False
                elif (args.keys or args.recent or args.query or args.times):
                    print_bookkeeping(args, current_ob=current,
                                      weat_db=weather_db_name)
                    loop_flag = False
                elif args.now or not (args.hourly or args.forecast):
                    import printers.current
                    printers.current.print_current(
                        current['current_observation'], args)
                    loop_flag = False
                elif args.hourly:
                    import printers.print_hourly
                    res = printers.print_hourly.print_hourly(
                        current['hourly_forecast'],
                        current['sun_phase'],
                        configs,
                        screen_width)
                    for lin in res:
                        print(lin)
                    loop_flag = False
                elif args.forecast:
                    #  print('args.forecst: {}'.format(args.forecast))
                    #  if args.forecast.startswith('w'):
                    if args.forecast[0].startswith('w'):
                        frmt = 'week'
                    elif args.forecast[0].startswith('g'):
                        frmt = 'grid'
                    else:
                        # the default, should be set in a config file
                        frmt = 'grid'
                    import printers.forecast
                    res = printers.forecast.print_forecast(
                        current['forecast']
                               ['simpleforecast']
                               ['forecastday'],
                        frmt=frmt,
                        screen_width=screen_width)
                    for lin in res:
                        print(lin)
                    loop_flag = False
            # if we've fallen through to here, do SOMETHING useful:
            if loop_flag is not False:
                update(verbose=args.verbose)
                loop_flag = False
        except KeyError as e:
            # update(verbose=args.verbose)
            message = "KeyError caught: {}".format(e)
            print(message)
            import traceback
            traceback.print_exception(*sys.exc_info())
            loop_flag = False
            logging.debug(message)
        except Exception as e:
            # tb = sys.exc_info()[2]
            message = "exception caught at top level: {}".format(e)
            print(message)
            import traceback
            traceback.print_exception(*sys.exc_info())
            loop_flag = False
            logging.debug(message)