def diff_all_table_data(self): failures = 0 print(bold(red('Starting table analysis.'))) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=sa_exc.SAWarning) tables = sorted( self.firstinspector.get_table_names(schema=self.schema)) if len(tables) == 0: print(bold(red(f'No tables found in schema: {self.schema}'))) return 0 for table in tables: if table in self.exclude_tables: print(bold(yellow(f"Ignoring table {table}"))) continue with Halo(text=f"Analysing table {table}. " f"[{tables.index(table) + 1}/{len(tables)}]", spinner='dots') as spinner: result, message = self.diff_table_data(table) if result is True: spinner.succeed(f"{table} - {message}") elif result is None: spinner.warn(f"{table} - {message}") else: failures += 1 spinner.fail(f"{table} - {message}") print(bold(green('Table analysis complete.'))) if failures > 0: return 1 return 0
def menu(): phone_book = {} while True: print(yellow("\n1-Mostrar lista de contactos")) print(yellow("2-Añadir contacto (nombre y teléfono)")) print(yellow("3-Borrar contacto (nombre)")) print(yellow("4-Salir\n")) menu = input("¿Menú a elegir?: ") if menu == "1": show_contacts(phone_book) elif menu == "2": name = input(green("¿Contacto que desea añadir?: ")) if name not in phone_book: phone = input(green("¿Número de contacto?: ")) add_contact(phone_book, name, phone) else: print(red("ERROR: este contacto ya existe")) elif menu == "3": name = input(green("¿Contacto que desea eliminar?: ")) remove_contact(phone_book, name) elif menu == "4": break else: print(red("ERROR: menú incorrecto!!"))
def annotated_source(sourcefile, marks=None, annotations=None, context=3, mark='*'): marks = marks or [] annotations = annotations or {} interresting = set(marks) | set(annotations) printed = [range(n - context, n + context + 1) for n in interresting] printed = set(sum(printed, [])) lastprinted = 0 with codecs.open(sourcefile, 'r', 'utf-8', 'replace') as f: print yellow(sourcefile) for n, line in enumerate(f, 1): if n in printed: m = red(mark if n in marks else ' ' * len(mark)) c = line.rstrip().expandtabs() if n in marks: c = red(c) if n in annotations: a = yellow('# ' + annotations[n]) else: a = '' print ' %4i %s %-80s %s' % (n, m, c, a) lastprinted = n elif lastprinted == n - 1: print bold(black(' %4s' % ('.' * len(str(n))))) else: pass
def pcapopen(fn = None): from pcap import pcapObject p = pcapObject() try: if fn: p.open_offline(fn) else: p.open_live('any' , 200, False, 100) p.dispatch(-1,cb) except Exception as e: print bold(red('error:')),red(str(e)) pass
def _printNode(self, key, val, padding='', last=False, maxdepth=None, maxcount=None): from fabulous.color import highlight_blue, red, blue, green, cyan, yellow, bold from tables import Array if isinstance(val, H5Node): val.printTree(padding=padding, last=last, maxdepth=maxdepth, maxcount=maxcount) else: if isinstance(val, Array): val = yellow('Array(%s,__dtype__=%s)' % (','.join(str(i) for i in val.shape), val.dtype)) elif isinstance(val, Table): val = green(val) else: val = red('%s,__dtype__=%s' % (str(val), type(val).__name__)) if last: print '%s `%s [%s]' % (padding[:-1], cyan(key), val) else: print '%s`%s [%s]' % (padding, cyan(key), val)
def make(items): for name, props in items: print print "make: %s" % (cyan(name)) print "-"*30 # move to this files parent directory and then to the bundle directory os.chdir(dirname + "/..") os.chdir(props["dir"]) for cmd in props["make"]: print yellow(cmd) c = subprocess.call(cmd_gen(cmd)) if c != 0: print red("Error encountered (%s: %s)" % (cyan(name), yellow(cmd))) sys.exit()
def main(): arguments = docopt(__doc__, version=pkg_resources.require("pgdatadiff")[0].version) first_db_connection_string = arguments['--firstdb'] second_db_connection_string = arguments['--seconddb'] chunk_size = arguments['--chunk-size'] count_only = arguments['--count-only'] full_data = arguments['--full-data'] only_sequences = arguments['--only-sequences'] if not first_db_connection_string.startswith("postgres://") or \ not second_db_connection_string.startswith("postgres://"): print(red("Only Postgres DBs are supported")) return 1 #doDiff(first_db_connection_string, second_db_connection_string, chunk_size, count_only, full_data, only_sequences, thread_number = 1) # ThreadCount should be equal in threads = 30 # Make the Pool of workers pool = ThreadPool(threads) for thread_number in range(threads): #print(thread_number) pool.apply_async(doDiff, args=( first_db_connection_string, second_db_connection_string, chunk_size, count_only, full_data, only_sequences, threads, thread_number, )) pool.close() pool.join() #differ = DBDiff(first_db_connection_string, second_db_connection_string, # chunk_size=arguments['--chunk-size'], # count_only=arguments['--count-only'], # full_data=arguments['--full-data'], # thread_number=thread_number) #if not arguments['--only-sequences']: # if differ.diff_all_table_data(): # if differ2.diff_all_table_data(): # return 1 #if not arguments['--only-data']: # if differ.diff_all_sequences(): # if differ2.diff_all_sequences(): # return 1 return 0
def count(self): ''' This scenario lets the drone count all the objects on a predefined trajectory ''' print highlight_magenta( ' COUNTING STARTED ') print magenta('fly to start point!') counting_list = [[50], [51], [52], [53], [54], [55], [56], [57], [58], [59], [60], [61], [62], [63], [64], [65], [66], [67], [68], [69], [70], [71], [72], [73], [74], [75], [76], [77], [78], [79]] red_c = 0 blue_c = 0 green_c = 0 counted_list = [] while [11] not in self.ids: rospy.sleep(0.5) print magenta('starting to count') while [12] not in self.ids: for i in self.ids: if i in counting_list: counting_list.remove(i) counted_list.append(i) print magenta(' >>> found one <<< ') rospy.sleep(0.5) for i in counted_list: if 50 <= i[0] <= 59: red_c += 1 elif 60 <= i[0] <= 69: blue_c += 1 elif 70 <= i[0] <= 79: green_c += 1 print highlight_magenta( ' REPORT ') print red(' red:' + str(red_c)) print blue(' blue:' + str(blue_c)) print green(' green:' + str(green_c)) print highlight_magenta( ' COUNTING COMPLETED ') self.task_str = ""
def run_as_checker(args): """Check for outstanding TODOs""" outstanding = [] with open(args.file, 'r') as todofile: for line in todofile.readlines(): if dt.today() > dt.strptime(line[:10], '%Y-%m-%d'): outstanding.append(line) if outstanding: print(color.bold(color.red( 'Warning! You should have already done this!:\n' '--------------------------------------------'))) for todo in outstanding: print(todo[:-1])
def run_as_checker(args): """Check for outstanding TODOs""" outstanding = [] with open(args.file, 'r') as todofile: for line in todofile.readlines(): if dt.today() > dt.strptime(line[:10], '%Y-%m-%d'): outstanding.append(line) if outstanding: print( color.bold( color.red('Warning! You should have already done this!:\n' '--------------------------------------------'))) for todo in outstanding: print(todo[:-1])
def diff_all_sequences(self): print(bold(red('Starting sequence analysis.'))) sequences = sorted(self.get_all_sequences()) for sequence in sequences: with Halo(text=f"Analysing sequence {sequence}. " f"[{sequences.index(sequence) + 1}/{len(sequences)}]", spinner='dots') as spinner: result, message = self.diff_sequence(sequence) if result is True: spinner.succeed(f"{sequence} - {message}") elif result is None: spinner.warn(f"{sequence} - {message}") else: spinner.fail(f"{sequence} - {message}") print(bold(green('Sequence analysis complete.')))
def error(msg, stacktrace=None): """Print an error message and exit. Params: ------- msg: str Error message. stacktrace: str Stacktrace. """ if stacktrace: print(stacktrace) print(bold(red(msg))) sys.exit(1)
def diff_all_sequences(self): print(bold(red('Starting sequence analysis.'))) sequences = sorted(self.get_all_sequences()) failures = 0 for sequence in sequences: status_update = StatusUpdate( f"Analysing sequence {sequence}. " f"[{sequences.index(sequence) + 1}/{len(sequences)}]") result, message = self.diff_sequence(sequence) status_update.complete(result, f"{sequence} - {message}") if result is False: failures += 1 print(bold(green('Sequence analysis complete.'))) if failures > 0: return 1 return 0
def main(): arguments = docopt(__doc__, version=pkg_resources.require("pgdatadiff")[0].version) first_db_connection_string = arguments['--firstdb'] second_db_connection_string = arguments['--seconddb'] if not first_db_connection_string.startswith("postgres://") or \ not second_db_connection_string.startswith("postgres://"): print(red("Only Postgres DBs are supported")) return 1 differ = DBDiff(first_db_connection_string, second_db_connection_string, chunk_size=arguments['--chunk-size']) if not arguments['--only-sequences']: differ.diff_all_table_data() if not arguments['--only-data']: differ.diff_all_sequences()
def _printNode(self, key, val, padding= '', last=False,maxdepth=None,maxcount=None): from fabulous.color import highlight_blue,red,blue,green,cyan,yellow,bold from tables import Array if isinstance(val,H5Node): val.printTree(padding=padding,last=last,maxdepth=maxdepth,maxcount=maxcount) else: if isinstance(val,Array): val = yellow('Array(%s,__dtype__=%s)'% (','.join(str(i) for i in val.shape),val.dtype)) elif isinstance(val,Table): val = green(val) else: val = red('%s,__dtype__=%s' % (str(val),type(val).__name__)) if last: print '%s `%s [%s]' % (padding[:-1], cyan(key), val ) else: print '%s`%s [%s]' % (padding, cyan(key), val )
def diff_all_table_data(self): print(bold(red('Starting table analysis.'))) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=sa_exc.SAWarning) tables = sorted( self.firstinspector.get_table_names(schema="public")) for table in tables: with Halo(text=f"Analysing table {table}. " f"[{tables.index(table) + 1}/{len(tables)}]", spinner='dots') as spinner: result, message = self.diff_table_data(table) if result is True: spinner.succeed(f"{table} - {message}") elif result is None: spinner.warn(f"{table} - {message}") else: spinner.fail(f"{table} - {message}") print(bold(green('Table analysis complete.')))
def menu(): exit = False while not exit: print(""" 1. Chequear si un número es par ó impar. 2. Salir. """) option = input("") if option == "1": v = read_int() if is_even(v): print(green("El número es par!")) else: print(red("El número es impar!")) elif option == "2": print("👋🏻 Hasta luego Lucas!") exit = True else: print(red_bg("La opción elegida no existe!"))
def main(): arguments = docopt(__doc__) first_db_connection_string = arguments['--firstdb'] second_db_connection_string = arguments['--seconddb'] if not first_db_connection_string.startswith("postgres://") or \ not second_db_connection_string.startswith("postgres://"): print(red("Only Postgres DBs are supported")) return 1 differ = DBDiff(first_db_connection_string, second_db_connection_string, chunk_size=arguments['--chunk-size'], count_only=arguments['--count-only'], tables=arguments['--tables']) if not arguments['--only-sequences']: if differ.diff_all_table_data(): return 1 if not arguments['--only-data']: if differ.diff_all_sequences(): return 1 return 0
def diff_all_table_data(self): failures = 0 self.create_aggregate_functions() print(bold(red('Starting table analysis.'))) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=sa_exc.SAWarning) tables = sorted( self.firstinspector.get_table_names(schema="public")) for table in tables: status_update = StatusUpdate( f"Analysing table {table}. " f"[{tables.index(table) + 1}/{len(tables)}]") result, message = self.diff_table_data(table) status_update.complete(result, f"{table} - {message}") if result is False: failures += 1 print(bold(green('Table analysis complete.'))) if failures > 0: return 1 return 0
def diff_all_sequences(self, thread_number): # run just once if thread_number > 0: return 0 print(bold(red('Starting sequence analysis.'))) sequences = sorted(self.get_all_sequences()) failures = 0 for sequence in sequences: with Halo(text=f"Analysing sequence {sequence}. " f"[{sequences.index(sequence) + 1}/{len(sequences)}]", spinner='dots') as spinner: result, message = self.diff_sequence(sequence) if result is True: spinner.succeed(f"{sequence} - {message}") elif result is None: spinner.warn(f"{sequence} - {message}") else: failures += 1 spinner.fail(f"{sequence} - {message}") print(bold(green('Sequence analysis complete.'))) if failures > 0: return 1 return 0
), 'INFO': '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'), module=col.cyan(('{r.module}')), levelname=col.green('{r.levelname}'), msg=col.bold(col.yellow('{r.msg}')), ), 'WARNING': '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'), module=col.cyan(('{r.module}')), levelname=col.bold(col.magenta('{r.levelname}')), msg=col.bold(col.yellow('{r.msg}')), ), 'ERROR': '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'), module=col.cyan(('{r.module}')), levelname=col.red('{r.levelname}'), msg=col.red('{r.msg}'), ), 'CRITICAL': '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'), module=col.cyan(('{r.module}')), levelname=col.bold(col.red('{r.levelname}')), msg=col.red('{r.msg}'), ), }
def show_contacts(phone_book): if phone_book == {}: print(red("No hay contactos en Phone_book")) else: for name, phone in phone_book.items(): print(cyan(name, ":", phone))
def assign(self, args): print(color.red(args))
import sys import os import config from fabulous.color import green, red, fg256 if sys.argv[1] == "open": os.system("picocom /dev/{} -b 115200".format(config.TTY_HANDLER)) elif sys.argv[1] == "deploy": print( fg256( "#e67e22", """ If it hangs on 'Connected to esp8266': - Be sure you are not connected in other session to TTY. If so, disconnect and try it again! - Otherwise, press CTRL-C, reset the NodeMCU by pressing the button on the board and try it again! """)) with open('uconfig.py', 'w') as f: f.write(f'DWEET_THING = "{config.DWEET_THING}"{os.linesep}') f.write(f'WIFI_SSID = "{config.WIFI_SSID}"{os.linesep}') f.write(f'WIFI_PASSWORD = "******"{os.linesep}') files = ";".join(f"put {file}" for file in config.FILES_TO_DEPLOY) error = os.system("mpfshell -n -c 'open {}; {}'".format( config.TTY_HANDLER, files)) if error: print(red("Deploy failed!")) else: print(green("All files were deployed successfully!!")) else: print("⚠️ Unknown option!")
def _colorize(success): if success: return green(" OK ") else: return red(" FAIL ")
def start_search(args: argparse.Namespace): """ This function is separated out in order to use code as module """ start_time = time.time() args.ignore = args.ignore + ["build", "\.min\.js", ".git"] # compile for performance reasons try: ignore_re = re.compile("a^") if args.ignore: ignore_re = re.compile("|".join(args.ignore)) filename_re = re.compile(".*") if args.filename: filename_re = re.compile("|".join(args.filename)) if args.lower or args.regex != args.regex.lower(): search_re = re.compile(args.regex) else: search_re = re.compile(args.regex, flags=re.IGNORECASE) except re.error as e: print(color.red("Error, bad regular expression:")) raise # get numworkers # default to numcores # backup is 6 or specified by user try: numworkers = mp.cpu_count() except NotImplementedError: numworkers = args.workers or 6 search_queue = mp.Queue() output = mp.Queue() final_queue = mp.Queue() # Use final queue for external output processes = [] indexer = mp.Process( name="indexer", target=index_worker, args=( args.directories, ignore_re, filename_re, numworkers, search_queue, args.depth, ), ) indexer.start() processes.append(indexer) for i in range(numworkers): worker = mp.Process( name="worker-{}".format(i + 1), target=file_searching_worker, args=(search_re, args.replace, search_queue, output), ) worker.start() processes.append(worker) printer = mp.Process( name="printer", target=print_worker, args=(start_time, numworkers, output, final_queue, args.pipe, args.edit), ) printer.start() processes.append(printer) return processes, final_queue
t_r = 0 if (args.RandomTest): env.Set_Randomization(default=False) else: env.incline_deg = args.WedgeIncline env.incline_ori = math.radians(args.WedgeOrientation) env.SetFootFriction(args.FrictionCoeff) env.SetLinkMass(0, args.FrontMass) env.SetLinkMass(11, args.BackMass) env.clips = args.MotorStrength env.pertub_steps = 300 env.y_f = args.PerturbForce state = env.reset() print(bold(blue("\nTest Parameters:\n")), green('\nWedge Inclination:'), red(env.incline_deg), green('\nWedge Orientation:'), red(math.degrees(env.incline_ori)), green('\nCoeff. of friction:'), red(env.friction), green('\nMass of the front half of the body:'), red(env.FrontMass), green('\nMass of the rear half of the body:'), red(env.BackMass), green('\nMotor saturation torque:'), red(env.clips)) log = env._pybullet_client.startStateLogging( fileName="stochsidehill.mp4", loggingType=env._pybullet_client.STATE_LOGGING_VIDEO_MP4) env._pybullet_client.resetDebugVisualizerCamera(1, 90, -20, [1, 0, 0]) for i_step in range(args.EpisodeLength): action = policy.dot(state) # action = [1.0,1.0,1.0,1.0, # 1.0,1.0,1.0,1.0, # 0.0,0.0,0.0,0.0,
def pronoun(self, args): print(color.red(args))
import sys from fabulous import text try: from BeautifulSoup import BeautifulSoup except ImportError: from bs4 import BeautifulSoup from humanfriendly.tables import format_pretty_table from fabulous.color import highlight_green, green, red, yellow baku_header = [ highlight_green('Qatar №-si'.decode("utf-8").strip()), green('Bakıdan çıxma'.decode("utf-8").strip()), green('Biləcəriyə çatma'.decode("utf-8").strip()), yellow('Biləcəridən getmə'.decode("utf-8").strip()), yellow('Xırdalana çatma'.decode("utf-8").strip()), red('Xırdalandan getmə'.decode("utf-8").strip()), red('Sumqayıta çatma'.decode("utf-8").strip()) ] sum_header = [ highlight_green('Qatar №-si'.decode("utf-8").strip()), green('Sumqayıtdan çıxma'.decode("utf-8").strip()), green('Xırdalana çatma'.decode("utf-8").strip()), yellow('Xırdalana getmə'.decode("utf-8").strip()), yellow('Biləcəriyə çatma'.decode("utf-8").strip()), red('Biləcəriyə getmə'.decode("utf-8").strip()), red('Bakıya çatma'.decode("utf-8").strip()) ] baku_table = [] sum_table = []
def print_worker( start_time: float, worker_count: int, output: mp.Queue, final_queue: mp.Queue, pipemode: bool, editmode: bool, ) -> None: file_count = 0 found_count = 0 exit_count = 0 line_count = 0 file_list = [] while True: statement = output.get() if statement[0] == "EXIT": exit_count += 1 line_count += statement[1] file_count += statement[2] found_count += statement[3] if exit_count == worker_count: break else: if len(statement) == 4: filename, linenum, matched, line = statement replace = None else: filename, linenum, matched, line, replace = statement final_queue.put(filename, linenum) if pipemode: print("{} {} {}".format(filename, linenum, matched)) else: print("{}:{}\n\t{}".format( filename, color.fg256("#00ff00", linenum), insert_colour(matched, line, extra_str=replace), )) file_list.append((statement[1], statement[0])) final_queue.put("EXIT") if not pipemode: print(("---------------\n" "Files Searched: {:,}\n" "Files Matched: {:,}\n" "Lines Searched: {:,}\n" "Duration: {:.3f}").format(file_count, found_count, line_count, time.time() - start_time)) if editmode: files_to_edit = ["+{} {}".format(num, name) for num, name in file_list] call_args = [_ for _ in files_to_edit[0].split(" ")] orientation = 0 for f in files_to_edit[1:]: call_args.append('+"{} {}"'.format("sp" if orientation else "vsp", f)) orientation ^= 1 if len(call_args) > 10: print( color.red( "Cowardly only accepting the first 10 files for editing")) call_string = "{} {}".format(EDITOR, " ".join(call_args[:10])) subprocess.call(call_string, shell=True)
def print_worker( start_time: float, worker_count: int, output: mp.Queue, final_queue: mp.Queue, pipemode: bool, editmode: bool, ) -> None: file_count = 0 found_count = 0 exit_count = 0 line_count = 0 file_list = [] while True: statement = output.get() if statement[0] == "EXIT": exit_count += 1 line_count += statement[1] file_count += statement[2] found_count += statement[3] if exit_count == worker_count: break else: if len(statement) == 4: filename, linenum, matched, line = statement replace = None else: filename, linenum, matched, line, replace = statement final_queue.put(filename, linenum) if pipemode: print("{} {} {}".format(filename, linenum, matched)) else: print( "{}:{}\n\t{}".format( filename, color.fg256("#00ff00", linenum), insert_colour(matched, line, extra_str=replace), ) ) file_list.append((statement[1], statement[0])) final_queue.put("EXIT") if not pipemode: print( ( "---------------\n" "Files Searched: {:,}\n" "Files Matched: {:,}\n" "Lines Searched: {:,}\n" "Duration: {:.3f}" ).format(file_count, found_count, line_count, time.time() - start_time) ) if editmode: files_to_edit = ["+{} {}".format(num, name) for num, name in file_list] call_args = [_ for _ in files_to_edit[0].split(" ")] orientation = 0 for f in files_to_edit[1:]: call_args.append('+"{} {}"'.format("sp" if orientation else "vsp", f)) orientation ^= 1 if len(call_args) > 10: print(color.red("Cowardly only accepting the first 10 files for editing")) call_string = "{} {}".format(EDITOR, " ".join(call_args[:10])) subprocess.call(call_string, shell=True)
def remove_contact(phone_book, name): if name in phone_book: del (phone_book[name]) else: print(red("ERROR: este contacto no existe"))
stairs=False, seed_value=args.seed, on_rack=False, gait='trot') steps = 0 t_r = 0 if (args.RandomTest): env.Set_Randomization(default=False) else: env.incline_deg = args.WedgeIncline env.incline_ori = math.radians(args.WedgeOrientation) state = env.reset() print(bold(blue("\nTest Parameters:\n")), green('\nWedge Inclination:'), red(env.incline_deg), green('\nWedge Orientation:'), red(math.degrees(args.WedgeOrientation)), green('\nCoeff. of friction:'), red(env.friction), green('\nMotor saturation torque:'), red(env.clips)) for i_step in range(args.EpisodeLength): print('Roll:', math.degrees(env.support_plane_estimated_roll), 'Pitch:', math.degrees(env.support_plane_estimated_pitch)) action = policy.dot(state) # action = [1.0,1.0,1.0,1.0, # 0.0,0.0,0.0,0.0, # -1.0,-1.0,-1.0,-1.0, # -1.0,-1.0,-1.0,-1.0, # 0.0,0.0,0.0,0.0 ] # action = [0.5,0.5,0.5,0.5, # 0,0,0,0,
env.Set_Randomization(default=False) else: env.incline_deg = args.WedgeIncline env.incline_ori = math.radians(args.WedgeOrientation) env.SetFootFriction(args.FrictionCoeff) # env.SetLinkMass(0,args.FrontMass) # env.SetLinkMass(11,args.BackMass) env.clips = args.MotorStrength env.pertub_steps = 300 env.y_f = args.PerturbForce state = env.reset() print( bold(blue("\nTest Parameters:\n")), green('\nWedge Inclination:'), red(env.incline_deg), green('\nWedge Orientation:'), red(math.degrees(env.incline_ori)), green('\nCoeff. of friction:'), red(env.friction), # green('\nMass of the front half of the body:'),red(env.FrontMass), # green('\nMass of the rear half of the body:'),red(env.BackMass), green('\nMotor saturation torque:'), red(env.clips)) # Simulation starts simstep = 1000 plot_data = [] t_r = 0 for i_step in range(simstep): action = np.array([
def send_message(): #keep sending messages until user sends :exit while (True): global Message global firstMessage global NextKey global currentKey global ip global sameMessage global sameKeys global counter #check if same key has to be used for encryption in case of retransmission if (not sameKeys): if (firstMessage): currentKey = sharedKey NextKey = randint(1, 127) firstMessage = False else: currentKey = NextKey NextKey = randint(1, 127) else: sameKeys = False if (not sameMessage): Message = input("Enter the message here : ") else: sameMessage = False # add shared key and next key to the message as a single character payload = Message + chr(sharedKey) + chr(NextKey) #generate hash hash = sha256(payload.encode()).hexdigest() #encrypt the message cipher = encrypt(payload + hash, currentKey) sock.sendto((str(counter) + str(cipher)).encode(), ip) f.write(str(counter) + "." + "\n") f.write("Message sent : " + Message + "\n") f.write("Next Key : " + str(NextKey) + "\n") f.write("Message with payload : " + payload + "\n") f.write("Hash of the message with payload : " + hash + "\n") f.write("Encrption : " + cipher + "\n") #check if ack recieved or not try: data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes except Exception: print( bold( red("Connection timed out. ACK not received. Sending the message again\n" ))) f.write( "Connection timed out. ACK not received. Sending the message again" + "\n") sameMessage = True sameKeys = True continue #check if ack/nack received valid = int(data.decode()[0:]) if (valid == 0): print( bold( red("NACK recieved. Generating and exchanging keys again. Sending the message again \n" ))) f.write( "NACK recieved. Generating and exchanging keys again. Sending the message again \n" ) counter = 0 firstMessage = True sameMessage = True diffie_hellman() break else: f.write("ACK recieved\n") counter = counter + 1 f.write("\n") #end connection if :exit sent if (Message == ":exit"): end_connection() break
def red(self): return ansi(c.red(self.txt))