def assert_success_runner(self, workdir, config, cmd, extra_config={}, extra_env={}, expected_runs=1): combined_config = config.copy() recursively_update(combined_config, extra_config) print(bold(cyan('\nrunning: ./pants {} (config={}) (extra_env={})' .format(' '.join(cmd), combined_config, extra_env)))) run_count = self._run_count(workdir) start_time = time.time() run = self.run_pants_with_workdir( cmd, workdir, combined_config, extra_env=extra_env, # TODO: With this uncommented, `test_pantsd_run` fails. # tee_output=True ) elapsed = time.time() - start_time print(bold(cyan('\ncompleted in {} seconds'.format(elapsed)))) runs_created = self._run_count(workdir) - run_count self.assertEquals( runs_created, expected_runs, 'Expected {} RunTracker run to be created per pantsd run: was {}'.format( expected_runs, runs_created, ) ) self.assert_success(run) return run
def console_output(self, targets): buildfile_aliases = self.context.build_configuration.registered_aliases( ) extracter = BuildDictionaryInfoExtracter(buildfile_aliases) alias = self.get_options().details if alias: tti = next(x for x in extracter.get_target_type_info() if x.symbol == alias) yield blue("\n{}\n".format(tti.description)) yield blue("{}(".format(alias)) for arg in tti.args: default = green("(default: {})".format(arg.default) if arg. has_default else "") yield "{:<30} {}".format( cyan(" {} = ...,".format(arg.name)), " {}{}{}".format(arg.description, " " if arg.description else "", default), ) yield blue(")") else: for tti in extracter.get_target_type_info(): yield "{} {}".format(cyan("{:>30}:".format(tti.symbol)), tti.description)
def verify(self, handle): """ Verifies that the user has valid credentials for accessing Tweepy API :param handle: the handle of the twitter user that the bot operator wishes to mimic :return: a 4-tuple of an API object, the bot's handle, the standardized handle of the other user, and the actual handle of the other user (can have uppercase letters) """ sys.stdout.write(colors.yellow("verifying credentials")) thread = Thread(target=self.loading()) # lol thread.daemon = True # kill this thread if program exits thread.start() api = self.authorize() handle = handle.strip().lower() # standardize name formatting for folder name try: who_am_i = handle if handle in "test" else api.get_user(handle).screen_name # test that API works me = api.me().screen_name except TweepError as e: err = e[:][0][0]["message"] raise ValueError("Awh dang dude, you gave me something bad: %s" % err) thread.join() # lol print colors.white(" verified\n") + colors.cyan("starting up bot ") + colors.white("@" + me) + colors.cyan( " as ") + colors.white("@" + who_am_i) + colors.cyan("!\n") return api, me, handle, who_am_i # api, the bot's name, the other user's name, full version of user's name
def console_output(self, targets): buildfile_aliases = self.context.build_file_parser.registered_aliases() extracter = BuildDictionaryInfoExtracter(buildfile_aliases) alias = self.get_options().details if alias: target_types = buildfile_aliases.target_types_by_alias.get(alias) if target_types: tti = next(x for x in extracter.get_target_type_info() if x.build_file_alias == alias) yield blue('\n{}\n'.format(tti.description)) yield blue('{}('.format(alias)) for arg in extracter.get_target_args(list(target_types)[0]): default = green('(default: {})'.format(arg.default) if arg. has_default else '') yield '{:<30} {}'.format( cyan(' {} = ...,'.format(arg.name)), ' {}{}{}'.format(arg.description, ' ' if arg.description else '', default)) yield blue(')') else: yield 'No such target type: {}'.format(alias) else: for tti in extracter.get_target_type_info(): description = tti.description or '<Add description>' yield '{} {}'.format( cyan('{:>30}:'.format(tti.build_file_alias)), description)
def console_output(self, targets): buildfile_aliases = self.context.build_file_parser.registered_aliases() extracter = BuildDictionaryInfoExtracter(buildfile_aliases) alias = self.get_options().details if alias: target_types = buildfile_aliases.target_types_by_alias.get(alias) if target_types: tti = next(x for x in extracter.get_target_type_info() if x.build_file_alias == alias) yield blue('\n{}\n'.format(tti.description)) yield blue('{}('.format(alias)) for arg in extracter.get_target_args(list(target_types)[0]): default = green('(default: {})'.format(arg.default) if arg.has_default else '') yield '{:<30} {}'.format( cyan(' {} = ...,'.format(arg.name)), ' {}{}{}'.format(arg.description, ' ' if arg.description else '', default)) yield blue(')') else: yield 'No such target type: {}'.format(alias) else: for tti in extracter.get_target_type_info(): description = tti.description or '<Add description>' yield '{} {}'.format(cyan('{:>30}:'.format(tti.build_file_alias)), description)
def console_output(self, targets): buildfile_aliases = self.context.build_configuration.registered_aliases( ) extracter = BuildDictionaryInfoExtracter(buildfile_aliases) alias = self.get_options().details if alias: tti = next(x for x in extracter.get_target_type_info() if x.symbol == alias) yield blue('\n{}\n'.format(tti.description)) yield blue('{}('.format(alias)) for arg in tti.args: default = green('(default: {})'.format(arg.default) if arg. has_default else '') yield '{:<30} {}'.format( cyan(' {} = ...,'.format(arg.name)), ' {}{}{}'.format(arg.description, ' ' if arg.description else '', default)) yield blue(')') else: for tti in extracter.get_target_type_info(): yield '{} {}'.format(cyan('{:>30}:'.format(tti.symbol)), tti.description)
def assert_success_runner(self, workdir, config, cmd, extra_config={}): combined_config = combined_dict(config, extra_config) print( bold( cyan('\nrunning: ./pants {} (config={})'.format( ' '.join(cmd), combined_config)))) run_count = self._run_count(workdir) start_time = time.time() run = self.run_pants_with_workdir( cmd, workdir, combined_config, # TODO: With this uncommented, `test_pantsd_run` fails. # tee_output=True ) elapsed = time.time() - start_time print(bold(cyan('\ncompleted in {} seconds'.format(elapsed)))) runs_created = self._run_count(workdir) - run_count self.assertEquals( runs_created, 1, 'Expected one RunTracker run to be created per pantsd run: was {}'. format(runs_created)) self.assert_success(run) return run
def eden(): print( colors.yellow( "very well young adventurer. so to pass, Master Lord (a weird reader) offers you the way if you answer his riddle:" )) print("") riddleans = input( colors.cyan( "the riddle is: There was a plane crash and every single person died, who survived?:" )) badans = True while badans: if riddleans == "married people": print("very well. you now have entered the %s." % (colors.red('EDEN'))) break else: print("") print( "the answer is not correct you shall not be granted the %s." % (colors.red("WAY"))) print(" ") print(" ") riddleans = input( colors.cyan( "the riddle is: There was a plane crash and every single person died, who survived?:" )) import encounter
def post_process(self, this, num, max_length): """ Colorizes items in print display (1) Makes most recently modified item cyan (2) Any directory yellow (3) Symlinks green (4) Files are left unchanged """ verbose = False verbose and print("in post process: {}".format(this)) item = str(this) if not this.is_mounted: strikeout = '☓' * len(str(num)) return (strikeout, green(item)) if this.default and this.force_default: return ( cyan(num), cyan(item) ) if this.default: return ( cyan(num), cyan(item) ) if this.is_directory: return ( num, yellow(item) ) if this.is_link: return ( num, green(item) ) else: # is file pass ffile, ext = os.path.splitext(item) if ext: return ( num, green(ffile + ext) ) else: return ( num, green(item) )
def assert_runner(self, workdir, config, cmd, extra_config={}, extra_env={}, expected_runs=1, success=True): combined_config = config.copy() recursively_update(combined_config, extra_config) print(bold(cyan('\nrunning: ./pants {} (config={}) (extra_env={})' .format(' '.join(cmd), combined_config, extra_env)))) run_count = self._run_count(workdir) start_time = time.time() run = self.run_pants_with_workdir( cmd, workdir, combined_config, extra_env=extra_env, # TODO: With this uncommented, `test_pantsd_run` fails. # tee_output=True ) elapsed = time.time() - start_time print(bold(cyan('\ncompleted in {} seconds'.format(elapsed)))) # TODO: uncomment this and add an issue link! runs_created = self._run_count(workdir) - run_count self.assertEqual( runs_created, expected_runs, 'Expected {} RunTracker run(s) to be created per pantsd run: was {}'.format( expected_runs, runs_created, ) ) if success: self.assert_success(run) else: self.assert_failure(run) return run
def _do_key_exchange(self): # Generate and send our side of the kex exchange handshake client_kex_init = _generate_client_kex_init() self.send(client_kex_init) # Receive the server's side of the key exchange handshake server_kex_init = self.read() data_ptr, ssh_msg_type = parse_byte(server_kex_init, 0) assert ssh_msg_type == SSH_MSG_NUMS['SSH_MSG_KEXINIT'] # Read the cookie from the server cookie = server_kex_init[data_ptr:data_ptr + COOKIE_LEN] data_ptr += COOKIE_LEN print colors.cyan('Cookie: %s' % repr(cookie)) # Read the algorithm lists from the server data_ptr, kex_algorithms = parse_name_list(server_kex_init, data_ptr) data_ptr, server_host_key_algorithms = parse_name_list(server_kex_init, data_ptr) data_ptr, encryption_algorithms_client_to_server = parse_name_list(server_kex_init, data_ptr) data_ptr, encryption_algorithms_server_to_client = parse_name_list(server_kex_init, data_ptr) data_ptr, mac_algorithms_client_to_server = parse_name_list(server_kex_init, data_ptr) data_ptr, mac_algorithms_server_to_client = parse_name_list(server_kex_init, data_ptr) data_ptr, compression_algorithms_client_to_server = parse_name_list(server_kex_init, data_ptr) data_ptr, compression_algorithms_server_to_client = parse_name_list(server_kex_init, data_ptr) data_ptr, _ = parse_name_list(server_kex_init, data_ptr) data_ptr, _ = parse_name_list(server_kex_init, data_ptr) # Check that the server did not try to predict the key exchange protocol we'd be using data_ptr, first_kex_packet_follows = parse_byte(server_kex_init, data_ptr) assert first_kex_packet_follows == 0, 'Additional data in key exchange packet' # Check that the reserved bytes are also present in the message assert len(server_kex_init) == data_ptr + KEX_RESERVED_BYTES_LEN, \ 'Wrong amount of data left in packet' # Check that we'll be able to talk to this server correctly assert KEX_ALGORITHM in kex_algorithms assert SERVER_HOST_KEY_ALGORITHM in server_host_key_algorithms assert ENCRYPTION_ALGORITHM in encryption_algorithms_client_to_server assert ENCRYPTION_ALGORITHM in encryption_algorithms_server_to_client assert MAC_ALGORITHM in mac_algorithms_client_to_server assert MAC_ALGORITHM in mac_algorithms_server_to_client assert COMPRESSION_ALGORITHM in compression_algorithms_client_to_server assert COMPRESSION_ALGORITHM in compression_algorithms_server_to_client # Derive Diffie Hellman shared keys self._run_diffie_hellman_group14_sha1_key_exchange(server_kex_init, client_kex_init) # Swap to using those keys self.send(generate_byte(SSH_MSG_NUMS['SSH_MSG_NEWKEYS'])) response = self.read() index, response_type = parse_byte(response, 0) assert response_type == SSH_MSG_NUMS['SSH_MSG_NEWKEYS'], \ 'Unknown SSH message type: %d' % response_type assert index == len(response), 'Additional data in response' self._encryption_negotiated = True print colors.cyan('Successfully exchanged keys!')
def _ask_for_creds(provider, url, realm): print(green('\nEnter credentials for:\n')) print('{} {}'.format(green('Provider:'), cyan(provider))) print('{} {}'.format(green('Realm: '), cyan(realm))) print('{} {}'.format(green('URL: '), cyan(url))) print(red('\nONLY ENTER YOUR CREDENTIALS IF YOU TRUST THIS SITE!\n')) username = input(green('Username: '******'Password: ')) return BasicAuthCreds(username, password)
def _ask_for_creds(provider, url, realm): print(green("\nEnter credentials for:\n")) print("{} {}".format(green("Provider:"), cyan(provider))) print("{} {}".format(green("Realm: "), cyan(realm))) print("{} {}".format(green("URL: "), cyan(url))) print(red("\nONLY ENTER YOUR CREDENTIALS IF YOU TRUST THIS SITE!\n")) username = input(green("Username: "******"Password: ")) return BasicAuthCreds(username, password)
def update(self, starting=None): """ By default, checks "{usr}_all_ids.json" for when tweets were most recently scraped, then scrapes from then until the present. If no tweets were collected or not file was found, begins scraping from their join date. :param starting: The date to start scraping from (FORMAT: YYYY-MM-DD) """ if not starting: # if not given, look from beginning starting = self.get_join_date() print colors.cyan("Updating corpus.json") scrape(self.handle, start=starting, api=self.keys)
def attack(attacker, victim): crit = random.randint(0, 10) if crit > 7: victim.hp = int(victim.hp) - int(attacker.dmg) * 2 print(victim.name, " takes ", colors.cyan(int(attacker.dmg) * 2), " damage") else: victim.hp = int(victim.hp) - int(attacker.dmg) print(victim.name, " takes ", colors.cyan(int(attacker.dmg)), " damage")
def disconnect(self): '''Close the connection to the remote server.''' msg = [] msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_DISCONNECT'])) msg.append(generate_uint32(11)) # SSH_DISCONNECT_BY_APPLICATION msg.append(generate_string('Closed by client')) msg.append(generate_string('')) self.send(''.join(msg)) self._socket.close() print colors.cyan('Disconnected!')
def _send_and_receive_id_strings(self): # Send our own header self._socket.sendall(self._client_id_string) # Receive the server's ID string (max size 255, as specified by the RFC) self._server_id_string = self._socket.recv(255) match = re.match(r'SSH-([^-]+)-([^ ]+)(?:( .*))?\r\n', self._server_id_string) assert match, 'Could not parse server ID string' # Check that we're speaking the right protocol proto_version, software_version, comments = match.groups() assert proto_version == '2.0', "Unknown SSH protocol version" % proto_version print colors.cyan("Great! I'm speaking to %s (%s)" % (software_version, comments))
def kmeans_v2(self, data_clust, data_test, X, X_test, init='k-means++'): """ Clustering of data using KMeans_v2 approach input data_clust : dataframe input data_test : dataframe input centers : array of centers return Xlabled,centers,labels,X_testlabled,labels_test,time """ t0 = perf_counter() # timer from sklearn.cluster import KMeans kmeans_v2 = KMeans(n_clusters=self.nb_clust, init=init, random_state=Cfg.RandomState, n_jobs=-1) labels = kmeans_v2.fit_predict(data_clust) centers = kmeans_v2.cluster_centers_ # centers labels = labels.reshape(data_clust.shape[0], 1) self.logger.info( cyan(" Kmeans-Train-Clustering: " + str(Counter(list(labels[:, 0]))))) labels_copy = self.lb.transform(labels) if Cfg.Normalize: labels_copy = preprocessing.normalize(labels_copy, axis=0, norm='l2') X = sparse.hstack([X[:, 0:Cfg.NbZones], data_clust, labels_copy], format="csr") # Labels prediction for test set labels_test = None if X_test.shape[0] > 0: labels_test = kmeans_v2.predict(data_test) labels_test = labels_test.reshape(data_test.shape[0], 1) self.logger.info( cyan(" Kmeans-Test-Clustering: " + str(Counter(list(labels_test[:, 0]))))) labels_test_copy = self.lb.transform(labels_test) if Cfg.Normalize: labels_test_copy = preprocessing.normalize(labels_test_copy, axis=0, norm='l2') X_test = sparse.hstack( [X_test[:, 0:Cfg.NbZones], data_test, labels_test_copy], format="csr") return X, centers, labels, X_test, labels_test, (round( perf_counter() - t0, 2))
def continue_game(): new_player.set_health() new_player.set_dexterity() new_player.set_luck() print('\n' 'Your stat after random roll:') print('\n', red('Health: '), new_player.health, '| ', cyan('Dexterity: '), new_player.dexterity, '| ', yellow('Luck: '), new_player.luck, '\n') main(reroll_menu)
def search_best_model(self,data): """ Search the best model using hyperopt & stock best model input data: (X_train, X_val, X_test, y_train, y_val, y_test) """ from hyperopt import Trials, tpe,rand from hyperas import optim t0 = perf_counter() # timer best_run, best_model,space = optim.minimize(model= create_model, data=data, rseed=Cfg.RandomState, algo=tpe.suggest, max_evals=Cfg.NbTrials, trials=Trials(), eval_space=True, verbose=False, return_space=True ) self.model = best_model self.best_run = best_run self.logger.info(' best-run: '+cyan(str(best_run))) self.logger.info(green(' The serach of best model took: ') + red(str(round(perf_counter()-t0,5))) + " " +green(".s") )
def main(): print(cyan("Prime Number Generator")) bbs = BlumBlumShub( 47549311472920909912209319415632546568615171647449776708088515456271882256688655472429960001356598002721056949199289005875090341339535679228762000284695578992694028821429479898585483427123161057642719497767775759219743666776381110838744061389431879168072462318464481040242866241897410149885018525271140808743387765598861025306828071770446075734192300013226299729071396927791922757802315939093736083879788104144364331864519291777448965862396859815581731257814820213290000280532074935599904323257225411772963246498810492981761448004460009228598633053, 107397595365822977137336244061581024502786353619930520168857195796487927688075184909580315280089385066594856534824324028916873227593184312306380432882318358133946408364432997211883642081142345263913093524717335572775257117166625838352501167314403619745327796928224603118553911877190432477897849958446446909190088634315248524470293658599768274374072505636243343338931450592489529079411012054264332025498428060511919416556838891807530769004624034148341042211078576228613399736180978723912602319129778598464870910571473064783677343206518408119156722081, 505681814266168811) lcg = LinearCongruentialGenerator( # a, x0, c, m 25214903917, 505681814266168811, 11, pow(2,60) # 60 -> 256 bits; 300 -> 512 bits; 780 -> 1024 bits; 1720 -> 2048 bits; 3650 -> 4096 bits ) start_time = time.time() print("RUNNING") for i in range(0,350): # num = bbs.next() num = lcg.next() # print(f"\n{num} ({sys.getsizeof(num)*8} bits) (iteration {i+1})") # if fermat(num): if miller_rabin(num): print(f"\nPRIME: {num} ({sys.getsizeof(num)*8} bits) (iteration {i+1}) (time {(time.time() - start_time)*1000} ms)") print("FINISHED")
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 _scoreOutput(self, scorePos, scoreNeg, output, cursor, line): perc = lambda neg, ln: str(((ln - neg) / ln) * 100)[:5] + '%' score = '({pos} / {neg} / {lineperc})'.format( pos=green(str(scorePos)), neg=red(str(scoreNeg)), lineperc=cyan(perc(scoreNeg, len(line))) ) CLI.write(output + cursor + ' ' + score)
def password(): time.sleep(3) bnc = random.randrange(10000000000,9000000000000) bnc = str(bnc) hashed = hashlib.sha256(str(bnc).encode('utf-8')).hexdigest() #Crypt the math result with 256 bits hashed = str(hashed) passw = "%"+str(hashed[:-52])+"~" print(cyan("Password Generated: "+passw,style="bold"))
def cave(): print(colors.yellow("very well young adventurer. so to pass, Master Ori (a weird bar tender) offers you the way if you answer his riddle:")) print("") riddleans=input(colors.cyan("the riddle is: what ios tall when its young and short when its old?:")) badans = True while badans: if riddleans == "candle": print("very well. you now have entered the %s." % (colors.red('CAVE'))) break else: print("") print("the answer is not correct you shall not be granted the %s." % (colors.red("WAY"))) print(" ") print(" ") riddleans=input(colors.cyan("the riddle is: what ios tall when its young and short when its old?:")) import encounter
def forest(): print(colors.yellow("very well young aprentice. so to pass, Master Elenoid (a weird basard) offers you the way if you answer his riddle:")) print("") riddleans=input(colors.cyan("the riddle is: what walks with four legs in the morning, two in the afternoon and three at night?:")) badans = True while badans: if riddleans == "man": print("very well. you now have entered the %s." % (colors.red('FOREST'))) break else: print("") print("the answer is not correct you shall not be granted the %s." % (colors.red("WAY"))) print(" ") print(" ") riddleans=input(colors.cyan("the riddle is: what walks with four legs in the morning, two in the afternoon and three at night?:")) import encounter
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 read(self): '''Read a packet from 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. Returns (string): the data sent by the remote server. ''' # Read the first <block_len> bytes of the packet, decrypt it if necessary, and parse out the # remaining packet length initial_packet = self._socket.recv(AES_BLOCK_LEN) if self._encryption_negotiated: initial_packet = self._aes_server_to_client.decrypt(initial_packet) _, packet_len = parse_uint32(initial_packet, 0) # Read the remaining bytes of the packet, decrypting if necessary, and checking the MAC remaining_msg = self._socket.recv(packet_len - (AES_BLOCK_LEN - 4)) if self._encryption_negotiated: remaining_msg = self._aes_server_to_client.decrypt(remaining_msg) # Read and verify the MAC received_mac = self._socket.recv(SHA1_LEN) calculated_mac = hmac.new( self._integrity_key_server_to_client, generate_uint32(self._packets_received_counter) + initial_packet + remaining_msg, hashlib.sha1 ).digest() assert received_mac == calculated_mac, \ 'MACs did not match: %s != %s' % (repr(received_mac), repr(calculated_mac)) print colors.cyan('MAC validated correctly!') # Pull the payload out of the message data = (initial_packet + remaining_msg)[4:] index, padding_len = parse_byte(data, 0) payload_len = packet_len - padding_len - index payload = data[index:payload_len + index] self._packets_received_counter += 1 print colors.green('< Received: %s' % repr(payload)) return payload
def lesson2(self): '''Colemak lesson 2 - Letters RI''' self.printHeader(2) # print(' -RST--NEI-- -SDF--JKL--') print( ' ' '-' + green('R') + cyan('S') + cyan('T', style='underline') + '-' '-' + cyan('N', style='underline') + cyan('E') + green('I') + '--' ' ' '-SD' + underline('F') + '--' + underline('J') + 'KL--' ) print('\n (colemak) (qwerty)\n') self.tutor.lines([ 'trite stress sire it entire terse tit sir tire sinner retire', 'rinse inn tree insist tier rite teeter resin stir siren enter', 'sitter insert site sneer intern tie inner series steer tin', 'riser its resent sin rise rent rein iris stern in titter resist', 'eerie inert street is renter sit nine risen sister serene', 'stint err snit intent entree nit inter rest tennis re tint' ])
def console_output(self, targets): buildfile_aliases = self.context.build_file_parser.registered_aliases() extracter = BuildDictionaryInfoExtracter(buildfile_aliases) alias = self.get_options().details if alias: tti = next(x for x in extracter.get_target_type_info() if x.symbol == alias) yield blue('\n{}\n'.format(tti.description)) yield blue('{}('.format(alias)) for arg in tti.args: default = green('(default: {})'.format(arg.default) if arg.has_default else '') yield '{:<30} {}'.format( cyan(' {} = ...,'.format(arg.name)), ' {}{}{}'.format(arg.description, ' ' if arg.description else '', default)) yield blue(')') else: for tti in extracter.get_target_type_info(): yield '{} {}'.format(cyan('{:>30}:'.format(tti.symbol)), tti.description)
def le_col(level, label="") -> str: ''' label level ''' lv = int(level) if lv == 0: return " " if 10 > lv > 0: return c.yellow(label + "0" + level, style='negative') if 20 > lv >= 10: return c.cyan(label + level, style='negative') if lv >= 20: return c.red(label + level, style='negative')
def build_json(user, api): print colors.yellow("beginning meta_data collection...") user = user.lower() auth = tweepy.OAuthHandler(api["consumer_key"], api["consumer_secret"]) auth.set_access_token(api["access_token"], api["access_token_secret"]) api = tweepy.API(auth) output_file = "bot_files/{0}/{0}.json".format(user) with open("bot_files/{0}/{0}_all_ids.json".format(user)) as f: ids = json.load(f)["ids"] all_data = [] start = 0 end = 100 limit = len(ids) i = int(math.ceil(limit / 100.0)) for go in range(i): print colors.cyan("currently getting {} - {}".format(start, end)) sleep(6) # needed to prevent hitting API rate limit id_batch = ids[start:end] start += 100 end += 100 tweets = api.statuses_lookup(id_batch) for tweet in tweets: all_data.append(dict(tweet._json)) results = [] for entry in all_data: results.append(make_tweet(entry)) print colors.cyan("metadata collection complete!\n") if len(results) is 0: raise EmptyCorpusException("Error: No tweets were collected.") print colors.yellow("creating json file...\n") with open(output_file, 'wb') as outfile: json.dump(results, outfile) import os os.system("say done") # spooky
def read(self): '''Read a packet from 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. Returns (string): the data sent by the remote server. ''' # Read the first <block_len> bytes of the packet, decrypt it if necessary, and parse out the # remaining packet length initial_packet = self._socket.recv(AES_BLOCK_LEN) if self._encryption_negotiated: initial_packet = self._aes_server_to_client.decrypt(initial_packet) _, packet_len = parse_uint32(initial_packet, 0) # Read the remaining bytes of the packet, decrypting if necessary, and checking the MAC remaining_msg = self._socket.recv(packet_len - (AES_BLOCK_LEN - 4)) if self._encryption_negotiated: remaining_msg = self._aes_server_to_client.decrypt(remaining_msg) # Read and verify the MAC received_mac = self._socket.recv(SHA1_LEN) calculated_mac = hmac.new( self._integrity_key_server_to_client, generate_uint32(self._packets_received_counter) + initial_packet + remaining_msg, hashlib.sha1).digest() assert received_mac == calculated_mac, \ 'MACs did not match: %s != %s' % (repr(received_mac), repr(calculated_mac)) print colors.cyan('MAC validated correctly!') # Pull the payload out of the message data = (initial_packet + remaining_msg)[4:] index, padding_len = parse_byte(data, 0) payload_len = packet_len - padding_len - index payload = data[index:payload_len + index] self._packets_received_counter += 1 print colors.green('< Received: %s' % repr(payload)) return payload
def format_goal(name: str, descr: str) -> str: name = name.ljust(chars_before_description) if self._use_color: name = cyan(name) description_lines = textwrap.wrap(descr, 80 - chars_before_description) if len(description_lines) > 1: description_lines = [ description_lines[0], *(f"{' ' * chars_before_description}{line}" for line in description_lines[1:]), ] formatted_descr = "\n".join(description_lines) return f"{name}{formatted_descr}\n"
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 do_new(_parser, args, _mys_config): package_name = os.path.basename(args.path) package_name_title = package_name.replace('_', ' ').title() authors = find_authors(args.authors) try: with Spinner(text=f"Creating package {package_name}"): validate_package_name(package_name) os.makedirs(args.path) path = os.getcwd() os.chdir(args.path) try: create_new_file('package.toml', package_name=package_name, authors=authors) create_new_file('.gitignore') create_new_file('.gitattributes') create_new_file('README.rst', package=package_name.replace('_', '-'), title=package_name.replace('_', ' ').title(), line='=' * len(package_name)) create_new_file('LICENSE') os.mkdir('src') create_new_file('src/lib.mys') create_new_file('src/main.mys') os.mkdir('doc') create_new_file('doc/index.rst', package_name=package_name_title, title_line='=' * len(package_name_title)) finally: os.chdir(path) except BadPackageNameError: box_print([ 'Package names must start with a letter and only', 'contain letters, numbers and underscores. Only lower', 'case letters are allowed.', '', 'Here are a few examples:', '', f'{cyan("mys new foo")}' f'{cyan("mys new f1")}' f'{cyan("mys new foo_bar")}' ], ERROR) raise Exception() cd = cyan(f'cd {package_name}') box_print([ 'Build and run the new package by typing:', '', f'{cd}', f'{cyan("mys run")}' ], BULB, width=53)
def assert_runner( self, workdir: str, config, cmd, extra_config=None, extra_env=None, success=True, expected_runs: int = 1, ): combined_config = config.copy() recursively_update(combined_config, extra_config or {}) print( bold( cyan("\nrunning: ./pants {} (config={}) (extra_env={})".format( " ".join(cmd), combined_config, extra_env)))) run_count = self._run_count(workdir) start_time = time.time() run = self.run_pants_with_workdir(cmd, workdir=workdir, config=combined_config, extra_env=extra_env or {}) elapsed = time.time() - start_time print(bold(cyan(f"\ncompleted in {elapsed} seconds"))) if success: run.assert_success() else: run.assert_failure() runs_created = self._run_count(workdir) - run_count self.assertEqual( runs_created, expected_runs, "Expected {} RunTracker run(s) to be created per pantsd run: was {}" .format(expected_runs, runs_created), ) return run
def lesson3(self): '''Colemak lesson 3 - Letters AO''' self.printHeader(3) # print(' ARST--NEIO- ASDF--JKL;-') print( ' ' + green('A') + cyan('RS') + cyan('T', style='underline') + '-' '-' + cyan('N', style='underline') + cyan('EI') + green('O') + '-' ' ' 'ASD' + underline('F') + '--' + underline('J') + 'KL;-' ) print('\n (colemak) (qwerty)\n') self.tutor.lines([ 'retain roe rant ratio toast sort stat tore earn noose', 'teat eater oat trio tear tone artist nor tattoo seat arise', 'noise start toss tenant oasis one aria no arson sonata ', 'soon rear to ass soot irate sane onset star root state', 'oar errant resort tartan sonnet notes eat rotten stain', 'ration arose reason noon sass retina iota torn stairs', 'iron estate toe are season not attire tenor innate', 'torso tease arisen note tar snort tarot', ])
def print_lint_message(message): location = f'{message["path"]}:{message["line"]}:{message["column"]}' level = message['type'].upper() symbol = message["symbol"] message = message["message"] if level == 'ERROR': level = red(level, style='bold') elif level == 'WARNING': level = yellow(level, style='bold') else: level = cyan(level, style='bold') print(f'{location} {level} {message} ({symbol})')
def check_tweets(self): """ tweet upkeep multi-processing method, can be run continuously to check for anyone tweeting @ the bot """ print(colors.cyan("Beginning polling...\n")) while 1: try: for tweet in tweepy.Cursor(self.api.search, q="@%s -filter:retweets" % self.me, tweet_mode="extended").items(): respond(tweet) except tweepy.TweepError as e: print RED + e.api_code + RESET sleep(30)
def printChars(): print('{:^20}|{:^14s}|{:^14s}|{:^14s}|'.format(colors.yellow('TYPE'), colors.yellow('ATK'), colors.yellow('DEF'), colors.yellow('HP'))) for chrtype in dictChar.keys(): chrStats = dictChar[chrtype] print('{:^20}|{:^5d}|{:^5d}|{:^5d}|'.format( colors.cyan(chrtype), chrStats['atk'], chrStats['def'], chrStats['hp'])) print() crclass = str(input("So, What are you?")) return crclass
def start(self): # Setup shell auto-complete. def complete(text, state): return (glob.glob(text + "*") + [None])[state] # Auto-complete on tabs. readline.set_completer_delims(" \t\n;") readline.parse_and_bind("tab: complete") readline.set_completer(complete) # Save commands in history file. def save_history(path): readline.write_history_file(path) # If there is an history file, read from it and load the history # so that they can be loaded in the shell. history_path = os.path.expanduser("~/.consolehistory") if os.path.exists(history_path): readline.read_history_file(history_path) # Register the save history at program's exit. atexit.register(save_history, path=history_path) # Main loop. while self.active: prompt = cyan("shell > ") data = raw_input(prompt).strip() # data = self.keywords(data) if not data: continue if data.startswith("!"): os.system(data[1:]) continue root, args = self.parse(data) if root in ("exit", "quit"): self.stop() continue if root in self.cmd.commands: self.cmd.commands[root]["obj"](*args) elif root in __modules__: module = __modules__[root]["obj"]() module.set_args(args) module.run()
def main(): path = sys.argv[1] if path == 0: usage(sys.argv[0]) exit() files_count = len([name for name in os.listdir(path) if os.path.isfile(os.path.join(path, name))]) sys.stdout.write("Total files in dir: %s\n" % str(files_count)) for pe_file in os.listdir(path): if os.path.isfile(os.path.join(path, pe_file)): sys.stdout.write(cyan(("\nFile: " + pe_file + "\n"))) if is_pe_file(os.path.join(path, pe_file)): print_eq_sections(os.path.join(path, pe_file), True) else: print_msg(1, "File is not valid PE") time.sleep(2)
def section(s): return cyan('[{0}]'.format(s))
def banner(s): print(cyan('=' * 63)) print(cyan('- {} {}'.format(s, '-' * (60 - len(s))))) print(cyan('=' * 63))
def _do_user_auth(self): # Ask the server whether it supports doing SSH user auth msg = [] msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_SERVICE_REQUEST'])) msg.append(generate_string(SSH_USERAUTH_STRING)) self._ssh_transport_connection.send(''.join(msg)) # Check that it says yes data = self._ssh_transport_connection.read() index, msg_type = parse_byte(data, 0) assert msg_type == SSH_MSG_NUMS['SSH_MSG_SERVICE_ACCEPT'], \ 'Unknown message type received: %d' % msg_type index, service_name = parse_string(data, index) assert service_name == SSH_USERAUTH_STRING print colors.cyan("Let's do ssh-userauth!") # Ask the server which authentication methods it supports msg = [] msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_USERAUTH_REQUEST'])) msg.append(generate_string(self.username.encode('utf-8'))) msg.append(generate_string('ssh-connection')) msg.append(generate_string('none')) self._ssh_transport_connection.send(''.join(msg)) # Check that publickey is one of them data = self._ssh_transport_connection.read() index, msg_type = parse_byte(data, 0) index, supported_auth_methods = parse_name_list(data, index) index, partial_success_byte = parse_byte(data, index) partial_success = partial_success_byte != 0 assert msg_type == SSH_MSG_NUMS['SSH_MSG_USERAUTH_FAILURE'], \ 'Unknown message type: %d' % msg_type assert 'publickey' in supported_auth_methods, \ 'Server does not support public key authentication' assert not partial_success # Try to public key auth rsa_key = RSA.importKey(open(self.keyfile)) pkcs_key = PKCS1_v1_5.new(rsa_key) msg = [] msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_USERAUTH_REQUEST'])) msg.append(generate_string(self.username.encode('utf-8'))) msg.append(generate_string('ssh-connection')) msg.append(generate_string('publickey')) msg.append(generate_byte(1)) # True: we really do want to authenticate msg.append(generate_string('ssh-rsa')) msg.append(generate_string( generate_string('ssh-rsa') + generate_mpint(rsa_key.e) + generate_mpint(rsa_key.n) )) # Desperately try to figure out how signing works in this silly encapsulating protocol signed_data = generate_string(self._ssh_transport_connection.session_id) + ''.join(msg) # OMG Pycrypto, did it have to be *your* SHA1 implementation? signature = pkcs_key.sign(SHA.new(signed_data)) msg.append(generate_string(generate_string('ssh-rsa') + generate_string(signature))) # Send the public key auth message to the server self._ssh_transport_connection.send(''.join(msg)) data = self._ssh_transport_connection.read() index, msg_type = parse_byte(data, 0) assert msg_type == SSH_MSG_NUMS['SSH_MSG_USERAUTH_SUCCESS'], \ 'Unknown message type: %d' % msg_type print colors.cyan('Successfully user authed!')
def _create_ssh_connection(self): # Read the global request that SSH sends us - this is trying to let us know all host keys, but # it's OpenSSH-specific, and we don't need it data = self._ssh_transport_connection.read() index, msg_type = parse_byte(data, 0) index, request_name = parse_string(data, index) index, want_reply_byte = parse_byte(data, index) want_reply = want_reply_byte != 0 assert msg_type == SSH_MSG_NUMS['SSH_MSG_GLOBAL_REQUEST'] assert request_name == '*****@*****.**' assert not want_reply # Reply to let OpenSSH know that we don't know what they're talking about msg = [] msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_REQUEST_FAILURE'])) self._ssh_transport_connection.send(''.join(msg)) # Actually get started with opening a channel for SSH communication window_size = 1048576 maximum_packet_size = 16384 # Request to open a session channel msg = [] msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_OPEN'])) msg.append(generate_string('session')) msg.append(generate_uint32(self._local_channel_number)) msg.append(generate_uint32(window_size)) msg.append(generate_uint32(maximum_packet_size)) self._ssh_transport_connection.send(''.join(msg)) # Check that a channel was opened successfully data = self._ssh_transport_connection.read() index, msg_type = parse_byte(data, 0) index, recipient_channel = parse_uint32(data, index) index, self._remote_channel_number = parse_uint32(data, index) index, initial_window_size = parse_uint32(data, index) index, maximum_packet_size = parse_uint32(data, index) print colors.cyan('Message type: %d' % msg_type) assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_OPEN_CONFIRMATION'] assert recipient_channel == self._local_channel_number print colors.cyan('Remote channel number: %d' % self._remote_channel_number) print colors.cyan('Initial window size: %d' % initial_window_size) print colors.cyan('Maximum window size: %d' % maximum_packet_size) # Ask to turn that session channel into a shell msg = [] msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_CHANNEL_REQUEST'])) msg.append(generate_uint32(self._remote_channel_number)) msg.append(generate_string('shell')) msg.append(generate_byte(1)) # True, we do want a reply here self._ssh_transport_connection.send(''.join(msg)) # OpenSSH then asks to increase their window size, that's fine, do it data = self._ssh_transport_connection.read() index, msg_type = parse_byte(data, 0) index, recipient_channel = parse_uint32(data, index) index, bytes_to_add = parse_uint32(data, index) assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_WINDOW_ADJUST'] initial_window_size += bytes_to_add # Check that they tell us they've opened a channel successfully data = self._ssh_transport_connection.read() index, msg_type = parse_byte(data, 0) assert msg_type == SSH_MSG_NUMS['SSH_MSG_CHANNEL_SUCCESS'] assert recipient_channel == self._local_channel_number print colors.cyan('Successfully opened shell!')
def section(s): return cyan("[{0}]".format(s))
hero_count, (hero_count / float(total_flaired)) * 100, hero_change2[hero], hero_change[hero] ))) write_score(i+1, hero, hero_count, (hero_count / float(total_flaired)) * 100, hero_change2[hero], hero_change[hero]) print_file(color_text, "\t[{0}]\t{1:<10} : {2:<5} - {3:>5.2f}% {4:<5} {5:<3}".format( i+1, hero, hero_count, (hero_count / float(total_flaired)) * 100, hero_change2[hero], hero_change[hero] )) hero_ranks[hero] = i total_flaired = conn.execute('select count(1) from user where flair_id != 1').fetchone()[0]; total_users = conn.execute('select count(1) from user').fetchone()[0]; flair_percentage = "\n\t({0} / {1}) - {2:.2f}% users flaired".format(total_flaired, total_users, (total_flaired / float(total_users)) * 100) print(cyan(flair_percentage)) print_file('cyan', flair_percentage) first = False print_end() time.sleep(15)
tokens_list = parse_expr.parse_expr(expr) expression_type = EXPR_TYPES[INFIX] for tokens in tokens_list: current_count = current_count + 1 rpn_expr = [] solution = "" if tokens == ["quit"]: sys.exit(0) elif len(tokens) > 0 and tokens[0] == "infix": expression_type = EXPR_TYPES[0] tokens = tokens[1:] elif len(tokens) > 0 and tokens[0] == "rpn": expression_type = EXPR_TYPES[1] rpn_expr = tokens[1:] if tokens != [] and expression_type == EXPR_TYPES[0]: rpn_expr = compile_to_rpn.compile_to_rpn(tokens) if rpn_expr != [] or expression_type == EXPR_TYPES[1]: solution = solve_rpn.solve_rpn(rpn_expr) if solution != "": print colors.green("Result(") + colors.cyan(str(current_count)) + colors.green("): ") + colors.blue(str(solution)) print ""
def begin_new_game(): print('\033c') print('\nHere is your character:', new_player.name) print('\n', red('Health: '), new_player.health, '| ', cyan('Dexterity: '), new_player.dexterity, '| ', yellow('Luck: '), new_player.luck) print('\nYour inventory contains: ', new_player.inventory, '\n') main(begin_new_game_menu)
def sect(s): return cyan('[{}]'.format(s))
def _run_diffie_hellman_group14_sha1_key_exchange(self, server_kex_init, client_kex_init): # q, g, and p from https://tools.ietf.org/html/rfc3526#section-3 q = 2 ** 2048 g = 2 p = int(''' 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E34 04DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F4 06B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8 FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E 462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2 261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF '''.replace(' ', '').replace('\n', ''), 16) x = random.SystemRandom().randint(2, q - 1) e = pow(g, x, p) # Send public key to server msg = [] msg.append(generate_byte(SSH_MSG_NUMS['SSH_MSG_KEXDH_INIT'])) msg.append(generate_mpint(e)) self.send(''.join(msg)) # Receive (K_S || f || s) from the server # i.e. host key blob, f, and the signature, from the server msg = self.read() index, ssh_msg_type = parse_byte(msg, 0) assert ssh_msg_type == SSH_MSG_NUMS['SSH_MSG_KEXDH_REPLY'] index, host_key_blob = parse_string(msg, index) index, f = parse_mpint(msg, index) index, signature = parse_string(msg, index) # Calculate a verifying key from the host key blob verifying_key = self._get_verifying_key(host_key_blob) # Also calculate the shared key, exchange hash, and session ID (this is the same as the exchange # hash) shared_key = pow(f, x, p) hashed_data = \ generate_string(self._client_id_string.strip('\r\n')) + \ generate_string(self._server_id_string.strip('\r\n')) + \ generate_string(client_kex_init) + \ generate_string(server_kex_init) + \ generate_string(host_key_blob) + \ generate_mpint(e) + \ generate_mpint(f) + \ generate_mpint(shared_key) exchange_hash = hashlib.sha1(hashed_data).digest() self.session_id = exchange_hash # Pull out the signature blob from the message index, ecdsa_identifier = parse_string(signature, 0) assert ecdsa_identifier == SERVER_HOST_KEY_ALGORITHM, \ 'Unknown signature type: %s' % ecdsa_identifier index, signature_blob = parse_string(signature, index) index, r = parse_mpint(signature_blob, 0) index, s = parse_mpint(signature_blob, index) # Verify that the signature on the message is correct assert verifying_key.verify( get_32_byte_repr(r) + get_32_byte_repr(s), exchange_hash, hashfunc=hashlib.sha256, sigdecode=ecdsa.util.sigdecode_string ) print colors.cyan('Signature validated correctly! OMG!') # Derive *all* the keys! key_derivation_options = { 'shared_key': shared_key, 'exchange_hash': exchange_hash, 'session_id': self.session_id, } # Client to server keys (these hard-coded ASCII letters brought to you by the RFC's key # derivation function: https://tools.ietf.org/html/rfc4253#section-7.2) initial_iv_client_to_server = _derive_encryption_key( key_derivation_options, 'A', AES_BLOCK_LEN) ctr = Counter.new( AES_BLOCK_LEN * 8, initial_value=int(initial_iv_client_to_server.encode('hex'), AES_BLOCK_LEN)) encryption_key_client_to_server = _derive_encryption_key( key_derivation_options, 'C', AES_BLOCK_LEN) self._aes_client_to_server = AES.new(encryption_key_client_to_server, AES.MODE_CTR, counter=ctr) self._integrity_key_client_to_server = _derive_encryption_key(key_derivation_options, 'E') # Server to client keys initial_iv_server_to_client = _derive_encryption_key( key_derivation_options, 'B', AES_BLOCK_LEN) ctr = Counter.new( AES_BLOCK_LEN * 8, initial_value=int(initial_iv_server_to_client.encode('hex'), AES_BLOCK_LEN)) encryption_key_server_to_client = _derive_encryption_key( key_derivation_options, 'D', AES_BLOCK_LEN) self._aes_server_to_client = AES.new(encryption_key_server_to_client, AES.MODE_CTR, counter=ctr) self._integrity_key_server_to_client = _derive_encryption_key(key_derivation_options, 'F')