Exemple #1
0
def print_information(destinations):

    print('\n' + bg(255,255,255) + fg(0,0,0) + '  Line    Time     Destination ' + rs.bg + '\n')    

    for stop in destinations:
        if stop['product'] == 'UBAHN':
            destination = stop['destination']
            time = stop['departureTimeMinutes']

            color = {'U1':bg(70, 132, 71),
                     'U2':bg(221, 61, 77),
                     'U3':bg(239, 136, 36),
                     'U4':bg(4, 175, 144),
                     'U5':bg(183, 135, 48),
                     'U6':bg(4, 114, 179),
                     'U7':fg(255,255,255) + bg(70, 132, 71) + ' U' + bg(221, 61, 77) + '7 ' + rs.bg,
                     'U' :fg(255,255,255) + bg(0, 108, 178) + ' U ' + rs.bg}
            
            finalLine = color[stop['label']] + fg(255,255,255) + ' ' + stop['label'] + ' ' + rs.bg

            sep_time = {"1":7, "2":6, "3":5}
            tam_time = str(len(str(time)))
            print('  {}     {}{}{}'.format(finalLine,time," "*sep_time[tam_time],destination))

    print('\n')
Exemple #2
0
def cPrint(string):
    global expectL
    global initLen
    j = 0
    for i in range(len(string) - (initLen - 1)):
        #if chance[i] is positive, it is more likely than average
        c0 = 0
        c1 = 0
        if expectL[i] < 0:
            c0 = int(-expectL[i] * 6 * 255)
            if c0 > 255:
                c0 = 255
        elif expectL[i] > 0:
            c1 = int(expectL[i] * 200)
        #clump together initial gram or passed root
        if i == 0:
            while j < initLen:
                print(bg(c0, c1, 0) + string[j] + bg.rs, end='')
                j += 1
        #print trailing \n as space
        elif i == len(string) - initLen:
            print(bg(c0, c1, 0) + " " + bg.rs, end='')
        #normally
        else:
            print(bg(c0, c1, 0) + string[j] + bg.rs, end='')
            j += 1
    print()
Exemple #3
0
    def color_op(option):
        colores = ""
        counter = 0
        for tone in Color:
            color = tone.value
            if counter == option:
                colores += (bg(color[0], color[1], color[2]) + " \u2573 " +
                            bg.rs + "\t")
                counter += 1
            else:
                colores += (bg(color[0], color[1], color[2]) + "   " + bg.rs +
                            "\t")
                counter += 1

        print(colores)
Exemple #4
0
def get_info(station):
    global print_information

    try:      

        Id = mvg_api.get_id_for_station(station)

        if Id:
            destinations = mvg_api.get_departures(Id)
            print_information(destinations)

        else:
            print('\n   ' + bg(255,0,0) + ' The station does not exists ' + rs.bg + '\n')

    except:
        print('\n   ' + bg(255,0,0) + ' Something wrong has happened ' + rs.bg + '\n')
Exemple #5
0
def benchmark(liste_fonction, liste_affichage, X_train, X_test, y_train,
              y_test, test):
    lut = [
        202, 203, 204, 205, 206, 207, 171, 135, 99, 63, 27, 33, 39, 45, 51, 49
    ]  #50, 48, 47, 46]
    colorbar = "\n"
    for l in lut:
        colorbar += bg(l) + "  " + bg.rs
    lut.reverse()
    defaut_debiles = [randomDumb, moyDumb, medDumb]
    defaut_intelligentes = [
        foret, sgdRegressor, gradientRegressor, mlpRegressor
    ]
    valeur_bg = {}
    valeur_brute = {}
    y_resultat = {}
    for f in defaut_debiles + defaut_intelligentes + liste_fonction:
        valeur_brute[f()], y_resultat[f()] = f(X_train, X_test, y_train,
                                               y_test)

    minimum = np.min([x for x in valeur_brute.values()])
    maximum = np.max([x for x in valeur_brute.values()])
    for f in defaut_debiles + defaut_intelligentes + liste_fonction:
        valeur_bg[f()] = lut[int((valeur_brute[f()] - minimum) /
                                 (maximum - minimum) * (len(lut) - 1))]
    print(
        "\033[5;37;40m     Root Mean Squared Error    "
    )  #erreur quadratique moyenne pris à la racine carrée pour avoir des jours
    print()

    print("\033[5;30;44m Méthodes naïves ")
    for f in defaut_debiles:
        pretty_print(f(), valeur_brute[f()], "30", "44", valeur_bg[f()])

    print()

    print("\033[5;30;44m Autres méthodes ")
    for f in defaut_intelligentes:
        pretty_print(f(), valeur_brute[f()], "30", "44", valeur_bg[f()])

    for f in liste_fonction:
        pretty_print(f(), valeur_brute[f()], "30", "46", valeur_bg[f()])
    print()

    print("\033[5;37;40m Statistiques Modes ")
    pretty_print("minimum", np.min(y_test), "37", "40", 235)
    pretty_print("1er quartile", np.quantile(y_test, 0.25), "37", "40", 235)
    pretty_print("moyenne", np.mean(y_test), "37", "40", 235)
    pretty_print("médiane", np.median(y_test), "37", "40", 235)
    pretty_print("3ème quartile", np.quantile(y_test, 0.75), "37", "40", 235)
    pretty_print("maximum", np.max(y_test), "37", "40", 235)

    print(colorbar)
    #show_distrib(train,y_train,'-')
    print()
    print("données tests")
    show_distrib(test, y_test, '-')
    for f in liste_affichage + liste_fonction:
        print(f())
        show_distrib(test, y_resultat[f()], '--')
Exemple #6
0
def scheme(vowels, congrps_bv, chunks, colorids):
    """
    Prints the ARPA with rhyme colors assigned
    """
    
    for j in range(len(vowels)):
        print([congrps_bv[j].consonant_list[i].name for i in range(len(congrps_bv[j].consonant_list))], end=" ")
        if vowels[j].root_word not in ['a', 'the', 'i', 'of', 'hustle', 'young']:
            print(bg(colorids[j][0], colorids[j][1], colorids[j][2]) + str([chunks[j].vowel.name]) +
                  str([chunks[j].congrp.consonant_list[i].name
                       for i in range(len(chunks[j].congrp.consonant_list))]) + bg.rs, end=" ")
        else:
            print(bg(255, 255, 255) +
                  str([chunks[j].vowel.name]) +
                  str([chunks[j].congrp.consonant_list[i].name
                       for i in range(len(chunks[j].congrp.consonant_list))]) + bg.rs, end=" ")
Exemple #7
0
 def printColor(self, rgb):
     for CLUSTERS in range(len(rgb)):
         r = int(rgb[CLUSTERS][0])
         g = int(rgb[CLUSTERS][1])
         b = int(rgb[CLUSTERS][2])
         foo = bg(r, g, b) + '                        ' + rs.bg
         print(str(CLUSTERS+1) + foo)
Exemple #8
0
def parse_word_val_list(word_list, h, n, val_list):
    sum_str = ""
    removed_str = ""
    token_removed_ct = 0
    to_highlight = np.asarray([i for i in val_list if i > h])
    scaler = MinMaxScaler(feature_range=(20, 255))
    scaler.fit(to_highlight.reshape(-1, 1))
    for sum_word in word_list:
        if float(sum_word[1]) > h:
            if dynamic:
                bgnum = int(
                    scaler.transform(sum_word[1].detach().numpy().reshape(
                        -1, 1)))
            else:
                bgnum = 50
            sum_str += ef.u + bg(bgnum, bgnum, 0)
            runner = par.add_run(sum_word[0] + " ")
            runner.underline = True
            runner.bold = True
            sum_str += " ".join([str(sum_word[0]), rs.all])
        elif float(sum_word[1]) > n:
            sum_str += ef.u
            runner = par.add_run(sum_word[0] + " ")
            runner.underline = True
            sum_str += " ".join([str(sum_word[0]), rs.all])
        else:
            token_removed_ct += 1
            sum_str += str(sum_word[0])
            runner = par.add_run(sum_word[0] + " ")
            sum_str += " "
            removed_str += str(sum_word[0])
            removed_str += " "
    return sum_str, removed_str, token_removed_ct
Exemple #9
0
def sgr_bg(names):

    items = [bg(name) + ' ' + name.ljust(12) + bg.rs for name in names]
    items.insert(8, rs.bg + '\n')
    items.insert(16 + 1, rs.fg + '\n')
    line = '\nSGR_BG:\n-------\n' + ''.join(items)

    return line
Exemple #10
0
 def _render(self, text, fg: ColorPoint, bg: ColorPoint = None):
     out = ''
     out += sty.fg(fg.ansi)
     if bg:
         out += sty.bg(bg.ansi)
     out += text
     out += sty.rs.all
     return out
Exemple #11
0
 def format_string_for_ids(self, fg_id=None, bg_id=None):
     s = '{}' + sty.rs.all
     if fg_id:
         s = sty.fg(fg_id.four_bit_color_name) + s
         self.used_color_ids.add(fg_id)
     if bg_id:
         s = sty.bg(bg_id.four_bit_color_name) + s
         self.used_color_ids.add(bg_id)
     return s
Exemple #12
0
 def __repr__(self) -> str:
     """
     formal version of printing tiles
     used in terminal version of game
     just displays color
     """
     color = self.color.value
     return str(
         bg(color[0], color[1], color[2]) + (" " * self.width) + bg.rs)
Exemple #13
0
 def _render(self, text, fg: ColorPoint, bg: ColorPoint = None):
     rgb = rgb_to_RGB255(fg.target.rgb)
     out = ''
     out += sty.fg(*rgb)
     if bg:
         bgrgb = rgb_to_RGB255(bg.target.rgb)
         out += sty.bg(*bgrgb)
     out += text
     out += sty.rs.all
     return out
Exemple #14
0
def convert_truecolor_char(rgba0, rgba1):
    top = rgba0[:3]
    bottom = rgba1[:3]
    char = "▄"
    if len(rgba0) > 3 and rgba0[3] == 0:
        top = fg.rs
    if len(rgba1) > 3 and rgba1[3] == 0:
        bottom = bg.rs
        char = " "

    result = bg(*top) + fg(*bottom) + char + rs.all
    return result
Exemple #15
0
def test_dynamic_attr_access(reps):

    print("Test Dynamic Attribute Access: ", end="")
    start = timer()

    for i in range(reps):
        f = fg("blue") + "" + rs("fg")
        b = bg("green") + "" + rs("bg")
        e = ef("underl") + "" + rs("underl")

    end = timer()
    print(end - start)
Exemple #16
0
def print_attributions(tokens, attributions, special=True):

    if not special:
        attributions = torch.tensor([
            e for e, w in zip(attributions, tokens)
            if w not in ("[CLS]", "[SEP]")
        ])
        tokens = [e for e in tokens if e not in ("[CLS]", "[SEP]")]

    print(" ".join([
        bg(*_get_color(a)) + w + bg.rs
        for w, a in zip(tokens, attributions / attributions.max())
    ]))
Exemple #17
0
class Salyangoz():
    def __init__(self, interpreter):
        self.__sys = interpreter.sistem

    def yaz(self, yazı, stil):
        ön = son = ""
        if t := stil.get("renk", None):
            ön += fg(*t)
            son += fg.rs
            
        if t := stil.get("arkaplan", None):
            ön += bg(*t)
            son += bg.rs
Exemple #18
0
    def printColors(self, colors):
        block = ' ' + ' ' * 4
        out_color = ''
        label = ''

        for color in colors:
            single_c = bg(color[0], color[1], color[2]) + block + bg.rs
            out_color += single_c
            label += ' #%s ' % self.rgb2hex(color)

        for i in range(2):
            print(out_color)
        print(label)
Exemple #19
0
def sgr_bg():
    output = ""
    for row_num in range(0, len(GROUPS[0])):
        line = ""
        for group in GROUPS:
            try:
                name = group[row_num]
            except IndexError:
                continue
            fore = fg.da_grey if name in ["white", "li_grey"] else ""
            line += fore + bg(name) + " " + name.rjust(12) + rs.all
        output += line + "\n"

    return "\nSGR_BG:\n-------\n" + output
Exemple #20
0
def verbose_status_code(value, elapsed):
    if value == 200:
        bg_status_code = bg(29, 139, 58)
        fg_elapsed = 'green'
    else:
        bg_status_code = bg.red
        fg_elapsed = 'red'

    click.secho(' * ', fg='green', nl=False)
    click.secho(bg_status_code + fg.white + ' ' + str(value) + ' ' + rs.all,
                bold=True,
                nl=False)
    click.secho(' ' + 'Request status ' + ' ', fg='white', nl=False)
    click.secho('- ' + str(elapsed) + '', fg=fg_elapsed)
Exemple #21
0
def check_vulnerability(browser, target, dork):
	url = '%s%s site:%s'%(query, dork, target)
	browser.get(url)
	try:
		#Search for reCaptcha
		browser.find_element_by_id('captcha-form')
		input('\nGoogle is trying to block you... solve captcha and hit enter when ready.\n')
	except:
			dork = dork.strip()
			try:
				browser.find_element_by_id('resultStats')
				print(bg(1)+fg(15)+"[ *** VULNERABILITY DETECTED! *** ] - %s site:%s"%(dork, target)+fg.rs+bg.rs)
				output.append('%s site:%s'%(dork, target))
			except:
				print('Dork failed - %s site:%s'%(dork, target))
def preview():
    print(f"{warn} Preview?")
    if (waitConfirm()):
        for y in range(im.size[1]):
            for x in range(im.size[0]):
                #print(f"{x=}{y=}")
                c = monochromize(pix[y][x])

                #double scale to introduce the flat lose.
                c = scaleIntensity(c, 255, intensity)
                c = scaleIntensity(c, intensity, 255)
                c = monochromize(pix[y][x])
                c = bg(c, c, c)
                print(c + " ", end='')
            print(bg.rs)
def printAttentionedWordsAndSentences(review, all_sent_index, sent_index,
                                      sorted_wordlist, MAX_SENTENCE_NUM):
    """
    Utility function for hanPredict that provides a colored terminal printing (thanks to Sty Python library) of most
    attentioned sentences and words in a predicted review (with partial weights from attention layers of Han network
    model).
    :param review: a string of the review.
    :param all_sent_index: all sentences index.
    :param sent_index: most important sencentences index.
    :param sorted_wordlist: most important words list, sorted by importance.
    :param MAX_SENTENCE_NUM: same parameter of network.
    :return: None
    """

    sentences = tokenize.sent_tokenize(review)
    all_sent_index = np.array(all_sent_index[:len(sentences)])

    nothing = '     '
    low = sty.bg(200, 200, 255) + '     ' + sty.bg.rs
    medium = sty.bg(100, 100, 255) + '     ' + sty.bg.rs
    high = sty.bg(0, 0, 255) + '     ' + sty.bg.rs

    high_word, medium_word, low_word = np.array_split(sorted_wordlist, 3)
    high_sent, medium_sent, low_sent, nothing_sent = np.array_split(
        all_sent_index, 4)

    sent_color = nothing
    for idx, sent in enumerate(sentences):
        if idx in high_sent and idx <= MAX_SENTENCE_NUM:
            sent_color = high
        elif idx in medium_sent and idx <= MAX_SENTENCE_NUM:
            sent_color = medium
        elif idx in low_sent and idx <= MAX_SENTENCE_NUM:
            sent_color = low
        else:
            sent_color = nothing

        sent_to_print = ''
        for idy, word in enumerate(tokenize.word_tokenize(sent)):
            if word in high_word and idx in sent_index:
                sent_to_print += (sty.bg(255, 70, 70) + word + sty.bg.rs + ' ')
            elif word in medium_word and idx in sent_index:
                sent_to_print += (sty.bg(255, 140, 140) + word + sty.bg.rs +
                                  ' ')
            elif word in low_word and idx in sent_index:
                sent_to_print += (sty.bg(255, 220, 220) + word + sty.bg.rs +
                                  ' ')
            else:
                sent_to_print += (word + ' ')
        print(sent_color, idx, sent_to_print)
Exemple #24
0
    def getCanvasText(self):
        '''
        Return a string representation of the canvas. This string is what will be printed for visuals.
        '''

        # Allocated all the memory for the string right at the start
        resultingString: List[str] = [""] * (self.width * self.height + 2)

        # Loop through all the characters of both the string and the formatString, and create the resulting string list
        previousTextColor = None
        previousBackgroundColor = None
        for j in range(self.height):
            for i in range(self.width):

                character = chr(self.characters[i, j])

                textColor = tuple(self.textColors[i, j])
                backgroundColor = tuple(self.backgroundColors[i, j])

                if not previousTextColor or textColor != previousTextColor:
                    character = fg(*textColor) + character
                    previousTextColor = textColor

                if not previousBackgroundColor or backgroundColor != previousBackgroundColor:
                    character = bg(*backgroundColor) + character
                    previousBackgroundColor = backgroundColor

                # If at the beginning of the line, need to include a new line \n to the character
                if i == 0:

                    if "win" in platform.system().lower():
                        character = "\n" + character

                resultingString[j * self.width + i] = character

        # Clear the terminal format after each draw
        resultingString[-2] = bg.rs
        resultingString[-1] = fg.rs

        # Add the last
        return "".join(resultingString)
Exemple #25
0
def print_stat(content, palette, cat_id_to_color_id):
    print('   images:', len(content['images']))
    print('   annotations:', len(content['annotations']))
    print('   categories:', len(content['categories']))
    per_cat_counts = defaultdict(int)
    per_cat_occluded_counts = defaultdict(int)
    per_cat_is_crowd_counts = defaultdict(int)
    
    for i, ann in enumerate(content['annotations']):
        per_cat_counts[ann['category_id']] += 1
        if ann.get('is_occluded', False):
            per_cat_occluded_counts[ann['category_id']] += 1
        if ann['iscrowd']:
            per_cat_is_crowd_counts[ann['category_id']] += 1

    for i, cat in enumerate(content['categories']):
        color = palette[cat_id_to_color_id[cat['id']]]
        print('      ', bg(*color) + '   ' + bg.rs + ' ' + str(cat) +
              f' objects {per_cat_counts[cat["id"]]}'
              f' occluded {per_cat_occluded_counts[cat["id"]]}'
              f' is_crowd {per_cat_is_crowd_counts[cat["id"]]}')
Exemple #26
0
 def get_str_representation(self):
     rows = ''
     for r in range(self.height):
         for c in range(self.width):
             color_decider=randint(0,25)
             if self.dungeon[r][c]=='#':
                 if color_decider<=8:
                     rows+= fg(22)+bg(22)+self.dungeon[r][c]+rs.bg
                 elif color_decider>12 and color_decider<=20:
                     rows+= fg(236)+bg(236)+self.dungeon[r][c]+rs.bg
                 else:
                     rows+= fg(237)+bg(237)+self.dungeon[r][c]+rs.bg
             else:
                 if color_decider<=14:
                     rows+= fg(242)+bg(242)+self.dungeon[r][c]+rs.bg
                 elif color_decider>14 and color_decider<=20:
                     rows+= fg(243)+bg(243)+self.dungeon[r][c]+rs.bg
                 else:
                     rows+= fg(244)+bg(244)+self.dungeon[r][c]+rs.bg
         rows+='\n'
     return rows
Exemple #27
0
 def draw(self, idx):
     if self.values[idx]:
         return bg(self.color) + " " + rs.bg
     return " "
Exemple #28
0
 def make_marker(label, ground_truth):
     if label == "reject":
         return bg("da_black") + " " + rs.bg
     return marker(label == ground_truth)
Exemple #29
0
# Add custom colors:

from sty import Style, RgbFg

fg.orange = Style(RgbFg(255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs

print(foo, bar, baz, qux, qui, buf, sep='\n')
# ===== End =====

# ===== Start =====
Example("gettings started: select dynamically")
a = ef('italic') + 'Italic text.' + rs.italic
b = fg('blue') + 'Blue text.' + rs.fg
c = bg(randint(0, 254)) + 'Random colored bg' + rs.bg

print(a, b, c, sep='\n')
# ===== End =====

# ===== Start =====
Example("gettings started: select 8bit and 24bit directly")
# select an 8bit color directly.
a = fg(196) + 'This is red text' + rs.fg

# select a 24bit rgb color directly.
b = bg(50, 255, 50) + 'Text with green bg' + rs.bg

print(a, b, sep='\n')
# ===== End =====
Exemple #30
0
def marker(correct):
    return bg("da_green" if correct else "da_red") + " " + rs.bg