def process_IN_MODIFY(self, event): now = time.time() report = "{0}s".format(str(round(now-self.lastupdate, 2))) self.lastupdate = now self.freq += 1 if not self.freq % 50: print colors.color(' '.join((event.name, report)), fg=self.fg)
def region_message(db): frame = ' ' sysinfo = db.get('sysinfo') if sysinfo: info = sysinfo.split('|') internetConnect = info[0] alarmSyncy = info[1] importMesg = info[2] else: internetConnect = 'unkown' alarmSyncy = 'unkown' importMesg = '0' print colors.bold(" Internet Connect: ", fg='white', bg='black') \ +colors.bold(internetConnect, fg='green', bg='black') \ +colors.color(44*frame, bg='black') \ +colors.bold("Alarms Syncy: ", fg='white', bg='black') \ +colors.bold(alarmSyncy, fg='green', bg='black') \ +colors.color(44*frame, bg='black') \ +colors.bold(" Important Messages: ", fg='white', bg='black') \ +colors.bold(importMesg, fg='magenta', bg='black') \ +colors.color(4*frame, bg='black') print "" messages = db.smembers('message') if messages: for message in messages: print colors.bold(">_ ", fg='red') + colors.blink2(message, fg='green') print ""
def success_rate_string(identifier, failure_count, total_count): """Only prints percentage if total_count is not None""" return " ".join((color(f"{identifier}: ", fg='cyan'), color(f"{failure_count} failures", fg='red'), "" if total_count is None else color(f"({((total_count - failure_count) / total_count) * 100:6.3f}% success rate)", fg='blue')))
def print_success_rate_and_expectation_warning(completed, expected_failed_builds, long_list_of_test_failures, failure_url_base): # "Build failures" will refer to jobs that went red # "Test failures" will refer to jobs whose output matched our parsing regex build_failure_count = len(expected_failed_builds) test_failure_set = {int(failure.build_json['name']) for failure in long_list_of_test_failures} test_failure_count = sum(1 for _ in test_failure_set) # Matched failure string (in long_list) but not an expected failure (box went red) test_failure_not_build_failure = [name for name in test_failure_set if name not in expected_failed_builds] # Expected failures (box went red) but did not match a failure string (in long_list) build_failure_not_test_failure = [name for name in expected_failed_builds if name not in test_failure_set] rate = (completed - test_failure_count) * 100 / completed print(" Overall build success rate:", color(f"{rate:.5f}% ({completed - test_failure_count} of {completed})", fg='blue')) if build_failure_not_test_failure: print(color(f'>>>>> {build_failure_count} jobs "went red," ' f'but only {test_failure_count} were detected test failures. <<<<<', fg='red', style='bold')) print(f"Maybe you have some timeouts or other issues please manually inspect the following builds:") for build_failure in build_failure_not_test_failure: print(f" {failure_url_base}{build_failure}") if test_failure_not_build_failure: print(color(f'>>>>> OH NO! A test failure was detected, but the job "went green" anyway!! <<<<', fg='red', style='bold')) print(f"Please manually inspect the following builds:") for test_failure in test_failure_not_build_failure: print(f" {failure_url_base}{test_failure}") print(YELLOW_STARS_SEPARATOR) print()
def validate_copy_args(args, repodb): """Proper argument positioning for a copy operation is slightly fussy; make sure cli users do not shoot themselves in the foot.""" evil = [] if not validate_meta(args, repodb): return 1 if args.src_distribution == args.dst_distribution and \ args.src_component == args.dst_component: LOG.fatal(color( 'The source and destination distribution and ' 'component flags cannot both match; you\'d have nothing ' 'to copy.', fg='red')) return 1 if not any((args.dst_distribution, args.dst_component)): LOG.fatal(color( 'You must specify at least one of a destination ' 'component or distribution when copying packages, ' 'otherwise what would be the point?', fg='red')) return 1 if not any((args.package, args.version)): evil.append( 'You are potentially copying up to an entire component\'s ' 'worth of packages!') return evil
def region_job_on(db): frame = ' ' nowtime = time.time() nowday = time.strftime('%Y-%m-%d', time.localtime(time.time())) jobs = db.smembers('liston') for job in jobs: if job: jobinfo = job.split('|') name = str(jobinfo[0]) start = str(jobinfo[1]) length = str(jobinfo[2]) progress = int(jobinfo[3]) spend = int(jobinfo[4]) alarmtime = time.mktime(time.strptime(nowday+' '+start+':00', '%Y-%m-%d %H:%M:%S')) spend = int((nowtime - alarmtime)/60/60) print colors.bold(" 事件: ", fg='red', bg='black')+colors.bold(name, fg='magenta', bg='black') \ +colors.color((144-len(name))*frame, bg='black') print colors.bold(" 预定开始于: ", fg='green')+colors.bold(start, fg='magenta')\ +45*frame\ +colors.bold(" 预定时长: ", fg='green')+colors.bold(length, fg='magenta')\ +50*frame \ +colors.bold(" 状态: ", fg='green')+colors.bold('on', fg='magenta') print "" print colors.bold(" 进行时长: ")+colors.color(spend*frame, bg='green') + colors.bold(' '+str(spend)+'小时') print colors.bold(" 进行进度: ")+colors.color(progress*frame, bg='magenta') + colors.bold(' '+str(progress)+'%') print ""
def validate_request(req, path_pattern, path_params, spec, url): print('Validating URL: {}'.format(url)) counters['requests'] += 1 openapi_request = RequestsOpenAPIRequest(req, path_pattern, path_params) validator = RequestValidator(spec) result = validator.validate(openapi_request) request_errors = result.errors r = req.prepare() s = requests.Session() res = s.send(r) openapi_response = RequestsOpenAPIResponse(res) validator = ResponseValidator(spec) result = validator.validate(openapi_request, openapi_response) response_errors = result.errors print('Request errors: {}'.format(request_errors)) print('Response errors: {}'.format(response_errors)) if request_errors or response_errors: errors_count = len(request_errors) + len(response_errors) print(color(' [FAIL] {:d} errors found '.format(errors_count), fg='white', bg='red', style='bold')) print("Response body: {}".format(res.text)) else: errors_count = 0 print(color(' [PASS] No errors found ', fg='white', bg='green', style='bold')) print() return errors_count
def _fetch_ports(self): if self.verbose: print color('blue', "Fetching port information ....") ports = [AttrDict(port) for port in self.neutron.list_ports()['ports']] for port in ports: self._ports[port.id] = port for sg_id in port.security_groups: self._sgs[sg_id].ports[port.id] = port
def log_local_message(message_format, *args): """ Log a request so that it matches our local log format. """ prefix = '{} {}'.format(color('INFO', fg=248), color('request', fg=5)) message = message_format % args sys.stderr.write('{} {}\n'.format(prefix, message))
def _fetch_security_groups(self): if self.verbose: print color('blue',"Fetching security group listing ....") sgs = [self._attrdict_sg(sg) for sg in self.neutron.list_security_groups(id=[])['security_groups'] ] for security_group in sgs: security_group.ports = {} self._sgs[security_group.id] = security_group
def repo_topic(action, args, repodb, repo): if action == 'add': topic_name = args.topic_name[0] LOG.warning(color('Setting up SNS topic "%s" for logging' % topic_name, fg='red')) if confirm(args): repodb.add_meta(topic_name=topic_name) elif action == 'rm': LOG.warning(color('Disabling SNS logging!', fg='red')) if confirm(args): repodb.rm_meta(topic_name=True) return repo_print_config(repodb, repo)
def showsteps(fitbit_auth_client): fitbit_stats = fitbit_auth_client._COLLECTION_RESOURCE('activities') goals_steps = fitbit_stats["goals"]["steps"] now_steps = fitbit_stats["summary"]["steps"] now_per = now_steps*100/goals_steps block = ' ' goals_steps_bar = (goals_steps/100) * block now_steps_bar = (now_steps/100) * block print colors.bold("目标步数: ")+colors.color(goals_steps_bar, bg='magenta') if now_per < 80: print colors.bold("今日达成: ")+colors.color(now_steps_bar, bg='red') + colors.bold(' '+str(now_per)+'%') else: print colors.bold("今日达成: ")+colors.color(now_steps_bar, bg='green') + colors.bold(' '+str(now_per)+'%')
def sg_rpc_mitigation_report(self): for bad_sg in self.iter_sgs_with_remote_group_ids(): self._extend_sg_info(bad_sg) print color('header',"\nsecurity_group %(id)s (%(name)s) has remote " "gid rules %(used_str)s\n tenant: " "%(tenant_name)s" % bad_sg) for port_id, port in bad_sg.ports.iteritems(): ip_addresses = ", ".join( [ip['ip_address'] for ip in port.fixed_ips]) port_info = {'id': port.id, 'ips': ip_addresses} print ("\tport %(id)s with ips: %(ips)s" % port_info) self._report_equivalent_subnet_CIDRs(bad_sg)
def format(self, record): if record.levelname == "DEBUG": record.levelname = color(record.levelname, fg=240) elif record.levelname == "INFO": record.levelname = color(record.levelname, fg=248) elif record.levelname == "WARNING": record.levelname = color(record.levelname, fg=220) elif record.levelname == "ERROR": record.levelname = color(record.levelname, fg=9) record.context = color("{0.name}:{0.lineno}".format(record), fg=5) return super(LocalFormat, self).format(record)
def region_list(db): frame = ' ' liston = db.smembers('liston') listoff = db.smembers('listoff') total = len(liston) + len(listoff) print colors.bold(" TODO List ", fg='white', bg='black') \ +colors.color(54*frame, bg='black') \ +colors.bold("Total: ", fg='white', bg='black') \ +colors.bold(str(total), fg='magenta', bg='black') \ +colors.color(53*frame, bg='black') \ +colors.bold("Start: ", fg='white', bg='black') \ +colors.bold(str(len(liston)), fg='magenta', bg='black') \ +colors.color(17*frame, bg='black') print ""
def raw_text(self,token): constructed = "" for c in token: if c in "<({[": constructed += ansicolors.color(c, fg=BracketCounter.bracket_ansicolors[ BracketCounter.bracket_index % len(BracketCounter.bracket_ansicolors)]) BracketCounter.bracket_index += 1 elif c in ">)}]": BracketCounter.bracket_index -= 1 constructed += ansicolors.color(c, fg=BracketCounter.bracket_ansicolors[ BracketCounter.bracket_index % len(BracketCounter.bracket_ansicolors)]) else: constructed += ansicolors.color(c, fg=BracketCounter.default_color) return constructed
def psolid(n, c): if n not in psolid_memo: psolid_memo[n] = solid_polygon(n) vlist = psolid_memo[n] vlist.colors = color(c) * (n * 3) vlist.draw(gl.GL_TRIANGLES)
def pwired(n, c): if n not in pwired_memo: pwired_memo[n] = wired_polygon(n) vlist = pwired_memo[n] vlist.colors = color(c) * n vlist.draw(gl.GL_LINE_LOOP)
def hexes(self,token): stream = "" for chr in re.findall("[0-9A-Fa-f]{2}", token): scale = (int(chr, 16) / 256.0) * len(NicerRainbowHex.char_ansicolors) stream += ansicolors.color(chr, fg=NicerRainbowHex.char_ansicolors[int(scale)]) return stream
def repo_add(thing, args, repodb, repo): abbrev = thing[0:4] + 's' argname = thing + '_names' candidates = getattr(args, argname) existing = getattr(repodb, abbrev) # the "all" architecture is special, you cannot remove it if abbrev == 'archs': while 'all' in args.architecture_names: LOG.error('You cannot add the "all" architecture, like the ' 'Vorlons it has always been here.') args.architecture_names.remove('all') while 'source' in args.architecture_names: LOG.error('You cannot add the "source" architecture, like the ' 'Vorlons it has always been here.') args.architecture_names.remove('source') for name in candidates: try: if name in existing: LOG.warning('%s %s already exists in repo %s', thing, name, args.simpledb_domain) continue except KeyError: LOG.fatal('No repo configuration found, did you forget to ' 'run "repoman setup"?') sys.exit(1) kwargs = {abbrev: candidates} LOG.warning(color( 'Adding %s(s): %s', fg='red'), thing, ','.join(candidates)) if confirm(args): res = repodb.add_meta(**kwargs) LOG.debug(res) return repo_print_config(repodb, repo)
def format(self, record): s = self.formatter.format(record) if record.levelname == 'CRITICAL': s = color(s, fg='red', style='negative') elif record.levelname == 'ERROR': s = color(s, fg='red') elif record.levelname == 'WARNING': s = color(s, fg='yellow') elif record.levelname == 'DEBUG': s = color(s, fg='blue') elif record.levelname == 'INFO': pass return s
def region_tips(db): tips = db.smembers('tips') frame = ' ' print colors.bold(" Tips ", fg='black', bg='green')+colors.color(146*frame, bg='green') print "" for tip in tips: print colors.bold("-- ", fg='red') + colors.blink2(tip, fg='green')
def evalbars(l): resl = [] for s in l: res = s[1:-1] if res[0:1] == "#": res = color(res[1:]) resl.append(res) return resl
def emit(self, record): level = record.levelname[0].upper() space = ' ' * self.nesting context = '{0}:{1}'.format( self.indicator, colors.color(level, fg=_log_level_color.get(level, 15))) self.out.write('[{0}] {1}{2}\n' .format(context, space, record.msg))
def format_token(token): "Formats a single token." ttype = token.ttype while ttype is not None and ttype not in STYLE and ttype.parent is not None: ttype = ttype.parent (fg, style) = STYLE[ttype] formatted = color(token.value, fg=fg, style=style) return formatted
def test_styles(bg, fg): for style in (None,) + STYLES: cname = fg or 'default' # renamed None color to default to avoid confusion wiht normal style if cname.startswith('bright'): cname = cname[6:].upper() text = cname[:5].ljust(6) print(color(text, fg=fg, bg=bg, style=style), end=' ') print()
def repo_origin(action, args, repodb, repo): if action == 'add': origin = args.origin[0] LOG.warning( color('Setting repository origin: "%s"' % origin, fg='red')) if confirm(args): repodb.add_meta(origin=origin) else: LOG.fatal('You cannot remove an origin, you can only change it.') sys.exit(1) return repo_print_config(repodb, repo)
def repo_label(action, args, repodb, repo): if action == 'add': label = args.label[0] LOG.warning( color('Setting repository label: "%s"' % label, fg='red')) if confirm(args): repodb.add_meta(label=label) else: LOG.fatal('You cannot remove an label, you can only change it.') sys.exit(1) return repo_print_config(repodb, repo)
def __str__(self): operation = self.operation if operation: operation = operation.split(".")[-1] operation = colors.magenta(operation) if self.source_node_name: source_name = colors.cyan(self.source_node_name) target_name = colors.cyan(self.target_node_name) context = "{}->{}|{}".format(source_name, target_name, operation) elif self.node_name: node_name = colors.cyan(self.node_name) context = node_name if operation: context = "{}.{}".format(node_name, operation) else: context = colors.cyan(self.workflow_id) message = colors.color(self.message, fg=_task_event_color.get(self.event_type, 15)) if self.level: level = colors.color(self.level.upper(), fg=_log_level_color.get(self.level, 15)) message = "{}: {}".format(level, message) return "[{}] {}".format(context, message)
def confirm(args, evil=[]): if not evil and not args.confirm: LOG.warning(color( 'You used the --confirm flag so we are proceeding ' 'without a review/confimation step. Good luck. ', fg='yellow')) return True if evil: for idx, message in enumerate(evil, start=1): LOG.warn(color( 'Found something scary. Problem #%d:\n', fg='red', style='bold'), idx) sys.stderr.write( color(message, fg='black', bg='yellow', style='bold') + '\n\n') if args.i_fear_no_evil: LOG.warning(color( 'You used the --i-fear-no-evil flag, so we are ' 'proceeding without review/confirmation even though ' 'you\'re trying to do something scary. I hope your ' 'insurance is fully paid up...', fg='red')) else: x = 'I FEAR NO EVIL' while input(color( '\nType exactly "%s" to proceed --> ' % x, fg='red')) != x: pass # yes, we do this even if we pass through the evil check; # that's intentional if args.confirm: while input(color('\nType "c" to confirm --> ', fg='cyan')) != 'c': pass return True
def run_docker(definition, dataset, count, runs, timeout, batch, cpu_limit, mem_limit=None): cmd = [ '--dataset', dataset, '--algorithm', definition.algorithm, '--module', definition.module, '--constructor', definition.constructor, '--runs', str(runs), '--count', str(count) ] if batch: cmd += ['--batch'] cmd.append(json.dumps(definition.arguments)) cmd += [json.dumps(qag) for qag in definition.query_argument_groups] client = docker.from_env() if mem_limit is None: mem_limit = psutil.virtual_memory().available container = client.containers.run(definition.docker_tag, cmd, volumes={ os.path.abspath('ann_benchmarks'): { 'bind': '/home/app/ann_benchmarks', 'mode': 'ro' }, os.path.abspath('data'): { 'bind': '/home/app/data', 'mode': 'ro' }, os.path.abspath('results'): { 'bind': '/home/app/results', 'mode': 'rw' }, }, cpuset_cpus=cpu_limit, mem_limit=mem_limit, detach=True) logger = logging.getLogger(f"annb.{container.short_id}") logger.info('Created container %s: CPU limit %s, mem limit %s, timeout %d, command %s' % \ (container.short_id, cpu_limit, mem_limit, timeout, cmd)) def stream_logs(): for line in container.logs(stream=True): logger.info(colors.color(line.decode().rstrip(), fg='blue')) t = threading.Thread(target=stream_logs, daemon=True) t.start() try: exit_code = container.wait(timeout=timeout) # Exit if exit code if exit_code not in [0, None]: logger.error(colors.color(container.logs().decode(), fg='red')) logger.error('Child process for container %s raised exception %d' % (container.short_id, exit_code)) except: logger.error('Container.wait for container %s failed with exception' % container.short_id) traceback.print_exc() finally: pass
else: rho_lo_p = mof_isotherms[mof]['rho_empty'] * crystal_density[mof] delta_G_lo_p = np.interp(rho_lo_p, n, mu) - mu_empty if basename == 'methane': rho_hi_p = mof_isotherms[mof]['rho_full'] #*crystal_density[mof] else: rho_hi_p = mof_isotherms[mof]['rho_full'] * crystal_density[mof] delta_G_hi_p = np.interp(rho_hi_p, n, mu) - mu_full plt.plot([delta_G_lo_p / (kJ / mol), delta_G_hi_p / (kJ / mol)], [(rho_hi_p - rho_lo_p) / density_units, (rho_hi_p - rho_lo_p) / density_units], colors.symbol(basename) + '-', label=colors.latex_mof(mof), color=colors.color(mof)) stepby = None if 20 < ymax < 200: stepby = 10 elif 200 < ymax < 1000: stepby = 100 elif 1000 < ymax < 3000: stepby = 500 if stepby is not None: plt.yticks( list(range(0, int(ymax), stepby)) + [round(ymax)] + list(range((int(ymax / stepby) + 1) * stepby, int(y_max_lim), stepby))) plt.legend(loc='lower right', framealpha=1.0, prop=small_font) plt.xlabel(r'$|\Delta g_{st}|$ (kJ/mol)')
def task_sleep1(): LOG.info(color("Stopping remote loop", fg="red")) node.send_nowait(sender=p1.pid_, receiver=remote_receiver_name, message=(Atom("example6"), Atom("stop")))
def print_color(fg: str, *args, **kwargs): p_list = [] for i in args: p_list.append(color(str(i), fg=fg)) print(*p_list, **kwargs)
def _highlight(string: str, start: int, end: int, **kwargs): return string[:start] + color(string[start:end], **kwargs) + string[end:]
def NotFoundBeep(s="Not Found"): if os.name == 'nt': winsound.Beep(440, 500) print(color(s, 'orange'))
from __future__ import print_function from colors import color def strgb(rgb_colour=None): string = "" if rgb_colour is not None: string = "rgb("+str(rgb_colour[0])+","+str(rgb_colour[1])+","+str(rgb_colour[2])+")" return string if __name__ == "__main__": print(color('Color #', fg=strgb((250,0,0)),style='blink2') ,end="")
def ErrorBeep(s="Error"): if os.name == 'nt': winsound.Beep(440, 500) print(color(s, 'red'))
def SuccessBeep(s="success"): if os.name == 'nt': winsound.Beep(1000, 300) print(color(s, 'green'))
rho_lo_p = mof_isotherms[mof]['rho_empty'] * crystal_density[mof] delta_G_lo_p = np.interp(rho_lo_p, n, mu) - mu_empty if basename == 'methane': rho_hi_p = mof_isotherms[mof]['rho_full'] #*crystal_density[mof] else: rho_hi_p = mof_isotherms[mof]['rho_full'] * crystal_density[mof] delta_G_hi_p = np.interp(rho_hi_p, n, mu) - mu_full if mof in mof_isotherms: plt.plot([delta_G_lo_p / (kJ / mol), delta_G_hi_p / (kJ / mol)], [(rho_hi_p - rho_lo_p) / density_units, (rho_hi_p - rho_lo_p) / density_units], colors.symbol(basename) + '-', label=colors.latex_mof(mof), color=colors.color(mof)) stepby = None if 20 < ymax < 200: stepby = 10 elif 200 < ymax < 1000: stepby = 100 elif 1000 < ymax < 3000: stepby = 500 if stepby is not None: plt.yticks( list(range(0, int(ymax), stepby)) + [round(ymax)] + list(range((int(ymax / stepby) + 1) * stepby, int(y_max_lim), stepby))) plt.ylim(0, 400) plt.xlim(0, 15)
# This example shows: # 1. Remotely killing a Pyrlang process, and a Erlang process # 2. Linking from Erlang to a Pyrlang process (and killing via the link) # 3. Monitoring from Erlang a Pyrlang process and observing it exit # # Run: `make example5a` in one terminal window, then `make example5b` in another # import logging from term import Atom from pyrlang.node import Node from pyrlang.process import Process from colors import color LOG = logging.getLogger(color("EXAMPLE5", fg='lime')) logging.getLogger("").setLevel(logging.DEBUG) class TestLinkProcess(Process): def __init__(self) -> None: Process.__init__(self) def handle_one_inbox_message(self, msg): LOG.info("TestLinkProcess: Incoming %s", msg) def exit(self, reason=None): LOG.info("TestLinkProcess: Received EXIT(%s)" % reason) node = self.get_node() #
def _colored(self, text, level): if self._enable_colors: c = self.colors.get(level, self.default_color) return color(text, c) return text
def main(): """ I need to fix the linter """ infile = sys.argv[1] outfile = infile.split(".")[0] + ".ans" if len(sys.argv) > 2: outfile = sys.argv[2] width = 60 if len(sys.argv) > 3: width = int(sys.argv[3]) mode = "full" if len(sys.argv) > 4: mode = sys.argv[4] height = int(width * 0.47) size = height, width with open(outfile, "w") as out: try: # Assume for now square images. TODO im = Image.open(infile) # im.thumbnail(size, Image.ANTIALIAS) im = im.resize((size[1] * 2, size[0] * 2), Image.ANTIALIAS) # wxh # im.save("thumbnail.png") data = np.asarray(im, dtype=np.uint16) # print("Resized pixel shape:", data.shape) done = 0 total = size[0] * size[1] for y in range(size[0]): # height for x in range(size[1]): # width pixels = data[y * 2:(y * 2) + 2, x * 2:(x * 2) + 2] distance = 0 top = pixels[0, :] bottom = pixels[1, :] left = pixels[:, 0] right = pixels[:, 1] right_diag = ( (pixels[0, 1] + pixels[1, 0]) / 2) #.astype(int) left_diag = ( (pixels[0, 0] + pixels[1, 1]) / 2) #.astype(int) dist_topbot = color_difference(top.mean(axis=0), bottom.mean(axis=0)) dist_lr = color_difference(left.mean(axis=0), right.mean(axis=0)) dist_diag = color_difference(left_diag, right_diag) dist_1 = color_difference( pixels[0, 0], (pixels.sum(axis=0).sum(axis=0) - pixels[0, 0]) / 3) dist_2 = color_difference( pixels[1, 0], (pixels.sum(axis=0).sum(axis=0) - pixels[1, 0]) / 3) dist_3 = color_difference( pixels[0, 1], (pixels.sum(axis=0).sum(axis=0) - pixels[0, 1]) / 3) dist_4 = color_difference( pixels[1, 1], (pixels.sum(axis=0).sum(axis=0) - pixels[1, 1]) / 3) distances = np.array([ dist_lr, dist_topbot, dist_diag, dist_1, dist_2, dist_3, dist_4 ]) contrast = np.argmax(distances) if contrast == 0: best_color_left = get_best_ansi_color( left.mean(axis=0), mode=mode) best_color_right = get_best_ansi_color( right.mean(axis=0), mode=mode) if best_color_right == best_color_left: out.write(color(" ", bg=best_color_left)) else: out.write( color("▐", bg=best_color_left, fg=best_color_right)) elif contrast == 2: best_color_left = get_best_ansi_color(left_diag, mode=mode) best_color_right = get_best_ansi_color(right_diag, mode=mode) if best_color_right == best_color_left: out.write(color(" ", bg=best_color_left)) else: out.write( color("▞", bg=best_color_left, fg=best_color_right)) elif contrast == 1: best_color_top = get_best_ansi_color(top.mean(axis=0), mode=mode) best_color_bottom = get_best_ansi_color( bottom.mean(axis=0), mode=mode) if best_color_bottom == best_color_top: out.write(color(" ", bg=best_color_top)) else: out.write( color("▄", bg=best_color_top, fg=best_color_bottom)) else: #▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟ # dist_1 = color_difference(pixels[0, 0], (pixels.sum(axis=0).sum(axis=0) - pixels[0, 0])/3) # dist_2 = color_difference(pixels[1, 0], (pixels.sum(axis=0).sum(axis=0) - pixels[1, 0])/3) # dist_3 = color_difference(pixels[0, 1], (pixels.sum(axis=0).sum(axis=0) - pixels[0, 1])/3) # dist_4 = color_difference(pixels[1, 1], (pixels.sum(axis=0).sum(axis=0) - pixels[1, 1])/3) shapes = ("▟", "▜", "▙", "▛") shape = shapes[contrast - 3] if contrast == 3: single = pixels[0, 0] elif contrast == 4: single = pixels[1, 0] elif contrast == 5: single = pixels[0, 1] else: single = pixels[1, 1] rest = (pixels.sum(axis=0).sum(axis=0) - single) / 3 best_color_single = get_best_ansi_color(single, mode=mode) best_color_rest = get_best_ansi_color(rest, mode=mode) if best_color_single == best_color_rest: out.write(color(" ", bg=best_color_single)) else: out.write( color(shape, bg=best_color_single, fg=best_color_rest)) done += 1 ct.progbar(done, total) out.write("\n") if mode == "full": np.savez("colormap_full.npz", colormap=colormap) except IOError, e: print("cannot create thumbnail for '%s'" % infile)
def UpdateBeep(s="updated"): if os.name == 'nt': winsound.Beep(1760, 100) print(color(s, 'blue'))
def __str__(self): return color(self.name, fg='white', style='bold')
def CheckInOutBeep(s="Check in/out"): if os.name == 'nt': winsound.Beep(1760, 100) print(color(s, 'cyan'))
from colors import color from enum import Enum import json import logging import os import requests logging.basicConfig(format='%(asctime)s | %(levelname)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG) logging.addLevelName(logging.DEBUG, color("DBG", 7)) logging.addLevelName(logging.INFO, "INF") logging.addLevelName(logging.WARNING, color('WRN', fg='red')) logging.addLevelName(logging.ERROR, color('ERR', bg='red')) log = logging.getLogger("{}.{}".format(__name__, "base")) # 'full', 'none', 'basic' (default) TELEMETRY_LEVEL = os.environ.get('TELEMETRY', 'basic') class TelemetryActions(Enum): BOOT = 'boot' # sent from apply_env.sh MIGRATEDB = 'migratedb' def __str__(self): return str(self.value) def is_telemetry_allowed(action): if action == TelemetryActions.BOOT:
def auditMode(roomId=None, autoMove=True, removeUser=False): """ audit mode is a smarter audit that update locations in SNIPEIT based on context checked out to user? leave checked out but update location_id checked out to location? check in then check back out to new location not checked out? only change location. not currently supported: items checked out to assets. roomId -- the room you are auditing. if not provided, you will be prompted with a list of locations. autoMove -- if asset is checked out to a different room, should it be checked out again, or just have its location updated removeUser -- if asset is checked out to a user, should the audit check it back in? """ w = getAllAssets() if roomId is None: #choose the room you are auditing. for loc in sorted(genericPayload('get', 'locations')['rows'], key=lambda x: x['name']): print("{id:5} - {name}".format(**loc)) roomId = int(input(' choose a room ID: ')) #scan labels forever and print success or failure while (1): ID = input('scan tag or SN: ') #check the inventory list items = list( filter( lambda x: x['asset_tag'].upper() == ID.upper() or x['serial']. upper() == ID.upper(), w)) if len(items) == 0: print(color('cant find {0}'.format(ID), 'red')) NotFoundBeep() continue if len(items) == 1: index = 0 else: for idx, i in enumerate(items): print('{0} - {1}'.format( idx, "{asset_tag} - {serial}".format_map(i))) index = int(input('choose idx: ')) myItem = items[index] #we now have an item that should be audited r = audit(myItem['asset_tag'], roomId) #todo: do we care what happens if its deployed to an asset? #deployed to a location? if (isDeployed(myItem) and deployedLocationId(myItem) is not None and deployedLocationId(myItem) != roomId): #that is not where i found it, then #checkin asset, with a note to the audited room, then check it out to the new room checkIn(myItem, roomId=roomId, note='auto checkin during audit') CheckInOutBeep() if autoMove: checkOut_location(myItem, roomId, note='auto checkout during audit') CheckInOutBeep() #deployed to a user elif isDeployedToUser(myItem) and (myItem['location'] is None or myItem['location']['id'] != roomId): if removeUser == True: checkIn(myItem, roomId=roomId, note='auto checkin during audit') CheckInOutBeep() update_location(myItem, roomId) UpdateBeep() elif not isDeployed(myItem): #not signed out to a user, or a location so in addition to auditing it, change its location. if autoMove: checkOut_location(myItem, roomId, note='auto checkout during audit') CheckInOutBeep() else: update_location(myItem, roomId) if r['status'] == 'success': SuccessBeep() print(color('success', fg='green')) else: ErrorBeep() print(color(r['status'], fg='red'))
from functools import partial import colors as c print(c.color('my string', fg='blue')) print(c.color('some text', fg='red', bg='yellow', style='underline')) print() for i in range(256): if i % 8 != 7: print(c.color('Color #{0}'.format(i).ljust(10), fg=i), end='|') else: print(c.color('Color #{0}'.format(i).ljust(10), fg=i), end='\n') print() # c.color(text*, fg, bg, style) print(c.color('orange on gray', 'orange', 'gray')) print(c.color('nice color', 'white', '#8a2be2')) print(c.red('This is red')) print(c.green('This is green')) print(c.blue('This is blue')) print(c.red('red on blue', bg='blue')) print(c.green('green on black', bg='black', style='underline')) print(c.red('very important', style='bold+underline')) important = partial(c.color, fg='red', style='bold+negative+blink') print(important('this is very important!')) print()
def strongColor(string): return color(string, fg="red")
def to_color(value): color_name = MOOD_SCALE[int(value)] color_string = color(DAY_BLOCK, fg=color_name) return color_string
plt.subplot(1, 2, 2) plt.ylim(5.2, 7.4) plt.xlim(25, 135) #fig1 = mpimg.imread('input_figures/murakami_book_chapter.png') #plt.imshow(fig1, extent=[25,135,5.0,7.6], aspect='auto') plt.plot(seis_p / 1.e9, seis_vs / 1.e3, color='k', linestyle='-', marker='None', markerfacecolor='w', markersize=4, label='PREM', linewidth=3.0, mew=1.5) plt.plot(seis_p/1.e9,mat_vs_1/1.e3,color=colors.color(3),marker='v',markerfacecolor=colors.color(3), \ markersize=4, markeredgecolor=colors.color(3),markevery=2,linewidth=1.5,label='perovskite') plt.plot(seis_p/1.e9,mat_vs_2/1.e3,color=colors.color(1),linestyle='-', \ linewidth=1.5,marker='^',markerfacecolor=colors.color(1), markersize=4, \ markeredgecolor=colors.color(1),markevery=2,label='periclase') plt.plot(seis_p/1.e9,mat_vs_4_wr/1.e3,color=colors.color(4),dashes=dashstyle3, \ linewidth=1.5,marker='o',markerfacecolor=colors.color(4), markersize=4, \ markeredgecolor=colors.color(4),markevery=2,label='92\% pv') plt.plot(seis_p/1.e9,mat_vs_3_wr/1.e3,color='g',linestyle='-',dashes=dashstyle2, \ linewidth=1.5,marker='o',markerfacecolor='w', markersize=4, markeredgecolor='g',markevery=2,label='83\% pv') plt.legend(loc='lower right', prop={'size': 12}) plt.title("Phase average on velocities") plt.xlabel("Pressure (GPa)")
getterObject = LayerGetter(sys.argv[1]) method_list = [ func for func in dir(LayerGetter) if callable(getattr(LayerGetter, func)) ] assert sys.argv[ 2] in method_list, f"the query should belong to {method_list}" print(" ".join(sys.argv[3:])) parser = argparse.ArgumentParser( "get function arguments, using this parser") parser.add_argument("-p", "--path") parser.add_argument("-n", "--layer_name") args = { k: v for k, v in vars(parser.parse_args(sys.argv[3:])).items() if v } # print(args) val = colors.color(f"'{sys.argv[1]}'", fg="#0fbd32") print( f"getterObject = {colors.color('LayerGetter', fg='#ffc400')}({colors.color('path', fg='#c87aff')}{colors.color('=', fg='#eb7065')}{val})" ) executed_str = f"getterObject.{colors.color(sys.argv[2], fg='#ffc400')}(" for k in args: val = colors.color(f"'{args[k]}'", fg="#0fbd32") executed_str += f"{colors.color(k, fg='#c87aff')}{colors.color('=', fg='#eb7065')}{val}," executed_str = executed_str[:-1] + ')' print(executed_str) getattr(getterObject, sys.argv[2])(**args)
def main(): """main method""" try: utils.clear() print( color(" ┌──────────────────────────────────────────┐", fg="#b61042")) print( color(" │ ", fg="#b61042") + color(f"π-hole 5 list tool v{__version__}", "#FFF") + color(" │", fg="#b61042")) print( color(" └──────────────────────────────────────────┘", fg="#b61042")) utils.info(" https://github.com/jessedp/pihole5-list-tool\n") db_file = "" use_docker = False docker = utils.find_docker() if docker[0] is True: utils.success(f"Found Running Docker config: {docker[1]}") use_docker = inquirer.confirm("Use Docker-ized config?", "n") if use_docker: db_file = docker[1] if not use_docker: db_file = inquirer.ask_db() list_type = inquirer.ask_list_type() print() utils.danger(" Do not hit ENTER or Y if a step seems to hang!") utils.danger( " Use CTRL+C if you're sure it's hung and report it.\n") if list_type == constants.BLOCKLIST: process_blocklists(db_file) if list_type == constants.ALLOWLIST: process_allowlists(db_file) if inquirer.confirm("Update Gravity for immediate effect?"): print() if use_docker: os.system( 'docker exec pihole bash "/usr/local/bin/pihole" "-g"') else: os.system("pihole -g") else: if use_docker: utils.info( "Update Gravity through the web interface or by running:\n\t" + '# docker exec pihole bash "/usr/local/bin/pihole" "-g"') else: utils.info( "Update Gravity through the web interface or by running:\n\t# pihole -g" ) utils.info("\n\tBye!") except (KeyboardInterrupt, KeyError): sys.exit(0)
import colors x = colors.color("/|\ ", 'RED') y = colors.color('/ \ ', 'RED') final = f''' _____ | / | |/ {colors.color('O', 'RED')} | {x} | {y} === ''' gibbet = ''' _____ | / | |/ | | === ''' stage_5 = ''' _____ | / | |/ O | /|\ | / === ''' stage_4 = '''
def run(self): try: if self.oop_engine: self.ngin = engine.Engine.oop_engine(self.config, pt_print=self.pt_print) else: self.ngin = engine.Engine(self.config, pt_print=self.pt_print) self.session = session.Session(self.config, self.ngin, self.PtPromptSession, self.history, self.pt_print) self.dispatcher = dispatch.Dispatcher(self.session, self.config, self.ngin) load_messages = self.ngin.get_load_messages() self.pt_print(load_messages) while True: try: # Wait a bit for any information on the stdout socket to be # printed out. TODO: this is not a good solution. time.sleep(.05) entry = self.session.prompt() except KeyboardInterrupt: self.ngin.send_interrupt() self.session.buffer.reset() continue if entry.strip() == '': continue try: # Dispatch may print to stdout/stderr before returning, so # we need to print the output prompt before calling it. self.pt_print(self.session.out_prompt_message()) # Dispatcher: figure out how to handle the user's command, # do it, and return in 'content' any content that should be # printed out. dispatch may also print content directly to # stdout. try: resp = self.dispatcher.dispatch(entry) if resp.kind == response.Response.Value: self.pt_print(resp.content) elif resp.kind == response.Response.Error: print( colors.color('Error: ', fg='red', style='bold') + resp.content) except Exception as det: if isinstance(det, EOFError) \ or isinstance(det, exceptions.Exiting): raise print( "An error occurred! Please report this as a " "bug: ", det, file=sys.stderr) traceback.print_exc() except KeyboardInterrupt: self.pt_print("\n\033[1;31mInterrupted\033[0m\n") finally: self.session.advance_lineno() except (EOFError, exceptions.Exiting): # Happens when the user presses Ctrl-D at the prompt print("Exiting...") return #sys.exit(0) finally: self.finish()
def stream_logs(): import colors for line in container.logs(stream=True): print(colors.color(line.decode().rstrip(), fg='yellow'))
def stream_logs(): for line in container.logs(stream=True): logger.info(colors.color(line.decode().rstrip(), fg='blue'))
def colored_print(text, use_color=True, color_name="white"): """Print with or without color codes""" if use_color: print(color(text, fg=color_name)) else: print(text)
def run_docker(definition, dataset, count, runs, timeout, batch, mem_limit=None): import colors # Think it doesn't work in Python 2 cmd = [ '--dataset', dataset, '--algorithm', definition.algorithm, '--module', definition.module, '--constructor', definition.constructor, '--runs', str(runs), '--count', str(count) ] if batch: cmd += ['--batch'] cmd.append(json.dumps(definition.arguments)) cmd += [json.dumps(qag) for qag in definition.query_argument_groups] print('Running command', cmd) client = docker.from_env() if mem_limit is None: mem_limit = psutil.virtual_memory().available print('Memory limit:', mem_limit) cpu_limit = "0-%d" % (multiprocessing.cpu_count() - 1) if not batch: # Limit to first cpu if not in batch mode cpu_limit = "0" print('Running on CPUs:', cpu_limit) container = client.containers.run(definition.docker_tag, cmd, volumes={ os.path.abspath('ann_benchmarks'): { 'bind': '/home/app/ann_benchmarks', 'mode': 'ro' }, os.path.abspath('data'): { 'bind': '/home/app/data', 'mode': 'ro' }, os.path.abspath('results'): { 'bind': '/home/app/results', 'mode': 'rw' }, }, cpuset_cpus=cpu_limit, mem_limit=mem_limit, detach=True) def stream_logs(): for line in container.logs(stream=True): print(colors.color(line.decode().rstrip(), fg='blue')) if sys.version_info >= (3, 0): t = threading.Thread(target=stream_logs, daemon=True) else: t = threading.Thread(target=stream_logs) t.daemon = True t.start() try: exit_code = container.wait(timeout=timeout) # Exit if exit code if exit_code == 0: return elif exit_code is not None: print(colors.color(container.logs().decode(), fg='red')) raise Exception('Child process raised exception %d' % exit_code) finally: container.remove(force=True)