def lesson2(self): '''Colemak lesson 2 - Letters RI''' self.printHeader(2) # print(' -RST--NEI-- -SDF--JKL--') print( ' ' '-' + green('R') + cyan('S') + cyan('T', style='underline') + '-' '-' + cyan('N', style='underline') + cyan('E') + green('I') + '--' ' ' '-SD' + underline('F') + '--' + underline('J') + 'KL--' ) print('\n (colemak) (qwerty)\n') self.tutor.lines([ 'trite stress sire it entire terse tit sir tire sinner retire', 'rinse inn tree insist tier rite teeter resin stir siren enter', 'sitter insert site sneer intern tie inner series steer tin', 'riser its resent sin rise rent rein iris stern in titter resist', 'eerie inert street is renter sit nine risen sister serene', 'stint err snit intent entree nit inter rest tennis re tint' ])
def lesson1(self): '''Colemak lesson 1 - Letters STNE''' self.printHeader(1) # print(' --ST--NE--- --DF--JK---') print( ' ' '--' + green('S') + green('T', style='underline') + '-' '-' + green('N', style='underline') + green('E') + '---' ' ' '-SD' + underline('F') + '--' + underline('J') + 'KL--' ) print('\n (colemak) (qwerty)\n') self.tutor.lines([ 'sets tens ten tnt sestet tenet seen nene testee tenets', 'essen sent senses tenses teens stent sense tent nets', 'tenseness net tense nests tennessee teen nest tents', 'net tens teen tenets senses nests nest nets tenet', 'sent sense tenses tennessee essen tnt tent teens', 'tense nene stent seen' ])
def print_headers(): resp = requests.get(args.url, headers=headers) if resp.ok: headtable = PrettyTable(["header", "value"]) headtable.header = False session_info = {} h = collections.OrderedDict(sorted(resp.headers.items())) for header in h: if header == 'x-akamai-session-info': aheadtable = PrettyTable(["header", "value"]) aheadtable.header = False si = [x.strip() for x in h[header].split(',')] for s in si: i = [x.strip() for x in s.split(';')] session_info[i[0][5:]] = i[1][6:] if len(i) > 2: t = i[2].split('=') session_info[t[0]] = t[1] elif header == 'x-check-cacheable': if h[header] == 'NO': headtable.add_row([blue(header), red(h[header])]) else: headtable.add_row([blue(header), green(h[header])]) elif header == 'x-cache': if 'TCP_MISS' in h[header]: headtable.add_row([blue(header), red(h[header])]) else: headtable.add_row([blue(header), green(h[header])]) else: headtable.add_row([blue(header), green(h[header])]) headtable.align = "l" print bold(underline(blue("### Headers"))) print headtable if session_info: if args.session: d = collections.OrderedDict(sorted(session_info.items())) for key in d: aheadtable.add_row([blue(key), green(d[key])]) aheadtable.align = "l" print bold(underline(blue("### Akamai Session Info"))) print aheadtable
def lesson3(self): '''Colemak lesson 3 - Letters AO''' self.printHeader(3) # print(' ARST--NEIO- ASDF--JKL;-') print( ' ' + green('A') + cyan('RS') + cyan('T', style='underline') + '-' '-' + cyan('N', style='underline') + cyan('EI') + green('O') + '-' ' ' 'ASD' + underline('F') + '--' + underline('J') + 'KL;-' ) print('\n (colemak) (qwerty)\n') self.tutor.lines([ 'retain roe rant ratio toast sort stat tore earn noose', 'teat eater oat trio tear tone artist nor tattoo seat arise', 'noise start toss tenant oasis one aria no arson sonata ', 'soon rear to ass soot irate sane onset star root state', 'oar errant resort tartan sonnet notes eat rotten stain', 'ration arose reason noon sass retina iota torn stairs', 'iron estate toe are season not attire tenor innate', 'torso tease arisen note tar snort tarot', ])
def stepline(cls, message): """A step underlined in a test section. eg. Aqf.stepline("Test that the antenna is stowed when X is set to Y") :param message: String. Message describe what the step will test. """ try: assert isinstance(message, list) except AssertionError: message = [message] message = colors.underline(''.join(message)) _state.store.add_step(message) cls.log_step(message)
def display_show(result_tuple): """Return string with an advisee's flattened responses. Input is in form: (email, [((timestamp, latest), field, response)]).""" if result_tuple is None or result_tuple == (): logging.error("No input tuple given") return display_strings.NO_RESPONSES EMAIL_INDEX = 0 RESPONSE_LIST_INDEX = 1 TIMESTAMP_INDEX = 0 TIMESTAMP_STR_INDEX = 0 TIMESTAMP_LATEST_INDEX = 1 FIELD_INDEX = 1 RESPONSE_INDEX = 2 result = textwrap.fill(display_strings.SHOW_COMMAND_HEADER.format( bold(result_tuple[EMAIL_INDEX])), width=80) + "\n\n" RESPONSE_LIST = result_tuple[RESPONSE_LIST_INDEX] if not RESPONSE_LIST: logging.error("No search results") return result + display_strings.NO_RESPONSES for response in RESPONSE_LIST: field = underline( map_fields.get_abbreviated_field(response[FIELD_INDEX])) timestamp_tuple = response[TIMESTAMP_INDEX] timestamp_latest = timestamp_tuple[TIMESTAMP_LATEST_INDEX] timestamp = negative(str(timestamp_tuple[TIMESTAMP_STR_INDEX]) ) if timestamp_latest else str( timestamp_tuple[TIMESTAMP_STR_INDEX]) response_string = str(response[RESPONSE_INDEX]) result += align(field, timestamp) + "\n" result += textwrap.fill(response_string, width=80) + "\n\n" return result
def get_todo_str(self, todo, date=False, completed_faint=False, notes=False): """Get a nicely formatted and colored string describing a task.""" todo_str = "%-*s" % (40, todo['text']) # If dates should be printed, add the planning and drop-dead dates if date: plan_date = "" plan_date_obj = todo.get_planning_date() if plan_date_obj: plan_date = pretty.date(plan_date_obj) due = "" if 'date' in todo.keys() and todo['date']: dt_obj = dateutil.parser.parse(todo['date']) due = pretty.date(dt_obj) todo_str += " Plan: %-*s Due:%-*s" % (15, plan_date, 15, due) # Underline the string if the task is urgent tags = [tag for tag in todo['tags'].keys() if todo['tags'][tag]] if 'urgent' in [self.user['tag_dict'][tag] for tag in tags]: todo_str = colors.underline(todo_str) # Make the string faint if it has been completed if completed_faint: if 'completed' in todo.keys() and todo['completed']: todo_str = colors.faint(todo_str) # Format the notes as an indented block of text if notes: wrapper = textwrap.TextWrapper(initial_indent=" "*4, subsequent_indent=""*4) todo_str += "\n" + wrapper.fill(todo['notes']) return todo_str
info = json.loads(open("model_info.json").read()) m2f = [] f2m = [] for model in info: m2f.append((model["name"], np.mean(model["m2f"]))) f2m.append((model["name"], np.mean(model["f2m"]))) m2f.sort(key=lambda x: x[1]) f2m.sort(key=lambda x: x[1]) for i, m in enumerate(m2f): colors.blue( "-----------------------------------------------------------------------" ) best = joblib.load(os.path.join("models", m[0])) params = best.get_params() keys = list(params.keys()) keys.sort() for key in keys: print( colors.underline(key) + ": " + str(params[key]).replace("\n", "")) print("\033[92mmodel\033[0m: " + str(params["regressor"].model)) colors.red("m2f: " + str(m[1])) colors.red("f2m: " + str(f2m[i][1])) input("")
def main(): # create the shared context context: Context = Context() try: # load the auto files from user home and cwd context.load_auto_files() # create the shared context and parse the command-line arguments args = parse_arguments(context) context.verbose = args.verbose context.confirm = ConfirmationMode[args.confirm] # print a cool header now... print('') with Logger( green( underline( bold( f"Deployster v{context.version} :heavy_check_mark: " f"Deploy with pleasure :smile:")))) as logger: pass # display the context context.display() # load & display the manifest manifest: Manifest = Manifest( context=context, manifest_files=[Path(p).absolute() for p in args.manifests]) manifest.display_plugs() # build the deployment plan, display, and potentially execute it executor: Executor = Executor(manifest=manifest) executor.bootstrap() executor.execute() except UserError as e: with Logger(indent_amount=0, spacious=False) as logger: logger.info('') if context and context.verbose: logger.error(traceback.format_exc().strip()) else: logger.error(e.message) exit(1) except termios.error as e: with Logger(indent_amount=0, spacious=False) as logger: logger.info('') logger.error(f"IO error: {e}") exit(1) except KeyboardInterrupt: with Logger(indent_amount=0, spacious=False) as logger: logger.info('') logger.error(f"Interrupted.") exit(1) except Exception: # always print stacktrace since this exception is an unexpected exception with Logger(indent_amount=0, spacious=False) as logger: logger.info('') logger.error(traceback.format_exc().strip()) exit(1)
def display_search(result_tuple, has_field=False): """Return string of list of advisees with responses that match search query. result_tuple takes on the form: (keyword, [((timestamp, latest), email, field, response)]).""" KEYWORD_INDEX = 0 # result_tuple differs based on whether it is returned by the query_search # or query_search_with_field function RESPONSE_LIST_INDEX = 2 if has_field else 1 FIELD_INDEX = 1 if has_field else 2 RESPONSE_INDEX = 2 if has_field else 3 TIMESTAMP_TUPLE_INDEX = 0 TIMESTAMP_STRING_INDEX = 0 TIMESTAMP_LATEST_INDEX = 1 EMAIL_INDEX = 1 if result_tuple is None: logging.error("result_tuple is None") return display_strings.NO_RESPONSES if result_tuple == (): logging.error("result_tuple is empty") return display_strings.NO_RESPONSES KEYWORD = bold(result_tuple[KEYWORD_INDEX]) if has_field: FIELD = bold(map_fields.get_field_string(result_tuple[FIELD_INDEX])) result = textwrap.fill( display_strings.SEARCH_WITH_FIELD_COMMAND_HEADER.format( KEYWORD, FIELD), width=80) + "\n\n" else: result = textwrap.fill( display_strings.SEARCH_COMMAND_HEADER.format(KEYWORD), width=80) + "\n\n" RESPONSE_LIST = result_tuple[RESPONSE_LIST_INDEX] if not RESPONSE_LIST: logging.error("No search results") return result + display_strings.NO_RESPONSES for response_tuple in RESPONSE_LIST: timestamp_tuple = response_tuple[TIMESTAMP_TUPLE_INDEX] timestamp_latest = timestamp_tuple[TIMESTAMP_LATEST_INDEX] timestamp_string = str(timestamp_tuple[TIMESTAMP_STRING_INDEX]) # if timestamp is latest, invert its color timestamp = negative( timestamp_string) if timestamp_latest else timestamp_string email = str(response_tuple[EMAIL_INDEX]) response = str(response_tuple[RESPONSE_INDEX]) if not has_field: field = underline( map_fields.get_abbreviated_field( (response_tuple[FIELD_INDEX]))) response_string = align( email, timestamp, timestamp_latest) + "\n" + field + "\n" + response + "\n\n" else: response_string = align( email, timestamp, timestamp_latest) + "\n" + response + "\n\n" result += response_string return result
def rainbow_maker_arg_help(color_name): return '{color} used when making rainbow, {typically} this would be {color_name}.'.format( color=bold('color'), typically=underline('typically'), color_name=color_kwargs[color_name])
('yellow', partial(color, fg='yellow', style='bold')), ('green', partial(color, fg='green', style='bold')), ('blue', partial(color, fg='blue', style='bold')), ('indigo', partial(color, fg='indigo', style='bold')), ('violet', partial(color, fg='violet', style='bold')))) positions = ['first', 'second', 'third', 'forth', 'fifth', 'sixth', 'seventh'] color_kwargs = { 'color': bold('color'), 'typically': underline('typically'), } color_pos = OrderedDict((p, v(p)) for v, p in zip(colors.values(), positions)) color_names = OrderedDict((k, v(k)) for k, v in colors.items()) if sys.version_info >= (3, 10): color_kwargs.update({ 'options_string': 'options', }) else: color_kwargs.update({ 'options_string': 'optional arguments', }) def rainbow_text(text):