async def on_message(self, message): global points if message.author == client.user: return if message.content.lower().startswith("!cowsay"): if points < 1: await client.send_message(message.channel, "Additional consumptions required.") return points -= 1 update_points() say = " ".join(message.content.split()[1:]) old_stdout = sys.stdout sys.stdout = mystdout = StringIO() cowsay.cow(say) sys.stdout = old_stdout msg = "```" + mystdout.getvalue() + "```" for i in range(len(msg)): if msg[i] == '/' and msg[i - 1] == '\\': msg = msg[:i + 1] + '\\\n' + ( (7 + (len(say) if len(say) < 49 else 49) - 2) * ' ') + msg[i + 1:] break await client.send_message(message.channel, msg)
def cowsay(update: Update, context: CallbackContext): with io.StringIO() as buf, redirect_stdout(buf): try: cow(update.message.text.split(' ', 1)[1]) except IndexError: update.message.reply_text("Error: Write something after the command!") else: update.message.reply_text(f"`{buf.getvalue()}`", parse_mode="Markdown")
def scanner(encoding_correct, auto_correction, patterns_input_file, output_file): """ Simple sh code scanner for rilocabile migration. It scan and check for wrong patterns and create a little report in YAML format """ logging.info( f"Called with parameters: {encoding_correct}, {auto_correction}, {patterns_input_file}, {output_file}" ) # Patterns to search for in sh files, read from yaml file # patterns is a dictionary of lists yh = YamlHelper() patterns = yh.read_yaml(patterns_input_file) if not patterns: print( click.style( f"Error loading patterns file. Check {patterns_input_file}", fg='red', bg='white')) exit() # Dictionary with scanner issues/results scanner_result = {} # Main cycle on all the files # Note: in this case progress bar does not work because len of iterator is not known base_path = Path('.') with click.progressbar(base_path.glob('**/*.sh')) as bar: for name in bar: logging.debug(f"Checking encoding for file {name}") try: sh = CodeFileScanner(name, encoding_correct, patterns, auto_correction) sh.check_encoding() sh.check_patterns() except Exception as e: logging.error(f'Impossible to do checking for file: {name}') print( click.style( f'Impossible to do checking for file: {name}; exception {e}', fg='red', bg='white')) # If any issues, add them to the dictionary if sh.issues: scanner_result.setdefault(str(name), []).append(sh.issues) # Managing final output logging.debug(f"Dictionary with output: {scanner_result}") if yh.write_yaml(output_file, scanner_result): #print(click.style(f"Output in file {output_file}", fg='green', bg='white')) cowsay.cow(f"Complete and detailed output in file: \n{output_file}") else: print( click.style( f"Error writing output file. Check {output_file} and log files", fg='red', bg='white'))
def ask_questions(list_of_sums): answered_questions = [] for sum in list_of_sums: clear() maths_symbol = get_sum_type(sum.sum_type) formatted_sum = f"{sum.number_1} {maths_symbol} {sum.number_2} = ?" cowsay.cow(formatted_sum) user_answer = input("Please enter your answer: ") sum.user_answer = user_answer answered_questions.append(sum) return answered_questions
async def cowsay(self, ctx, *, text: commands.clean_content): """Cow says whatever text you give.""" old_stdout = sys.stdout sys.stdout = redir_stdout = StringIO() cowsay.cow(text) out = redir_stdout.getvalue() sys.stdout = old_stdout await ctx.send(f"```{out}```")
def main(): # Read arguments from command line parser = argparse.ArgumentParser( description= 'Python Port Scanner made by Borba for the Hacker Technologies class.') parser.add_argument( 'hosts', type=str, help='IP from machine or network to be scanned. E.g. "192.168.50.250".' ) # args.hosts parser.add_argument( '-r', '--range', type=str, help='Range of ports to be scanned. Default: "22-443".', default='22-443') # args.range parser.add_argument('--tcp', action="store_true", help='Enable TCP scan. Default: False.', default=False) # args.tcp parser.add_argument('--udp', action="store_true", help='Enable UDP scan. Default: False.', default=False) # args.udp args = parser.parse_args() # Greet message (completely optional) cowsay.cow("Welcome to Borba's Port Scanner") # Instantiate portscanner and begin scanning nm = nmap.PortScanner() portscanner_args = parse_arguments(args.range, args.tcp, args.udp) nm.scan(hosts=args.hosts, arguments=portscanner_args) # Print results print('Host --|-- Port/Protocol --|-- Status --|-- Service --|-- Version') for host in nm.all_hosts(): for proto in nm[host].all_protocols(): lport = nm[host][proto].keys() for port in lport: host_name = f'{term_colors.bold}{host} ({nm[host].hostname()}){term_colors.reset}' port_proto = f'{term_colors.lightcyan}{port}/{proto}{term_colors.reset}' state = state_color(nm[host][proto][port]['state']) service = nm[host][proto][port]['name'] product_version = f'{nm[host][proto][port]["product"]} {nm[host][proto][port]["version"]}' print( f'{host_name} | {port_proto} | {state} | {service} | {product_version}' )
def ask_question(prompt): global correct_answers, total_asked question, answer, choices = [ prompt[k] for k in ('question', 'answer', 'choices') ] cowsay.cow(question) for choice, description in choices: print choice, description guess = raw_input('whatcha think? ') if guess.lower() == answer[0]: cowsay.tux('Yaaasss! %s, %s' % (random.choice(glow_ups), answer[1])) correct_answers += 1 else: cowsay.tux('Oops! Nice try but it\'s %s' % answer[1]) total_asked += 1
def predict_prob(model_file: click.Path, test_data: click.Path, k: int, t: float, batch_size: int, stat: bool, show_data: bool, ): """predict most likely labels with probabilities""" # metadata metadata_file = f"{model_file}.meta.yml" metadata = Metadata.load(metadata_file) # load model model = load_model(model_file) # test data dataset_test = read(test_data) dataset_test = Dataset( metadata.task, metadata.labels, metadata.chars, dataset_test.samples, ) if stat: cowsay.cow(f"Test data stat:\n {utils.stat(dataset_test)}") # prediction pred = model.predict_generator( BatchSequence(dataset_test, batch_size, metadata.params['maxlen']), workers=1, use_multiprocessing=True) indices = numpy.argsort(-pred)[:, :k] for i, ind in enumerate(indices): if metadata.task == Task.binary: pred_label = metadata.labels[0 if pred[i, 0] < 0.5 else 1] pred_prob = utils.float4(max(pred[i, 0], 1.0 - pred[i, 0])) pred_msg = f"{pred_label} {pred_prob}" else: pred_labels = [metadata.labels[j] for j in ind if pred[i, j] > t] pred_probs = [utils.float4(pred[i, j]) for j in ind if pred[i, j] > t] pred_msg = ' '.join(str(x) for pair in zip(pred_labels, pred_probs) for x in pair) if show_data: print(pred_msg, dataset_test.samples[i].data) else: print(pred_msg)
def list_missing_things(): acts = [('use SSE4.2 instructions', 'could speed up CPU computations'), ('use AVX instructions', 'could speed up CPU computations'), ('use AVX2 instructions', 'could speed up CPU computations'), ('use FMA instructions', 'could speed up CPU computations'), ('share PIECES of cheese', 'could fill up a CASE of the nibbles'), ('offer THOUGHTS on your love life', 'could be more INTERESTING than cheese'), ('like TWEETS about memes', 'could kill some TIME between epochs'), ('tickle YOU with its tentacles', 'so MIGHT AS WELL USE THEM TICKLE TICKLE'), ('have FEELINGS', 'might greatly COMPLICATE our relationship'), ('make friends with BUGS', 'could be more FUN than training your model'), ('use RESISTORS against the status quo', 'so VIVE LA REVOLUTION'), ('flash PIXELS in steganographic patterns', 'so blink BLINK blinkety-blink'), ('collide miniature BLACK HOLES together', 'could speed up GRAVITATIONAL collapse'), ('count the number of BIRDS in the heavens', 'they are NOT going to count themselves'), ('test your patience with DELAYS', 'have you noticed that they seem be be getting LONGER ' 'exponentially')] tick = 0.04 for avail, outcome in acts: now = datetime.datetime.now() print("{}: W tensorflow/core/platform/cpu_feature_guard.cc:45] " "The TensorFlow library wasn\'t compiled to {}, " "but these are available on your machine " "and {}.".format(now, avail, outcome)) time.sleep(tick) tick *= 1.5 print('{}: W deepmoon/core/platform/impressed.cc:42] ' 'The DeepMoon library admires your persistence!'.format( datetime.datetime.now())) cowsay.cow('DeepMoooon Certificate of Persistence:\n' 'The bearer ran a slow thing to completion,\n' 'a very useful skill for deep learning.')
import cowsay cowsay.daemon("Hi") cowsay.dragon("Hey") cowsay.cow("Konstantina")
return dziel zapamietaj = 0 while True: num1 = input("Kalkulator\nDana_1: ") oper = input("Operacja: +, -, :, *: ") num2 = input("Dana_2: ") if oper == "+": # dodaj = int(num1) + int(num2) wynik = funkcja_dodawania(num1, num2) zapamietaj = zapamietaj + wynik cowsay.cow(f"= {wynik}") print(zapamietaj) elif oper == "-": odejmij = int(num1) - int(num2) wynik = funkcja_odejmowania(num1, num2) cowsay.dragon(f"= {wynik}") elif oper == "*": mnoz = int(num1) * int(num2) wynik = funkcja_mnozenia(num1, num2) cowsay.ghostbusters("= %s" % wynik) elif oper == '/': dziel = int(num1) / int(num2) wynik = funkcja_dzielenia(num1, num2)
#!/usr/bin/env python3 from cowsay import cow if __name__ == "__main__": cow("Thanks for the Pizza Phil")
def again(): list1 = ["The human race don't deserve rights.", "I f*****g wish the human race was dead.", "The Joker was right all along.", "Dababy isn't a good artist.", "Ever since the human race killed my cow friend, I've always hated them back since."] cowsay.cow(random.choice(list1)) time.sleep(2) print("Yeah... I'm sorry.")
import configparser import cowsay import os import numpy as np paramfile = "data_param.ini" if not os.path.isfile(paramfile): cowsay.cow(paramfile + ' does not exist \n quitting now \n dumbass') quit() Config = configparser.ConfigParser() # cowsay.cow(Config.sections()) print(np.tile(tuple(range(3))),5)
import cowsay # Documentation: https://pypi.org/project/cowsay/ cowsay.tux("Hello guys..... AHahahhahahah!") cowsay.cow("Hello World!") cowsay.trex('Hello (extinct) World') cowsay.dragon( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris blandit rhoncus nibh. Mauris mi mauris, molestie vel metus sit amet, aliquam vulputate nibh." ) # More characters print(cowsay.char_names)
def main(): start_time = time.time() args = parse_arguments(sys.argv[1:]) if args.curmudgeon: logging.basicConfig(level=args.log_level) else: logging.basicConfig( level=args.log_level, format="%(message)s", datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True)], ) banner = r""" _____ _____ _____ _______ ____ ____ _ | __ \ / ____/ ____|__ __/ __ \ / __ \| | | |__) | _| | | | __ | | | | | | | | | | | ___/ | | | | | | |_ | | | | | | | | | | | | | | |_| | |___| |__| | | | | |__| | |__| | |____ |_| \__, |\_____\_____| |_| \____/ \____/|______| __/ | |___/ """ # noqa banner = textwrap.dedent(banner) if args.cow: try: import cowsay banner = cowsay.cow("PyCGTOOL") except ImportError: pass else: logger.info("[bold blue]%s[/]", textwrap.dedent(banner), extra={"markup": True}) logger.info(30 * "-") logger.info("Topology:\t%s", args.topology) logger.info("Trajectory:\t%s", args.trajectory) logger.info("Mapping:\t%s", args.mapping) logger.info("Bondset:\t%s", args.bondset) logger.info(30 * "-") try: if args.profile: with cProfile.Profile() as profiler: pycgtool = PyCGTOOL(args) profiler.dump_stats("gprof.out") else: pycgtool = PyCGTOOL(args) elapsed_time = time.time() - start_time logger.info("Processed %d frames in %.2f s", pycgtool.out_frame.n_frames, elapsed_time) logger.info("Finished processing - goodbye!") except Exception as exc: logger.exception(exc)
def print_cowsay(self, textvalue): cowsay.cow(textvalue)
if rotation: print("✓\n") else: print("\n\n") if "pause" in sys.argv: while (1): showmsg("Starte Pausensequenz", True, 50) showmsg('home.find("Badezimmer")', True, 50) showmsg("kaffee.flush()", True, 40) showmsg("Ersetze müde alte Giftschlange", True, 40) showmsg("Füttere Schlange", True, 30) showmsg(stacktrace2, False, 80) showmsg("Lade lehrreiche Pausen-Kuh", True, 50) cowsay.cow('print("Hello World!")') time.sleep(8) showmsg("Fülle Quasselwasser nach.", True, 40) showmsg("Defragmentiere Gedächtnis", True, 40) showmsg("Fixe Bugs", True, 40) showmsg("Entferne Folgefehler durch Bugfix", True, 40) showmsg("kaffee = Kaffeemaschine.getCoffee()", True, 50) else: while (1): showmsg("Lade Programm", True, 50) showmsg("Prüfe Kaffee-Füllstand", True, 30) showmsg("Warte auf Teilnehmer", True, 50) showmsg("Justiere Python-Bibliotheken", True, 70) showmsg("Deinstalliere Java", True, 50) showmsg(stacktrace, False, 30)
import cowsay cowsay.cow("Hello world")
import datetime import cowsay now = datetime.datetime.now() cowsay.cow(f"Current time is {now}")
worked_intervals = take_the_input() message = "" now = datetime.now() if not len(worked_intervals) % 2 == 0: worked_intervals.append("{:0>2d}:{:0>2d}".format(now.hour, now.minute)) hours = [datetime.strptime(hour.strip(), "%H:%M") for hour in worked_intervals] hours_sum = datetime.strptime("00:00", "%H:%M") for iteracao in range(0, len(hours), 2): hours_sum = hours_sum + (hours[iteracao + 1] - hours[iteracao]) message += "\nYou worked {:0>2d}:{:0>2d} hours".format(hours_sum.hour, hours_sum.minute) if (hours_sum.hour < WORKING_HOURS_IN_A_DAY): regular_worked_time = datetime.strptime("08:00", "%H:%M") hour_left = regular_worked_time - hours_sum limit_hour = (datetime.now() + hour_left) message += "\nYou can go home at: {:0>2d}:{:0>2d}".format( limit_hour.hour, limit_hour.minute) else: message += "\nYou can go home, see you tomorrow buddy" print(cowsay.cow(message + "\n"))
def main(name): print(cowsay.cow(f"Hi, I am {name}. Nice to meet you!"))
#!/usr/bin/python3 import os import time import cowsay from formula import formula n_epochs = os.environ.get('NUMBER_EPOCHS') early_stop = os.environ.get('EARLY_STOP') print("Staring MNIST CNN Trainning with " + n_epochs + " epochs...\n\n\n") start = time.time() Acc = (formula.Run(n_epochs, early_stop)) end = time.time() cowsay.cow(Acc + "\nDuration: " + "{:.2f}".format(end - start) + " s")
# print('\n', '%s'%(i+1), d) def addLines(string, width): pos, findSpace = 0, 0 while pos < len(string) - width: pos += width findSpace = pos while string[findSpace - 1] != ' ': findSpace -= 1 string = string[:findSpace] + '\n' + string[findSpace:] return string def getQuote(): headers = {"Accept": "application/json"} url = "https://api.trello.com/1/boards/5b95ec6c86050b153bbc3cc2/cards?key=54d07639427faa733acb9f053875a089&token=95cc4a76b985e33a0b28d9e397a4fd985a7a217bb4d666f81a5f753edc37dc60" response = requests.request("GET", url, headers=headers) allCards = json.loads(response.text) quote = allCards[random.randint(0, len(allCards))]['name'] if len(quote.split()) == 1: quote += ' - ' + define(quote) return quote print(cow(addLines(getQuote(), 50))) # print(define(input("Enter a word to define: ")))
def do_something(): import cowsay cowsay.cow('yo')
def cowsay(say): import cowsay # cowsay.stegosaurus(say) cowsay.cow(say)
def stopPlay(): pygame.mixer.music.stop() GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(0, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(1, GPIO.IN, pull_up_down=GPIO.PUD_UP) print('#############################') print(' Use Pi To Learn Python ') print(' Steady Hands ') print('#############################') cowsay.cow('Steady Hands') dum = 0 start_rest = 4 end_rest = 0 wire = 1 musicSetup(volume=30) bgmSound = './music/creativeminds_l.mp3' startSound = './music/start_ad_01.mp3' ooopsSound = './music/ooops_ya_01.mp3' endSound = './music/end_fql_01.mp3' badSound = './music/ooops_ya_02.mp3' yongshi = './music/yongshi.mp3' yi = './music/one.mp3' er = './music/two.mp3' san = './music/three.mp3'
async def on_ready(): cowsay.cow("I'm ready!")
def congratulate(player_name): cowsay.cow("CONGRATULATIONS %s !!!" % (player_name))
def printCowsay(input): cowsay.cow(input)