示例#1
0
def print_progress(iteration,
                   total,
                   prefix='',
                   suffix='',
                   decimals=1,
                   bar_length=100):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        bar_length  - Optional  : character length of bar (Int)
    """
    if iteration == 0:
        cursor.hide()

    bar_length = shutil.get_terminal_size()[0] // 2

    str_format = "{0:." + str(decimals) + "f}"
    percents = str_format.format(100 * (iteration / float(total)))
    filled_length = int(round(bar_length * iteration / float(total)))
    bar = '+' * filled_length + '-' * (bar_length - filled_length)

    progress_bar = "\r%s |%s| %s%s %s" % (prefix, bar, percents, '%', suffix)

    print(progress_bar, end='', flush=True)

    if iteration == total:
        print("")
        cursor.show()
示例#2
0
def do(index, writer):
    cursor.hide()
    result = review(data, index)
    print(f"Done with {index}/{total}. That's {((index/total)*100):.2f}%")
    print(
        f"{color.BOLD}Do over? ({color.RED}Y(0){color.END}/{color.BOLD}{color.GREEN}N(1){color.END}{color.BOLD}){color.END} or quit (Q)"
    )
    do = getch.getch()
    if do == 'Q':
        cursor.show()
        return [index, True]
    while do == 'Y' or do == '0':
        result = review(data, index)
        print(f"Done with {index}/{total}. That's {((index/total)*100):.2f}%")
        print(
            f"{color.BOLD}Do over? ({color.RED}Y(0){color.END}/{color.BOLD}{color.GREEN}N(1){color.END}{color.BOLD}){color.END} or quit (Q)"
        )
        do = getch.getch()
    writer.writerow([
        index, REVIEWER, result["model"], result["isPsych"],
        result["botRubric"]["clarity"], result["botRubric"]["specificity"],
        result["botRubric"]["psycology"], result["humanRubric"]["clarity"],
        result["humanRubric"]["specificity"],
        result["humanRubric"]["psycology"], result["botTuring"],
        result["humanTuring"]
    ])
    cursor.show()
    return [index, False]
示例#3
0
    def loop(self, generations=1, toCMD=None, singlePNG=None, singlePNGscale=1,
             multiPNG=None, multiPNGscale=1, loopLen=5, depth=2):
        """
        Plays the game of life, can print to cmd or save as png's

        Args:
            generations:  number of iterations
            toCMD:    if True the game will be printed to the
                      command line
            singlePNG:  if True the final outcome will be saved as PNG
            singlePNGscale:  scales the size that one matrix value will
                             take in pixels
            multiPNG: if True the playthrough will be saved as PNG
            multiPNGscale:  scales the size that one matrix value will
                            take in pixels
            loopLen:  number of matrizes that are recorded going back
                      from most recent
            depth:    how deep list checks for duplicates
        """
        if toCMD:
            cursor.hide()
        for i in range(generations + 1):
            if toCMD:
                self.toCMD(self.progress[-1], i)
            if self.caught(depth):
                print('caught in loop')
                break
            if i != generations:
                self.iterate(self.progress[-1])
        if multiPNG:
            self.toPNG(multiPNGscale)
        if singlePNG:
            self.toPNG(singlePNGscale, self.progress[-1])
        if toCMD:
            cursor.show()
示例#4
0
def main():
    """Main loop."""
    os.system("cls")
    cursor.hide()

    snake = Snake(25, 50)

    process_key = mp.Process(target=get_key, args=(snake.direction, ))
    process_key.daemon = True
    process_key.start()
    process_render = mp.Process(target=render, args=(snake.grid, ))
    process_render.daemon = True
    process_render.start()

    timer = Timer(10)
    while not snake.dead:
        if timer.ready:
            snake.move()
            timer.reset()

    process_key.terminate()
    process_render.terminate()

    os.system("cls")
    cursor.show()
示例#5
0
def progressBar(completed_tasks_ref, total_tasks):
    """\
displays a progress bar based on number of tasks completed and returns 0 when
	completed_tasks_ref == total_tasks

Arguments:
completed_tasks_ref --- reference to the variable that holds the total number
	of completed tasks. only read to prevent threading conflicts
total_tasks --- total number of tasks
"""
    cursor.hide()
    bar_width = 30
    while completed_tasks_ref["tasks"] < total_tasks:
        completed_tasks = completed_tasks_ref["tasks"]
        num_ticks = int(ceil(bar_width * (completed_tasks / total_tasks)))
        num_blank = bar_width - num_ticks
        sys.stdout.write("[" + "=" * num_ticks + " " * num_blank + "]")
        sys.stdout.flush()
        sleep(0.01)
        sys.stdout.write("\b" * (bar_width + 2))
        sys.stdout.flush()

    sys.stdout.write("[" + "=" * bar_width + "]" + "\n\n")
    sys.stdout.flush()

    cursor.show()
    return 3
示例#6
0
def animated_loading(flag):

    if (flag == 0):
        msg = "loading dataframe     "
        chars = "▁▂▃▄▅▆▇█▇▆▅▄▃▁"
    if (flag == 1):
        chars = "◢ ◣ ◤ ◥"
        msg = "removing incosistency "
    if (flag == 2):
        chars = "▖▘▝▗"
        msg = "inserting metadata    "
    if (flag == 3):
        chars = "▖▘▝▗"
        msg = "finding geo info      "
    cursor.hide()

    if (flag == 4):
        chars = "⣾⣽⣻⢿⡿⣟⣯⣷"
        msg = "saving dataframe      "
    cursor.hide()

    for char in chars:

        sys.stdout.write('\r' + msg + '' + char)
        time.sleep(.1)
        sys.stdout.flush()
    cursor.show()
def page_fuction(idx):
    if idx == 0:
        refresh(0)
        xyprint(
            20, 10,
            Fore.GREEN + '\tOption Zero Selected!' + Style.NORMAL + Fore.BLACK)
        refresh(1)

    if idx == 1:
        refresh(0)
        xyprint(
            20, 10,
            Fore.GREEN + '\tOption One Selected!' + Style.NORMAL + Fore.BLACK)
        refresh(1)

    if idx == 2:
        refresh(0)
        xyprint(
            20, 10,
            Fore.GREEN + '\tOption Two Selected!' + Style.NORMAL + Fore.BLACK)
        refresh(1)

    if idx == 3:
        print(Style.RESET_ALL)
        cursor.show()
        deinit()
        refresh(0)
        return exit(
        )  #This is where the funtions for selected index's are stored.
示例#8
0
    def download(self, download: Download):
        cursor.hide()
        if not os.path.isdir(Rf'{tempfile.gettempdir()}\electric'):
            os.mkdir(Rf'{tempfile.gettempdir()}\electric')

        path = Rf'{tempfile.gettempdir()}\electric\{download.name}{download.extension}'

        with open(path, 'wb') as f:
            response = requests.get(download.url, stream=True)
            total_length = response.headers.get('content-length')
            if total_length is None:
                f.write(response.content)
            else:
                dl = 0
                full_length = int(total_length)

                for data in response.iter_content(chunk_size=4096):
                    dl += len(data)
                    f.write(data)

                    complete = int(20 * dl / full_length)
                    fill_c, unfill_c = '█' * complete, ' ' * (20 - complete)
                    try:
                        sys.stdout.write(
                            f"\r[{fill_c}{unfill_c}] ⚡ {round(dl / full_length * 100, 1)} % ⚡ {round(dl / 1000000, 1)} / {round(full_length / 1000000, 1)} MB")
                    except UnicodeEncodeError:
                        pass
                    sys.stdout.flush()

        paths.update({download.display_name: {'path': path,
                                              'display_name': download.display_name}})
        cursor.show()
def main():
    if 3 != len(sys.argv):
        print()
        print('Please provide input and output filepaths.')
        print()
        print('Usage: python3 redacter.py $INPUT $OUTPUT')
        print()

    else:
        in_path = os.path.abspath(sys.argv[1])
        out_path = os.path.abspath(sys.argv[2])

        if os.path.isfile(in_path):
            print()
            print('Input path:  ' + in_path)
            print('Output path: ' + out_path)
            print()
            try:
                redact(in_path, out_path)
            except KeyboardInterrupt:
                pass
            cursor.show()
        else:
            print()
            print('The input file')
            print()
            print('  ' + in_path)
            print()
            print('does not exist.')
            print()
示例#10
0
 def input(self, text):
     show()
     set_echo(True)
     res = input(bg("dark_gray") + text)
     clear()
     hide()
     set_echo(False)
     return res
def main():
    cursor.hide()

    try:

        preamble()

        time.sleep(0.5)

        working_dir = os.getcwd()

        print()
        print('This program will use the following directory as the working directory:')
        print()
        print('  ' + working_dir)

        guard_prerequisites(working_dir)

        time.sleep(0.5)
        print()
        cursor.show()
        base_url = input('Enter a base url for URLs, or leave blank to use the output directory:\n\n  ')
        cursor.hide()
        print()

        if '' == base_url: base_url = 'file://' + working_dir + '/output/'

        run_scripts(working_dir, base_url)

        time.sleep(0.5)

        print()
        print()
        print('\033[1mThe index has been generated.')
        time.sleep(0.5)
        print()
        print('Thank you for using this program.')
        time.sleep(0.5)
        print()
        print('\033[38;5;155mGood bye!\033[0m')
        time.sleep(1)

    except KeyboardInterrupt:
        print()
        print()
        print('Quitting via keyboard interrupt.')
        print()
        time.sleep(1)

    except MissingPrerequisite:
        print()
        print()
        print('Quitting due to failed prerequisites.')
        print()
        time.sleep(1)

    cursor.show()
def main():
    print('Press CTRL+C to abort animation')

    cursor.hide()
    try:
        main_loop()
    except KeyboardInterrupt:
        cursor.show()
        os.system('clear')
示例#13
0
 def download_dir(self,
                  download_from_dir,
                  upload_to_dir='.',
                  exclude_ext=None,
                  with_root_path=True):
     cursor.hide()
     tasks = (self.download_dir_async(download_from_dir, upload_to_dir,
                                      exclude_ext, with_root_path), )
     asyncio.run(asyncio.wait(tasks))
     cursor.show()
示例#14
0
def charprint(string, color, cursorused=True, end="\n"):
    if cursorused == True:
        cursor.show()
    for i in string:
        sys.stdout.write(colored(i, color=color))
        sys.stdout.flush()
    sys.stdout.write(end)
    sys.stdout.flush()
    if cursorused == True:
        cursor.hide()
示例#15
0
def spam(text, t):
    cursor.hide()
    length = len(text)
    wait = t / length

    text = ''.join(filter(whitelist.__contains__, text))
    for l in text.lower():
        time.sleep(wait)
        print(color + table[l], end='\r')

    cursor.show()
示例#16
0
 def _runSelected(self):
     cursor.show()
     print("Running", self.options[self.location][0])
     self.lastRender = ""
     try:
         if self.CoreLoop is not None:
             exec(self.options[self.location][1])
         else:
             print("Cannot run due to no core loop")
     except Exception as e:
         print(e)
def dots():
    cursor.hide()
    time.sleep(5)
    print("\n\tОбождите.", sep=' ', end='', flush=True)

    for i in range(10):
        print(".", sep=' ', end='', flush=True)
        time.sleep(1)

    cursor.show()
    print()
    start()
示例#18
0
def animate_network(k=2, leave_trace=False, speed=10):
    cursor.hide()

    n = Network(k)
    n.print_states()
    n.states[-1] = 'g'
    while n.states[0] != '!':
        sleep(1.0/speed)
        n.print_states(leave_trace)
        n.update()
    n.print_states()

    cursor.show()
示例#19
0
 def render(self):
     z = 0
     print("\033c", end="")
     cursor.hide()
     try:
         for y in range(self.rows):
             for x in range(self.cols):
                 print(self.data[z], end="")
                 z = z + 1
             print("\n", end="")
     except:
         cursor.show()
     cursor.show()
示例#20
0
    def __init__(self, chars=1, raw=False):
        if raw:
            tty.setraw(FD)
        else:
            tty.setcbreak(FD)

        cursor.hide()

        self.ch = sys.stdin.read(chars)

        termios.tcsetattr(FD, termios.TCSADRAIN, SETTINGS)

        cursor.show()
示例#21
0
    def clear(self, restore_cursor=None):
        """
        Erase the previously logged lines.

        This will only affect the log since the last done() call.

        You can eventualy decide to restore the cursor by giving
        the `restore_cursor=True` keyword argument.
        """
        self.stream.write(erase_lines(self.prev_line_count))
        if restore_cursor:
            cursor.show()
        self.prev_line_count = 0
        return self
示例#22
0
def main():
    global args
    global videoAudio
    parser = argparse.ArgumentParser()
    parser.add_argument("url", help="指定YouTube視訊網址")
    parser.add_argument("-sd", action="store_true", help="選擇普通(480P)畫質")
    parser.add_argument("-hd", action="store_true", help="選擇HD(720P)畫質")
    parser.add_argument("-fhd", action="store_true", help="選擇Full HD(1080P)畫質")
    parser.add_argument("-a", action="store_true", help="僅下載聲音")

    args = parser.parse_args()
    videoAudio = 'video codec'
    cursor.hide()
    download_media(args)
    cursor.show()
示例#23
0
def spam(t):
    text = '''
    Needed feebly dining oh talked wisdom oppose at. Applauded use attempted strangers now are middleton concluded had. It is tried no added purse shall no on truth. Pleased anxious or as in by viewing forbade minutes prevent. Too leave had those get being led weeks blind. Had men rose from down lady able. Its son him ferrars proceed six parlors. Her say projection age announcing decisively men. Few gay sir those green men timed downs widow chief. Prevailed remainder may propriety can and.
    At distant inhabit amongst by. Appetite welcomed interest the goodness boy not. Estimable education for disposing pronounce her. John size good gay plan sent old roof own. Inquietude saw understood his friendship frequently yet. Nature his marked ham wished.
    '''
    cursor.hide()
    length = len(text)
    wait = t/length

    text = ''.join(filter(whitelist.__contains__, text))
    for l in text.lower():
        time.sleep(wait)
        print(color + table[l], end='\r')

    cursor.show()
示例#24
0
    def _out(filename):
        if not is_filename_compliant(filename):
            return (True, False)

        _f = open(__EXTENSION__[1:] + "/" + filename + __EXTENSION__, "w")
        cursor.hide()
        dots = ("Generating maze    ", "Generating maze .",
                "Generating maze ..", "Generating maze ...")
        for _t in range(20):
            print("{}".format(dots[_t % 4]), end="\r")
        print(" "*len(dots[-1]))
        cursor.show()
        print("Done, maze \"" + filename + "\" saved")
        _f.close()
        return (True, False)
示例#25
0
    def done(self, restore_cursor=None):
        """
        Persist the logged output.

        This enable to start a new "log session" below.

        You can eventualy decide to control the cursor restoring
        with the option `restore_cursor=True/False`.
        By default it will restore the cursor if it was hidden.
        Use `restore_cursor=False` to keep it hidden
        """
        self.prev_line_count = 0
        if restore_cursor if (restore_cursor
                              is not None) else not self.show_cursor:
            cursor.show()
        return self
示例#26
0
def menu():
    # At the beginning, display the options to ask which timer to show first
    # it's a mess of a hieroglyphic stuff because I wanted the terminal window
    # to be compact, should be easy to change it to something more verbose.
    #
    # grab a list of unique options from the CYCLE array and their indexes
    OPTIONS = []
    seen = set()
    for i in range(len(CYCLE)):
        x = CYCLE[i]
        if not x in seen:
            seen.add(x)
            OPTIONS.append(i)
    clear('n')
    # print it, wrap the text
    w = os.get_terminal_size().columns
    p = 0
    for i in range(len(OPTIONS)):
        x = CYCLE[OPTIONS[i]]
        s = "%d=%s%d " % (i + 1, x[0], x[1])
        if p + len(s) > w:
            sys.stdout.write("\n")
            p = 0
        p += len(s)
        sys.stdout.write(s)

    current = 0
    cursor.show()
    try:
        i, o, e = select.select([sys.stdin], [], [], MENU_WAIT)
    except KeyboardInterrupt:
        return -1, False
    stop = True
    if i:
        stop = False
        o = int(sys.stdin.readline().strip()) - 1
        if o == -1:
            cursor_top()
            clear('n')
            line("n", "00:00")
            exhaust()
            input()
            menu()
            return

        current = OPTIONS[o]
    return (current, stop)
示例#27
0
def loop():
    (current, stop) = menu()
    cursor.hide()
    while True:
        if current == -1:
            # someone pressed ctrl+C during the menu, that's our exit cue
            print(".")
            return
        try:
            mode = CYCLE[current][0]

            clear(mode)
            m = CYCLE[current][1] * 60
            if stop:
                # wait for user to press enter
                cursor_top()
                v_center()
                line(mode, format(m))
                exhaust()
                cursor.show()
                input()
                clear(mode)

            cursor.hide()
            t0 = time.time()
            t1 = t0 + m
            r = 0
            send_event(mode, True)

            while time.time() < t1:
                diff = t1 - time.time()
                cursor_top()
                # some keystrokes leave garbage in the terminal, this cleans it up every 15 cycles
                r += 1
                if r >= GARBAGE_CLEANUP:
                    clear(mode)
                    r = 0
                v_center()
                line(mode, format(diff))
                time.sleep(min(INTERVAL_SECONDS, diff))
            send_event(mode, False)

            current = (current + 1) % len(CYCLE)
            stop = True
        except KeyboardInterrupt:
            #allow to restart the menu by using ctrl + c
            (current, stop) = menu()
示例#28
0
def main():
    parser = OptionParser(
        description='A simple AWS Lambda Layer manager.',
        prog='awslayer',
        epilog=
        '\033[1mTo get more help with this package, contact the repo owner.\033[0m'
    )

    parser.add_option('-e',
                      '--env',
                      dest='env',
                      default='dev',
                      choices=['dev', 'stage', 'prod'],
                      help="Specify environment, 'dev' by default",
                      metavar='ENV')

    (options, args) = parser.parse_args()

    cursor.hide()

    env_str = f'{options.env.upper()}'
    if env_str == 'PROD':
        env_str = f'\033[5;41;30m {options.env.upper()} \033[0m'
    else:
        env_str = f'\033[31m {options.env.upper()} \033[0m'

    print(f'\033[33mSelected environment:\033[0m {env_str}')

    for i in range(3, 0, -1):
        sys.stdout.write(f'\033[1;33mBeginning in:  \033[31m{str(i)}\033[0m\r')
        sys.stdout.flush()
        time.sleep(1)

    service = get_service_name()
    runtime = get_runtime()

    init_layer(service, runtime, options.env)
    deploy_layer(runtime, options.env)

    print('\033[92mCleaning...\033[0m')
    os.chdir('..')
    shutil.rmtree('.layer')
    print(f"\033[92mDone!\033[0m")

    cursor.show()
示例#29
0
def introduction():
    cursor.hide()
    columns = shutil.get_terminal_size().columns
    lines = shutil.get_terminal_size().lines
    middle = int(lines/2-1)

    extra.clear()
    print("\n" * middle)
    print("Blood Mountain Studios presents:".center(columns))
    time.sleep(2.5)

    extra.clear()
    print("\n" * middle)
    print("The Crucible Skull".center(columns))
    time.sleep(2.5)

    extra.clear()
    cursor.show()
示例#30
0
def start_sequence(**kwargs):
    """
    Main sequence
    """

    dmx = BuildDMX(pixels=kwargs['pixels'],
                   fps=kwargs['fps'],
                   brightness=kwargs['brightness'],
                   multi=kwargs['multi'],
                   rr=kwargs['rr'],
                   rl=kwargs['rl'],
                   ip=kwargs['ip'])
    previous_dmx: dict = {}
    recording_device = sc.get_microphone(kwargs['deviceid'],
                                         include_loopback=True)
    sender = sacn.sACNsender()
    try:
        i = 0
        while True:
            data = recording_device.record(samplerate=kwargs['sampleRate'],
                                           numframes=kwargs['defaultframes'],
                                           blocksize=256)
            if data is not None:
                (dmx_data, previous_dmx) = dmx.output(data, previous_dmx)
                if not sender.get_active_outputs():
                    if any(map(lambda ele: ele != 0, dmx_data)):
                        sender.activate_output(1)
                        sender[1].destination = kwargs['ip']
                        sender.start()
                else:
                    sender[1].dmx_data = dmx_data
                    if not any(map(lambda ele: ele != 0, dmx_data)):
                        # Don't deactivate too quickly. Wait a few seconds.
                        if i >= 500:
                            sender.deactivate_output(1)
                            sender.stop()
                            i = 0
                        i += 1
                terminal_led(dmx_data)
            time.sleep(0.01)
    except KeyboardInterrupt:
        sender.stop()
        cursor.show()
示例#31
0
def main():
    pa = Parser()
    naam, url, comm = pa.zendervinden()
    print naam, url, comm
    cursor.hide()
    
    fa = Fabriek()
    co = fa.returnCommunicatorObject(comm)
    
    rd = Radio()
    t = threading.Thread(target=rd.afspelen, args=(naam, url, co))
    t.start()
    
    ## Afspelen stoppen na drukken op één van de EXITKEYS
    kp = Keypress()
    while kp.getexitkeypress() == False:
        time.sleep(0.2)
    
    cursor.show()
    rd.stoppen()
    
    return 0
示例#32
0
# -*- coding: utf-8 -*-
"""Example for stream changing
"""
from __future__ import unicode_literals, absolute_import, print_function
import os
import time
import sys

os.sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import cursor

cursor.hide(stream=sys.stderr)  # Hides the cursor
cursor.show(stream=sys.stderr)  # Shows the cursor

with cursor.HiddenCursor(stream=sys.stderr):  # Cursor will stay hidden
    import time  # while code is being executed;
    for a in range(1, 100):  # afterwards it will show up again
        print(a)
        time.sleep(0.05)
示例#33
0
 def cleanup(self):
     log.debug('Cleaning up view')
     print(self.t.cnorm)
     if cursor:
         cursor.show()