def main(args): """Main method :param args: arguments :return: None """ opts = parse_cmdline_params(args[1:]) if opts.b is not None and opts.l is not None: nb = True else: nb = False sequences = cloning(opts.fastq, opts.n, nb, opts.b, opts.l) # sequences = create_fastq_dict('sampleFastq') total_error_num = 0 total_errors = 0 total_lengths = 0 for key in sequences: error_seq_string = '' seq_name = key seq_string = sequences[key] position = 0 error_num = 0 for base in seq_string: if base not in 'AGCTN': raise ValueError("This base,", base, ", is not an A, G, C, T, or N!") position += 1 error_prob = 0.001 * position if error_prob * 100 <= 0: raise ValueError( "The error probability must be greater than 0!") # Checks if it needs to add an error if random.randint(1, 1000) < (error_prob) * 1000: error_seq_string = add_error(error_seq_string, base, True) error_num += 1 else: error_seq_string = add_error(error_seq_string, base, False) total_errors += error_num total_error_num += 1 error_perc = error_num / len(seq_string) total_lengths += len(seq_string) print_errors(blue(seq_name), seq_string, error_seq_string, green(str(error_num))) print 'The error percent for this sequence is:', yellow( str(error_perc * 100)), '%' print 'The new quality string is: ', create_quality_scores( seq_string), '\n' print 'The average number of errors generated was:' \ '', magenta(str(int(total_errors / total_error_num))) print 'The total error percentage is:', magenta( str(total_errors / total_lengths * 100)), '%'
def get_from_multiplechoice(options, message_when_failing): """Show the options and let the user choose""" if len(options) is 0: print yellow(message_when_failing) abort() if len(options) is 1: # check how certain we are if options[0]['similarity'] > 0.9: return options[0]['dirname'] # no good enough match found, show the failing message print "" # create some space print yellow(message_when_failing) print "Is the following name correct?" print_options(options) answer = raw_input("Y/n/a: ") if answer == "" or answer.lower() == "y": print magenta("Option " + options[0]['dirname'] + " chosen") return options[0]['dirname'] if answer.lower() == "n" or answer.lower() == "a": abort() # no option chosen, lets retry print red("No valid answer given") return get_from_multiplechoice(options, message_when_failing) # multiple possible options, display the message and give the options print "" # create some space print yellow(message_when_failing) print "Choose one of the following:" # sort the options options = sorted(options, key=lambda k: k['similarity'], reverse=True) print_options(options, True) answer = raw_input("Enter a number or press enter for the default (1): ") if answer.lower() == "a": abort() else: if not answer: answer = 1 # the default if not str(answer).isdigit(): print red("Answer not recognized") return get_from_multiplechoice(options, message_when_failing) answer = int(answer) if len(options) > answer-1: print magenta("Option " + options[0]['dirname'] + " chosen") return options[0]['dirname'] else: print 'Answer out of bounds' return get_from_multiplechoice(options, message_when_failing)
def chosePath(): print("") print("Well then, you are free to go. Let me give you some information:") print("") print( "You have arrived at the new world, a strange new land which has recently been discovered, and has started to be colonized. Reports have been arriving that there are ruins and strange creatures out in the wild, which still largely remain unexplored. You have probably arrived as an adventurer, looking to search these parts. Anyway, off you go" ) print("") print( "You arrive at a fork on the road, where a sign points to three paths. Were do you wanna go?" ) print("") print(colors.red("-Forest")) print(colors.red("-Cave")) print(colors.red("-Eden")) print("") answer = input(colors.magenta("So where:")) if answer == "forest": import forest elif answer == "cave": import cave elif answer == "eden": import eden else: print("You wrote it wrong")
def print_headers(headers, format_names=False): if headers is not None: for key in sorted(headers): value = headers[key] if format_names: key = format_header_name(key) print '{}: {}'.format(colors.magenta(key), value)
def branch(): branches_yaml_path = path(ctx.user_config.inputs['branches_file']) branches_yaml = yaml.safe_load(branches_yaml_path.text()) for instance in ctx.env.storage.get_node_instances(): active_branch_set = instance.runtime_properties.get( 'active_branch_set') if active_branch_set: active_branch_set = active_branch_set['name'] break else: active_branch_set = None for name, branch_set in branches_yaml.items(): indicator = '*' if name == active_branch_set else ' ' print '{} {}:'.format(colors.red(indicator), colors.magenta(name)) indent = ' ' * 4 branch = branch_set.get('branch') if branch: print '{}branch: {}'.format(indent, colors.green(branch)) base = branch_set.get('base') if base: print '{}base: {}'.format(indent, colors.green(base)) repos = branch_set.get('repos') if repos: print '{}repos:'.format(indent) if isinstance(repos, list): for repo in repos: print '{}- {}'.format(indent, colors.green(repo)) else: for repo, branch in repos.items(): print '{} {}: {}'.format(indent, colors.green(repo), colors.green(branch)) print
def printBiomeMap(self): for y in range(0, self.height): print("") for x in range(0, self.width): if (self.tiles[x][y].settlement != None): sys.stdout.write( color(self.tiles[x][y].settlement.type, self.tiles[x][y].colorX)) elif (self.tiles[x][y].color == "cyan"): sys.stdout.write(cyan(self.tiles[x][y].biome)) elif (self.tiles[x][y].color == "white"): sys.stdout.write(white(self.tiles[x][y].biome)) elif (self.tiles[x][y].color == "green"): sys.stdout.write(green(self.tiles[x][y].biome)) elif (self.tiles[x][y].color == "yellow"): sys.stdout.write(yellow(self.tiles[x][y].biome)) elif (self.tiles[x][y].color == "blue"): sys.stdout.write(blue(self.tiles[x][y].biome)) elif (self.tiles[x][y].color == "magenta"): sys.stdout.write(magenta(self.tiles[x][y].biome)) elif (self.tiles[x][y].color == "red"): sys.stdout.write(red(self.tiles[x][y].biome)) elif (self.tiles[x][y].colorX != None): sys.stdout.write( color(self.tiles[x][y].biome, self.tiles[x][y].colorX)) else: sys.stdout.write(self.tiles[x][y].biome)
def libs(): verb = input("Type in a verb: ") word_list.append(verb) noun = input("Type in a noun: ") word_list.append(noun) pronoun = input("Type in a pronoun: ") word_list.append(pronoun) adjective = input("Type in an adjective: ") word_list.append(adjective) print(red('verb:red')) print(green('noun:green')) print(blue('pronoun:blue')) print(yellow('adjective:yellow')) print("I {} some {} then I've seen {}. I didn't realize it's {}".format( red(verb), green(noun), blue(pronoun), yellow(adjective))) inputs = input('Enter R to show results: ') if inputs == 'r' or inputs == 'R': for list_item in word_list: print(magenta(list_item))
def show_latest_run_msg(): url = 'http://localhost:%d/run/latest' % port try: from colors import magenta url = magenta(url) except ImportError: pass reporting_queue.put('Automatically see latest run at %s' % url)
def print_eq_sections(in_file, flag=True, section_name=""): if not in_file: print_msg(-1, "File is't exist") return sample = pefile.PE(in_file) for section in sample.sections: if (section.Misc_VirtualSize == section.SizeOfRawData) and (section_name in section.Name): sys.stdout.write(magenta("Name: %0s" % section.Name + "\tRawSize = 0x%08x" % section.SizeOfRawData)) sys.stdout.write(magenta("\tVirtualSize = 0x%08x" % section.Misc_VirtualSize)) sys.stdout.write(magenta("\tEntropy = %02d" % section.get_entropy() + "\n")) elif flag == False: print_msg(1, "No sections with equal RSize and VSize") elif flag == True: sys.stdout.write(blue("Name: %0s" % section.Name + "\tRawSize = 0x%08x" % section.SizeOfRawData)) sys.stdout.write(blue("\tVirtualSize = 0x%08x" % section.Misc_VirtualSize)) sys.stdout.write(blue("\tEntropy = %02d" % section.get_entropy() + "\n"))
def main(args): """Main method :param args: arguments :return: None """ opts = parse_cmdline_params(args[1:]) if opts.b is not None and opts.l is not None: nb = True else: nb = False sequences = cloning(opts.fastq, opts.n, nb, opts.b, opts.l) # sequences = create_fastq_dict('sampleFastq') total_error_num = 0 total_errors = 0 total_lengths = 0 for key in sequences: error_seq_string = '' seq_name = key seq_string = sequences[key] position = 0 error_num = 0 for base in seq_string: if base not in 'AGCTN': raise ValueError("This base,", base, ", is not an A, G, C, T, or N!") position += 1 error_prob = 0.001 * position if error_prob * 100 <= 0: raise ValueError("The error probability must be greater than 0!") # Checks if it needs to add an error if random.randint(1, 1000) < (error_prob) * 1000: error_seq_string = add_error(error_seq_string, base, True) error_num += 1 else: error_seq_string = add_error(error_seq_string, base, False) total_errors += error_num total_error_num += 1 error_perc = error_num / len(seq_string) total_lengths += len(seq_string) print_errors(blue(seq_name), seq_string, error_seq_string, green(str(error_num))) print 'The error percent for this sequence is:', yellow(str(error_perc * 100)), '%' print 'The new quality string is: ', create_quality_scores(seq_string), '\n' print 'The average number of errors generated was:' \ '', magenta(str(int(total_errors / total_error_num))) print 'The total error percentage is:', magenta(str(total_errors / total_lengths * 100)), '%'
def useskill(player, skill, target): if skill != []: print(len(player.skill)) print("Type the number corresponding to the skill you want to use \n") for skills in player.skill: print(player.skill.index(skills) + 1, skills["name"], "\n") sk = int(input()) skill = player.skill[sk - 1] if (int(player.mp) - int(skill["mpcost"])) > 0: crit = random.randint(0, 10) if crit > 7: print("You use", skill["name"]) target.hp = int( target.hp) - (int(skill["addeddmg"]) + int(player.dmg)) * 2 print( target.name, " takes ", colors.cyan( (int(skill["addeddmg"]) + int(player.dmg)) * 2), " damage") if target.hp > 0: print(target.name, " HP left: ", colors.magenta(target.hp)) else: print(target.name, "died") player.mp = int(player.mp) - int(skill["mpcost"]) print(colors.cyan("MP"), colors.cyan(player.mp), colors.cyan("/"), colors.cyan(player.maxmp)) else: print("You use", skill["name"]) target.hp = int( target.hp) - (int(skill["addeddmg"]) + int(player.dmg)) print(target.name, " takes ", colors.cyan((int(skill["addeddmg"]) + int(player.dmg))), " damage") if target.hp > 0: print(target.name, " HP left: ", colors.magenta(target.hp)) else: print(target.name, "died") player.mp = int(player.mp) - int(skill["mpcost"]) print(colors.cyan("MP"), colors.cyan(player.mp), colors.cyan("/"), colors.cyan(player.maxmp)) else: print("Not enough mana") else: print("You do not have any skills to use")
def count_df_queries(df): num_samples = { 0.6: df.query('surfer_experience == 0.6').shape[0], 0.8: df.query('surfer_experience == 0.8').shape[0], 1.0: df.query('surfer_experience == 1.0').shape[0], 'all': df.shape[0], } print(magenta(num_samples)) return num_samples
def check_discreteness(df, feat_x, feat_y): len_unique_x = len(df[feat_x].unique()) len_unique_y = len(df[feat_y].unique()) if len_unique_x < 10 and len_unique_y < 10: discreteness = True print(magenta('Features are discrete')) else: discreteness = False return discreteness
def main(args): opts = parse_cmdline_params(args[1:]) sequences = createFastqDict(opts.fastq) #sequences = createFastqDict('sampleFastq') total_error_num = 0 total_errors = 0 total_lengths = 0 for key in sequences: error_seq_string = '' seq_name = key seq_string = sequences[key] position = 0 error_num = 0 quality_string = createQualityScores(seq_string) for base in seq_string: if base not in 'AGCT': raise ValueError("This base,", base, ",is not an A, G, C, or T!") position += 1 error_prob = 0.001 * position if error_prob * 100 <= 0: raise ValueError( "The error probability must be greater than 0!") #Checks if it needs to add an error if (random.randint(1, 1000) < (error_prob) * 1000): error_seq_string = addError(error_seq_string, base, True) error_num += 1 else: error_seq_string = addError(error_seq_string, base, False) total_errors += error_num total_error_num += 1 error_perc = error_num / len(seq_string) total_lengths += len(seq_string) printErrors(blue(seq_name), seq_string, error_seq_string, green(str(error_num))) print 'The error percent for this sequence is:', yellow( str(error_perc * 100)), '%' print 'The new quality string is: ', quality_string, '\n' print 'The average number of errors generated was:', magenta( str(int(total_errors / total_error_num))) print 'The total error percentage is:', magenta( str(total_errors / total_lengths * 100)), '%'
def libs(): location = input("Location of favorite place to eat: ") word_list.append(location) food = input("What is your favorite food?: ") word_list.append(food) animal = input("What is your favorite animal?: ") word_list.append(animal) instrument = input("What is your favorite instrument?: ") word_list.append(instrument) noun = input("Put in a noun: ") word_list.append(noun) car = input("Put in a type of car: ") word_list.append(car) sport = input("Favorite Sport: ") word_list.append(sport) print( "I went to {} then cruised down the street in my {} to get some grub over at {}. Went to the {} to get the scoop. {} out there shooting some hoop. All I wanted to do was go home and play my {} but then quickly realized I didn't get enough {}. Headed back home and went to sleep after watching {}." .format(red(location), green(car), blue(location), yellow(location), magenta(noun), cyan(instrument), blue(animal), magenta(sport)))
def send(self, payload): '''Send a packet to the remote server. Assuming the initial connection has completed (i.e. #connect has been called, and returned), this data will be encrypted, and its authenticity guaranteed. Args: payload (string): The data to send to the remote server. ''' # This maths is horrific, but essentially we're calculating how much padding we need to add, # given that we must have at least 4 bytes, and that the total message length must be a multiple # of the AES block length padding_len = MIN_PADDING_LEN padding_len += AES_BLOCK_LEN - ((4 + 1 + len(payload) + padding_len) % AES_BLOCK_LEN) packet_len = 1 + len(payload) + padding_len msg_parts = [] msg_parts.append(generate_uint32(packet_len)) msg_parts.append(generate_byte(padding_len)) msg_parts.append(payload) msg_parts.append(random_bytes(padding_len)) msg = ''.join(msg_parts) # If the packet is encrypted, add the MAC and encrypt the message. The weird order of operations # here is because SSH is encrypt-and-mac (that is, the mac is on the plaintext, which is also # encrypted), rather than encrypt-then-mac or mac-then-encrypt if self._encryption_negotiated: mac = hmac.new( self._integrity_key_client_to_server, generate_uint32(self._packets_sent_counter) + msg, hashlib.sha1 ).digest() msg = self._aes_client_to_server.encrypt(msg) msg += mac self._packets_sent_counter += 1 print colors.magenta('> Sending: %s' % repr(''.join(msg))) self._socket.send(msg)
def paddedColoredOutput(string, maxlen, color2=False): '''Fill string with spaces up to maxlen characters This is a workaround for setting padding using python str.format e.g. ``{:{padding}}`` which does not work properly when outputting ANSI colors ''' div = maxlen - len(string) if sys.stdout.isatty(): if color2: return '{}{}'.format(magenta(string), ' ' * div) return '{}{}'.format(green(string), ' ' * div) return '{}{}'.format(string, ' ' * div)
def send(self, payload): '''Send a packet to the remote server. Assuming the initial connection has completed (i.e. #connect has been called, and returned), this data will be encrypted, and its authenticity guaranteed. Args: payload (string): The data to send to the remote server. ''' # This maths is horrific, but essentially we're calculating how much padding we need to add, # given that we must have at least 4 bytes, and that the total message length must be a multiple # of the AES block length padding_len = MIN_PADDING_LEN padding_len += AES_BLOCK_LEN - ( (4 + 1 + len(payload) + padding_len) % AES_BLOCK_LEN) packet_len = 1 + len(payload) + padding_len msg_parts = [] msg_parts.append(generate_uint32(packet_len)) msg_parts.append(generate_byte(padding_len)) msg_parts.append(payload) msg_parts.append(random_bytes(padding_len)) msg = ''.join(msg_parts) # If the packet is encrypted, add the MAC and encrypt the message. The weird order of operations # here is because SSH is encrypt-and-mac (that is, the mac is on the plaintext, which is also # encrypted), rather than encrypt-then-mac or mac-then-encrypt if self._encryption_negotiated: mac = hmac.new(self._integrity_key_client_to_server, generate_uint32(self._packets_sent_counter) + msg, hashlib.sha1).digest() msg = self._aes_client_to_server.encrypt(msg) msg += mac self._packets_sent_counter += 1 print colors.magenta('> Sending: %s' % repr(''.join(msg))) self._socket.send(msg)
def _reporter(func, *args, **kwargs): PRETTY_PREFIX = "[ " + c.magenta("narc-ctl") + " ] " descriptor = ":".join([func.__name__] + [a for a in args if a]) print PRETTY_PREFIX, "Running:", descriptor output = None try: output = func(*args, **kwargs) if not output: raise Exception print PRETTY_PREFIX, "[ " + c.green('OK') + " ]", descriptor except Exception: print PRETTY_PREFIX, "[ " + c.red('FAIL') + " ]", descriptor return output
def main(args): opts = parse_cmdline_params(args[1:]) sequences = createFastqDict(opts.fastq) #sequences = createFastqDict('sampleFastq') total_error_num = 0 total_errors = 0 total_lengths = 0 for key in sequences: error_seq_string = '' seq_name = key seq_string = sequences[key] position = 0 error_num = 0 quality_string = createQualityScores(seq_string) for base in seq_string: if base not in 'AGCT': raise ValueError("This base,", base ,",is not an A, G, C, or T!") position += 1 error_prob = 0.001 * position if error_prob * 100 <= 0: raise ValueError("The error probability must be greater than 0!") #Checks if it needs to add an error if (random.randint(1,1000) < (error_prob)*1000): error_seq_string = addError(error_seq_string,base,True) error_num += 1 else: error_seq_string = addError(error_seq_string,base,False) total_errors += error_num total_error_num += 1 error_perc = error_num/len(seq_string) total_lengths += len(seq_string) printErrors(blue(seq_name),seq_string,error_seq_string,green(str(error_num))) print 'The error percent for this sequence is:',yellow(str(error_perc*100)),'%' print 'The new quality string is: ',quality_string,'\n' print 'The average number of errors generated was:',magenta(str(int(total_errors/total_error_num))) print 'The total error percentage is:',magenta(str(total_errors/total_lengths*100)),'%'
def showstats(self): for attr, value in self.__dict__.items(): if attr == "inventory": self.showinventory() elif attr == "skill": print(colors.cyan("Your skills are \n")) for i in range(0, len(self.skill)): for key, val in self.skill[i].items(): print(colors.magenta(key), ":", val) elif attr == "itemslots": print(colors.yellow("You currently have equiped ")) for key, val in self.itemslots.items(): print(key, ":", val) else: print(attr, ":", value)
def mainLoop(self): while True: time.sleep(0.05) lines = self.gsm.normalizedRecv() for l in lines: l = l.strip() if l.startswith(b'+CLIP:'): self.answerCallClip(l) if l.startswith(b'RING'): callingNumber = self.getCallingNumber() if callingNumber: self.answerCall(callingNumber) if l.startswith(b'+CMTI:'): self.readAndHandleSMS() if b"POWER DOWN" in l: time.sleep(4) self.resetIfNeeded() if os.path.isfile(GATEUP_TRIGGER_FILE): os.unlink(GATEUP_TRIGGER_FILE) self.gateUp() if os.path.isfile(KILL_FILE): os.unlink(KILL_FILE) logPrint(colors.magenta("KTHXBYE")) return False if self.telegramBot and (TELEGRAM_CHECK_INTERVAL < (time.time() - self.lastTelegramCheck)): self.lastTelegramCheck = time.time() self.handleMessages(self.telegramBot.getMessages(), 'telegram_whitelist.txt', False) if PING_INTERVAL < (time.time() - self.lastPing): logPrint("Pi temperature is %f" % get_pi_temperature()) self.resetIfNeeded() if not validate_usb(): self.usbFailCount += 1 if MAX_USB_FAIL_COUNT < self.usbFailCount: logPrint( colors.red("Too many USB failures, rebooting!")) time.sleep(20) reboot_system() else: self.usbFailCount = 0 self.lastPing = time.time() if self.rfCtl.should_open_the_gate(): logPrint(colors.green("Gate up by RF remote control")) self.gateUp()
def printColor(self, msg, volcano): if volcano == "Misti": print(colors.blue(msg)) elif volcano == "Sabancaya": print(colors.yellow(msg)) elif volcano == "Ubinas": print(colors.cyan(msg)) elif volcano == "Ticsani": print(colors.magenta(msg)) elif volcano == "Inuse": print(colors.red(msg)) else: print(msg)
def getskill(player): fi = '' fto = str(player.occupation) + 'Skills' + '.txt' skills = open(fto, 'r') x = skills.readlines() for i in range(0, len(x) - 1): fi = fi + x[i] choices = [] it = re.finditer(r'\{[^\}]*\}', fi, re.S | re.I) for i in it: a = eval(i.group(0)) choices.append(a) for skill in choices: if int(s.level) == int(skill["unlocklvl"]): print("You have gained a new skill: ", colors.magenta(skill["name"])) player.skill.append(skill)
def t_col(level) -> str: ''' user level ''' l = int(level) if 10 > l: return c.yellow("0" + level, style='negative') if 30 > l >= 10: return c.green(level, style='negative') if 40 > l >= 30: return c.cyan(level, style='negative') if 50 > l >= 40: return c.blue(level, style='negative') if 80 > l >= 50: return c.magenta(level, style='negative') if 100> l > 80: return c.red(level, style='negative') if l > 100: return c.yellow(level, style='negative')
def parse_subset(self, logs, file): """ :param logs: :param file: :return: """ regex = re.compile(r"(?:(" + re.escape(white(file)) + ")|(" + re.escape(magenta(file)) + "))" # Starts with the file name r"\s+\|\s+([0-9;]+)\s+\|\s+" # Nodes Count r"([a-zA-Z0-9 \n\|\:\;]+)\+---" # Colonnes ) regex_tests = re.compile(r"(?:(?:\|\s+)+)?((?:[A-Za-z0-9:]+\s)+)") for _, match, nodes, text in regex.findall(logs): tests = [l.strip() for l in regex_tests.findall(text)] return nodes, tests
def warn(msg): """ Print warning message, but do not abort execution. This function honors Fabric's :doc:`output controls <../../usage/output_controls>` and will print the given ``msg`` to stderr, provided that the ``warnings`` output level (which is active by default) is turned on. """ from fabric.state import output, env if not env.colorize_errors: magenta = lambda x: x else: from colors import magenta if output.warnings: sys.stderr.write(magenta("\nWarning: %s\n\n" % msg))
def set_plot_name_and_save(pair, kind, s_exp, s=None): if len(pair) == 4: x, y, i, j = pair reg_name = f'{i}-{j}_{y}-{x}' full_path = f'_output/correlation/{kind}/{reg_name}.png' else: x, y = pair if s_exp: reg_name = f's{s}_{s_exp}_{y}-{x}' else: reg_name = f's{s}_{y}-{x}' full_path = f'_output/steps/{reg_name}.png' plt.savefig(full_path, bbox_inches="tight") print(f'<-- {green(full_path)}\t\texported') root_path = os.path.dirname(sys.modules['__main__'].__file__) print(f"\tfile:///{root_path}/{full_path}") print(kind, magenta(reg_name))
def get_job(): jobs = sorted(client.get_my_jobs(), key=lambda j: ( j.find('Client').find('Name').text.strip(), j.find('Name').text.strip(), )) print() for i, job in enumerate(jobs): print('{index}: {job} | {client}'.format( index=colors.bold('{:3}'.format(i + 1)), client=colors.blue(job.find('Client').find('Name').text.strip()), job=colors.magenta(job.find('Name').text.strip()), )) return input_valid( '\npick a job (1-{}): '.format(len(jobs)), lambda i: jobs[int(i) - 1], )
def _print_feature(name, feature, active_feature): indicator = '*' if name == active_feature else ' ' print '{} {}:'.format(colors.red(indicator), colors.magenta(name)) indent = ' ' * 4 branch = feature.get('branch') if branch: print '{}branch: {}'.format(indent, colors.green(branch)) base = feature.get('base') if base: print '{}base: {}'.format(indent, colors.green(base)) repos = feature.get('repos') if repos: print '{}repos:'.format(indent) if isinstance(repos, list): for repo in repos: print '{}- {}'.format(indent, colors.green(repo)) else: for repo, branch in repos.items(): print '{} {}: {}'.format(indent, colors.green(repo), colors.green(branch)) print
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 showstats(self): if self.rarity == "Rare": print(colors.cyan(self.name), "\n", "HP + ", self.hpi, "\n", "MP + ", self.mpi, "\n", "Damage + ", self.dmgi, "\n", "Rarity: ", self.rarity) elif self.rarity == "Common": print(colors.yellow(self.name), "\n", "HP + ", self.hpi, "\n", "MP + ", self.mpi, "\n", "Damage + ", self.dmgi, "\n", "Rarity: ", self.rarity) elif self.rarity == "Uncommon": print(colors.green(self.name), "\n", "HP + ", self.hpi, "\n", "MP + ", self.mpi, "\n", "Damage + ", self.dmgi, "\n", "Rarity: ", self.rarity) elif self.rarity == "Epic": print(colors.magenta(self.name), "\n", "HP + ", self.hpi, "\n", "MP + ", self.mpi, "\n", "Damage + ", self.dmgi, "\n", "Rarity: ", self.rarity) else: print(colors.orange(self.name), "\n", "HP + ", self.hpi, "\n", "MP + ", self.mpi, "\n", "Damage + ", self.dmgi, "\n", "Rarity: ", self.rarity)
def get_job(): jobs = sorted( client.get_my_jobs(), key=lambda j: ( j.find('Client').find('Name').text.strip(), j.find('Name').text.strip(), ) ) print() for i, job in enumerate(jobs): print('{index}: {job} | {client}'.format( index=colors.bold('{:3}'.format(i+1)), client=colors.blue(job.find('Client').find('Name').text.strip()), job=colors.magenta(job.find('Name').text.strip()), )) return input_valid( '\npick a job (1-{}): '.format(len(jobs)), lambda i: jobs[int(i)-1], )
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 _log(self): print( magenta('PantsDaemonMonitor: pid is {} is_alive={}'.format( self._pid, self.is_alive())))
def __process_list(self,use_format, use_thread, inst_list, fun,*args, **kwargs): def worker(task_queue,result_queue,fun,*args,**kwargs): proc_name = multiprocessing.current_process().name pid=multiprocessing.current_process().pid, print (pid,proc_name) obj=task_queue.get() res=getattr(obj,fun)(*args,**kwargs) print " %s:%s" % (proc_name,str(res)) result_queue.put(res) from multiprocessing.dummy import Pool as ThreadPool import multiprocessing import time results = [] cross_print = False error_count = len(inst_list) elapsed_sum = 0 proc_fun = fun work_manager = None try: if use_thread: #work_manager = WorkManager(thread_num=5) record = [] tasks = multiprocessing.Queue() task_results=multiprocessing.Queue() for i in inst_list: p=multiprocessing.Process(target=worker,args=(tasks,task_results,fun)+args,kwargs=kwargs) p.start() tasks.put(i) record.append(p) for i in record: i.join(15) tasks.close() tasks.join_thread() for i in record: if i.exitcode() == None: i.terminate() print "aa" return for instance in inst_list: if instance is None: continue if not use_format: print colors.magenta( str(getattr(instance,"server") if hasattr(instance,"server") else instance), prompt=False) if hasattr(instance, fun): if use_thread: work_manager.add_job(getattr(instance, proc_fun), *args, **kwargs) else: res = getattr(instance, proc_fun)(*args, **kwargs) results.append(res) if use_thread: work_manager.start_queue() work_manager.wait_allcomplete() for i in range(work_manager.result_queue.qsize()): # results.append(work_manager.result_queue.get()) one_result = work_manager.result_queue.get() results.append(one_result) work_manager.result_queue.task_done() for result in results: if result and (not cross_print) and string.find(result.result, '\n') != -1: cross_print = True #if result is None or result.succeed == False: #error_count -=1 if result is not None and result.succeed: elapsed_sum += result.elapsed error_count -= 1 if use_format: self.__print_result(results, len(inst_list), error_count, elapsed_sum, cross_print) os.system('stty sane') except Exception, e: print "Error:%s" % e traceback.print_exc()
def _log(self): print( magenta( f"PantsDaemonMonitor: pid is {self._pid} is_alive={self.is_alive()}" ))
def __set_prompt(self, node): self.prompt = """%s%s%s%s>""" % (colors.blue("Corrin", prompt=True), '[', colors.magenta(str(node), prompt=True), ']')
def intro(charName): understood = True print("%s, right? Not the name I would have chosen." % (colors.yellow(charName))) print("") print("anyways, are you a %s or a %s" % (colors.cyan("female"), (colors.cyan("male")))) crgender = input("") badans = True while badans: if crgender == "male": print((colors.cyan('Perfect!'))) break elif crgender == "female": print(colors.magenta("Perfect!")) break else: print("gender %s" % (colors.yellow("NOT FOUND!"))) print("please write one of the %s:" % (colors.red("ABOVE"))) crgender = input("") print("") print("Let me make some things clear right off the bat:") print( "With the exception of your name, all words and commands and etc will need to be clear: If you are inputting a number, make it just a number. If you are making an action, make it just one word, all lowercase. Is that clear ? :" ) print("") print(colors.cyan("Options: yes, no")) while understood: ans = str(input("")) if ans == "Yes": print("Repeat, in lowercase") elif ans == "No": print("Repeat, in lowercase") elif ans == "no": print( "With the exception of Your Name, All words and commands amd etc will need to be clear: If you are inputting a number, make it just a number. If you are making an action, make it just one word, all lowercase. Is that clear ? " ) print("") print("Options: yes, no") elif ans == "yes": print("Great! Now we can understand each other") understood = False else: print("Options: yes, no") print("") print( "It looks like you are finally awake. Not even the storm lat night could wake you. I heard them say we finally reached the new world. Quiet now, I hear the guards coming." ) print("") print("You, come with us, we need to take your census") print( "We don't have any records of you, so please tell us your occupation,and we will let you be on your way." ) print("") print("")
def __str__(self): 'Return the colorized name of this mob.' name = Character.__str__(self) return magenta(name)
def _log(self): print(magenta( 'PantsDaemonMonitor: pid is {} is_alive={}'.format(self._pid, self.is_alive())) )
def damage_speech_constant(): DAMAGE_SPEECH = (colors.green('tickled'), colors.yellow('pierced'), colors.red('amputated'), colors.magenta('obliterated'), colors.cyan("decimated"), colors.blue("deleted")) return DAMAGE_SPEECH
# load the narc config ctl_config = config.load_config() # Add moksha's src dir to the path so we can import it sys.path.insert(0, ctl_config['moksha-src-dir']) # Import moksha from its source directory import moksha.ctl.core.ctl as moksha_ctl # Override moksha config with narc config moksha_ctl.ctl_config.update(ctl_config) pid_files = ['paster.pid', 'orbited.pid', 'moksha-hub.pid'] PRETTY_PREFIX = "[ " + c.magenta("narc-ctl") + " ] " @decorator.decorator def _with_virtualenv(func, *args, **kwargs): with virtualenvcontext.VirtualenvContext(ctl_config['venv']): return func(*args, **kwargs) @decorator.decorator def _in_srcdir(func, *args, **kwargs): with utils.DirectoryContext(ctl_config['narc-src-dir']): return func(*args, **kwargs) @decorator.decorator def _with_moksha_faked(func, *args, **kwargs):
def debug(*args): """ Debug output """ if DEBUG: print(magenta(('{} ' * len(args)).format(*args)))