def print_information(destinations): print('\n' + bg(255,255,255) + fg(0,0,0) + ' Line Time Destination ' + rs.bg + '\n') for stop in destinations: if stop['product'] == 'UBAHN': destination = stop['destination'] time = stop['departureTimeMinutes'] color = {'U1':bg(70, 132, 71), 'U2':bg(221, 61, 77), 'U3':bg(239, 136, 36), 'U4':bg(4, 175, 144), 'U5':bg(183, 135, 48), 'U6':bg(4, 114, 179), 'U7':fg(255,255,255) + bg(70, 132, 71) + ' U' + bg(221, 61, 77) + '7 ' + rs.bg, 'U' :fg(255,255,255) + bg(0, 108, 178) + ' U ' + rs.bg} finalLine = color[stop['label']] + fg(255,255,255) + ' ' + stop['label'] + ' ' + rs.bg sep_time = {"1":7, "2":6, "3":5} tam_time = str(len(str(time))) print(' {} {}{}{}'.format(finalLine,time," "*sep_time[tam_time],destination)) print('\n')
def pprint(x, ts=True, r=False): """ Identical to other color functions, except you have more control over the string color(s). Example: '<33>Hello world!</33>' would print the string 'Hello world!' in the corresponding sty color value (blue) """ color_rgx1 = re.compile('<([\d{,2}]*)>') color_rgx2 = re.compile('<\/([\d{,2]*)>') bold_rgx = re.compile('(<b>)', re.IGNORECASE) bold_rgx2 = re.compile('(<\/b>)', re.IGNORECASE) und_rgx = re.compile('(<u>)', re.IGNORECASE) und_rgx2 = re.compile('(<\/u>)', re.IGNORECASE) if ts: tstmp = fg(246) + '[' + datetime.now().strftime( "%Y-%m-%d %H:%M:%S") + ']' + rs.fg x = f'{x} {tstmp}' out = color_rgx2.sub( rs.fg, color_rgx1.sub( lambda x: fg(int(x.group(1))), bold_rgx2.sub( rs.bold_dim, bold_rgx.sub(ef.bold, und_rgx2.sub(rs.all, und_rgx.sub(ef.u, x)))))) if r: return out else: print(out)
def __str__(self): result = f' {fg.li_blue}' for i in range(0, len(self.categories)): result += f'{self.categories[i]:>8}' result += f' accuracy{fg.rs}\n' all_total = 0 for i in range(0, len(self.categories)): line = f'{fg.li_blue}{self.categories[i]:<10}{fg.rs}' total = 0 for j in range(0, len(self.categories)): total += self.matrix[i, j] if i == j: clr = fg(255) else: clr = fg(248) line += f'{clr}{self.matrix[i, j]:8.0f}{fg.rs}' line += f'{fg.yellow}{self.matrix[i, i] / total * 100:9.1f}%{fg.rs}' result += f'{line} \n' all_total += total total_correct = 0 line = f'{fg.li_blue}Precision {fg.yellow}' for i in range(0, len(self.categories)): total = 0 for j in range(0, len(self.categories)): total += self.matrix[j, i] total_correct += self.matrix[i, i] line += f'{self.matrix[i, i] / total * 100:7.1f}%' result += f'{line}' result += f'{fg(255)}{total_correct / all_total * 100:9.1f}%{fg.rs}' return result
def remove(self, c_split): # This is set to prioritise removing things from the BAG FIRST. # It is for changing the initiative OUTSIDE combat or for correcting errors, not during combat! try: if c_split[-1].isnumeric( ): # Remember the last element is taken as a QUANTITY if it is numeric assert len( c_split ) > 1 # Ensure we'll still have something usable as a name after removing that else: assert len( c_split ) > 0 # We must have a nonzero amount of instruction to act on order = self.extract_counter(c_split, default=1000) possible_removals = self.contents & order possible_table_removals = (order - possible_removals) & self.table for k, v in possible_removals.items(): # At the moment each order can only give one key-value pair. # Seems weird to do this in a for loop but I don't know how to do it otherwise. print( fg(*self.colour_lookup[k]) + f'Removing tokens from the bag: {v}x {k}' + fg.rs) self.contents -= possible_removals for k, v in possible_table_removals.items(): # Second verse, same as the first print( fg(*self.colour_lookup[k]) + f'Removing tokens from the table: {v}x {k}' + fg.rs) self.table -= possible_table_removals except Exception as e: print('Removing token failed!' + str(e)) print( 'Required format: add [token name] [amount to take, default 1000]' ) self.report()
def print_id(self, id, short=True, pad=True): color = fg(hash(id) % 214 + 17) if id == 'system': color = fg('red') if short and '-' in id: id = id[:id.rfind('-')] self.idlen = max(self.idlen, len(id)) self.print(color + id.ljust(self.idlen if pad else 0) + rs.all)
def retrieve_messages(): token = TOKEN print( fg(138, 197, 62) + ef.bold + ">> " + rs.bold_dim + fg.rs + "Type " + fg.cyan + "/cancel xxxx " + fg.rs + "or just " + fg.cyan + "xxxx " + fg.rs + fg(255, 153, 0) + "to cancel a reset." + fg.rs) print("") arguments = {"api_token": token} r = requests.Session() last_comment = "" can_display = False while 1: # print("check") can_display = False commentaires = r.post(url, headers=header_test, params=arguments).json()["html"] if last_comment == "": for commentaire in commentaires: soup = BeautifulSoup(commentaire, "lxml") last_comment = soup.text last_comment_format = colorize_message(last_comment) if show_only_reset and "reset" in last_comment: emit(UNSAVE_CURSOR) print(last_comment_format) emit(SAVE_CURSOR, GOTO_INPUT, CLEAR_LINE) elif not show_only_reset: print(last_comment_format) else: for commentaire in commentaires: soup = BeautifulSoup(commentaire, "lxml") if soup.text == last_comment: can_display = True elif can_display: last_comment = soup.text last_comment_format = colorize_message(last_comment) #print(last_comment_format) if show_only_reset and "reset" in last_comment: emit(UNSAVE_CURSOR) print(last_comment_format) emit(SAVE_CURSOR, GOTO_INPUT, CLEAR_LINE) elif not show_only_reset: emit(SAVE_CURSOR, GOTO_INPUT, CLEAR_LINE) emit(UNSAVE_CURSOR) print(last_comment_format) time.sleep(5)
def swap(data, x, y, visible=True, color=201): data[x], data[y] = data[y], data[x] if not visible or x == y: return if x > y: x, y = y, x print(*data[:x], fg(color) + str(data[x]) + fg.rs, *data[x + 1:y], fg(color) + str(data[y]) + fg.rs, *data[y + 1:])
def color_opts(x=None): """ When nothing is passed entire list of sty's color options with their corresponding numbers are returned. Alternatively you can pass a specific number to see what color it corresponds to in sty. """ if x is None: for i in range(256): print(fg(i) + 'fg({0})'.format(i) + rs.all) return None else: print(fg(int(x)) + 'fg({0})'.format(x) + rs.all)
def main_process(): questions = [inquirer.Text("stop",message=fg(255,255,255) +"Stop")] station = inquirer.prompt(questions)['stop'] while station != 'exit': if station != 'exit': get_info(station) questions = [inquirer.Text("stop",message=fg(255,255,255) +"Stop")] station = inquirer.prompt(questions)['stop']
def PrintShareLink(artist, title, url): text = quote(title + " by " + artist) url = quote(url) print( fg(29, 161, 242) + 'Twitter:' + fg.rs, f"https://twitter.com/intent/tweet?hashtags=NowPlaying&related=spotify&text={text}&url={url}" ) print( fg(32, 164, 226) + 'Telegram:' + fg.rs, f"https://telegram.me/share/url?url={url}")
def renderImg(img): # img = cv2.imread("deadpool.jpg") width, height, _ = img.shape aspectRatio = height / width newWidth = 120 newHeight = int(newWidth * aspectRatio * 0.25) img = cv2.resize(img, (newWidth, newHeight)) colorCodes = [] for row in img: colorCodes.append([rgb2short_fast(pixel) for pixel in row]) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) chars = ["B", "S", "#", "&", "@", "$", "%", "*", "+", "!", ":", "."] newImg = [] for rowIndex in range(len(img)): temp = [] for cellIndex in range(len(img[rowIndex])): print( fg(colorCodes[rowIndex][cellIndex]) + chars[img[rowIndex][cellIndex] // 25], end="", ) temp.append( fg(colorCodes[rowIndex][cellIndex]) + chars[img[rowIndex][cellIndex] // 25] ) newImg.append("".join(temp)) print() import sys with open("test.txt", "w") as fl: fl.writelines(newImg) CURSOR_ONE_UP = "\033[A" for i in range(len(img)): sys.stdout.write(CURSOR_ONE_UP) def main(): vid = cv2.VideoCapture(0) while True: ret, frame = vid.read() renderImg(frame) if cv2.waitKey(1) & 0xFF == ord('q'): break vid.release() cv2.destroyAllWindows() if __name__ == "__main__": main()
def print_text(text, type): if type == "error": fgColor = fg(255, 0, 0) prep = '[!] ' elif type == "action": fgColor = fg(255, 194, 0) prep = '[*] ' elif type == "ok": fgColor = fg(54, 205, 20) prep = '[+] ' else: fgColor = fg(255, 255, 255) prep = '' print(fgColor + prep + text + fg.rs)
def logo(): os.system("cls||clear") x = random.randint(16, 224) print("\033[1;0H") print(fg(x) + "███▄▄▄▄ ▄████████ ▄█ ▄█▄ ▄██████▄ ████████▄ ▄██████▄ ▄█ ▄█ "+ fg.rs) print(fg(x+1) +"███▀▀▀██▄ ███ ███ ███ ▄███▀ ███ ███ ███ ▀███ ███ ███ ███ ███ "+ fg.rs) print(fg(x+1) +"███ ███ ███ █▀ ███▐██▀ ███ ███ ███ ███ ███ ███ ███ ███ "+ fg.rs) print(fg(x+2) +"███ ███ ▄███▄▄▄ ▄█████▀ ███ ███ ███ ███ ███ ███ ███ ███ "+ fg.rs) print(fg(x+3) +"███ ███ ▀▀███▀▀▀ ▀▀█████▄ ███ ███ ███ ███ ███ ███ ███ ███ "+ fg.rs) print(fg(x+4) +"███ ███ ███ █▄ ███▐██▄ ███ ███ ███ ███ ███ ███ ███ ███ "+ fg.rs) print(fg(x+5) +"███ ███ ███ ███ ███ ▀███▄ ███ ███ ███ ▄███ ███ ███ ███▌ ▄ ███▌ ▄ "+ fg.rs) print(fg(x+4) +" ▀█ █▀ ██████████ ███ ▀█▀ ▀██████▀ ████████▀ ▀██████▀ █████▄▄██ █████▄▄██ "+ fg.rs) print("") print(fg(x + 2) + 'Express Crypto autoclaim create by Nekodoll ' + fg.rs) print(fg(x + 1) + '-' * 90 + fg.rs)
def add(self, c_split): try: if c_split[-1].isnumeric( ): # Remember the last element is taken as a QUANTITY if it is numeric assert len( c_split ) > 1 # Ensure we'll still have something usable as a name after removing that else: assert len( c_split ) > 0 # We must have a nonzero amount of instruction to act on order = self.extract_counter(c_split, default=2) for k, v in order.items(): # This might be a new token: check if it's got an associated colour. if k not in self.colour_lookup.keys(): self.colour_lookup[k] = self.colourise(k) else: pass # At the moment each order can only give one key-value pair. # Seems weird to do this in a for loop but I don't know how to do it otherwise. print( fg(*self.colour_lookup[k]) + f'Tokens going into the bag: {v}x {k}' + fg.rs) self.contents += order except Exception as e: print('Adding token failed!' + str(e)) print( 'Required format: add [token name] [amount to add, default 1]') self.report()
def print_usertoscreen(channel, username, message): currentDT = datetime.datetime.now() color = "15" if not (username == ""): color = get_user_color(username) username = (username[:15] + '') if len(username) > 15 else username channel = (channel[:15] + '') if len(channel) > 15 else channel lines = 0 while len(message) > 0: if len(message) < MAX_MSG_SIZE: msg = message message = "" else: msg = message[:MAX_MSG_SIZE] message = message[MAX_MSG_SIZE:len(message)] lines += 1 if lines == 1: print('{:<7s}{:<16s}{:s}{:s}{:<15s}{:s}{:^3s}{:s}'.format(currentDT.strftime("%H:%M"), channel, "| ", fg(int(color)), username, fg.rs, ":", msg)) else: print( '{:<7s}{:<16s}{:s}{:s}{:<15s}{:s}{:^3s}{:s}'.format(currentDT.strftime("%H:%M"), channel, "| ", fg(int(color)), "", fg.rs, ":", msg))
def show(self): for x in range(8): for y in range(4): r, g, b = self.grid[y][x] #print("("+str(r)+","+str(g)+","+str(b)+")") print(fg(r, g, b) + "*" + fg.rs, end="") print()
def text_format(self, key, **kwargs): out = "" texts = super().text_format(key, **kwargs) out += texts[0] colors = texts[1::2] for index, text in enumerate(texts[2::2]): color = colors[index] if text: if color == "-": out += sty.rs.all + text elif color == "b": out += sty.ef.bold + text elif color == "i": out += sty.ef.italic + text elif color == "info": out += sty.ef.bold + sty.bg.cyan + sty.fg.white + text else: if color.isdigit(): out += sty.fg(int(color)) + text else: out += text out += sty.rs.all return out.replace("\n", "\r\n")
def test_notebooks(notebook): """Function to run a notebook. Parameters ---------- notebook : str Path and name of notebook to be tested. """ # Break up the path. psplit = notebook.split('/') name = psplit.pop(-1) print(fg.red + '\ntesting notebook: ' + fg.rs + fg.green + '{}\n'.format(name) + fg.rs) dirpath = '/'.join(psplit) # Execute the jupyter notebook. cmd = 'jupyter nbconvert {} --to notebook --execute '.format(notebook) cmd += '--ExecutePreprocessor.timeout=6000 --output out_file' subprocess.call(cmd, shell=True) # Try and clean up output. Otherwise fail and exit. try: os.remove('{}/out_file.ipynb'.format(dirpath)) except FileNotFoundError: print(ef.bold + fg(201) + '\n{} failed\n'.format(name) + fg.rs + rs.bold) exit()
def load(self): # Looks in the local folder for yaml files, lists them, attempts to load the one the user specifies. # Load it into a temporary holder. Check to see that it's actually a dict where each item is valid. # If it passes muster, display the dict nicely to the user, with colour. # If the user agrees that that is what they want, put it into the main bag and clear the holder. folder_contents = self.list_files() print('Existing YAML files in the local folder:') for i, v in enumerate(folder_contents): print(f'[{i}] {v}') selection = input('Load which file? Input only the index number.]> ') try: assert selection.isnumeric() with open(folder_contents[int(selection)], 'r') as f: temp_holder = yaml.load(f, Loader=yaml.FullLoader) assert isinstance(temp_holder, dict) print('\nLoaded data:') if len(temp_holder) == 0: print('Absolutely nothing!') else: for k, v in temp_holder.items(): if k not in self.colour_lookup.keys(): self.colour_lookup[k] = self.colourise(k) else: pass print(fg(*self.colour_lookup[k]) + f'{v}x {k}' + fg.rs) decision = input('OK to put into the bag? y to commit.]> ').lower() if decision == 'y': self.contents += Counter(temp_holder) print('Loading complete!') self.report() else: print('Loading cancelled, returning to main menu...') except Exception as e: print('Loading failed! ', e) pass
def p_color(data): try: from sty import fg, rs logvalue = math.log(data) / math.log(2) return '\033[1m' + fg(int(logvalue)) + str(data) + fg.rs except ImportError: return data
def _render(self, text, fg: ColorPoint, bg: ColorPoint = None): out = '' out += sty.fg(fg.ansi) if bg: out += sty.bg(bg.ansi) out += text out += sty.rs.all return out
def pcolor(x, cid, ts=True, r=False): """Same as all color printing functions, just lets you pass specific color ID (from color_opts()).""" bold_rgx = re.compile('(<b>)', re.IGNORECASE) bold_rgx2 = re.compile('(<\/b>)', re.IGNORECASE) und_rgx = re.compile('(<u>)', re.IGNORECASE) und_rgx2 = re.compile('(<\/u>)', re.IGNORECASE) if ts: x = f'{x} [{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}]' out = fg(cid) + und_rgx2.sub( rs.all + fg(cid), und_rgx.sub(ef.u, bold_rgx2.sub(rs.all + fg(cid), bold_rgx.sub(ef.bold, x)))) + rs.all if r: return out else: print(out)
def errorOnRequest(self, driver): if "Error 429" in driver.title: print(fg.yellow + 'Waiting...' + fg.rs) driver.refresh() if "Oops! There was a problem displaying this page." in driver.page_source or "Hoppla! Beim Anzeigen dieser Seite ist ein Fehler aufgetreten." in driver.page_source: print(fg(201) + 'Invalid Code' + fg.rs) return False return True
def format_string_for_ids(self, fg_id=None, bg_id=None): s = '{}' + sty.rs.all if fg_id: s = sty.fg(fg_id.four_bit_color_name) + s self.used_color_ids.add(fg_id) if bg_id: s = sty.bg(bg_id.four_bit_color_name) + s self.used_color_ids.add(bg_id) return s
def colorize(text, heat1, heat2): remainder_intensity = 255 - MIN_INTENSITY r, g, b = [MIN_INTENSITY] * 3 if heat1 < 0: r += int(remainder_intensity * (-heat1)) elif heat1 > 0: g += int(remainder_intensity * heat1) b += int(remainder_intensity * heat2) return fg(*(r, g, b)) + text + fg.rs
def run(self): headers = { 'cookie': self.cookie, 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36', } scraper = cloudscraper.Session() while True: r = scraper.get(self.site, headers=headers) soup = BeautifulSoup(r.text, "html.parser") succ = soup.find("div", {"class": "alert alert-success"}) a = random.randint(77, 167) if soup.find("div", {"class": "alert alert-success"}) is not None: print(fg(a) + succ.text) else: print(fg(a) + soup.title.text + " Success Claim :D") time.sleep(self.delay)
def get_status_color(status: str) -> str: # Set a color depending on status. if status == "pending": return sty.fg(214) # orange elif status == "created": return sty.fg.rs elif status == "running": return sty.fg(226) # yellow elif status == "success": return sty.fg.green elif status == "canceled": return sty.fg(124) # dark red elif status == "skipped": return sty.fg.li_black elif status == "failed": return sty.fg(196) # light red else: return sty.fg.rs
def sgr_fg(names): items = [fg(name) + ' ' + name.ljust(12) for name in names] items.insert(8, rs.fg + '\n') items.insert(16 + 1, rs.fg + '\n') line = '\nSGR_FG:\n-------\n' + ''.join(items) + rs.fg return line
def _ascii_flare(): """ Draw Pr0t0mate banner !!! """ text = "protomate" ascii_color = fg(123, 239, 178) ascii_style = art.text2art(text, font="glenyn-large") ascii_banner = ascii_color + ascii_style + fg.rs cprint(ascii_banner, attrs=["bold"])
def ticker(symbols): urlData = "https://query2.finance.yahoo.com/v7/finance/quote?symbols=" + ','.join( symbols) webUrl = urllib.request.urlopen(urlData) data = webUrl.read() tickerData = json.loads(data) result = () b = np.array([['SYM', 'PR', 'CCY', 'CHG', '%', 'STATE', 'TYPE']]) for i in enumerate(symbols): stringSymbol = fg(255, 100, 10) + i[1] + fg.rs stringregularMarketPrice = ( tickerData["quoteResponse"]["result"][i[0]]["regularMarketPrice"]) stringregularMarketCurrency = ( tickerData["quoteResponse"]["result"][i[0]]["currency"]) stringmarketState = ( tickerData["quoteResponse"]["result"][i[0]]["marketState"]) stringquoteType = ( tickerData["quoteResponse"]["result"][i[0]]["quoteType"]) if tickerData["quoteResponse"]["result"][ i[0]]["regularMarketChange"] < 0: stringregularMarketChange = fg( 255, 10, 10) + str(tickerData["quoteResponse"]["result"][i[0]] ["regularMarketChange"]) + fg.rs stringregularMarketChangePercent = fg( 255, 10, 10) + str(tickerData["quoteResponse"]["result"][i[0]] ["regularMarketChangePercent"]) + '' + fg.rs else: stringregularMarketChange = fg.green + str( tickerData["quoteResponse"]["result"][ i[0]]["regularMarketChange"]) + fg.rs stringregularMarketChangePercent = fg.green + str( tickerData["quoteResponse"]["result"][ i[0]]["regularMarketChangePercent"]) + '' + fg.rs b = np.append(b, [[ stringSymbol, stringregularMarketPrice, stringregularMarketCurrency, stringregularMarketChange, stringregularMarketChangePercent, stringmarketState, stringquoteType ]], axis=0) click.echo( tabulate(b, headers='firstrow', tablefmt='github', floatfmt=".2f")) return result