Пример #1
0
 def print_task_line(self, t):
     """Print a Task readout for the user."""
     box_color = bg(20)
     repeat_color = bg(28)
     reset = attr('reset')
     if t.repeat_mode == '':
         print("    {0}[{1}]{2} {3}".format(box_color, t.task_id, reset, t.body)) 
     else:
         print("    {0}[{1}]{2} {3}[Repeat]{4} {5}".format(box_color, t.task_id, reset, repeat_color, reset, t.body)) 
Пример #2
0
    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"]
Пример #3
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'))
Пример #4
0
	def print_(self, pixels):
		y = ""
		for pixel in pixels:
			x = pixel.get_colors()
			y += ('%s %s' % (bg(x256.from_rgb(x[0], x[1], x[2])), attr(0)))
		sys.stdout.write(y)
		sys.stdout.flush()
		self.restart_line()
Пример #5
0
 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
Пример #6
0
def print_row(a):
    for x in a:
        foo = np.around(math.floor(x * 999))
        index = int(foo / 100)
        color = colored.bg(lookup[10-index])
        res   = colored.attr('reset')
        sys.stdout.write (color + str(int(foo)) + res)
        #sys.stdout.write(" ")
    sys.stdout.write("\n")
Пример #7
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")
Пример #8
0
    def _colorize_line(line):
        if line.startswith('T'):
            line = colored.fg("grey_62") + line + colored.attr('reset')
            line = re.sub(r"\{(.*?)\}", colored.fg("orange_3") + r"\1"+colored.fg('grey_35'), line)
            return line

        line = re.sub(r"\[(F.*?)\]",
                      colored.bg("black") + colored.fg("cyan") + r"[\1]"+colored.attr('reset'),
                      line)
        line = re.sub(r"\[(g.*?)\]",
                      colored.bg("dark_gray") \
                      + colored.fg("grey_0") \
                      + r"[\1]"+colored.attr('reset'),
                      line)
        line = re.sub(r"\{(.*?)\}",
                      colored.fg("orange_3") + r"\1"+colored.attr('reset'),
                      line)
        line = re.sub(r"<(.*?)>",
                      colored.fg("cyan") + r"\1"+colored.attr('reset'),
                      line)
        return line
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']
Пример #10
0
    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("")
Пример #11
0
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']
Пример #12
0
 def print_news(self, impact=False):
     tcd = {'Broncos':   {'fg': 208, 'bg': 18},
            'Vikings':   {'fg': 11, 'bg': 54},
            'Falcons':   {'fg': 0, 'bg': 1},
            'Saints':    {'fg': 136, 'bg': 0},
            'Chargers':  {'fg': 226, 'bg': 21},
            'Lions':     {'fg': 27, 'bg': 244},
            'Cowboys':   {'fg': 244, 'bg': 27},
            'Browns':    {'fg': 202, 'bg': 52},
            'Eagles':    {'fg': 231, 'bg': 29},
            'Steelers':  {'fg': 11, 'bg': 0},
            'Giants':    {'fg': 9, 'bg': 19},
            'Patriots':  {'fg': 9, 'bg': 19},
            'Buccaneers':{'fg': 0, 'bg': 9},
            'Cardinals': {'fg': 0, 'bg': 1},
            'Chiefs':    {'fg': 196, 'bg': 0},
            'Jaguars':   {'fg': 11, 'bg': 30},
            'Redskins':  {'fg': 231, 'bg': 88},
            'Jets':      {'fg': 231, 'bg': 22},
            'Ravens':    {'fg': 11, 'bg': 55},
            'Colts':     {'fg': 15, 'bg': 18},
            'Packers':   {'fg': 11, 'bg': 22},
            'Titans':    {'fg': 231, 'bg': 4},
            'Free Agent':{'fg': 0, 'bg': 231},
            'Bills':     {'fg': 231, 'bg': 27},
            'Texans':    {'fg': 18, 'bg': 196},
            '49ers':     {'fg': 15, 'bg': 124},
            'Seahawks':  {'fg': 10, 'bg': 21},
            'Panthers':  {'fg': 0, 'bg': 33},
            'Dolphins':  {'fg': 208, 'bg': 29},
            'Bengals':   {'fg': 202, 'bg': 0},
            'Rams':      {'fg': 184, 'bg': 19},
            'Raiders':   {'fg': 247, 'bg': 0},
            'Bears':     {'fg': 208, 'bg': 17},
            'Player':    {'fg': 0, 'bg': 180}}
     for team in self._team_news.keys():
         print('%s%s %s %s' % (fg(tcd[team]['fg']), bg(tcd[team]['bg']), team, attr(0)))
         for player in self._team_news[team].keys():
             for news in self._team_news[team][player]:
                 print('\t***** ' + news[0])
                 if impact == True:
                     print('\t\t- ' + news[1].strip())
def CPrint(text, fgc=500, bgc=500, attrc="", newline=True):
        from colored import fg, bg, attr, style
        import sys
        if newline is True:
            if fgc != 500:
                if bgc == 500:
                    if attrc == "":
                        print(fg(fgc) + text + style.RESET)
                    else:
                        print(fg(fgc) + attr(attrc) + text + style.RESET)
                else:
                    if attrc == "":
                        print(fg(fgc) + bg(bgc) + text + style.RESET)
                    else:
                        print(fg(fgc) + bg(bgc) + attr(attrc) + text + style.RESET)
            else:
                if bgc != 500:
                    if attrc == "":
                        print(bg(bgc) + text + style.RESET)
                    else:
                        print(bg(bgc) + attr(attrc) + text + style.RESET)
        else:
            if fgc != 500:
                if bgc == 500:
                    if attrc == "":
                        sys.stdout.write(fg(fgc) + text + style.RESET)
                    else:
                        sys.stdout.write(fg(fgc) + attr(attrc) + text + style.RESET)
                else:
                    if attrc == "":
                        sys.stdout.write(fg(fgc) + bg(bgc) + text + style.RESET)
                    else:
                        sys.stdout.write(fg(fgc) + bg(bgc) + attr(attrc) + text + style.RESET)
            else:
                if bgc != 500:
                    if attrc == "":
                        sys.stdout.write(bg(bgc) + text + style.RESET)
                    else:
                        sys.stdout.write(bg(bgc) + attr(attrc) + text + style.RESET)
Пример #14
0
def colorize(message, format, color=False):
    '''
    Returns the given message in a colorized format
    string with ANSI escape codes for colorized console outputs:
    - message:   the message to be formatted.
    - format:    triple containing format information:
                 (bg-color, fg-color, bf-boolean) supported colors are
                 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
    - color:     boolean determining whether or not the colorization
                 is to be actually performed.
    '''
    if color is False: return message
    (bg, fg, bold) = format
    params = []
    if bold:
        params.append(colored.attr('bold'))
    if bg:
        params.append(colored.bg(bg))
    if fg:
        params.append(colored.fg(fg))

    return colored.stylize(message, set(params))
Пример #15
0
def colorPrint(text, fgc=500, bgc=500, attrc="", newline=True, debug=0):
    from colored import fg, style, attr, bg
    import sys

    if newline is True:
        if fgc != 500:
            if bgc == 500:
                if attrc == "":
                    color = fg(fgc)
                    att = attr(attrc)
                    print(color + text + style.RESET)
                else:
                    color = fg(fgc)
                    att = attr(attrc)
                    print(color + att + text + style.RESET)
            else:
                if attrc == "":
                    color = fg(fgc) + bg(bgc)
                    att = attr(attrc)
                    print(color + text + style.RESET)
                else:
                    color = fg(fgc) + bg(bgc)
                    att = attr(attrc)
                    print(color + att + text + style.RESET)
        else:
            if bgc != 500:
                if attrc == "":
                    color = bg(bgc)
                    att = attr(attrc)
                    print(color + text + style.RESET)
                else:
                    color = bg(bgc)
                    att = attr(attrc)
                    print(color + att + text + style.RESET)
    else:
        if fgc != 500:
            if bgc == 500:
                if attrc == "":
                    color = fg(fgc)
                    att = attr(attrc)
                    sys.stdout.write(color + text + style.RESET)
                else:
                    color = fg(fgc)
                    att = attr(attrc)
                    sys.stdout.write(color + att + text + style.RESET)
            else:
                if attrc == "":
                    color = fg(fgc) + bg(bgc)
                    att = attr(attrc)
                    sys.stdout.write(color + text + style.RESET)
                else:
                    color = fg(fgc) + bg(bgc)
                    att = attr(attrc)
                    sys.stdout.write(color + att + text + style.RESET)
        else:
            if bgc != 500:
                if attrc == "":
                    color = bg(bgc)
                    att = attr(attrc)
                    sys.stdout.write(color + text + style.RESET)
                else:
                    color = bg(bgc)
                    att = attr(attrc)
                    sys.stdout.write(color + att + text + style.RESET)
Пример #16
0
def main() -> None:
    screens = Screens(pathlib.Path(art_module.__file__).parent)
    parser = argparse.ArgumentParser(
        "cls", description="Shows random art to clear the screen.")
    parser.add_argument(
        "--color",
        required=False,
        type=int,
        default=None,
        help="Select color from list provided by `colored` package (0-256).",
    )
    parser.add_argument(
        "--drab",
        action="store_true",
        help="don't use a random color each time",
    )
    parser.add_argument(
        "--index",
        help=f"Index of art to pick (max {screens.length - 1}",
        required=False,
        default=None,
        type=int,
    )
    parser.add_argument("--name",
                        required=False,
                        default=None,
                        help="Name of art")
    parser.add_argument("--ls",
                        help="List all the screens",
                        action="store_true")
    parser.add_argument("--ls-colors",
                        help="List all colors",
                        action="store_true")
    args = parser.parse_args()

    if args.ls:
        print("Selections:")
        for index, name in screens.names:
            print(f"\t{index: > 3} {name}")
        sys.exit(0)

    if args.ls_colors:
        print("Selections:")
        for index in range(256):
            print("\t" + colored.fg(index) + f"{index: > 4} " +
                  colored.style.RESET + colored.bg(index) + " " * 20 +
                  colored.style.RESET)
        sys.exit(0)
    try:
        if args.name is not None:
            art = screens.get_by_name(args.name)
        elif args.index is not None:
            art = screens.get_by_index(args.index)
        else:
            art = screens.random()
    except InvalidChoice as ic:
        print('Invalid selection "{}". Pick a number from 0 - {}.'.format(
            ic.arg, screens.length))
        sys.exit(1)

    if not args.drab:
        if args.color is None:
            c_index = int(random.random() * 255)
        else:
            c_index = args.color
        print(colored.fg(c_index))

    print_art(format_horizontal_lines(art))

    if not args.drab:
        print(colored.style.RESET)
Пример #17
0
 def __init__(self, default_bg=0):
     self.default_bg = bg(default_bg)
Пример #18
0
def logWithTitle(title, text="noTextSet"):
    print("")
    print( stylize("------------- " + title + " -----------", bg("grey_42")+fg("white")+attr("bold")) )
    if(str(text) != "noTextSet"):
        print(text)
Пример #19
0
 def __init__(self, title):
      super().__init__(title,1, fg('white') + bg('deep_pink_3b') )
Пример #20
0
def run(args) -> None:
    # TODO: acquire in the same with?
    with handle_cd_revertible(args.dir):
        with acquire_lock():
            experiment = Experiment.deserialize()
            experiment.collect_results()

            if args.r:
                for sample in experiment.samples:
                    if sample.result is not None:
                        print(sample.result)

                return

            best_res = None
            best_sample = None

            ok_samples = []

            for sample in experiment.samples:
                if sample.result is not None:
                    try:
                        if best_res is None or (sample.result
                                                and sample.result > best_res):
                            best_res = sample.result
                            best_sample = sample
                    except ValueError:
                        # TODO: cleanup checks
                        job_id = sample.job.job_id if sample.job else "NOJOB_ERR"
                        logging.error(
                            "Sample {} failed to parse".format(job_id))
                        continue

                ok_samples.append(sample)

            bad_samples = list(set(experiment.samples) - set(ok_samples))

            if args.b and best_sample:
                print(best_res)
                return

            print("Hyperparameters:")
            for param in experiment.hyperparameters:
                print(f"\t{param}")

            if best_sample:
                best_job_id = best_sample.job.job_id if best_sample.job else "NO_JOB"

                print("\nBEST (id={}): {}".format(best_job_id, best_res))
                assert best_sample is not None

                if best_sample.job:
                    run_str = experiment.runner.script_path + " \\\n   "
                    for h, v in best_sample.hyperparam_values.mapping.items():
                        if isinstance(v, float):
                            v = round(v, 2)
                        run_str += " --{}={}".format(h.name, v)

                    print(run_str)
                    print()

            print("STATS:")
            print(f"OK: {len(ok_samples)}\tBAD: {len(bad_samples)}")
            print()

            print("Evaluations:")
            for sample in ok_samples:
                job = sample.job

                proc_stats = ""
                if job and psutil.pid_exists(job.job_id):
                    process = psutil.Process(job.job_id)
                    mem = process.memory_info()
                    proc_stats += f"Process:{process.status()}"
                    proc_stats += f", cpu={process.cpu_percent()}"
                    # TODO fix this on osx, shared={mem.shared}"
                    proc_stats += f", rss={mem.rss}, vms={mem.vms}"

                print(f"{sample}\t{proc_stats}")

            from colored import fg, bg, attr
            for sample in bad_samples:
                print(bg("red") + sample)

            print(attr("reset"))
Пример #21
0
def process_command(command, marked_id, option):
    conn = sqlite3.connect(DBNAME)
    cur = conn.cursor()

    # Check if there are multiple searching:
    item_dic = {}
    if command.find('|') != -1:
        try:
            command_list = command.split('|')
            for c in command_list:
                try:
                    ope = c.split(':')
                    item_dic[ope[0]] = ope[1]
                except:
                    print("Invalid command!")
        except:
            print("Invalid command!")
    else:
        try:
            ope = command.split(':')
            item_dic[ope[0]] = ope[1]
        except:
            print("Invalid command!")  

    # Print a leading welcome remark!
    print ("%s%s Thanks for choosing!!! %s\n" % (fg('white'), bg('cornflower_blue'), attr('reset')))
    print(load_help_text('detail_help.txt'))
    
    # Search by details:
    sort_ls = input("Please choose how you would like to observe the data, or you can input 'exit' to quit: ")
    while sort_ls != "exit":
        # Default value:
        sortby = "Price"
        order = "top"
        number = 5
        if sort_ls.find('|') != -1:
            sort = sort_ls.split('|')[0]
            ls = sort_ls.split('|')[1]
            if sort.split('=')[0] == "sort" and (ls.split('=')[0] == "top" or ls.split('=')[0] == "bottom"):
                try:
                    sortby = sort.split('=')[1]
                    order = ls.split('=')[0]
                    number = int(ls.split('=')[1])
                except:
                    print("Invalid command!")
            else:
                print("Invalid command!")
        elif sort_ls != '':
            if sort_ls.find('sort') != -1:
                try:
                    sortby = sort_ls.split('=')[1]
                except:
                    print("Invalid command!")
            if sort_ls.find('top') != -1 or sort_ls.find('bottom') != -1:
                try:
                    order = sort_ls.split('=')[0]
                    number = int(sort_ls.split('=')[1])
                except:
                    print("Invalid command!")

        # Form a sql statement to execute the searching:
        key_list = ["brand","price","memory","storage","processor","rating","color","size"]
        base_statement = "SELECT Id,[Name],Brand,Size,Processor,Price,[Memory(GB)],Storage,Color,[Review Number],[Average Rating] FROM Laptops WHERE "
        statement = base_statement
        for item in item_dic.items():
            if item[0] != list(item_dic.keys())[0]:
                statement += "AND "
            if item[0] not in key_list:
                print("Invalid command!")
                return
            # Different categories:
            if item[0] == "brand":
                name = item[1]
                statement += "Brand = '%s' "%name
            elif item[0] == "price":
                min_price = float(item[1].split(' ')[0])
                max_price = float(item[1].split(' ')[1])
                statement += "Price >= %f AND Price <= %f "%(min_price, max_price)
            elif item[0] == "memory":
                value = int(item[1])
                statement += "[Memory(GB)] = %d "%value
            elif item[0] == "storage":
                des = item[1]
                statement += "Storage LIKE '%{des}%' ".format(des=des)
            elif item[0] == "processor":
                name = item[1]
                statement += "Processor LIKE '%{name}%' ".format(name=name)
            elif item[0] == "rating":
                min_rating = float(item[1].split(' ')[0])
                max_rating = float(item[1].split(' ')[1])
                statement += "[Average Rating] >= %f AND [Average Rating] <= %f "%(min_rating, max_rating)
            elif item[0] == "color":
                color = item[1]
                statement += "Color LIKE '%{color}%' ".format(color=color)       
            else:
                if item[1].find(' ') != -1:
                    min_size = float(item[1].split(' ')[0])
                    max_size = float(item[1].split(' ')[1])
                    statement += "Size >= %f AND Size <= %f "%(min_size, max_size)
                else:
                    size = item[1]
                    statement += "Size = %f "%size

        if order == "top":
            statement += "ORDER BY %s DESC "%sortby
        else:
            statement += "ORDER BY %s "%sortby
        statement += "LIMIT %d"%number
        # Execute the sql statement:
        try:
            results = cur.execute(statement)
            print_out_results = results.fetchall()
            # Print out words if no search results:
            print ("%s%s Generating your data table... %s" % (fg('white'), bg('cornflower_blue'), attr('reset')))
            if len(print_out_results) == 0:
                print("\nIt seems no searching results found... What about trying another one?\n")
            # Print filtered data:
            if option == "1":
                x = PrettyTable()
                x.field_names = ["Id", "Name", "Brand", "Size","Processor","Price","Memory","Storage","Color","#Review","Avg. Rating"]
                for row in print_out_results:
                    x.add_row(list(row))
                print(x)
            elif option == "2":
                trace = go.Table(
                    header=dict(
                        values=["Id", "Name", "Brand", "Size","Processor","Price","Memory","Storage","Color","#Review","Avg. Rating"],
                        line_color='darkslategray',
                        fill_color='royalblue',
                        font=dict(color='white', size=20),
                        align="center"
                    ),
                    cells=dict(
                        values=pd.DataFrame.from_records(data = print_out_results).T, 
                        line_color='darkslategray',
                        font = dict(color = 'darkslategray', size = 15),
                        align = "center"
                    )
                )
                layout = dict(autosize=True)
                fig = go.Figure(data = [trace], layout = layout)
                fig.update_layout(
                    showlegend = False,
                    title_text = "This is your filtered data:",
                )
                fig.write_html('filtered.html', auto_open = True)
            elif option == "3":
                with open('temp_filtered.csv', 'w', newline='') as csvfile:
                    writer = csv.writer(csvfile, delimiter=',')
                    for i in range(len(print_out_results)):
                        writer.writerow(list(print_out_results[i]))
            
        except:
            print ("%s%s There's problem with your execution, go and check your execution statement:  %s" % (fg('white'), bg('cornflower_blue'), attr('reset')))
            print(statement)
        
        print("\n")

        print(load_help_text('mark_help.txt'))
        marked = input("Do you want to marked any product (Input the id): ")
        if marked != "" and re.match(r'^[0-9 ]*$', marked):
            if marked.find(' ') != -1:
                for number in marked.split(' '):
                    marked_id.append(int(number))
            else:
                marked_id.append(int(marked))
            marked_id = list(set(marked_id))
        elif marked != "" and re.match(r'^[0-9 ]*$', marked):
            print("This is not an id!")
        
        sort_ls = input("\nPlease choose how you would like to observe the data, or you can input 'exit' to quit: ")

    conn.close()
    return marked_id
Пример #22
0
def colorize(string, foreground, background='black'):
    colorized = fg(foreground) + bg(background) + string + attr('reset')
    return colorized
Пример #23
0
from typing import Callable

from colored import bg, fg, attr, stylize


def _make_color_function(color: str) -> Callable:
    def wrapped(msg: str) -> str:
        return str(stylize(msg, color))
    return wrapped


noticeRed = _make_color_function(fg(255) + bg(9) + attr('bold'))
noticeGreen = _make_color_function(fg(255) + bg(76) + attr('bold'))
noticeYellow = _make_color_function(fg(255) + bg(208) + attr('bold'))


red = _make_color_function(fg(9) + bg(0))
red_bold = _make_color_function(fg(9) + bg(0) + attr('bold'))
green = _make_color_function(fg(28) + bg(0))
green_bold = _make_color_function(fg(76) + bg(0) + attr('bold'))
yellow = _make_color_function(fg(208) + bg(0))
yellow_bold = _make_color_function(fg(208) + bg(0) + attr('bold'))
dim_grey = _make_color_function(fg(241) + bg(0) + attr('dim'))
dim_light_grey = _make_color_function(fg(251) + bg(0) + attr('dim'))
Пример #24
0
def get_number(Flag, player_name, input_text, success_text, error_text1,
               error_text2, previous_bet):
    while True:
        try:
            # get the input from the user
            number = str(
                input(
                    input_text.format(fg(31), bg(234), str(player_name),
                                      attr(0))))
            # checks if it is an int
            number = int(number)
            # if it gets the Ace value from the user
            if Flag == 'Ace':
                # checks if it is either 1 or 11; it can't get any other value
                if number == 1 or number == 11:
                    print(
                        success_text.format(fg(3), bg(234), str(number),
                                            attr(0)))
                    # correct the value of Ace
                    if number == 11:
                        return 'Ace11'
                    else:
                        return 'Ace1'
                    break
                # if the value of Ace is an int but not 1 or 11
                else:
                    print(
                        error_text1.format(fg(1), bg(15), str(number),
                                           attr(0)))
                    continue

            elif Flag == 'Bet':
                # checks if the bet is bigger than 0 and the previous one
                if number > 0 and number >= previous_bet:
                    print(
                        success_text.format(fg(3), bg(234), str(number),
                                            attr(0)))
                    return number
                    break
                # if the bet is smaller or equals to zero
                elif number <= 0:
                    print(
                        error_text1.format(fg(1), bg(15), str(number),
                                           attr(0)))
                    continue
                # if the new bet is smaller than the previous one
                if number < previous_bet:
                    error = config.Messages.BET_ERROR_TXT2
                    print(
                        error.format(fg(1), bg(15), str(previous_bet),
                                     attr(0)))
                    continue

            # if it is none of the above
            print(success_text.format(fg(3), bg(234), str(number), attr(0)))
            return number
            break
        # if it is not an int, shows an error message and try agian
        except ValueError:
            print(error_text2.format(fg(1), bg(15), str(number), attr(0)))
            continue
Пример #25
0
def colorPrint(text, fgc=500, bgc=500, attrc="", newline=True, debug=0):
    try:
        import logger

        lloc = "File: output.py | Function: colorPrint | Message: "
        logger.write(
            "i",
            "Trying to use colorPrint with arguments: text=["
            + str(text)
            + "], fgc=["
            + str(fgc)
            + "], bgc=["
            + str(fgc)
            + "], attrc=["
            + str(attrc)
            + "], newline=["
            + str(newline)
            + "],debug=["
            + str(debug)
            + "]!",
            lloc=lloc,
        )
        from colored import fg, style, attr, bg
        import sys

        if newline is True:
            if fgc != 500:
                if bgc == 500:
                    if attrc == "":
                        color = fg(fgc)
                        att = attr(attrc)
                        print(color + text + style.RESET)
                        return True
                    else:
                        color = fg(fgc)
                        att = attr(attrc)
                        print(color + att + text + style.RESET)
                        return True
                else:
                    if attrc == "":
                        color = fg(fgc) + bg(bgc)
                        att = attr(attrc)
                        print(color + text + style.RESET)
                        return True
                    else:
                        color = fg(fgc) + bg(bgc)
                        att = attr(attrc)
                        print(color + att + text + style.RESET)
                        return True
            else:
                if bgc != 500:
                    if attrc == "":
                        color = bg(bgc)
                        att = attr(attrc)
                        print(color + text + style.RESET)
                        return True
                    else:
                        color = bg(bgc)
                        att = attr(attrc)
                        print(color + att + text + style.RESET)
                        return True
        else:
            if fgc != 500:
                if bgc == 500:
                    if attrc == "":
                        color = fg(fgc)
                        att = attr(attrc)
                        sys.stdout.write(color + text + style.RESET)
                        return True
                    else:
                        color = fg(fgc)
                        att = attr(attrc)
                        sys.stdout.write(color + att + text + style.RESET)
                        return True
                else:
                    if attrc == "":
                        color = fg(fgc) + bg(bgc)
                        att = attr(attrc)
                        sys.stdout.write(color + text + style.RESET)
                        return True
                    else:
                        color = fg(fgc) + bg(bgc)
                        att = attr(attrc)
                        sys.stdout.write(color + att + text + style.RESET)
                        return True
            else:
                if bgc != 500:
                    if attrc == "":
                        color = bg(bgc)
                        att = attr(attrc)
                        sys.stdout.write(color + text + style.RESET)
                        return True
                    else:
                        color = bg(bgc)
                        att = attr(attrc)
                        sys.stdout.write(color + att + text + style.RESET)
                        return True
    except ImportError:
        logger.write("e", "ImportError: Some module could not be imported!", lloc=lloc)
        return False
    except StopIteration:
        logger.write("e", "StopIteration: next() method does not point at any object!", lloc=lloc)
        return False
    except SystemExit:
        logger.write("e", "SystemExit: sys.exit() was executed!", lloc=lloc)
        return False
    except ArithmeticError:
        logger.write("e", "ArithmeticError: Numeric calculation error!", lloc=lloc)
        return False
    except OverflowError:
        logger.write("e", "OverflowError: Calculation exceeded maximum limit for numeric type!", lloc=lloc)
        return False
    except FloatingPointError:
        logger.write("e", "FloatingPointError: FloatingPoint calculation failed!", lloc=lloc)
        return False
    except ZeroDivisionError:
        logger.write("e", "ZeroDivisionError: Division or modulo by Zero took place!", lloc=lloc)
        return False
    except AssertionError:
        logger.write("e", "AssertionError: Assert statement failed!", lloc=lloc)
        return False
    except AttributeError:
        logger.write("e", "AttributeError: Failure of attribute reference or assignment!", lloc=lloc)
        return False
    except EOFError:
        logger.write("e", "EOFError: No input from raw_input() or input() as the file has ended!", lloc=lloc)
        return False
    except ImportError:
        logger.write("e", "ImportError: Import statement failed!", lloc=lloc)
        return False
    except KeyboardInterrupt:
        logger.write("e", "KeyboardInterrupt: Program has ended, during KeyboardInterrupt (Ctrl + C)!", lloc=lloc)
        return False
    except LookupError:
        logger.write("e", "LookupError: LookupError!", lloc=lloc)
        return False
    except IndexError:
        logger.write("e", "IndexError: Index in sequence was not found!", lloc=lloc)
        return False
    except KeyError:
        logger.write("e", "KeyError: Key in dictionary was not found!", lloc=lloc)
        return False
    except NameError:
        logger.write("e", "NameError: Identifier was not found in local or global namespace!", lloc=lloc)
        return False
    except UnboundLocalError:
        logger.write("e", "UnboundLocalError: No value was assigned to variable in function or method!", lloc=lloc)
        return False
    except EnvironmentError:
        logger.write("e", "EnvironmentError: Exception occurred outside the Python environment!", lloc=lloc)
        return False
    except IOError:
        logger.write("e", "IOError: Input / Output operation failed!", lloc=lloc)
        return False
    except SyntaxError:
        logger.write("e", "SyntaxError: Syntax error in python code!", lloc=lloc)
        return False
    except IndentationError:
        logger.write("e", "IndentationError: Indentation is not specified properly!", lloc=lloc)
        return False
    except SystemError:
        logger.write("e", "SystemError: Interpreter found internal problem, but interpreter has not exited!", lloc=lloc)
        return False
    except TypeError:
        logger.write(
            "e", "TypeError: Operation or Function is attempted which is invalid for the specific data type!", lloc=lloc
        )
        return False
    except ValueError:
        logger.write(
            "e",
            "ValueError: Built-in function for data type has valid type of arguments, but arguments have invalid values specified!",
            lloc=lloc,
        )
        return False
    except RuntimeError:
        logger.write("e", "RuntimeError: Generated error does not fall into any category!", lloc=lloc)
        return False
    except NotImplementedError:
        logger.write(
            "e",
            "NotImplementedError: Abstract method that needs to be implemented in an inherited class is not actually implemented!",
            lloc=lloc,
        )
        return False
Пример #26
0
 def __getattr__(self, color):
     try:
         bg_color, fg_color = color.split('__')
         return partial(self.format, bg(bg_color) + fg(fg_color))
     except ValueError:
         return partial(self.format, self.default_bg + fg(color))
from githubgateway import GithubAPIGateway
from misc import Helper
import argparse
from colored import fg, bg, attr
from misc.color_translations import rgb2short
from misc.helper2 import get_script_name_from_python_file

parser = argparse.ArgumentParser(prog = get_script_name_from_python_file(__file__))
parser.add_argument("-i", "--issue_number", required=True)
parser.add_argument("-l", "--labels", nargs='+', required=True)
parser.add_argument("-f", "--force-label-creation", dest='force_label_creation', action='store_true')
parser.set_defaults(force_label_creation=False)

args = parser.parse_args()
results, status = GithubAPIGateway(*Helper.owner_and_repo()).add_labels_to_issue(args.issue_number, args.labels, args.force_label_creation)

if status == 200:
  print "Issue {0} labels:".format(args.issue_number)
  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 results['message']
Пример #28
0
#!/bin/env python3


import colored

print('https://pypi.org/project/colored/')

for i in range(1,255):  
    print('%s color test %s%s' %  ( colored.fg(i), colored.attr(0),i ))
    
input("enter to continue")

for i in range(1,255):  
    #print('%s color test %s' %  ( colored.fg(i), colored.attr(0),i ))
    for ii in range(1,255):
        print('%s%s color test %s %s %s' %  ( colored.fg(i), colored.bg(ii), colored.attr(0),i,ii ))
Пример #29
0
import datetime
import json
import re
import select
import sys

import six

from colored import fg, bg, attr

from kafka import KafkaConsumer

colors = {'DEBUG': attr(0),
          'INFO': fg('cyan'),
          'WARNING': fg('orange_1'),
          'ERROR': fg('red')+bg('white'),
          'CRITICAL': fg('magenta_1'),
}
match_color = bg('yellow')+attr(1)
msg_format = "{level} {time}: {msg} [{topic}:{offset}]"

def json_value_deserializer(m):
    try:
        v = json.loads(m.decode('ascii'))
    except ValueError:
        v = '[ValueError in log] ' + m.decode('ascii')
    return v

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("topic")
#!/usr/bin/env python
# coding=utf-8
from colored import bg, fg, attr
"""
    @author: Adrian Verdugo
    @contact: [email protected]
    @github: adrian273
"""

# array para los datos de los trabajadores
data_workers = []
total = 0
"""
    @type = variables para dar estilos
"""
colors = [bg('blue') + fg(15), bg('red') + fg(15), bg('purple_3') + fg(15)]
reset = attr('reset')
bold = attr('bold')

print bold + colors[0] + "Ejercicio numero 3" + reset
for i in range(3):
    #_____________ datos de trabajadores _______________________
    print "¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨"
    name = str(raw_input('>> ingresa nombre \n'))
    hours_work = int(raw_input('>> ingresa horas de trabajo \n'))
    value_hours = int(raw_input('>> ingresa valor hora \n'))
    number_cargo = int(raw_input('>> Ingrese numero carga \n'))
    #_____________ salario normal del trabajador _______________
    salary = hours_work * value_hours
    if number_cargo >= 3:
        salary = salary * 1.1
Пример #31
0
def main():

    colors = (

        "#000000",
        "#800000",
        "#008000",
        "#808000",
        "#000080",
        "#800080",
        "#008080",
        "#C0C0C0",
        "#808080",
        "#FF0000",
        "#00FF00",
        "#FFFF00",
        "#0000FF",
        "#FF00FF",
        "#00FFFF",
        "#FFFFFF",
        "#000000",
        "#00005F",
        "#000087",
        "#0000AF",
        "#0000D7",
        "#0000FF",
        "#005F00",
        "#005F5F",
        "#005F87",
        "#005FAF",
        "#005FD7",
        "#005FFF",
        "#008700",
        "#00875F",
        "#008787",
        "#0087AF",
        "#0087D7",
        "#0087FF",
        "#00AF00",
        "#00AF5F",
        "#00AF87",
        "#00AFAF",
        "#00AFD7",
        "#00AFFF",
        "#00D700",
        "#00D75F",
        "#00D787",
        "#00D7AF",
        "#00D7D7",
        "#00D7FF",
        "#00FF00",
        "#00FF5F",
        "#00FF87",
        "#00FFAF",
        "#00FFD7",
        "#00FFFF",
        "#5F0000",
        "#5F005F",
        "#5F0087",
        "#5F00AF",
        "#5F00D7",
        "#5F00FF",
        "#5F5F00",
        "#5F5F5F",
        "#5F5F87",
        "#5F5FAF",
        "#5F5FD7",
        "#5F5FFF",
        "#5F8700",
        "#5F875F",
        "#5F8787",
        "#5F87AF",
        "#5F87D7",
        "#5F87FF",
        "#5FAF00",
        "#5FAF5F",
        "#5FAF87",
        "#5FAFAF",
        "#5FAFD7",
        "#5FAFFF",
        "#5FD700",
        "#5FD75F",
        "#5FD787",
        "#5FD7AF",
        "#5FD7D7",
        "#5FD7FF",
        "#5FFF00",
        "#5FFF5F",
        "#5FFF87",
        "#5FFFAF",
        "#5FFFD7",
        "#5FFFFF",
        "#870000",
        "#87005F",
        "#870087",
        "#8700AF",
        "#8700D7",
        "#8700FF",
        "#875F00",
        "#875F5F",
        "#875F87",
        "#875FAF",
        "#875FD7",
        "#875FFF",
        "#878700",
        "#87875F",
        "#878787",
        "#8787AF",
        "#8787D7",
        "#8787FF",
        "#87AF00",
        "#87AF5F",
        "#87AF87",
        "#87AFAF",
        "#87AFD7",
        "#87AFFF",
        "#87D700",
        "#87D75F",
        "#87D787",
        "#87D7AF",
        "#87D7D7",
        "#87D7FF",
        "#87FF00",
        "#87FF5F",
        "#87FF87",
        "#87FFAF",
        "#87FFD7",
        "#87FFFF",
        "#AF0000",
        "#AF005F",
        "#AF0087",
        "#AF00AF",
        "#AF00D7",
        "#AF00FF",
        "#AF5F00",
        "#AF5F5F",
        "#AF5F87",
        "#AF5FAF",
        "#AF5FD7",
        "#AF5FFF",
        "#AF8700",
        "#AF875F",
        "#AF8787",
        "#AF87AF",
        "#AF87D7",
        "#AF87FF",
        "#AFAF00",
        "#AFAF5F",
        "#AFAF87",
        "#AFAFAF",
        "#AFAFD7",
        "#AFAFFF",
        "#AFD700",
        "#AFD75F",
        "#AFD787",
        "#AFD7AF",
        "#AFD7D7",
        "#AFD7FF",
        "#AFFF00",
        "#AFFF5F",
        "#AFFF87",
        "#AFFFAF",
        "#AFFFD7",
        "#AFFFFF",
        "#D70000",
        "#D7005F",
        "#D70087",
        "#D700AF",
        "#D700D7",
        "#D700FF",
        "#D75F00",
        "#D75F5F",
        "#D75F87",
        "#D75FAF",
        "#D75FD7",
        "#D75FFF",
        "#D78700",
        "#D7875F",
        "#D78787",
        "#D787AF",
        "#D787D7",
        "#D787FF",
        "#D7AF00",
        "#D7AF5F",
        "#D7AF87",
        "#D7AFAF",
        "#D7AFD7",
        "#D7AFFF",
        "#D7D700",
        "#D7D75F",
        "#D7D787",
        "#D7D7AF",
        "#D7D7D7",
        "#D7D7FF",
        "#D7FF00",
        "#D7FF5F",
        "#D7FF87",
        "#D7FFAF",
        "#D7FFD7",
        "#D7FFFF",
        "#FF0000",
        "#FF005F",
        "#FF0087",
        "#FF00AF",
        "#FF00D7",
        "#FF00FF",
        "#FF5F00",
        "#FF5F5F",
        "#FF5F87",
        "#FF5FAF",
        "#FF5FD7",
        "#FF5FFF",
        "#FF8700",
        "#FF875F",
        "#FF8787",
        "#FF87AF",
        "#FF87D7",
        "#FF87FF",
        "#FFAF00",
        "#FFAF5F",
        "#FFAF87",
        "#FFAFAF",
        "#FFAFD7",
        "#FFAFFF",
        "#FFD700",
        "#FFD75F",
        "#FFD787",
        "#FFD7AF",
        "#FFD7D7",
        "#FFD7FF",
        "#FFFF00",
        "#FFFF5F",
        "#FFFF87",
        "#FFFFAF",
        "#FFFFD7",
        "#FFFFFF",
        "#080808",
        "#121212",
        "#1C1C1C",
        "#262626",
        "#303030",
        "#3A3A3A",
        "#444444",
        "#4E4E4E",
        "#585858",
        "#626262",
        "#6C6C6C",
        "#767676",
        "#808080",
        "#8A8A8A",
        "#949494",
        "#9E9E9E",
        "#A8A8A8",
        "#b2b2b2",
        "#bCbCbC",
        "#C6C6C6",
        "#D0D0D0",
        "#DADADA",
        "#E4E4E4",
        "#EEEEEE"

    )

    for color in colors:
        print(
            "{}This text is colored: {}{}".format(
                fg(color),
                color,
                attr("reset")))
        print(
            "{}This text is colored: {}{}".format(
                bg(color),
                color,
                attr("reset")))
        time.sleep(0.1)
Пример #32
0
 def background(self, color):
     self.background_color = color
     for y in self.grid:
         for x in self.grid[y]:
             pixel = self.grid[y][x]
             pixel['pixel'] = stylize(" ", colored.bg(color))
Пример #33
0
#!/usr/bin/python3

import requests
import sys, os
from bs4 import BeautifulSoup
import time
from vid2mp3 import *
from colored import fg, bg, attr

index_color = fg("black") + bg("yellow") + attr("bold")
dur_color = fg("orchid")
color = fg("yellow") + attr("bold")
reset = attr("reset")

youtube = "https://www.youtube.com"
search_url = "/results?search_query="


def search(data):
    print("\nRetrieving results.... \n")

    count = 1
    url = []

    for page in range(1, 6):
        res = requests.get(youtube + search_url + data + "&page=" + str(page))
        res.raise_for_status()

        soup = BeautifulSoup(res.text)
        search_r_title = soup.select(".yt-lockup-title a")
        search_r_duration = soup.select(".yt-lockup-title span")
def load_from_firebase(
    dbURL="https://tingle-pilot-collected-data.firebaseio.com/",
    notes=False,
    start=None,
    stop=None,
    combine=False,
    marked=False
): # pragma: no cover
    """
    Function to load data from Firebase.
    Requires [Firebase service account credentials](https://console.firebase.google.com/project/tingle-pilot-collected-data/settings/serviceaccounts/adminsdk)
    in JSON format.

    Parameters
    ----------
    dbURL : string (optional)
        Firebase database to pull data from

    notes : Boolean (optional)
        Return notes as well as data?

    start : date or datetime (optional)
        start time of data to include (eg, `datetime.date(2018,3,6)`)

    stop : date or datetime (optional)
        stop time of data to include (eg, `datetime.date(2018,3,6)`)

    combine : Boolean (optional)
        combine coordinators into a single row?

    marked : Boolean (optional)
        only include ontarget==True rows?

    Returns
    -------
    data : DataFrame
        Pandas DataFrame of data from Firebase

    notes : DataFrame (optional)
        Pandas DataFrame of notes from Firebase iff parameter notes==True,
    """
    # Fetch the service account key JSON file contents
    try:
        creds = [
            key for key in os.listdir(
                os.path.join(
                    'firebase-credentials'
                )
            ) if (
                "tingle-pilot-collected-data-firebase-adminsdk" in key
            ) and key.endswith(
                ".json"
            )
        ]
        cred = credentials.Certificate(os.path.join(
            "firebase-credentials",
            creds[0]
        ))
    except:
        print(stylize(
            "Data not loaded from Firebase!",
            colored.fg(
                "red"
            ) + colored.bg(
                226
            )
        ))
        if len(creds):
            print(
                "Save Firebase service account credentials "
                "in the directory \"firebase-credentials\" in JSON format with "
                "\"tingle-pilot-collected-data-firebase-adminsdk\" in the "
                "filename. Current files in \"firebase-credentials\":{0}".format(
                    "\n\t".join(creds)
                )
            )
        else:
            print(
                "Save Firebase service account credentials "
                "in the directory \"firebase-credentials\" in JSON format with "
                "\"tingle-pilot-collected-data-firebase-adminsdk\" in the "
                "filename."
            )
        print(
            "\nDownload credentials JSON from https://console.firebase.google.com"
            "/project/tingle-pilot-collected-data/settings/serviceaccounts/"
            "adminsdk"
        )
        return(pd.DataFrame())
    try:
        # Initialize the app with a service account, granting admin privileges
        firebase_admin.initialize_app(cred, {
            'databaseURL': dbURL
        })
    except ValueError as e:
        print(e)
    samples = db.reference('samples').get()
    batches = {
        k: v for d in [
            samples[key] for key in samples
        ] for k, v in d.items()
    }
    for batch in batches:
        b2 = []
        for row in batches[batch]['batchedData']:
            b2.append(
                {
                    **row,
                    'coordinator': batches[
                        batch
                    ][
                        'username'
                    ]
                }
            )
        batches[batch]['batchedData'] = b2
    data = pd.DataFrame(
        list(
            chain.from_iterable(
                [
                    batches[
                        batch
                    ][
                        'batchedData'
                    ] for batch in batches
                ]
            )
        )
    )
    data["human-readable timestamp"] = pd.to_datetime(
        data["timestamp"]*1000000
    )
    if stop:
        stop = start + datetime.timedelta(days=1) if (
            (start) and
            (stop == start)
        ) else stop
    data = data[
            (data["human-readable timestamp"] >= start) &
            (data["human-readable timestamp"] <= stop)
        ] if (start and stop) else data[
            data["human-readable timestamp"] >= start
        ] if start else data[
            data["human-readable timestamp"] <= stop
        ] if stop else data
    data.sort_values(
        "timestamp",
        inplace=True
    )
    data = data.reset_index(drop=True)
    data = combine_coordinators(data) if combine else data
    data = data[data.ontarget == True] if marked else data
    data = data.reset_index(drop=True)
    print(stylize(
        "Data loaded from Firebase!",
        colored.fg(
            "green"
        )
    ))
    if not notes:
        return(data)
    else:
        notesNotesNotes = db.reference('notes').get()
        notesBatches = {
            k: v for d in [
                notesNotesNotes[
                    key
                ] for key in notesNotesNotes
            ] for k, v in d.items()
        }
        notes = pd.DataFrame([{
            k if k!= "lastsample" else "timestamp": notesBatches[
                i
            ][
                k
            ] if k != "lastsample" else notesBatches[
                i
            ][
                k
            ][
                "timestamp"
            ] if "timestamp" in notesBatches[
                i
            ][
                k
            ] else None for k in [
                "notes",
                "lastsample",
                "username"
            ] if k in notesBatches[i]
        } for i in notesBatches])
        notes["human-readable timestamp"] = pd.to_datetime(
            notes["timestamp"]*1000000
        )
        notes = notes[
                (notes["human-readable timestamp"] >= start) &
                (notes["human-readable timestamp"] <= stop)
            ] if (start and stop) else notes[
                notes["human-readable timestamp"] >= start
            ] if start else notes[
                notes["human-readable timestamp"] <= stop
            ] if stop else notes
        notes = notes[
            notes["timestamp"] > 0
        ].sort_values("timestamp")
        data = pd.merge(
            data,
            notes.set_index(
                "human-readable timestamp"
            ).reindex(
                data["human-readable timestamp"],
                method="ffill"
            ).drop(
                "timestamp",
                axis=1
            ).drop_duplicates(),
            left_on="human-readable timestamp",
            right_index=True,
            how="outer"
        )
        data = dropX(data)
    return(data, notes)
Пример #35
0
def _visualize(query, keyword, answers, request_options, html=None): # pylint: disable=too-many-locals

    search_mode = bool(keyword)

    highlight = not bool(request_options and request_options.get('no-terminal'))
    color_style = request_options.get('style', '')
    if color_style not in COLOR_STYLES:
        color_style = ''

    found = True            # if the page was found in the database
    editable = False        # can generated page be edited on github (only cheat.sheets pages can)
    result = ""
    for topic, answer in answers:   # pylint: disable=too-many-nested-blocks

        if topic == 'LIMITED':
            result += colored.bg('dark_goldenrod') \
                    + colored.fg('yellow_1') \
                    + ' ' +  answer + ' ' \
                    + colored.attr('reset') + "\n"
            break

        topic_type = get_topic_type(topic)
        highlight = (highlight
                     and topic not in [":list", ":bash_completion"]
                     and topic_type not in ["unknown"]
                    )
        found = found and not topic_type == 'unknown'
        editable = editable or topic_type == "cheat.sheets"

        if topic_type == "internal" and highlight:
            answer = _colorize_internal(topic, answer, html)
        else:
            answer = _colorize_ansi_answer(
                topic, answer, color_style,
                highlight_all=highlight,
                highlight_code=(topic_type == 'question'
                                and not request_options.get('add_comments')
                                and not request_options.get('remove_text')),
                unindent_code=request_options.get('unindent_code')
                )

        if search_mode:
            if not highlight:
                result += "\n[%s]\n" % topic
            else:
                result += "\n%s%s %s %s%s\n" % (colored.bg('dark_gray'),
                                                colored.attr("res_underlined"),
                                                topic,
                                                colored.attr("res_underlined"),
                                                colored.attr('reset'))
        result += answer

    result = result.strip('\n') + "\n"

    if search_mode:
        editable = False
        repository_button = ''
    else:
        repository_button = _github_button(topic_type)

    if html:
        result = _render_html(
            query, result, editable, repository_button, request_options)


    return result, found
Пример #36
0
      
        else:
            print("Please correct your inputs!")

        print(load_help_text('mark_help2.txt'))
        command = input("Input your choice: ")
            
    conn.close()
    return marked_id


if __name__ == "__main__":
    # Figure out the very beginning interface:
    f = Figlet(font='slant')
    print(f.renderText(" Laptop World "))
    print ("%s%s Welcome to Yirui's database for laptops!!! %s\n" % (fg('white'), bg('cornflower_blue'), attr('reset')))
    print(load_help_text('help.txt'))
    option = input("Please select either 1 or 2 or 3 to choose your option: ")
    print("\n\n")

    # Print out help text if the user selects to stay in console:
    print(load_help_text('console_help.txt'))
    attri = input("Please choose the attribute(s) you want to focus on, or you can input 'exit' to quit: ")
    marked_id = []
    while attri != "exit":
        
        # Add marking functionality:
        marked_id = process_command(attri, marked_id, option)

        # Now is the marked interface:
        marked_id = marked_command(marked_id, option)
Пример #37
0
arr1 = [
    '6 Génopode - Center for Integrative Genomics', 'Université de Lausanne',
    '1015 Lausanne', 'Switzerland.'
]
arr2 = [
    '7 Department of Plastic Surgery', 'China-Japan Friendship Hospital',
    'Beijing', 'China.'
]
arr3 = [
    '8 Department of Emergency', 'China-Japan Friendship Hospital', 'Beijing',
    'China.'
]
arr4 = [
    '2 Department of Pathogen Biology',
    'The Chinses Center for Disease Control and Prevention', 'Beijing',
    'China.'
]
arr5 = [
    '2 Department of Biomedical and Health Informatics',
    "The Children's Hospital of Philadelphia", 'Philadelphia', 'PA', '19104',
    'USA.'
]
lugar = placesDisplay(arr5, abuscar)

error = bg(1) + fg('white')
reset = attr('reset')
print(error, lugar, reset)

print(lugar)
Пример #38
0
def marked_command(marked_id, option):
    conn = sqlite3.connect(DBNAME)
    cur = conn.cursor()
    print ("%s%s Welcome to your marked cart! %s" % (fg('white'), bg('cornflower_blue'), attr('reset')))
    print(load_help_text('mark_help2.txt'))
    command = input("Input your choice: ")
    while command != "leave marked":
        if command == "marked check":

            if option == "1":
                x = PrettyTable()
                x.field_names = ["Id", "Name", "Brand", "Size","Processor","Price","Memory","Storage","Color","#Review","Avg. Rating"]

                for id_ in marked_id:
                    statement = "SELECT Id,[Name],Brand,Size,Processor,Price,[Memory(GB)],Storage,Color,[Review Number],[Average Rating] FROM Laptops WHERE Id = %d"%id_
                    result = cur.execute(statement).fetchone()
                    x.add_row(list(result))
                print(x)

            elif option == "2":
                statement = "SELECT Id,[Name],Brand,Size,Processor,Price,[Memory(GB)],Storage,Color,[Review Number],[Average Rating] FROM Laptops WHERE Id IN ({seq})".format(seq = ','.join('?'*len(marked_id)))
                print_out_results = cur.execute(statement, marked_id).fetchall()

                trace = go.Table(
                    header=dict(
                        values=["Id", "Name", "Brand", "Size","Processor","Price","Memory","Storage","Color","#Review","Avg. Rating"],
                        line_color='darkslategray',
                        fill_color='paleturquoise',
                        font=dict(color='black', size=20),
                        align="center"
                    ),
                    cells=dict(
                        values=pd.DataFrame.from_records(data = print_out_results).T, 
                        fill_color='lavender',
                        font = dict(color = 'darkslategray', size = 15),
                        align = "center"
                    )
                )
                layout = dict(autosize=True)
                fig = go.Figure(data = [trace], layout = layout)
                fig.update_layout(
                    showlegend=False,
                    title_text="These are your marked laptops:",
                )
                fig.write_html('marked.html', auto_open = True)  

            elif option == "3":
                statement = "SELECT Id,[Name],Brand,Size,Processor,Price,[Memory(GB)],Storage,Color,[Review Number],[Average Rating] FROM Laptops WHERE Id IN ({seq})".format(seq = ','.join('?'*len(marked_id)))
                print_out_results = cur.execute(statement, marked_id).fetchall()
                with open('temp_marked.csv', 'w', newline='') as csvfile:
                    writer = csv.writer(csvfile, delimiter=',')
                    for i in range(len(print_out_results)):
                        writer.writerow(list(print_out_results[i]))                

        elif command.find("marked delete") != -1:
            delete_id = int(command[(command.find("marked delete")+14):])
            for id_ in marked_id:
                if id_ == delete_id:
                    marked_id.remove(delete_id)
                    break
            marked_id = list(set(marked_id))
            print("Laptop of Id %d has been deleted!"%delete_id)
        
        elif command.find("marked reviews") != -1:
            print ("%s%s Reviews:  %s" % (fg('white'), bg('cornflower_blue'), attr('reset')))
            review_id = int(command[(command.find("marked reviews")+15):])
            statement = "SELECT t2.[Review 1],t2.[Review 2],t2.[Review 3],t2.[Review 4],t2.[Review 5],t2.[Review 6],t2.[Review 7] FROM Laptops AS t1 JOIN Reviews AS t2 ON t1.SKU=t2.SKU WHERE t1.Id = %d"%review_id
            results = cur.execute(statement).fetchone()
            if option == "1":
                i = 1
                for review in results:
                    if review != "":
                        print("%d.%s"%(i,review))
                        print('\n\n')
                        i += 1
            elif option == "2":
                df = pd.DataFrame(columns=["Reviews"])
                for result in results:
                    df.loc[len(df)] = result

                trace = go.Table(
                    header=dict(
                        values=["Reviews"],
                        line_color='lightgrey',
                        fill_color='paleturquoise',
                        font=dict(color='white', size=20),
                        align="center"
                    ),
                    cells=dict(
                        values=df.T, 
                        fill_color='lavender',
                        font = dict(color = 'darkslategray', size = 15),
                        align = "center"
                    )
                )
                fig = go.Figure(data = [trace])
                fig.update_layout(
                    showlegend=False,
                    title_text="Look at the reviews:",
                )
                fig.write_html('reviews.html', auto_open = True)
            elif option == "3":
                with open('temp_reviews.csv', 'w', newline='') as csvfile:
                    writer = csv.writer(csvfile)
                    for i in results:           
                        writer.writerow([i]) 

            print('\n')
        
        elif command.find("marked compare") != -1:
            id1 = int(command.split(' ')[2])
            id2 = int(command.split(' ')[3])
            if option == "1":
                x = PrettyTable()
                x.field_names = ["Id", "Name", "Brand", "Size","Processor","Price","Memory","Storage","Color","#Review","Avg. Rating"]
                
                statement = "SELECT Id,[Name],Brand,Size,Processor,Price,[Memory(GB)],Storage,Color,[Review Number],[Average Rating] FROM Laptops WHERE Id = %d"%id1
                result = cur.execute(statement).fetchone()
                x.add_row(list(result))
                statement = "SELECT Id,[Name],Brand,Size,Processor,Price,[Memory(GB)],Storage,Color,[Review Number],[Average Rating] FROM Laptops WHERE Id = %d"%id2
                result = cur.execute(statement).fetchone()
                x.add_row(list(result))

                print(x)
            elif option == "2":
                columns =["Id", "Name", "Brand", "Size","Processor","Price","Memory","Storage","Color","#Review","Avg. Rating"]
                df = pd.DataFrame(columns=columns)

                statement = "SELECT Id,[Name],Brand,Size,Processor,Price,[Memory(GB)],Storage,Color,[Review Number],[Average Rating] FROM Laptops WHERE Id = %d"%id1
                result1 = list(cur.execute(statement).fetchone())
                statement = "SELECT Id,[Name],Brand,Size,Processor,Price,[Memory(GB)],Storage,Color,[Review Number],[Average Rating] FROM Laptops WHERE Id = %d"%id2
                result2 = list(cur.execute(statement).fetchone())
                df.loc[0] = result1
                df.loc[1] = result2 

                fig = make_subplots(rows=2, cols=4,
                    specs=[[{"type": "table","colspan": 4},None,None,None],
                        [{"type": "pie"},{"type": "pie"},{"type": "pie"},{"type": "pie"}]],
                    subplot_titles=("Record Table","Price Comparison","Size Comparison","Memory Comparison","Average Rating Comparison")
                )

                fig.add_trace(
                    go.Table(
                        header=dict(
                            values=["Id", "Name", "Brand", "Size","Processor","Price","Memory","Storage","Color","#Review","Avg. Rating"],
                            line_color='darkslategray',
                            fill_color='paleturquoise',
                            font=dict(color='black', size=20),
                            align="center"
                        ),
                        cells=dict(
                            values = df.T, 
                            fill_color='lavender',
                            font = dict(color = 'darkslategray', size = 15),
                            align = "center",
                            height=30
                        )
                    ),
                    row=1, col=1
                )
                fig.add_trace(
                    go.Pie(
                        labels = ['%d'%id1,'%d'%id2],
                        values = [df.loc[0, "Price"], df.loc[1, "Price"]],
                        hole=.3,
                        hoverinfo = 'label',
                        textinfo='value', 
                        textfont_size=20,
                    ),
                    row=2, col=1
                )
                fig.add_trace(
                    go.Pie(
                        labels = ['%d'%id1,'%d'%id2],
                        values = [df.loc[0, "Size"], df.loc[1, "Size"]],
                        hole=.3,
                        hoverinfo = 'label',
                        textinfo='value', 
                        textfont_size=20,
                    ),
                    row=2, col=2
                )
                fig.add_trace(
                    go.Pie(
                        labels = ['%d'%id1,'%d'%id2],
                        values = [df.loc[0, "Memory"], df.loc[1, "Memory"]],
                        hole=.3,
                        hoverinfo = 'label',
                        textinfo='value', 
                        textfont_size=20,
                    ),
                    row=2, col=3
                )
                fig.add_trace(
                    go.Pie(
                        labels = ['%d'%id1,'%d'%id2],
                        values = [df.loc[0, "Avg. Rating"], df.loc[1, "Avg. Rating"]],
                        hole=.3,
                        hoverinfo = 'label',
                        textinfo='value', 
                        textfont_size=20,
                    ),
                    row=2, col=4
                )
                  
                fig.update_layout(
                    height=800,
                    showlegend=True,
                    title_text="Compare laptops Id %d and Id %d"%(id1,id2),
                )
                fig.write_html('compare.html', auto_open = True)
            elif option == "3":
                statement = "SELECT Id,[Name],Brand,Size,Processor,Price,[Memory(GB)],Storage,Color,[Review Number],[Average Rating] FROM Laptops WHERE Id = %d"%id1
                result1 = list(cur.execute(statement).fetchone())
                statement = "SELECT Id,[Name],Brand,Size,Processor,Price,[Memory(GB)],Storage,Color,[Review Number],[Average Rating] FROM Laptops WHERE Id = %d"%id2
                result2 = list(cur.execute(statement).fetchone())
                with open('temp_compared.csv', 'w', newline='') as csvfile:
                    writer = csv.writer(csvfile, delimiter=',')
                    writer.writerow(result1) 
                    writer.writerow(result2) 
      
        else:
            print("Please correct your inputs!")

        print(load_help_text('mark_help2.txt'))
        command = input("Input your choice: ")
            
    conn.close()
    return marked_id
Пример #39
0
You can use the arrow keys (left, right, up, and down) to scroll around the table as well as the PageUp/PageDown keys.
You can quit out of the pager by typing "q".  You can also search for text within the pager using "/".

WARNING: This example requires the tableformatter module: https://github.com/python-tableformatter/tableformatter
- pip install tableformatter
"""
import argparse
from typing import Tuple

import cmd2
import tableformatter as tf

# Configure colors for when users chooses the "-c" flag to enable color in the table output
try:
    from colored import bg
    BACK_PRI = bg(4)
    BACK_ALT = bg(22)
except ImportError:
    try:
        from colorama import Back
        BACK_PRI = Back.LIGHTBLUE_EX
        BACK_ALT = Back.LIGHTYELLOW_EX
    except ImportError:
        BACK_PRI = ''
        BACK_ALT = ''


# Formatter functions
def no_dec(num: float) -> str:
    """Format a floating point number with no decimal places."""
    return "{}".format(round(num))
Пример #40
0
from sqlalchemy.orm import sessionmaker, scoped_session, Query
from sqlalchemy.sql import func, select, case, functions
from sqlalchemy import create_engine
from sshame.db import Host, Base, Key, Credential, Command, CommandAlias

version = "0.11"

try:
    from colorama import Back
    BACK_RESET = Back.RESET
    BACK_GREEN = Back.LIGHTGREEN_EX
    BACK_BLUE = Back.LIGHTBLUE_EX
except ImportError:
    try:
        from colored import bg
        BACK_RESET = bg(0)
        BACK_BLUE = bg(27)
        BACK_GREEN = bg(119)
    except ImportError:
        BACK_RESET = ''
        BACK_BLUE = ''
        BACK_GREEN = ''

# https://www.pythoncentral.io/sqlalchemy-orm-examples/
# db = sqlite3.connect('session.db')

logging.getLogger().setLevel(logging.DEBUG)
asyncssh.set_log_level(logging.DEBUG)
log = logging.getLogger('sshame')
asyncssh.set_debug_level(2)
Пример #41
0
import vlc
from main import play_sound
from colored import fg, bg, attr
from graphics import print_board
from graphics import init_board

# Global variables
ALLOWED_LETTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
ALLOWED_NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
color_sea = fg('#C0C0C0') + bg('deep_sky_blue_4b')
color_miss = fg('grey_7') + bg('deep_sky_blue_4b')
color_hit = fg('orange_red_1') + bg('deep_sky_blue_4b')
color_sunk = fg('red_1') + bg('deep_sky_blue_4b')
res = attr('reset')


def get_touching_coords(coord):
    '''
    Get horizantally or vertically neighbour coordinates of a coordinate
        @param list coord The coordinate of which neighbours will be returned
        @return list The neighbour coordinates
    '''
    touching = []
    # corner case
    if coord == [0, 0]:
        touching.extend([[0, 1], [1, 0]])
    elif coord == [0, 9]:
        touching.extend([[0, 8], [1, 9]])
    elif coord == [9, 0]:
        touching.extend([[9, 1], [8, 0]])
    elif coord == [9, 9]:
Пример #42
0
def logStartOfScript():
    date_string = datetime.datetime.now().strftime("%d.%b.%Y - %H:%M:%S %z")
    print(stylize("START@ " + date_string, bg('dark_blue')+fg('white')+attr("bold") ))
Пример #43
0
#coding:utf8
from colored import fg, bg, attr
from colored import fore, back, style
print '%s Hello World !!! %s' % (fg(1), attr(0))
print '%s%s Hello World !!! %s' %  (fg(1), bg(15), attr(0))

print ('%s%s Hello World !!! %s' % (fg('white'), bg('yellow'), attr('reset')))
print ('%s%s Hello World !!! %s' % (fg('orchid'), attr('bold'), attr('reset')))

color = fg('#c0c0c0') + bg('#00005f')
reset = attr('reset')
print color + 'Hello World' + reset
color = bg('indian_red_1a') + fg('white')
print color + 'Hello World' + reset

print fore.LIGHT_BLUE + back.RED + style.BOLD + 'Hello World' + style.RESET
Пример #44
0
def print_board(board, score):

    # Prints the game board.
    os.system('clear')
    print(
          '%s' % (fg(130)) + u'    \u250F'+u'\u2501'*31+u'\u2513\n'
          u'    \u2503'+'%s' % (attr(0))+' {} {:22} '.format('Score:', score)+'%s' % (fg(130))
          + u'\u2503\n' '%s' % (fg(130)) + u'    \u2517'+u'\u2501'*31+u'\u251B\n'
    )
    print('%s' % (fg(130)) + u'    \u250F'+(u'\u2501'*7+u'\u2533')*3+u'\u2501'*7+u'\u2513'+'%s' % (attr(0)))
    n = 0
    for i in board:
        j = (i[0:])
        c = 0
        clist = [250, 250, 250, 250]
        for k in board:
            j = (i[0:])
            c = 0
            for l in range(4):
                if j[l] == 2:
                    clist[l] = 240
                if j[l] == 4:
                    clist[l] = 235
                if j[l] == 8:
                    clist[l] = 212
                if j[l] == 16:
                    clist[l] = 211
                if j[l] == 32:
                    clist[l] = 210
                if j[l] == 64:
                    clist[l] = 209
                if j[l] == 128:
                    clist[l] = 216
                if j[l] == 256:
                    clist[l] = 215
                if j[l] == 512:
                    clist[l] = 214
                if j[l] == 1024:
                    clist[l] = 83
                if j[l] == 2048:
                    clist[l] = 82
                if j[l] == 4096:
                    clist[l] = 4
                if j[l] == 8192:
                    clist[l] = 27
                if j[l] == 16384:
                    clist[l] = 21
                if j[l] == 32768:
                    clist[l] = 20
                if j[l] == 65536:
                    clist[l] = 19
        c1 = clist[0]
        c2 = clist[1]
        c3 = clist[2]
        c4 = clist[3]
        row = '%s' % (fg(130))+u'    \u2503'+'%s' % (attr(0)) \
              + '%s%s %s{:>5} %s'.format(str(j[0])) % (fg(255), bg(c1), attr(1), attr(0)) \
              + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) \
              + '%s%s %s{:>5} %s'.format(str(j[1])) % (fg(255), bg(c2), attr(1), attr(0)) \
              + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) \
              + '%s%s %s{:>5} %s'.format(str(j[2])) % (fg(255), bg(c3), attr(1), attr(0)) \
              + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) \
              + '%s%s %s{:>5} %s'.format(str(j[3])) % (fg(255), bg(c4), attr(1), attr(0)) \
              + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0))
        print(
              '%s' % (fg(130))+u'    \u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c1), bg(c1), attr(0))
              + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c2), bg(c2), attr(0))
              + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c3), bg(c3), attr(0))
              + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c4), bg(c4), attr(0))
              + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0))
        )
        print(row)
        if n < 3:
            print(
                  '%s' % (fg(130))+u'    \u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c1), bg(c1), attr(0))
                  + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c2), bg(c2), attr(0))
                  + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c3), bg(c3), attr(0))
                  + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c4), bg(c4), attr(0))
                  + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0))
            )
            print('%s' % (fg(130)) + u'    \u2523'+(u'\u2501'*7+u'\u254B')*3+u'\u2501'*7+u'\u252B'+'%s' % (attr(0)))
        else:
            print(
                  '%s' % (fg(130))+u'    \u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c1), bg(c1), attr(0))
                  + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c2), bg(c2), attr(0))
                  + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c3), bg(c3), attr(0))
                  + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0)) + '%s%s       %s' % (fg(c4), bg(c4), attr(0))
                  + '%s' % (fg(130))+u'\u2503'+'%s' % (attr(0))
            )
            print('%s' % (fg(130)) + u'    \u2517'+(u'\u2501'*7+u'\u253B')*3+u'\u2501'*7+u'\u251B'+'%s' % (attr(0)))
        n += 1
    print('\n{:<10} {:^20} {:>10}'.format('w = up', 'a = left', 'x = quit'))
    print('{:<10} {:^22} {:>12}'.format('s = down', 'd = right', 'n = new game'))
Пример #45
0
def main():

    colors = (

        "black",
        "red",
        "green",
        "yellow",
        "blue",
        "magenta",
        "cyan",
        "light_gray",
        "dark_gray",
        "light_red",
        "light_green",
        "light_yellow",
        "light_blue",
        "light_magenta",
        "light_cyan",
        "white",
        "grey_0",
        "navy_blue",
        "dark_blue",
        "blue_3a",
        "blue_3b",
        "blue_1",
        "dark_green",
        "deep_sky_blue_4a",
        "deep_sky_blue_4b",
        "deep_sky_blue_4c",
        "dodger_blue_3",
        "dodger_blue_2",
        "green_4",
        "spring_green_4",
        "turquoise_4",
        "deep_sky_blue_3a",
        "deep_sky_blue_3b",
        "dodger_blue_1",
        "green_3a",
        "spring_green_3a",
        "dark_cyan",
        "light_sea_green",
        "deep_sky_blue_2",
        "deep_sky_blue_1",
        "green_3b",
        "spring_green_3b",
        "spring_green_2a",
        "cyan_3",
        "dark_turquoise",
        "turquoise_2",
        "green_1",
        "spring_green_2b",
        "spring_green_1",
        "medium_spring_green",
        "cyan_2",
        "cyan_1",
        "dark_red_1",
        "deep_pink_4a",
        "purple_4a",
        "purple_4b",
        "purple_3",
        "blue_violet",
        "orange_4a",
        "grey_37",
        "medium_purple_4",
        "slate_blue_3a",
        "slate_blue_3b",
        "royal_blue_1",
        "chartreuse_4",
        "dark_sea_green_4a",
        "pale_turquoise_4",
        "steel_blue",
        "steel_blue_3",
        "cornflower_blue",
        "chartreuse_3a",
        "dark_sea_green_4b",
        "cadet_blue_2",
        "cadet_blue_1",
        "sky_blue_3",
        "steel_blue_1a",
        "chartreuse_3b",
        "pale_green_3a",
        "sea_green_3",
        "aquamarine_3",
        "medium_turquoise",
        "steel_blue_1b",
        "chartreuse_2a",
        "sea_green_2",
        "sea_green_1a",
        "sea_green_1b",
        "aquamarine_1a",
        "dark_slate_gray_2",
        "dark_red_2",
        "deep_pink_4b",
        "dark_magenta_1",
        "dark_magenta_2",
        "dark_violet_1a",
        "purple_1a",
        "orange_4b",
        "light_pink_4",
        "plum_4",
        "medium_purple_3a",
        "medium_purple_3b",
        "slate_blue_1",
        "yellow_4a",
        "wheat_4",
        "grey_53",
        "light_slate_grey",
        "medium_purple",
        "light_slate_blue",
        "yellow_4b",
        "dark_olive_green_3a",
        "dark_green_sea",
        "light_sky_blue_3a",
        "light_sky_blue_3b",
        "sky_blue_2",
        "chartreuse_2b",
        "dark_olive_green_3b",
        "pale_green_3b",
        "dark_sea_green_3a",
        "dark_slate_gray_3",
        "sky_blue_1",
        "chartreuse_1",
        "light_green_2",
        "light_green_3",
        "pale_green_1a",
        "aquamarine_1b",
        "dark_slate_gray_1",
        "red_3a",
        "deep_pink_4c",
        "medium_violet_red",
        "magenta_3a",
        "dark_violet_1b",
        "purple_1b",
        "dark_orange_3a",
        "indian_red_1a",
        "hot_pink_3a",
        "medium_orchid_3",
        "medium_orchid",
        "medium_purple_2a",
        "dark_goldenrod",
        "light_salmon_3a",
        "rosy_brown",
        "grey_63",
        "medium_purple_2b",
        "medium_purple_1",
        "gold_3a",
        "dark_khaki",
        "navajo_white_3",
        "grey_69",
        "light_steel_blue_3",
        "light_steel_blue",
        "yellow_3a",
        "dark_olive_green_3",
        "dark_sea_green_3b",
        "dark_sea_green_2",
        "light_cyan_3",
        "light_sky_blue_1",
        "green_yellow",
        "dark_olive_green_2",
        "pale_green_1b",
        "dark_sea_green_5b",
        "dark_sea_green_5a",
        "pale_turquoise_1",
        "red_3b",
        "deep_pink_3a",
        "deep_pink_3b",
        "magenta_3b",
        "magenta_3c",
        "magenta_2a",
        "dark_orange_3b",
        "indian_red_1b",
        "hot_pink_3b",
        "hot_pink_2",
        "orchid",
        "medium_orchid_1a",
        "orange_3",
        "light_salmon_3b",
        "light_pink_3",
        "pink_3",
        "plum_3",
        "violet",
        "gold_3b",
        "light_goldenrod_3",
        "tan",
        "misty_rose_3",
        "thistle_3",
        "plum_2",
        "yellow_3b",
        "khaki_3",
        "light_goldenrod_2a",
        "light_yellow_3",
        "grey_84",
        "light_steel_blue_1",
        "yellow_2",
        "dark_olive_green_1a",
        "dark_olive_green_1b",
        "dark_sea_green_1",
        "honeydew_2",
        "light_cyan_1",
        "red_1",
        "deep_pink_2",
        "deep_pink_1a",
        "deep_pink_1b",
        "magenta_2b",
        "magenta_1",
        "orange_red_1",
        "indian_red_1c",
        "indian_red_1d",
        "hot_pink_1a",
        "hot_pink_1b",
        "medium_orchid_1b",
        "dark_orange",
        "salmon_1",
        "light_coral",
        "pale_violet_red_1",
        "orchid_2",
        "orchid_1",
        "orange_1",
        "sandy_brown",
        "light_salmon_1",
        "light_pink_1",
        "pink_1",
        "plum_1",
        "gold_1",
        "light_goldenrod_2b",
        "light_goldenrod_2c",
        "navajo_white_1",
        "misty_rose1",
        "thistle_1",
        "yellow_1",
        "light_goldenrod_1",
        "khaki_1",
        "wheat_1",
        "cornsilk_1",
        "grey_100",
        "grey_3",
        "grey_7",
        "grey_11",
        "grey_15",
        "grey_19",
        "grey_23",
        "grey_27",
        "grey_30",
        "grey_35",
        "grey_39",
        "grey_42",
        "grey_46",
        "grey_50",
        "grey_54",
        "grey_58",
        "grey_62",
        "grey_66",
        "grey_70",
        "grey_74",
        "grey_78",
        "grey_82",
        "grey_85",
        "grey_89",
        "grey_93"
    )

    for color in colors:
        print(
            "{}This text is colored: {}{}".format(
                fg(color),
                color,
                attr("reset")))
        print(
            "{}This text is colored: {}{}".format(
                bg(color),
                color,
                attr("reset")))
        time.sleep(0.1)
Пример #46
0
 def colored(string, color=None, highlight=None, attrs=None):
     """Apply styles to a given string"""
     # Colors list: https://pypi.org/project/colored/
     return colored.stylize(string, (colored.fg(color) if color else '') + \
                                    (colored.bg(highlight) if highlight else '') + \
                                    (colored.attr(attrs) if attrs else ''))
Пример #47
0
def printc(to_print, fg_code=15, bg_code=0, end_line=True):
    print(fg(fg_code) + bg(bg_code) + to_print + attr('reset'), end="")
    if end_line: print()
Пример #48
0
def main():

    colors = (
        "black", "red", "green", "yellow", "blue", "magenta", "cyan",
        "light_gray", "dark_gray", "light_red", "light_green", "light_yellow",
        "light_blue", "light_magenta", "light_cyan", "white", "grey_0",
        "navy_blue", "dark_blue", "blue_3a", "blue_3b", "blue_1", "dark_green",
        "deep_sky_blue_4a", "deep_sky_blue_4b", "deep_sky_blue_4c",
        "dodger_blue_3", "dodger_blue_2", "green_4", "spring_green_4",
        "turquoise_4", "deep_sky_blue_3a", "deep_sky_blue_3b", "dodger_blue_1",
        "green_3a", "spring_green_3a", "dark_cyan", "light_sea_green",
        "deep_sky_blue_2", "deep_sky_blue_1", "green_3b", "spring_green_3b",
        "spring_green_2a", "cyan_3", "dark_turquoise", "turquoise_2",
        "green_1", "spring_green_2b", "spring_green_1", "medium_spring_green",
        "cyan_2", "cyan_1", "dark_red_1", "deep_pink_4a", "purple_4a",
        "purple_4b", "purple_3", "blue_violet", "orange_4a", "grey_37",
        "medium_purple_4", "slate_blue_3a", "slate_blue_3b", "royal_blue_1",
        "chartreuse_4", "dark_sea_green_4a", "pale_turquoise_4", "steel_blue",
        "steel_blue_3", "cornflower_blue", "chartreuse_3a",
        "dark_sea_green_4b", "cadet_blue_2", "cadet_blue_1", "sky_blue_3",
        "steel_blue_1a", "chartreuse_3b", "pale_green_3a", "sea_green_3",
        "aquamarine_3", "medium_turquoise", "steel_blue_1b", "chartreuse_2a",
        "sea_green_2", "sea_green_1a", "sea_green_1b", "aquamarine_1a",
        "dark_slate_gray_2", "dark_red_2", "deep_pink_4b", "dark_magenta_1",
        "dark_magenta_2", "dark_violet_1a", "purple_1a", "orange_4b",
        "light_pink_4", "plum_4", "medium_purple_3a", "medium_purple_3b",
        "slate_blue_1", "yellow_4a", "wheat_4", "grey_53", "light_slate_grey",
        "medium_purple", "light_slate_blue", "yellow_4b",
        "dark_olive_green_3a", "dark_green_sea", "light_sky_blue_3a",
        "light_sky_blue_3b", "sky_blue_2", "chartreuse_2b",
        "dark_olive_green_3b", "pale_green_3b", "dark_sea_green_3a",
        "dark_slate_gray_3", "sky_blue_1", "chartreuse_1", "light_green_2",
        "light_green_3", "pale_green_1a", "aquamarine_1b", "dark_slate_gray_1",
        "red_3a", "deep_pink_4c", "medium_violet_red", "magenta_3a",
        "dark_violet_1b", "purple_1b", "dark_orange_3a", "indian_red_1a",
        "hot_pink_3a", "medium_orchid_3", "medium_orchid", "medium_purple_2a",
        "dark_goldenrod", "light_salmon_3a", "rosy_brown", "grey_63",
        "medium_purple_2b", "medium_purple_1", "gold_3a", "dark_khaki",
        "navajo_white_3", "grey_69", "light_steel_blue_3", "light_steel_blue",
        "yellow_3a", "dark_olive_green_3", "dark_sea_green_3b",
        "dark_sea_green_2", "light_cyan_3", "light_sky_blue_1", "green_yellow",
        "dark_olive_green_2", "pale_green_1b", "dark_sea_sreen_2",
        "dark_sea_sreen_1", "pale_turquoise_1", "red_3b", "deep_pink_3a",
        "deep_pink_3b", "magenta_3b", "magenta_3c", "magenta_2a",
        "dark_orange_3b", "indian_red_1b", "hot_pink_3b", "hot_pink_2",
        "orchid", "medium_orchid_1a", "orange_3", "light_salmon_3b",
        "light_Pink_3", "pink_3", "plum_3", "violet", "gold_3b",
        "light_Goldenrod_3", "tan", "misty_rose_3", "thistle_3", "plum_2",
        "yellow_3b", "khaki_3", "light_goldenrod_2a", "light_yellow_3",
        "grey_84", "light_steel_blue_1", "yellow_2", "dark_olive_green_1a",
        "dark_olive_green_1b", "dark_sea_green_1", "honeydew_2",
        "light_cyan_1", "red_1", "deep_pink_2", "deep_pink_1a", "deep_pink_1b",
        "magenta_2b", "magenta_1", "orange_red_1", "indian_red_1c",
        "indian_red_1d", "hot_pink_1a", "hot_pink_1b", "medium_orchid_1b",
        "dark_orange", "salmon_1", "light_coral", "pale_violet_red_1",
        "orchid_2", "orchid_1", "orange_1", "sandy_brown", "light_salmon_1",
        "light_pink_1", "pink_1", "plum_1", "gold_1", "light_goldenrod_2b",
        "light_goldenrod_2c", "navajo_white_1", "misty_rose1", "thistle_1",
        "yellow_1", "light_goldenrod_1", "khaki_1", "wheat_1", "cornsilk_1",
        "grey_100", "grey_3", "grey_7", "grey_11", "grey_15", "grey_19",
        "grey_23", "grey_27", "grey_30", "grey_35", "grey_39", "grey_42",
        "grey_46", "grey_50", "grey_54", "grey_58", "grey_62", "grey_66",
        "grey_70", "grey_74", "grey_78", "grey_82", "grey_85", "grey_89",
        "grey_93")

    for color in colors:
        print("{}This text is colored: {}{}".format(fg(color), color,
                                                    attr("reset")))
        print("{}This text is colored: {}{}".format(bg(color), color,
                                                    attr("reset")))
        time.sleep(0.1)
Пример #49
0
    until = since + timedelta(days=1)

    ooni = OoniRepository()
    results = ooni.list_tests(since, until, "telegram", args.country)

    # Organize per ASN
    asns = {}
    for r in results['results']:
        if r['probe_asn'] in asns:
            asns[r['probe_asn']].append(r)
        else:
            asns[r['probe_asn']] = [r]

    # Analyze stuff
    for asn in asns:
        print("%s%s# %s%s" % (fg('white'), bg('yellow'), asn.upper(), attr(0)))
        for r in sorted(asns[asn], key=lambda x: x['test_start_time']):
            data = ooni.download_file(r['download_url'])
            colors = {'KO': 'red', 'OK': 'green', 'None': 249}
            if data['test_keys']['telegram_http_blocking'] is None:
                http_blocking = "None"
            else:
                if data['test_keys']['telegram_http_blocking']:
                    http_blocking = 'KO'
                else:
                    http_blocking = 'OK'
            print("%s\t %sHTTP: %s\t%sTCP: %s\t\t%sWeb: %s%s" % (
                    r['test_start_time'],
                    fg(colors[http_blocking]),
                    http_blocking,
                    fg('red') if data['test_keys']['telegram_tcp_blocking'] else fg('green'),
Пример #50
0
def text_with_color(text, color):
    return "%s%s %s %s" % (fg(color), bg(0), text, attr(0))
Пример #51
0
		try:
			time.sleep(show_time)
			os.system('clear')
		except:
			pass



func.func('show', 1, 4, Descriptions.show, Built_In_Functions.show)
os.system('clear')
Built_In_Functions.show('text')

line = 1
while True:
	command = input('>>> ')

	if 'func' == command[:5] and '!' in command:
		#Assuming that the the command is a function:
		#EXAMPLE FUNCTION: func funcname : parameter1, parameter2, parameter3
		command = command[4:]
		print(command)
		basic_func_parts = command.split('!')
		func_info = func.find_func(basic_func_parts[0])
		if func_info == False:
			print(bg('red') + 'Line ' + str(line) + ':\nfunction not found' + attr('reset'))
			break


	line += 1

Пример #52
0
    def format_help(self):
        """Individual formatting of sections in the help text.

        When we use the same formatter for all, we either would lose the
        explicit spacing in the epilog, or lose the formatting in other
        sections. In this function we change the formatters, render
        different sections differently, and then concatenate everything
        into a single output.
        """

        # we get our formatters here, fill them up down bleow, and finally render them at the end:
        usage_formatter = argparse.ArgumentDefaultsHelpFormatter(self.prog)
        description_formatter = argparse.RawDescriptionHelpFormatter(self.prog)
        epilog_formatter = argparse.RawDescriptionHelpFormatter(prog=self.prog)
        separator_formatter = argparse.RawDescriptionHelpFormatter(
            prog=self.prog)

        # usage
        usage_formatter.add_usage(self.usage, self._actions,
                                  self._mutually_exclusive_groups)

        # positionals, optionals and user-defined groups
        for action_group in self._action_groups:
            if atty:
                section_title = action_group.title + ' ' * (80 - len(
                    action_group.title) if len(action_group.title) < 80 else 0)
                section_header = bg(250) + fg(236) + attr(
                    'bold') + section_title + attr('reset')
            else:
                section_header = action_group.title

            usage_formatter.start_section(section_header)
            usage_formatter.add_text(action_group.description)
            usage_formatter.add_arguments(action_group._group_actions)
            usage_formatter.end_section()

        # separator
        separator_formatter.add_text('━' * 80 + '\n')

        # description
        if atty:
            description_text = [
                attr('bold') + '🔥 Program description:' + attr('reset'), ''
            ]
        else:
            description_text = ['🔥 Program description:', '']

        description_text.extend([
            textwrap.indent(l, '   ') for l in textwrap.wrap(
                " ".join(textwrap.dedent(self.description).split()), width=77)
        ])
        description_formatter.add_text('\n'.join(description_text))

        # epilog
        epilog_formatter.add_text(self.epilog)

        # determine help from format above
        help_text = '\n'.join([
            usage_formatter.format_help().replace(":\n", "\n")
            if atty else usage_formatter.format_help(),
            separator_formatter.format_help(),
            description_formatter.format_help(),
            epilog_formatter.format_help(),
            separator_formatter.format_help()
        ]) + '\n'

        return help_text
Пример #53
0
        print('%s%sResult different from tf graph inference!%s' %
              (fg('white'), bg('red'), attr('reset')))


if __name__ == '__main__':
    print("Comparing the results of different inference methods...")

    checkpoint = 'graph_data/model.best'
    frozen_model = 'graph_data/frozen_graph.pb'
    intermediate_rep_cpu = 'graph_data/optimized_graph_FP32'
    intermediate_rep_myriad = 'graph_data/optimized_graph_FP16'
    query_img = 'query_imgs/frame_00000.png'
    num_iterations = 1000

    print('%s%s--------------------------------------------------%s' %
          (fg('white'), bg('blue'), attr('blink')))
    print("Plain tensorflow inference")
    print('%s%s--------------------------------------------------%s' %
          (fg('white'), bg('blue'), attr('reset')))
    predictions_plain_tf = plain_tf.plain_tf_inference(checkpoint, query_img,
                                                       num_iterations)
    print(predictions_plain_tf)

    print('%s%s--------------------------------------------------%s' %
          (fg('white'), bg('blue'), attr('blink')))
    print("Feed frozen graph using tensorflow")
    print('%s%s--------------------------------------------------%s' %
          (fg('white'), bg('blue'), attr('reset')))
    predictions_frozen_tf = frozen_tf.frozen_tf_inference(
        frozen_model, query_img, num_iterations, print_ops_in_graph=False)
    print(predictions_frozen_tf)
Пример #54
0
'''
Henry Quillin
9 - 17 - 2020
Learning to use colored library
'''

from colored import fg, bg, attr
import colored
from colored import stylize

color = fg('#C0C0C0') + bg('#00005f')
res = attr('reset')

print('%s Hello World !!! %s' % (fg(1), attr(0)))
print('%s%s Hello World !!! %s' % (fg(50), bg(15), attr(0)))

print(color + "|\---/|" + res)
print(color + "| o_o |" + res)
print(color + " \_^_/" + res)

print('''%s
                           o                    
                       _---|         _ _ _ _ _ 
                    o   ---|     o   ]-I-I-I-[ 
   _ _ _ _ _ _  _---|      | _---|    \ ` ' / 
   ]-I-I-I-I-[   ---|      |  ---|    |.   | 
    \ `   '_/       |     / \    |    | /^\| 
     [*]  __|       ^    / ^ \   ^    | |*|| 
     |__   ,|      / \  /    `\ / \   | ===| 
  ___| ___ ,|__   /    /=_=_=_=\   \  |,  _|
  I_I__I_I__I_I  (====(_________)___|_|____|____
Пример #55
0
def check_result(prediction, ground_truth):
    error = ((prediction - ground_truth)**2).sum()
    if error > 0.05:
        print('%s%sResult different from tf graph inference!%s' %
              (fg('white'), bg('red'), attr('reset')))
Пример #56
0
#! /usr/bin/python3
from colored import fg, bg, attr
from os import system as S
from os import popen

# screen size
a = popen("stty size", "r").read().split()
HEIGHT, WIDTH = int(a[0]), int(a[1])
del a

# colors
C0 = bg('#af00ff') + "  " + attr(0)
C1 = bg('#8700af') + "  " + attr(0)
C2 = bg('#d700d7') + "  " + attr(0)
C3 = bg('#d787af') + "  " + attr(0)
C4 = bg('#dfa7df') + "  " + attr(0)

# Logo. 33x12
BASE_LOGO = [\
        C2*33,\
        C2 + C0*6 + C2*4 + C0*3 + C2*4 + C0*6 + C2*2 + C0*6 + C2,\
        C2 + C0*2 + C1*2 + C0*3 + C2*2 + C0*2 + C1 + C0*2 + C2*2 + C0*6 + C2*2 + C0*6 + C2*2,\
        C3*2 + C0*2 + C1*2 + C0*2 + C3 + C0*2 + C1*3 + C0*2 + C3 + C0*2 + C3*6 + C0*2 + C3*6,\
        C3*2 + C0 + C1*2 + C0*3 + C3 + C0 + C1*2 + C0 + C1*2 + C0 + C3 + C0*5 + C3*3 + C0*2 + C3*6,\
        C4*2 + C0*5 + C4*2 + C0 + C1 + C0*3 + C1 + C0 + C4*2 + C0*5 + C4*3 + C0*6 + C4,\
        C4*2 + C0*5 + C4*2 + C0*7 + C4*5 + C0*3 + C4*2 + C0*6 + C4,\
        C3*2 + C0 + C1*2 + C0*3 + C3 + C0*3 + C3 + C0*3 + C3*6 + C0*2 + C3 + C0*2 + C3*6,\
        C3*2 + C0*2 + C1*2 + C0*2 + C3 + C0*3 + C3 + C0*3 + C3*5 + C0*3 + C3 + C0*2 + C3*6,\
        C2 + C0*2 + C1*2 + C0*3 + C2 + C0*2 + C2*3 + C0*2 + C2*2 + C0*6 + C2 + C0*6 + C2*2,\
        C2 + C0*6 + C2*2 + C0 + C2*5 + C0 + C2 + C0*6 + C2*3 + C0*6 + C2,\
        C2*33\
Пример #57
0
def snapshot_diff_style(text: Union[str, int]) -> str:
    return _stylize(text, colored.bg(90) + colored.fg(225))
Пример #58
0
def bgc(p):
    global color
    if color:
        return bg(p)
    else:
        return ''
Пример #59
0
def received_diff_style(text: Union[str, int]) -> str:
    return _stylize(text, colored.bg(23) + colored.fg(195))