def search(q, size, start, slop): """ Search documents. """ results = config.es.search( "osp", "document", body={ "size": size, "from": start, "fields": [], "query": {"match_phrase": {"body": {"query": q, "slop": slop}}}, "highlight": {"pre_tags": ["\033[1m"], "post_tags": ["\033[0m"], "fields": {"body": {}}}, }, ) term = Terminal() # Total hits. hits = str(results["hits"]["total"]) + " docs" click.echo(term.standout_cyan(hits)) # Hit highlights. for hit in results["hits"]["hits"]: click.echo("\n" + term.underline(hit["_id"])) for hl in hit["highlight"]["body"]: click.echo(hl)
def main(): """Play Conway's Game of Life on the terminal.""" def die((x, y)): """Pretend any out-of-bounds cell is dead.""" if 0 <= x < width and 0 <= y < height: return x, y LOAD_FACTOR = 9 # Smaller means more crowded. NUDGING_LOAD_FACTOR = LOAD_FACTOR * 3 # Smaller means a bigger nudge. term = Terminal() width = term.width height = term.height board = random_board(width - 1, height - 1, LOAD_FACTOR) detector = BoredomDetector() cells = cell_strings(term) with nested(term.fullscreen(), term.hidden_cursor()): try: while True: frame_end = time() + 0.05 board = next_board(board, die) draw(board, term, cells) # If the pattern is stuck in a loop, give it a nudge: if detector.is_bored_of(board): board.update(random_board(width - 1, height - 1, NUDGING_LOAD_FACTOR)) stdout.flush() sleep_until(frame_end) clear(board, term, height) except KeyboardInterrupt: pass
def show_progress(siteId, groupId, curr, total): '''Show the progress for sending the digest :param str siteId: The identifier for the site that contains the group. :param str groupId: The identifier for the group. :param int curr: The current index of the group. :param int total: The total number of groups. :func:`show_progress` displays the *verbose* feedback, including the name of the site and group. A progress bar is also displayed if the terminal supports it.''' t = Terminal() # Write the site and group if curr > 0 and t.does_styling: # Clear the line above (the progress bar) sys.stdout.write(t.move_up + t.move_x(0) + t.clear_eol) sys.stdout.flush() m = 'Sending digest to {0} on {1}\n' sys.stdout.write(t.white(m.format(groupId, siteId))) # Display progress if t.does_styling: # Length of the bar = (width of term - the two brackets) * progress p = int(((t.width - 2) * (curr / total))) bar = '=' * (p + 1) # +1 because Python is 0-indexed # Space at end = terminal width - bar width - brackets - 1 # (0-indexed) space = ' ' * (t.width - p - 3) sys.stdout.write(t.bold('[' + bar + space + ']\n')) sys.stdout.flush()
async def task_term_info(body): task = await fetch_task(body["status"]["taskId"]) name = task["metadata"]["name"] description = task["metadata"]["description"] task_id = body["status"]["taskId"] t = Terminal() return "{} {} {}".format(t.bold(task_id), name, t.dim(description))
def console(): t = Terminal() # clear screen print(t.clear, end="") # retrieve vended display object try: calculon.disp = Pyro4.Proxy(ENV['uri']) except: print(t.bold("Failed to connect to display")) calculon.disp = None repl.disp = calculon.disp # connect to voltron calculon.V = VoltronProxy() calculon.V.disp = calculon.disp calculon.V.update_disp() # run repl code.InteractiveConsole.runsource = repl.CalculonInterpreter().runsource code.interact(local=locals()) # clean up calculon.V._disconnect() if calculon.disp: calculon.disp._pyroRelease()
class TerminalView: """ Terminal view to basic CLI information. """ def __init__(self): self.term = Terminal() def print_error_and_exit(self, message): """ Print an error in red and exits the program. """ sys.exit(self.term.bold_red('[ERROR] ' + message)) def print_info(self, message): """ Print an informational text. """ print(message) def text_in_color(self, message, color_code): """ Print with a beautiful color. See codes at the top of this file. """ return self.term.color(color_code) + message + self.term.normal def format_question(self, message): """ Return an info-formatted string. """ return self.term.bold(message)
def dump_all(out_dir, heatmaps): stats = {} t = Terminal() t.clear() sys.stdout.write("\x1b[2J\x1b[H") print ('{t.underline}{outdir}{t.normal}\n'.format(t=t, outdir=out_dir)) keys = list(heatmaps.keys()) keys.sort() for layer in keys: if len(heatmaps[layer].log) == 0: continue with open ("%s/%s.json" % (out_dir, layer), "w") as f: json.dump(heatmaps[layer].get_heatmap(), f) stats[layer] = heatmaps[layer].get_stats() left = stats[layer]['hands']['left'] right = stats[layer]['hands']['right'] print ('{t.bold}{layer}{t.normal} ({total:,} taps):'.format(t=t, layer=layer, total=int(stats[layer]['total-keys'] / 2))) print (('{t.underline} | ' + \ 'left ({l[usage]:6.2f}%) | ' + \ 'right ({r[usage]:6.2f}%) |{t.normal}').format(t=t, l=left, r=right)) print ((' {t.bright_magenta}pinky{t.white} | {left[pinky]:6.2f}% | {right[pinky]:6.2f}% |\n' + \ ' {t.bright_cyan}ring{t.white} | {left[ring]:6.2f}% | {right[ring]:6.2f}% |\n' + \ ' {t.bright_blue}middle{t.white} | {left[middle]:6.2f}% | {right[middle]:6.2f}% |\n' + \ ' {t.bright_green}index{t.white} | {left[index]:6.2f}% | {right[index]:6.2f}% |\n' + \ ' {t.bright_red}thumb{t.white} | {left[thumb]:6.2f}% | {right[thumb]:6.2f}% |\n' + \ '').format(left=left['fingers'], right=right['fingers'], t=t))
class Input(object): prompt = '?> ' def __init__(self, config): self.config = config self.term = Terminal() self.commands = {} for name, member in inspect.getmembers(self): if inspect.ismethod(member) and name.startswith('do_'): self.commands[name[3:]] = member.__doc__ # A Command self.say_hello() self.say_prompt() def _validate(self, cmd): if cmd in self.commands: getattr(self, 'do_{}'.format(cmd))() else: print 'ERROR' def say_hello(self): if self.intro: print self.term.bold(self.intro) print '-'*len(self.intro) if self.commands: for name, help in self.commands.items(): print self.term.bold(name), ' ', help def say_prompt(self): input = raw_input(self.prompt) self._validate(input)
def tree(path, rel_to, indent=None): import sys from blessings import Terminal t = Terminal() # available in locals() left_t = LEFT_T last_t = LAST_T next_t = NEXT_T none_t = NONE_T if indent is None: sys.stdout.write(t.bold_blue(os.path.relpath(path, rel_to)) + "\n") indent = [] last_index = len(os.listdir(path)) - 1 for index, entry in enumerate(os.listdir(path)): is_last = index == last_index sys.stdout.write(u"{indent}{pre}{entry}\n".format(indent=''.join(indent), pre=is_last and last_t or left_t, entry=entry)) file = join(path, entry) if os.path.isdir(file): if is_last: tree(file, rel_to, indent + [none_t]) else: tree(file, rel_to, indent + [next_t])
def show_events(city): events = [['Group Name', 'Venue Name','Address', 'URL']] + get_events(city) terminal = Terminal() print "Showing events from city:", terminal.bold(city) event_table = AsciiTable(events) print event_table.table
def print_formatted(self, fp=sys.stdout, force_color=False, no_color=False, show_cmd=False, show_user=False, show_pid=False, show_power=None, gpuname_width=16, show_header=True, eol_char=os.linesep, **kwargs ): # ANSI color configuration if force_color and no_color: raise ValueError("--color and --no_color can't" " be used at the same time") if force_color: t_color = Terminal(kind='linux', force_styling=True) # workaround of issue #32 (watch doesn't recognize sgr0 characters) t_color.normal = u'\x1b[0;10m' elif no_color: t_color = Terminal(force_styling=None) else: t_color = Terminal() # auto, depending on isatty # appearance settings entry_name_width = [len(g.entry['name']) for g in self] gpuname_width = max([gpuname_width or 0] + entry_name_width) # header if show_header: time_format = locale.nl_langinfo(locale.D_T_FMT) header_template = '{t.bold_white}{hostname:{width}}{t.normal} ' header_template += '{timestr} ' header_template += '{t.bold_black}{driver_version}{t.normal}' header_msg = header_template.format( hostname=self.hostname, width=gpuname_width + 3, # len("[?]") timestr=self.query_time.strftime(time_format), driver_version=self.driver_version, t=t_color, ) fp.write(header_msg.strip()) fp.write(eol_char) # body for g in self: g.print_to(fp, show_cmd=show_cmd, show_user=show_user, show_pid=show_pid, show_power=show_power, gpuname_width=gpuname_width, term=t_color) fp.write(eol_char) fp.flush()
def __show_lines(self, lines, header, highlight=None): lines_as_string = "" t = Terminal() color = 0 for line in lines: if line[0]['name'] == '_SEPARATOR_': #import pdb;pdb.set_trace() lines_as_string += "%s\n" % self.__get_dots(header) continue else: lines_as_string += self.column_token for cell in line: try: name = cell['name'] if highlight in name: name = "%s" % t.bold_black_on_yellow(name) lines_as_string += " %s%s %s" % (name, " " * (cell['len'] - len(cell['name'])), self.column_token) except TypeError: if self.color: if color == 1: lines_as_string += " %s%s%s%s%s %s" % (self.c.get_cell_a_background_color(), self.c.get_cell_a_color(), name, " " * (cell['len'] - len(str(cell['name']))), self.c.ENDC, self.column_token) else: lines_as_string += " %s%s%s%s%s %s" % (self.c.get_cell_b_background_color(), self.c.get_cell_b_color(), name, " " * (cell['len'] - len(str(cell['name']))), self.c.ENDC, self.column_token) else: lines_as_string += " %s%s %s" % (name, " " * (cell['len'] - len(str(cell['name']))), self.column_token) if self.color: if color == 0: color = 1 else: color = 0 lines_as_string += "\n" print lines_as_string.strip("\n") self.__show_dots(header)
def main(): parser = argparse.ArgumentParser( description="Command line tool to watch torrents") parser.add_argument("name", help="The name of the series or movie") parser.add_argument("season_number", default=None, nargs="?", type=int, help="Season number") parser.add_argument("episode_number", default=None, nargs="?", type=int, help="Episode number") parser.add_argument("--sub", nargs='?', default=None, help="Subtitle language") parser.add_argument("--serve", action="store_true", help="Do not run VLC") parser.add_argument("--quality", nargs='?', default=None, help="quality of the video [normal|hd|fullhd]") parser.add_argument("--daemon", action="store_true", help="Daemonize the process"), parser.add_argument("--port", "-p", default="8888", help="The port where the stream will be served") parser.add_argument("--verbose", action="store_true", default=None, help="Show _all_ the logs") parser.add_argument("--player", default='vlc', help="Player to use. vlc|omxplayer|chromecast") parser.add_argument("--search", default=None, help="search lib to use (only option right now is 'kat' for kickass torrents)") parser.add_argument("--nocache", action="store_false", default=True, help="Search for the torrent again"), args = parser.parse_args() log_set_up(args.verbose) log.info("Starting touchandgo") log.debug("Running Python %s on %r", sys.version_info, sys.platform) log.debug("Libtorrent version: %s", libtorrent_version) try: if args.sub is not None: Language(args.sub) touchandgo = SearchAndStream(args.name, season=args.season_number, episode=args.episode_number, sub_lang=args.sub, serve=args.serve, quality=args.quality, port=args.port, player=args.player, search=args.search, use_cache=args.nocache) if args.daemon: def callback(): touchandgo.serve = True touchandgo.watch() daemonize(args, callback) else: term = Terminal() with term.fullscreen(): touchandgo.watch() except ValueError as e: print(e)
def run(self, args, cfg): terminal = Terminal() src = sources.load_source(cfg, args.source) if src.rulesDeny(args.src_ip, args.dst_ip, args.app): if not args.quiet: print terminal.black_on_green("Flow denied") else: if not args.quiet: print terminal.black_on_red("Flow not denied") sys.exit(1)
def print_on_line(txt,line_nb): term=Terminal() with term.location(0,line_nb): #with term.location(line_nb,0): # print " "*term.width #print term.move(line_nb,0)+" "*term.width #with term.location(line_nb,0): print(txt+" ") #print term.move(line_nb,0)+txt print(term.move(term.height-2,0))
def print_exit_msg(): term = Terminal() print "\n\nEnd of Line.\n\n" print ( " " + term.bold(term.green("<")) + "bn" + term.bold(term.green("/>")) ) print " Benito-Nemitz Inc."
class Components(object): def __init__(self, apk): self.logger = Logger() self.t = Terminal() self.apk = apk self.activities = list() self.services = list() self.receivers = list() self.providers = list() def sort_unique(self): """ """ return def enumerate_components(self): """ Enumerate the activities, broadcast receivers, services, and content providers from the target application's AndroidManifest.xml. Args: None Returns: None """ # TODO List comprehension # This is ugly f*****g code ... self.logger.log("info", "Loading components ...\n") try: if self.apk.get_activities(): for a in self.apk.get_activities(): self.activities.append(a) if self.activities: print(self.t.yellow("\t--> Loaded activities (!)")) if self.apk.get_services(): for s in self.apk.get_services(): self.services.append(s) if self.services: print(self.t.yellow("\t--> Loaded services (!)")) if self.apk.get_receivers(): for r in self.apk.get_receivers(): self.receivers.append(r) if self.receivers: print(self.t.yellow("\t--> Loaded receivers (!)")) if self.apk.get_providers(): for p in self.apk.get_providers(): self.providers.append(p) if self.providers: print(self.t.yellow("\t--> Loaded providers (!)")) print("\n") self.logger.log("info", "Finished loading components ...") except Exception as e: ComponentsError(e.message)
def main(dir1: Path, dir2: Path, recursive: bool) -> None: # For now, only take the common files. dircmp = filecmp.dircmp(dir1, dir2) if recursive: files1, files2, dir1_only, dir2_only = get_common_files_recursive(dir1, dir2) else: files1 = get_common_files_nonrecursive(dir1, dircmp.common_files) files2 = get_common_files_nonrecursive(dir2, dircmp.common_files) dir1_only = [f for f in joinpaths(dir1, dircmp.left_only) if f.is_file()] dir2_only = [f for f in joinpaths(dir2, dircmp.right_only) if f.is_file()] # For displaying full paths, calculate the needed column width from the # longest possible path. width1 = max(len(str(p)) for p in files1 + dir1_only) width2 = max(len(str(p)) for p in files2 + dir2_only) t = Terminal() map_diff_to_color = { DiffType.SAME: t.green, DiffType.INNER_PATHS_DIFFER: t.cyan, DiffType.SOMETHING_ELSE_DIFFERS: t.red, } diffs = [] for f1, f2 in zip(files1, files2): diff = Diff.from_files(f1, f2) diffs.append(diff) line = f"{diff.d1} {diff.d2} {str(f1):{width1}s} {str(f2):{width2}s}" print(map_diff_to_color[diff.diff_type](line)) # Print the unique files separately. FIXME scope hack using the last diff for f1 in dir1_only: line = f"{' ' * len(str(diff.d1))} {' ' * len(str(diff.d2))} {str(f1):{width1}s} {' ' * width2}" print(t.yellow(line)) for f2 in dir2_only: line = f"{' ' * len(str(diff.d1))} {' ' * len(str(diff.d2))} {' ' * width1} {str(f2):{width2}s}" print(t.yellow(line)) if args.write_files: with open("compare_diff.txt", "w") as handle: for diff in diffs: if diff.diff_type == DiffType.SOMETHING_ELSE_DIFFERS: handle.write(f"{str(diff.f1)} {str(diff.f2)}\n") # Write out the unique filenames. with open("compare_dir1_only.txt", "w") as handle: if dir1_only: for f in dir1_only: handle.write(f"{str(f)}\n") with open("compare_dir2_only.txt", "w") as handle: if dir2_only: for f in dir2_only: handle.write(f"{str(f)}\n") return
def __setHeader(self): t = Terminal() h = "\n" h += t.bold_yellow("Initializing: ") + t.bold_white(self.name + "\n") h += t.bold_yellow("Author: ") + t.bold_white(self.author + "\n") h += t.bold_yellow("Version: ") + t.bold_white(self.version + "\n") h += t.bold_yellow("Info: ") + t.bold_white(self.info) print h
def poll_chargepoint_stations(scraper, stations_of_interest=None, stations_to_ignore=None): if stations_to_ignore is None: stations_to_ignore = [] if stations_of_interest is None: stations_of_interest = scraper.get_station_data()['stations'].keys() stations_of_interest = [x for x in stations_of_interest if x not in stations_to_ignore] old_free_spots = None old_open_stations = [] t = Terminal() try: i = 0 while True: new_free_spots = 0 new_open_stations = [] try: data = scraper.get_station_data() except ChargePointAuthenticationExpiredException: data = scraper.get_station_data() if i % 10 == 0: print '\t\t\t' + '\t'.join([station for station in stations_of_interest]) line_parts = [data['time'].strftime('%Y/%m/%d %H:%M:%S')] for k in stations_of_interest: line_part = '%d / %d'.center(9) % (data['stations'][k]['available'], data['stations'][k]['total']) if data['stations'][k]['available'] == data['stations'][k]['total']: line_part = t.black_on_green(line_part) elif data['stations'][k]['available'] == 0: line_part = t.black_on_red(line_part) else: line_part = t.black_on_yellow(line_part) line_parts.append(line_part) new_free_spots += data['stations'][k]['available'] new_open_stations.extend([k] * data['stations'][k]['available']) print '\t'.join(line_parts) if old_free_spots is not None and new_free_spots > old_free_spots: newly_open_stations = new_open_stations for elem in old_open_stations: try: newly_open_stations.remove(elem) except ValueError: pass title = '%s station(s) are open' % ', '.join(newly_open_stations) message = '%d Free Spots' % new_free_spots if _platform == 'darwin': Notifier.notify(title=title, message=message) send_boxcar_notification(title=title, message=message) old_free_spots = new_free_spots old_open_stations = new_open_stations i += 1 sleep(60) except KeyboardInterrupt: pass except KeyError: exit("Unexpected response json.")
def tie_a_tie(): """ Interactive tie tying. """ def throw(): print(term.clear()) with term.location(10, term.height): print("Please enter a valid choice.") sleep(1) print(term.clear()) def start_knot(): print(term.clear()) starting_point = input("Start in or out? ").lower() if starting_point in ["i", "in"]: return Knot('Li') elif starting_point in ["o", "out"]: return Knot('Lo') else: return Knot() term = Terminal() with term.location(0,0): tie = start_knot() while tie.final() != 'Ti': print(term.clear()) choices = tie.legal_intersection() tie_str = str(tie) try: while True: with term.location(0,3): possibilities = [name for walk, name in NAMED_KNOTS.items() if tie_str == walk[:len(tie_str)]] print("\nPossible knots:\n{}\n".format("\n".join(possibilities))) next_step = input("Your knot so far: {}\nNext step ({}{}): " .format(tie_str, choices, " back" if len(tie) > 1 else "")).title() if next_step == "Back" and len(tie) > 1: tie.pop() break if next_step == "Back" and len(tie) == 1: tie = start_knot() break if next_step in choices: tie.append(next_step) break if not next_step: tie.append(choices[0]) break else: throw() except: throw() print(term.clear()) tie.analyze()
def print_matrix_with_fabulousness(matrix): t = Terminal() colors = [t.red, t.green, t.blue] if len(matrix) == 0: #print t.yellow('[]') return t.yellow('[') fmatrix = [['%.2f' % col for col in row] for row in matrix] ret_s = t.bold(' '.join([' '] + [str(c) for c in range(len(fmatrix[0]))]) + "\n") for n, row in enumerate(fmatrix): ret_s += colors[n % 3](' '.join([str(n)] + row) + "\n") return ret_s + '\n'
def run_report(self): """ Compile and print the task report. """ wdays = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"] letters = 3 # No of letters to use for wday names. 1 - 3 istty = True indent = letters # The indent per week day # TODO "indent" is used and defined here an in construct_cmdline. Define once? if istty: # This is currently hard coded, but can be an input. term = Terminal() else: term = Terminal(stream="not tty") # When not run from a tty # Calcs how many task lines can fit onto the screen. taskspace = (term.height if term.is_a_tty else 40) - (5 + letters) # Compile the line showing each Monday's date. dateline = self.weekstart.strftime("%d %b %Y") if self.weeks > 1: # Add additional Mondays if required for week in range(1, self.weeks): # i.e. week 1 is the second week. # No of spaces to add on to existing dateline before # inserting next date weekindent = len(wdays) * week * indent - len(dateline) dateline = dateline + ' ' * weekindent + (self.weekstart + \ timedelta(days=7 * week)).strftime("%d %b %Y") # Position # Compile the day header sting (includes newlines) dayheader = '' for lineNo in range(letters): for day in wdays * self.weeks: # add the letter and spacing to indent for each day and makes mondays bold dayheader = dayheader + (term.bold(day[lineNo]) if (day == \ "MON" and not self.selector) else day[lineNo]) + ' ' \ * (indent - 1) dayheader = dayheader + '\n' # Compile the multiline string containing the tasklines taskstring = "" for task in self.tasks: # Step through list of task dictionary objects taskline, tdate = self.compile_taskline(task) if tdate.date() < date.today(): # Add newline if not end of list and colour red taskstring = taskstring + ('\n' if len(taskstring) != 0 else '' ) + term.red(taskline) elif tdate.date() == date.today(): taskstring = taskstring + '\n' + term.yellow(taskline) elif tdate.date() > date.today(): taskstring = taskstring + '\n' + taskline # Removes lines that will not fit onto screen terminal_lines = ''.join(taskstring.splitlines(True)[0:taskspace]) print dateline + '\n' + dayheader + terminal_lines
def main(): term = Terminal() args = get_args() dir = '.' if args.path: dir = args.path print dir pattern = re.compile(args.regex) fname_pattern = re.compile(r".+") if args.file_name_pattern: fname_pattern = re.compile(args.file_name_pattern) lA, lB = 0, 0 if args.l_before: lB = args.l_before if args.l_after: lA = args.l_after blacklist = [] if args.exclude_paths: blacklist = args.exclude_paths.split(',') for root, dirs, files in os.walk(dir): if root in blacklist: continue for fname in files: if fname_pattern.match(fname): try: file_path = os.path.join(root, fname) with open(file_path, 'r') as source_file: contents = source_file.read() if pattern.search(contents): print term.bold("\n--- " + file_path + ':') content_lines = contents.split('\n') for line_no in range(len(content_lines)): m_obj = pattern.search( content_lines[line_no] + '\n') if m_obj: start = max(line_no - lB, 0) end = min(line_no + lA + 1, len(content_lines) - 1) line_nos = range(start, end) snippet = content_lines[start:end] # snippet_with_line_nos = [str(x[0]) + ' ' + x[1] for x in zip(line_nos, snippet)] csnippet = colorize( line_nos, line_no, snippet, m_obj, term ) pretty_print('\n'.join(csnippet)) except IOError as e: print e
def list_menu(args = 0): # Note: This is currentingly Work In Progress t = Terminal() try: items = get_menu() print "---------------" print "Grub2 Boot Menu:" print "Current Kernel: " + t.red(get_current()) print "Default Option: " + t.green(get_default()) print "---------------" for line in items: if items.index(line) < 10: pad = 3 else: pad = 2 if line == get_default(): print t.green("{") + t.red(str(items.index(line))) + t.green("}".ljust(pad) + line) else: print "[" + t.red(str(items.index(line))) + "]".ljust(pad) + line print "---------------" except IOError: print_error('You need to be root to perform this action.') except: print_error("Unknown Error")
def run(self): term = Terminal() print("%s (%s)" % (term.bold("krill 0.3.0"), term.underline("https://github.com/p-e-w/krill"))) while True: try: self.update() if self.args.update_interval <= 0: break time.sleep(self.args.update_interval) except KeyboardInterrupt: # Do not print stacktrace if user exits with Ctrl+C sys.exit()
def import_tsv(file_name): t = Terminal() with open(file_name) as importee: file_length = sum(1 for _ in importee) print('Importing {} relations'.format(file_length)) with open(file_name) as importee: print('Parsing file') print() count = 0 for line in importee: line = line.split('\t') start_data = line[0].split(':') start_word = None if '[[' not in line[0]: start_check = Word.query.filter_by(language=start_data[0], orig_form=start_data[1]).first() if start_check is None: start = Word(None, start_data[1], start_data[0]) db.session.add(start) else: start = start_check end_data = line[2].split(':') end = None if '[[' not in line[2]: end_check = Word.query.filter_by(language=end_data[0], orig_form=end_data[1]).first() if end_check is None: end = Word(None, end_data[1], end_data[0]) db.session.add(start) else: end = end_check rel_type = REL_CONVERTER[line[1][4:]] if rel_type[0] == 'root': if rel_type[1]: # flip order rel = Rel(None, start, end, 'Etymological Wordnet') else: rel = Rel(None, end, start, 'Etymological Wordnet') db.session.add(rel) count += 1 with t.location(0): print(t.move_up + str(count) + ' lines added' + t.clear_eol) print('Committing to database') db.session.commit()
class Renderer(): """renders a grid with values""" cell_width = 7 cell_height = 3 def __init__(self, grid): self.term = Terminal() self.grid = grid def _draw_cell(self, x, y, color, value, pos): x_mid = math.floor(self.cell_width/2) y_mid = math.floor(self.cell_height/2) for i in range(self.cell_width): for j in range(self.cell_height): char = ' ' print(self.term.move(y+j, x+i) + self.term.on_color(color) + '{}'.format(char) + self.term.normal) v = str(value) cx = x_mid + x cy = y_mid + y offset = len(v)//2 if value < 0: highlight = 1 elif value > 0: highlight = 2 else: highlight = 245 for i, char in enumerate(v): x = cx - offset + i print(self.term.move(cy, x) + self.term.on_color(color) + self.term.color(highlight) + char + self.term.normal) print(self.term.move(y, x) + self.term.on_color(color) + self.term.color(248) + '{},{}'.format(*pos) + self.term.normal) def render(self, pos=None): """renders the grid, highlighting the specified position if there is one""" print(self.term.clear()) for r, row in enumerate(self.grid): for c, val in enumerate(row): if val is None: continue color = 252 if (r + c) % 2 == 0 else 253 if pos is not None and pos == (r, c): color = 4 self._draw_cell(c * self.cell_width, r * self.cell_height, color, val, (r,c)) # move cursor to end print(self.term.move(len(self.grid) * self.cell_height, 0))
def take_action(self, args): if args.monitor: term = Terminal() while True: try: status = self.get_status() self.app.stdout.write(status) self.app.stdout.write(term.move_y(term.height - len(status.split('\n')))) time.sleep(1) except KeyboardInterrupt: self.app.stdout.write(term.move_y(term.height) + '\n') return else: self.app.stdout.write(self.get_status() + '\n')
def run(self): term = Terminal() print("%s (%s)" % (term.bold("krill++ 0.4.1"), term.underline("https://github.com/kyokley/krill"))) try: self.update() self.flush_queue(interval=0) if self.args.update_interval > 0: while True: time.sleep(self.args.update_interval) self.update() self.flush_queue(interval=self.text_speed) except KeyboardInterrupt: # Do not print stacktrace if user exits with Ctrl+C sys.exit()
# Setup GlobalLogger try: import logging logger = logging.getLogger('DroidFuzzer') except ImportError as e: raise e import json from os import getcwd from cmd2 import Cmd as DroidFuzzer from blessings import Terminal from framework.commands.enum import CommandEnum t = Terminal() class Run(DroidFuzzer): def __int__(self): DroidFuzzer.__init__(self) @staticmethod def do_fuzzers(args): """ Fuzz! Usage: fuzzer show Usage: fuzzer module <module> """ try: if len(args) < 2: logger.error("Not enough arguments (!)") logger.debug("Usage: fuzzers show")
def main(): terminal = Terminal() all_templates = template.get_installed_templates() all_formatters = formatter.get_installed_formatters() parser = argparse.ArgumentParser() parser.add_argument( '--template', dest='template', default=None, choices=all_templates.keys(), ) parser.add_argument( '--session', '-s', dest='session_path', default=None, ) parser.add_argument( '--editor-format', '-f', dest='editor_format', default=None, choices=all_formatters.keys() ) parser.add_argument( '--debugger', '-d', dest='debugger', default=False, action='store_true', ) args = parser.parse_args() exit_code = 0 if args.session_path and os.path.exists(args.session_path): if args.template or args.editor_format: parser.error( "You cannot set a template or editor format when " "resuming a pre-existing session." ) elif args.template and args.template not in all_templates: parser.error( "Template '{name}' does not exist.".format( name=args.template, ) ) conf = config.get_config() default_template_name = ( conf.get('benzo', {}).get('default_template', 'json') ) default_formatter_name = ( conf.get('benzo', {}).get('default_editor_format', 'json') ) try: result, response = editor.benzo_request( template_name=args.template or default_template_name, formatter_name=args.editor_format or default_formatter_name, session_path=args.session_path, ) except exceptions.RequestFailed as e: print( u"{t.bold}{t.red}Request failed (status: {status})!{t.normal} " u"{t.red}{message}{t.normal}".format( t=terminal, status=e.result.status_code, message=six.text_type(e) ) ) exit_code = 2 except exceptions.RequestAborted as e: print( u"{t.bold}{t.red}Request aborted:{t.normal} " "{t.red}Empty editor.{t.normal}".format( t=terminal, ) ) exit_code = 3 except Exception as e: print( u"{t.bold}{t.red}Unhandled exception occurred:{t.normal} " u"{t.red}{message}\n" "{traceback}{t.normal}".format( t=terminal, message=six.text_type(e), traceback=traceback.format_exc() ) ) exit_code = 1 else: print( u"{t.green}{message}{t.normal}".format( t=terminal, message=response, ) ) if args.debugger: pdb.set_trace() sys.exit(exit_code)
class Logger(object): def __init__(self): self.t = Terminal() def log(self, t, m): """ Log a message to the console. Args: param1: Type of log {info, warn, critical} param2: Log message Returns: None """ if t == "info": print( self.t.green("[{}] ".format(datetime.now())) + "{}".format(m)) if t == "warn": print( self.t.yellow("[{}] ".format(datetime.now())) + self.t.white("{}".format(m))) elif t == "critical": print( self.t.red("[{}] ".format(datetime.now())) + self.t.white("{}".format(m))) def surgical_log(self, t, m): """ Log a message to the console. Args: param1: Type of log {info, warn, critical} param2: Log message Returns: None """ if t == "info": print( self.t.yellow("[{}] ".format(datetime.now())) + "{}".format(m)) elif t == "critical": print( self.t.red("[{}] ".format(datetime.now())) + self.t.white("{}".format(m))) def binja_log(self, t, m): """ Log a message to the console. Args: param1: Type of log {info, warn, critical} param2: Log message Returns: None """ if t == "info": print(self.t.cyan("[{}] ".format(datetime.now())) + "{}".format(m)) elif t == "critical": print( self.t.red("[{}] ".format(datetime.now())) + self.t.white("{}".format(m)))
EXAMPLES python timesheets.py $LISTOFREPOS --start=2017-05-01 --end=2017-05-31 python timesheets.py $LISTOFREPOS --month=2017-05 """ import calendar from datetime import date, datetime import os from blessings import Terminal import click import git from dateutil import parser TERM = Terminal() TEMPLATE = '{ts} ' \ '{t.yellow}{commit}{t.normal} ' \ '{t.green}({author}){t.normal} ' \ '{t.yellow}{repo}{t.normal} ' \ '{t.red}[{branch}]{t.normal} ' \ '{subject}' @click.command() @click.option('-s', '--start', help='Start date (ex: "2017-05-01")') @click.option('-e', '--end', help='End date (ex: "2017-05-31")') @click.option('-m', '--month', help='Month (ex: "2017-05")') @click.argument('filename') def main(start, end, month, filename):
else: auth = None cluster = Cluster(hosts, port=port, auth_provider=auth) session = None statement = None history = ((ConsistencyLevel.ONE, []), (ConsistencyLevel.TWO, []), (ConsistencyLevel.THREE, []), (ConsistencyLevel.ALL, []), (ConsistencyLevel.QUORUM, []), (ConsistencyLevel.SERIAL, []), (ConsistencyLevel.EACH_QUORUM, []), (ConsistencyLevel.LOCAL_ONE, []), (ConsistencyLevel.LOCAL_QUORUM, []), (ConsistencyLevel.LOCAL_SERIAL, [])) term = Terminal() print(term.clear) print(". = Success") print( "C = Not enough live replicas to satisfy the requested consistency level") print( "E = All connections are busy, defunct, closed, or resulted in errors when used." ) print("T = Timeout") print("X = Server error. Session will be reopened.") print() y_offset = 7 longest_name = 0 for (consistency, _) in history: display_name = ConsistencyLevel.value_to_name[consistency]
from operator import itemgetter # Import invoke libs from invoke import task # Import 3rd-party libs try: import boto3 HAS_BOTO = True except ImportError: HAS_BOTO = False if HAS_BOTO: import botocore.exceptions try: from blessings import Terminal terminal = Terminal() HAS_BLESSINGS = True except ImportError: terminal = None HAS_BLESSINGS = False REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TIMESTAMP_UI = ' -timestamp-ui' if 'DRONE' in os.environ else '' PACKER_TMP_DIR = os.path.join(REPO_ROOT, '.tmp', '{}') def exit_invoke(exitcode, message=None, *args, **kwargs): if message is not None: if exitcode > 0: warn(message, *args, **kwargs) else:
def error(message: str): t = Terminal() print(t.red(message)) sys.exit(101)
#!/usr/bin/env python2.7 import argparse import sys import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from blessings import Terminal t = Terminal() # Check for args, print logo and usage if not len(sys.argv[1:]): print t.cyan(""" ____ _ _____ _ | \ ___ ___| |_| | |___| |_ | | | . | _| '_| | | | -_| _| |____/|___|_| |_,_|_|___|___|_| Welcome to DorkNet. To start using this script please provide one or more command line arguments and their corresponding value, where applicable. To display all options available use -h or --help. Example:
def __init__(self, ): """ Input: location - tuple of ints (x, y), the position of the bar in the terminal """ self.t = Terminal()
@author: Owen Neuber Program which will recursivly replace all instances of a string with another string. Flags of the starting directory, and the names of the things to replace will be optional. The defualt directory is the current directory (i.e. $ pwd) and the default replacments will be 'BITTR' with 'BLISTR'. This program will NOT be case sensitive, by defualt, unless the case sensitive flag is deployed. """ import os import subprocess from blessings import Terminal import argparse colours = Terminal() parser = argparse.ArgumentParser() parser.add_argument("--sensitive", "-s", help="Makes the find and replace functions case sensitive. (case sensitve would mean that 'Bittr' becomes 'Blistr', all caps becomes all caps, and lowercase becomes lowercase)", action="store_true") parser.add_argument("--path", "-p", help="Path to the directory where we would like to start our recursive find and replace") parser.add_argument("--find", "-f", help="The string the user would like to have replaced") parser.add_argument("--replace", "-r", help="The string the user would like to use as the replacement") args = parser.parse_args() path = os.getcwd() find = 'BITTR' replace = 'BLISTR' if args.path: path = args.path if args.find: find = args.find
def _print_error(self, error): print("") print(Terminal().bright_red(error))
#!/usr/bin/env python import re from blessings import Terminal t = Terminal() class PreProcessText(object): def __init__(self): pass @staticmethod def process(text): text = PreProcessText.convert_lowercase(text) text = PreProcessText.remove_all_instances(text) text = PreProcessText.remove_and_replace(text) return text @staticmethod def remove_numbers(text): return re.sub('\d+', '', text) @staticmethod def convert_lowercase(text): return text.lower() @staticmethod def remove_and_replace(text): """ Remove mupltiple occurences and replace it with single occurence
#!/usr/bin/env python3 from blessings import Terminal t = Terminal() print(t.clear()) print(t.bold('Hi there!')) print(t.move_down) print(t.bold_red_on_bright_green('It hurts my eyes!')) print(t.move_down + t.bold_underline_black_on_yellow( 'Look! A 1997 web page! No, the font would have to be blinking')) print(t.move_down) print(" Terminal width: ", t.width) print(" Terminal height: ", t.height) print(t.move_down + "A one-liner way to show terminal width and height", t.reverse, t.width, "by", t.height, " ") with t.location(20, t.height - 1): print(t.reverse + t.blink('This is at the bottom and printed in REVERSE.'))
from blessings import Terminal t = Terminal() print(t.bold('This should be bold')) print(t.black + t.on_red(' This should be red ')) print(t.bold_black_on_white('What does this look like?')) print(t.reverse('Reversed')) print(t.blink('Blink')) print(t.underline('underline')) print('H' + t.subscript('2')) # Not working print(t.standout('standout')) print(t.shadow('shadow')) print(t.italic('italic')) print(t.number_of_colors) print('This last word should be{t.bold} bold'.format(t=t)) print(t.clear) for i in range(t.number_of_colors + 1): print(f'{t.color(i)}{i}', end=', ')
from termcolor import cprint import os from roulette_board import main as print_board import random from blessings import Terminal import time import sys term = Terminal() def clear(): os.system('clear') def clear_screen(cash): clear() print_default(cash) def print_default(cash): print_board() print_cash_box(cash) def money_input(): while True: try: value = int( input( term.bold_white +
from blessings import Terminal term = Terminal() import os import sys import time import War import multiprocessing os.system("clear") starttime = time.time() #Some terminal option configuations #Todo add some terminal configuring options avcores = multiprocessing.cpu_count() - 1 number_of_total_games = 33000000 # 33 million print("Playing %i games." % (number_of_total_games // avcores * avcores)) rtstatlist = [] for loops in range(0, avcores): stat = multiprocessing.Array( 'i', range(4)) #creating a statistic list for a thread to utalize for kount in range(0, 4): stat[kount] = 0 rtstatlist.append(stat) #Playing functions def warthread(numgames, threadnum, statlist): print("Thread %i online" % threadnum) for i in range(0, numgames): result = War.playwar() if result == 1:
def warn(message: str): t = Terminal() print(t.yellow(message))
def __init__(self, cmdargs=None, doc=""): self.t = Terminal() if not cmdargs: cmdargs = None self.cmdargs = cmdargs self.doc = doc
#!/usr/bin/env python # -*- coding: utf-8 -*- # sudo pip install blessings (for color terminal output) import os from couchbase.client import Couchbase from blessings import Terminal t = Terminal() os.system('clear') print t.bold_red( "--------------------------------------------------------------------------" ) print t.bold_red("Couchbase Storage Operations") print t.bold_red( "--------------------------------------------------------------------------" ) print # establish connection couchbase = Couchbase("127.0.0.1:8091", "default", "") # connect to default bucket cb = couchbase["default"] print t.bold("Set a Key-Value") print # create a key-value pair, set("key", ttl, flags, value) cb.set("mytest", 0, 0, 1)
class Run(SurgicalCmd): def __init__(self, vm, vmx): SurgicalCmd.__init__(self) self.logger = Logger() self.t = Terminal() self.u = Util() self.vm = vm self.vmx = vmx self.methods = self.vm.get_methods() self.intent = IntentModule() self.zip = ZipModule() self.socket = SocketModule() self.system = SystemModule() self.crypto = CryptoModule() self.modules = [ m for m in self.zip, self.intent, self.socket, self.system, self.crypto ] self.target_module = None self.methods_api_usage = list() def _cmd_completer(self, name, text, line, begidx, endidx): fn = getattr(self, 'do_' + name) if not hasattr(fn.im_func, "_expected_args"): return [] a = [arg for arg in fn.im_func._expected_args if arg.startswith(text)] return a def complete_modules(self, *args): return self._cmd_completer("modules", *args) @cmd_arguments(["list", "select"]) def do_modules(self, *args): """ List and select target API modules. := modules list := modules select """ # Locals arg0 = args[0] selection = None try: if arg0 == "list": if self.modules: print("\n") for i, m in enumerate(self.modules): print(self.t.cyan("\t--> [{}] {}".format(i, m.name))) print("\n") if arg0 == "select": if self.modules: selection = raw_input( self.t.yellow("[{}] ".format(datetime.now())) + "Select module : ") try: index = int(selection) except ValueError: index = -1 for i, m in enumerate(self.modules): if selection == m.name or i == index: self.target_module = m break self.logger.surgical_log( "info", "{} module selected (!)".format( self.target_module.name)) except Exception as e: SurgicalError(e.message) def complete_api(self, *args): return self._cmd_completer("api", *args) @cmd_arguments(["list", "select", "analyzed"]) def do_api(self, *args): """ List and select methods from a given loaded API module := api list := api select := api analyzed list := api analyzed select """ # Locals arg0 = args[0].split(" ")[0] arg1 = None class_selection = None method_selection = None surgical_lib = None try: # List the available API methods from the target module if arg0 == "list": if self.target_module: print("\n") for k, v in self.target_module.model.values.items(): print("\n") for m in v: print( self.t.cyan("\t--> {} : {} : {}".format( self.target_module.name, k.split(".")[-1], m))) print("\n") else: self.logger.surgical_log( "info", "Target module has not been loaded (!)") # Select an API method from the target module elif arg0 == "select": if self.target_module: # TODO Consider building a wrapper around raw_input() class_selection = raw_input( self.t.yellow("[{}] ".format(datetime.now())) + "Select class : ") method_selection = raw_input( self.t.yellow("[{}] ".format(datetime.now())) + "Select method : ") for k, v in self.target_module.model.values.items(): # This is so we can support classes with identical # method names --> Ex: java.util.zip.ZipFile if class_selection == k.split(".")[-1]: for m in v: if m == method_selection: self.logger.surgical_log( "info", "Analyzing ...") from core.brains.surgical.lib.libsurgical import SurgicalLib # Begin processing and return the results # from the selected api surgical_lib = SurgicalLib( self.target_module, self.vmx, self.vm, k, method_selection, self.methods) # methods_api_usage will contain a list of # tuples self.methods_api_usage = surgical_lib.search( ) else: self.logger.surgical_log( "warn", "Method not found (!)") # Analyze the processed method list elif arg0 == "analyzed": if args[0].split(" ")[1]: arg1 = args[0].split(" ")[1] # List the methods that have been processed if arg1 == "list": if self.methods_api_usage: print("\n") for i, m in enumerate(self.methods_api_usage): print( self.t.cyan("\t--> [{}] {} -> {} ".format( i, m[0].class_name, m[0].name))) print("\n") else: SurgicalError("API usage not found (!)") # Select from the processed method list elif arg1 == "select": if self.methods_api_usage: selection = raw_input( self.t.yellow("[{}] ".format(datetime.now())) + "Select method : ") try: index = int(selection) except ValueError: index = -1 for i, m in enumerate(self.methods_api_usage): if selection == m[0].name or i == index: print("\n") print( self.t.cyan("\t--> Class : {}".format( m[0].class_name))) print( self.t.cyan("\t\t--> Method : {}".format( m[0].name))) print( self.t.cyan( "\t\t\t --> XREFS ###########")) self.u.print_xref("T", m[1].method.XREFto.items) self.u.print_xref("F", m[1].method.XREFfrom.items) print("\n") print( highlight(m[2], JavaLexer(), TerminalFormatter())) else: SurgicalError("API usage not found (!)") except Exception as e: SurgicalError(e.message)
def __init__(self): self.t = Terminal()
def print_to( self, fp, with_colors=True, # deprecated arg show_cmd=False, show_user=False, show_pid=False, show_power=None, gpuname_width=16, term=Terminal(), ): # color settings colors = {} def _conditional(cond_fn, true_value, false_value, error_value=term.bold_black): try: if cond_fn(): return true_value else: return false_value except: return error_value colors['C0'] = term.normal colors['C1'] = term.cyan colors['CName'] = term.blue colors['CTemp'] = _conditional( lambda: int(self.entry['temperature.gpu']) < 50, term.red, term.bold_red) colors['CMemU'] = term.bold_yellow colors['CMemT'] = term.yellow colors['CMemP'] = term.yellow colors['CUser'] = term.bold_black # gray colors['CUtil'] = _conditional( lambda: int(self.entry['utilization.gpu']) < 30, term.green, term.bold_green) colors['CPowU'] = _conditional( lambda: float(self.entry['power.draw']) / self.entry[ 'enforced.power.limit'] < 0.4, term.magenta, term.bold_magenta) colors['CPowL'] = term.magenta if not with_colors: for k in list(colors.keys()): colors[k] = '' def _repr(v, none_value='??'): if v is None: return none_value else: return str(v) # build one-line display information # we want power use optional, but if deserves being grouped with temperature and utilization reps = "%(C1)s[{entry[index]}]%(C0)s %(CName)s{entry[name]:{gpuname_width}}%(C0)s |" \ "%(CTemp)s{entry[temperature.gpu]:>3}'C%(C0)s, %(CUtil)s{entry[utilization.gpu]:>3} %%%(C0)s" if show_power: reps += ", %(CPowU)s{entry[power.draw]:>3}%(C0)s " if show_power is True or 'limit' in show_power: reps += "/ %(CPowL)s{entry[enforced.power.limit]:>3}%(C0)s " reps += "%(CPowL)sW%(C0)s" else: reps += "%(CPowU)sW%(C0)s" reps += " | %(C1)s%(CMemU)s{entry[memory.used]:>5}%(C0)s / %(CMemT)s{entry[memory.total]:>5}%(C0)s MB" reps = (reps) % colors reps = reps.format( entry={k: _repr(v) for (k, v) in self.entry.items()}, gpuname_width=gpuname_width) if "hard" in self.entry['lock']: lock_col = term.red elif "soft" in self.entry['lock']: lock_col = term.orange elif "weak" in self.entry['lock']: lock_col = term.yellow else: lock_col = term.green reps += " | {0:s}{1:^9s}{2:s}".format(lock_col, self.entry['lock'], term.normal) reps += " |" def process_repr(p): r = '' if show_cmd: if r: r += ':' r += "{C1}{}{C0}".format( _repr(p.get('command', p['pid']), '--'), **colors) if show_pid: r += ("/%s" % _repr(p['pid'], '--')) r += '({CMemP}{}M{C0})'.format(_repr(p['gpu_memory_usage'], '?'), **colors) return r if show_user: reps += " {CUser}{}{C0}".format(_repr(self.entry['user'], '--'), **colors) if self.entry['processes'] is not None: if self.entry['processes']: reps += ':' for p in self.entry['processes']: reps += process_repr(p) fp.write(reps) return fp
def main(): """Handles External PRs (PRs from forks) Performs the following operations: 1. If the external PR's base branch is master we create a new branch and set it as the base branch of the PR. 2. Labels the PR with the "Contribution" label. (Adds the "Hackathon" label where applicable.) 3. Assigns a Reviewer. 4. Creates a welcome comment Will use the following env vars: - CONTENTBOT_GH_ADMIN_TOKEN: token to use to update the PR - EVENT_PAYLOAD: json data from the pull_request event """ t = Terminal() payload_str = get_env_var('EVENT_PAYLOAD') if not payload_str: raise ValueError('EVENT_PAYLOAD env variable not set or empty') payload = json.loads(payload_str) print(f'{t.cyan}Processing PR started{t.normal}') org_name = 'demisto' repo_name = 'content' gh = Github(get_env_var('CONTENTBOT_GH_ADMIN_TOKEN'), verify=False) content_repo = gh.get_repo(f'{org_name}/{repo_name}') pr_number = payload.get('pull_request', {}).get('number') pr = content_repo.get_pull(pr_number) # Add 'Contribution' Label to PR contribution_label = 'Contribution' pr.add_to_labels(contribution_label) print(f'{t.cyan}Added "Contribution" label to the PR{t.normal}') # check base branch is master if pr.base.ref == 'master': print(f'{t.cyan}Determining name for new base branch{t.normal}') branch_prefix = 'contrib/' new_branch_name = f'{branch_prefix}{pr.head.label.replace(":", "_")}' existant_branches = content_repo.get_git_matching_refs( f'heads/{branch_prefix}') potential_conflicting_branch_names = [ branch.ref.lstrip('refs/heads/') for branch in existant_branches ] # make sure new branch name does not conflict with existing branch name while new_branch_name in potential_conflicting_branch_names: # append or increment digit if not new_branch_name[-1].isdigit(): new_branch_name += '-1' else: digit = str(int(new_branch_name[-1]) + 1) new_branch_name = f'{new_branch_name[:-1]}{digit}' master_branch_commit_sha = content_repo.get_branch('master').commit.sha # create new branch print(f'{t.cyan}Creating new branch "{new_branch_name}"{t.normal}') content_repo.create_git_ref(f'refs/heads/{new_branch_name}', master_branch_commit_sha) # update base branch of the PR pr.edit(base=new_branch_name) print( f'{t.cyan}Updated base branch of PR "{pr_number}" to "{new_branch_name}"{t.normal}' ) # assign reviewers / request review from reviewer_to_assign = determine_reviewer(REVIEWERS, content_repo) pr.add_to_assignees(reviewer_to_assign) pr.create_review_request(reviewers=[reviewer_to_assign]) print(f'{t.cyan}Assigned user "{reviewer_to_assign}" to the PR{t.normal}') print( f'{t.cyan}Requested review from user "{reviewer_to_assign}"{t.normal}') # create welcome comment body = WELCOME_MSG.format(selected_reviewer=reviewer_to_assign) pr.create_issue_comment(body) print(f'{t.cyan}Created welcome comment{t.normal}')
class SSTTextTestResult(unittest.TestResult): """ A superclass to support SST required testing, this is a modified version of unittestTextTestResult from python 2.7 modified for SST's needs. """ separator1 = '=' * 70 separator2 = '-' * 70 indent = ' ' * 4 _test_class = None if blessings_loaded: _terminal = Terminal() colours = { None: text_type, 'error': _terminal.bold_yellow, 'expected': _terminal.green, 'fail': _terminal.bold_red, 'skip': _terminal.bold_blue, 'success': _terminal.green, 'title': _terminal.magenta, 'unexpected': _terminal.bold_red, } else: colours = {None: text_type} if pygments_loaded: formatter = formatters.Terminal256Formatter() lexer = Lexer() def __init__(self, stream, descriptions, verbosity, no_colour_output=False): super(SSTTextTestResult, self).__init__(stream, descriptions, verbosity) self.testsuitesresultsdict = SSTTestSuitesResultsDict() self._test_name = "undefined_testname" self._testcase_name = "undefined_testcasename" self._testsuite_name = "undefined_testsuitename" self._junit_test_case = None self.stream = stream self.showAll = verbosity > 1 self.dots = verbosity == 1 self.descriptions = descriptions if blessings_loaded: self.no_colour_output = no_colour_output else: self.no_colour_output = True def getShortDescription(self, test): doc_first_line = test.shortDescription() if self.descriptions and doc_first_line: return '\n'.join((str(test), doc_first_line)) else: return str(test) def getLongDescription(self, test): doc_first_line = test.shortDescription() if self.descriptions and doc_first_line: return '\n'.join((str(test), doc_first_line)) return str(test) def getClassDescription(self, test): test_class = test.__class__ doc = test_class.__doc__ if self.descriptions and doc: return doc.strip().split('\n')[0].strip() return strclass(test_class) ### def startTest(self, test): super(SSTTextTestResult, self).startTest(test) #log_forced("DEBUG - startTest: Test = {0}\n".format(test)) if self.showAll: if not test_engine_globals.TESTENGINE_CONCURRENTMODE: if self._test_class != test.__class__: self._test_class = test.__class__ title = self.getClassDescription(test) if self.no_colour_output: self.stream.writeln(self.colours[None](title)) else: self.stream.writeln(self.colours['title'](title)) self.stream.flush() self._test_name = "undefined_testname" _testname = getattr(test, 'testname', None) if _testname is not None: self._test_name = test.testname if self._is_test_of_type_ssttestcase(test): self._testcase_name = test.get_testcase_name() self._testsuite_name = test.get_testsuite_name() else: self._testcase_name = "FailedTest" self._testsuite_name = "FailedTest" timestamp = datetime.utcnow().strftime("%Y_%m%d_%H:%M:%S.%f utc") self._junit_test_case = JUnitTestCase(self._test_name, self._testcase_name, timestamp=timestamp) def stopTest(self, test): super(SSTTextTestResult, self).stopTest(test) #log_forced("DEBUG - stopTest: Test = {0}\n".format(test)) testruntime = 0 if self._is_test_of_type_ssttestcase(test): testruntime = test.get_test_runtime_sec() self._junit_test_case.junit_add_elapsed_sec(testruntime) if not self._is_test_of_type_ssttestcase(test): return if not test_engine_globals.TESTENGINE_CONCURRENTMODE: test_engine_globals.TESTRUN_JUNIT_TESTCASE_DICTLISTS['singlethread'].\ append(self._junit_test_case) else: test_engine_globals.TESTRUN_JUNIT_TESTCASE_DICTLISTS[self._testsuite_name].\ append(self._junit_test_case) ### def get_testsuites_results_dict(self): """ Return the test suites results dict """ return self.testsuitesresultsdict ### def printResult(self, test, short, extended, colour_key=None, showruntime=True): if self.no_colour_output: colour = self.colours[None] else: colour = self.colours[colour_key] if self.showAll: self.stream.write(self.indent) self.stream.write(colour(extended)) self.stream.write(" -- ") self.stream.write(self.getShortDescription(test)) testruntime = 0 if self._is_test_of_type_ssttestcase(test): testruntime = test.get_test_runtime_sec() if showruntime: self.stream.writeln(" [{0:.3f}s]".format(testruntime)) else: self.stream.writeln(" ".format(testruntime)) self.stream.flush() elif self.dots: self.stream.write(colour(short)) self.stream.flush() ### def addSuccess(self, test): super(SSTTextTestResult, self).addSuccess(test) #log_forced("DEBUG - addSuccess: Test = {0}\n".format(test)) self.printResult(test, '.', 'PASS', 'success') if not self._is_test_of_type_ssttestcase(test): return self.testsuitesresultsdict.add_success(test) def addError(self, test, err): super(SSTTextTestResult, self).addError(test, err) #log_forced("DEBUG - addError: Test = {0}, err = {1}\n".format(test, err)) self.printResult(test, 'E', 'ERROR', 'error') if not self._is_test_of_type_ssttestcase(test): return self.testsuitesresultsdict.add_error(test) _junit_test_case = getattr(self, '_junit_test_case', None) if _junit_test_case is not None: err_msg = self._get_err_info(err) _junit_test_case.junit_add_error_info(err_msg) def addFailure(self, test, err): super(SSTTextTestResult, self).addFailure(test, err) #log_forced("DEBUG - addFailure: Test = {0}, err = {1}\n".format(test, err)) self.printResult(test, 'F', 'FAIL', 'fail') if not self._is_test_of_type_ssttestcase(test): return self.testsuitesresultsdict.add_failure(test) _junit_test_case = getattr(self, '_junit_test_case', None) if _junit_test_case is not None: err_msg = self._get_err_info(err) _junit_test_case.junit_add_failure_info(err_msg) def addSkip(self, test, reason): super(SSTTextTestResult, self).addSkip(test, reason) #log_forced("DEBUG - addSkip: Test = {0}, reason = {1}\n".format(test, reason)) self.printResult(test, 's', 'SKIPPED: {0!r}'.format(reason), 'skip', showruntime=False) if not self._is_test_of_type_ssttestcase(test): return self.testsuitesresultsdict.add_skip(test) _junit_test_case = getattr(self, '_junit_test_case', None) if _junit_test_case is not None: _junit_test_case.junit_add_skipped_info(reason) def addExpectedFailure(self, test, err): # NOTE: This is not a failure, but an identified pass # since we are expecting a failure super(SSTTextTestResult, self).addExpectedFailure(test, err) #log_forced("DEBUG - addExpectedFailure: Test = {0}, err = {1}\n".format(test, err)) self.printResult(test, 'x', 'EXPECTED FAILURE', 'expected') if not self._is_test_of_type_ssttestcase(test): return self.testsuitesresultsdict.add_expected_failure(test) def addUnexpectedSuccess(self, test): # NOTE: This is a failure, since we passed, but were expecting a failure super(SSTTextTestResult, self).addUnexpectedSuccess(test) #log_forced("DEBUG - addUnexpectedSuccess: Test = {0}\n".format(test)) self.printResult(test, 'u', 'UNEXPECTED SUCCESS', 'unexpected') if not self._is_test_of_type_ssttestcase(test): return self.testsuitesresultsdict.add_unexpected_success(test) _junit_test_case = getattr(self, '_junit_test_case', None) if _junit_test_case is not None: _junit_test_case.junit_add_failure_info( "RECEIVED SUCCESS WHEN EXPECTING A FAILURE") ### def printErrors(self): if self.dots or self.showAll: self.stream.writeln() log("=" * 70) log("=== TESTS FINISHED " + ("=" * 51)) log("=" * 70 + "\n") self.printErrorList('ERROR', self.errors) self.printErrorList('FAIL', self.failures) def printErrorList(self, flavour, errors): if self.no_colour_output: colour = self.colours[None] else: colour = self.colours[flavour.lower()] for test, err in errors: self.stream.writeln(self.separator1) title = '%s: %s' % (flavour, self.getLongDescription(test)) self.stream.writeln(colour(title)) self.stream.writeln(self.separator2) if pygments_loaded: self.stream.writeln(highlight(err, self.lexer, self.formatter)) else: self.stream.writeln(err) #### def _get_err_info(self, err): """Converts a sys.exc_info() into a string.""" exctype, value, tback = err msg_lines = traceback.format_exception_only(exctype, value) msg_lines = [x.replace('\n', ' ') for x in msg_lines] return ''.join(msg_lines) #### def _is_test_of_type_ssttestcase(self, test): """ Detirmine if this is is within a valid SSTTestCase object by checking if a unique SSTTestCase function exists return: True if this is a test within a valid SSTTestCase object """ return getattr(test, 'get_testcase_name', None) is not None
def test_turn_off_colors(self, mock_user_conf): mock_user_conf.return_value = {'COLOR': '0'} stream = StringIO() _out('Hello world', None, Terminal().red, stream) self.assertEquals('Hello world\n', stream.getvalue())
#!/usr/bin/env Python2.7 import sys import os, os.path import shodan import pickle import socket from datetime import datetime from blessings import Terminal t = Terminal() ts = datetime.now() reset = False logging = False api = "" print t.cyan(""" .d88888b dP 88. "' 88 `Y88888b. 88d888b. .d8888b. .d8888b. dP dP 88d888b. `8b 88' `88 88' `88 88' `88 88 88 88' `88 d8' .8P 88 88 88. .88 88. .88 88. .88 88 88 Y88888P dP dP `88888P' `8888P88 `88888P' dP dP .88 d8888P """) print t.cyan("\n SHOGUN - Shodan Command Line Interface\n")
def test_colors(self, mock_user_conf): mock_user_conf.return_value = {} stream = StringIO() _out('Hello world', None, Terminal().red, stream) # RHEL 6 doesn't have self.assertRegexpMatches unfortunately self.assertTrue(re.match('.+Hello world.+\n', stream.getvalue()))
# the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import curses from blessings import Terminal try: term = Terminal() # pylint: disable=invalid-name except curses.error: # handle issues with terminals and force not to style anything # should not be necessary with blessings > 1.7 anymore term = Terminal(force_styling=None) # pylint: disable=invalid-name def ok(message): print(message, '[', term.green('ok'), ']') def fail(message): print(message, '[', term.red('fail'), ']') def error(message):
#!/usr/bin/env python3 from blessings import Terminal t = Terminal() print(t.clear()) print(t.bold('Hi there!')) print(t.move_down) print(t.bold_red_on_bright_green('It hurts my eyes!')) print(t.move_down+t.bold_underline_black_on_yellow('Look! A 1997 web page! No, the font would have to be blinking')) print(t.move_down) print(" Terminal width: ",t.width) print(" Terminal height: ",t.height) print(t.move_down+"A one-liner way to show terminal width and height",t.reverse,t.width, "by",t.height, " ") with t.location(20, t.height - 1): print('This is at the bottom')
def __init__(self): # instance attributes, feels safer self.name = None self.default_host = None self.default_port = None self.default_user = None self.default_password = None self.options = None self.args = None self.__verbose_default = 0 self.__verbose = self.__verbose_default self.__timeout_default = 10 self.__timeout = None self.__timeout_max = 86400 self.__total_run_time = time.time() self.topfile = get_topfile() self._docstring = get_file_docstring(self.topfile) if self._docstring: self._docstring = '\n' + self._docstring.strip() + '\n' if self._docstring is None: self._docstring = '' self._topfile_version = get_file_version(self.topfile) # this doesn't work in unit tests # if self._topfile_version: # raise CodingError('failed to get topfile version - did you set a __version__ in top cli program?') self._cli_version = self.__version__ self._utils_version = harisekhon.utils.__version__ # returns 'python -m unittest' :-/ # prog = os.path.basename(sys.argv[0]) self._prog = os.path.basename(self.topfile) self._github_repo = get_file_github_repo(self.topfile) # _hidden attributes are shown in __dict__ self.version = '{prog} version {topfile_version} '.format(prog=self._prog, topfile_version=self._topfile_version) + \ '=> CLI version {cli_version} '.format(cli_version=self._cli_version) + \ '=> Utils version {utils_version}'.format(utils_version=self._utils_version) self.usagemsg = 'Hari Sekhon{sep}{github_repo}\n\n{prog}\n{docstring}\n'.format(\ sep=' - ' if self._github_repo else '', github_repo=self._github_repo, prog=self._prog, docstring=self._docstring) self.usagemsg_short = 'Hari Sekhon%(_github_repo)s\n\n' % self.__dict__ # set this in simpler client programs when you don't want to exclude # self.__parser = OptionParser(usage=self.usagemsg_short, version=self.version) # self.__parser = OptionParser(version=self.version) # will be added by default_opts later so that it's not annoyingly at the top of the option help # also this allows us to print full docstring for a complete description and not just the cli switches # description=self._docstring # don't want description printed for option errors width = os.getenv('COLUMNS', None) if not isInt(width) or not width: try: width = Terminal().width except _curses.error: width = 80 #width = min(width, 200) self.__parser = OptionParser( add_help_option=False, formatter=IndentedHelpFormatter(width=width)) # duplicate key error or duplicate options, sucks # self.__parser.add_option('-V', dest='version', help='Show version and exit', action='store_true') self.setup()