Exemple #1
0
def load_data() -> List[Dict[str, Any]]:
    discover = tmdb.Discover()

    data: List = []

    with ProgressBar(title=MD('**Discovering Movies:**')) as pb:

        def add_discover(page_num: int):
            data.extend(discover.movie(page=page_num)['results'])

        with ThreadPoolExecutor(max_workers=5) as executor:
            future = [
                executor.submit(add_discover, i)
                for i in range(1, TOTAL_PAGES + 1)
            ]

            for _ in pb(as_completed(future),
                        label='Querying TMDB:',
                        total=TOTAL_PAGES):
                pass

    print()

    with ProgressBar(title=MD('**Compiling Information:**')) as pb:

        def scan_crew(movie: Dict[str, Any]):
            movie['year'] = movie['release_date'][:4]

            crew = tmdb.Movies(movie['id']).credits()['crew']

            for person in crew:
                if person['job'] == 'Director':
                    if 'directors' not in movie:
                        movie['directors'] = [person]

                    else:
                        movie['directors'].append(person)

        with ThreadPoolExecutor(max_workers=10) as executor:
            future = [executor.submit(scan_crew, movie) for movie in data]

            for _ in pb(as_completed(future),
                        label='Scanning Cast and Crew:',
                        total=len(data)):
                pass

    data = list(filter(lambda x: 'directors' in x, data))

    print()

    with open('data/movies.json', 'w') as f:
        json.dump(data, f)

    return data
Exemple #2
0
def base_begin(title: str, answer: str) -> List[Dict[str, Any]]:
    tmdb.API_KEY = os.getenv('TMDB_API_KEY')

    config = load_config() or {}

    # Load Movies
    ids = set()

    # if config['data'].get('load_default_movies'):
    #     data, changed = load_discovery(ids)

    # else:
    data = []
    changed = False

    with ProgressBar(title=MD('**Loading Custom Lists:**')) as pb:
        if path.isfile('data/movies.json'):
            with open('data/movies.json', 'r') as f:
                list_data = json.load(f)
        else:
            list_data = {'lists': {}, 'movies': {}}

        for l in pb(config['data']['lists'], label='Adding Lists'):
            url = l['url']
            if url not in list_data['lists']:
                changed = True
                title, creator, url, movie_urls = scrape_list(url)
                list_data['lists'][url] = [scrape_movie(m) for m in movie_urls]

            ids.update(list_data['lists'][url])

    with ProgressBar() as pb:
        for i in pb(ids, label='Loading Movies'):
            if i not in list_data['movies'].keys():
                changed = True
                list_data['movies'][i] = load_movie(i)

            data.append(list_data['movies'][i])

    if changed:
        with open('data/movies.json', 'w') as f:
            json.dump(list_data, f)

    print_formatted_text(MD(f'Welcome to the **{title}** quiz!'), end='')
    print_formatted_text(
        MD(f'When presented with a title, enter the **{answer}**'), end='')
    print('Enter # to exit and have fun!')
    print()

    return data
Exemple #3
0
def main():
    with ProgressBar(
        title=HTML("<b>Example of many parallel tasks.</b>"),
        bottom_toolbar=HTML("<b>[Control-L]</b> clear  <b>[Control-C]</b> abort"),
    ) as pb:

        def run_task(label, total, sleep_time):
            for i in pb(range(total), label=label):
                time.sleep(sleep_time)

        threads = []

        for i in range(160):
            label = "Task %i" % i
            total = random.randrange(50, 200)
            sleep_time = random.randrange(5, 20) / 100.0

            threads.append(
                threading.Thread(target=run_task, args=(label, total, sleep_time))
            )

        for t in threads:
            t.daemon = True
            t.start()

        # Wait for the threads to finish. We use a timeout for the join() call,
        # because on Windows, join cannot be interrupted by Control-C or any other
        # signal.
        for t in threads:
            while t.is_alive():
                t.join(timeout=0.5)
Exemple #4
0
def elmo_to_text(vocabulary_file, output_path, layer='nocontext'):
    """
    :param vocabulary_file: Vocabulary file. Note that usually no vocabulary file is provided with ELMo embeddings.
    :param output_path: Output file path
    :param layer: Either 'full' which equals to full Elmo after second biLSTM layer or
                  'nocontext' (context-insensitive)
    
    (Reused from original CogniVal paper)
    """
    if layer == 'full':
        layer_idx = 2
    elif layer == 'nocontext':
        layer_idx = 0
    else:
        raise ValueError('"layer" must be either "full" or "nocontext"')

    elmo = ElmoEmbedder()

    with open(vocabulary_file, 'r') as f:
        words = f.readlines()

    # Create directory
    os.makedirs(output_path.parent, exist_ok=True)

    with open(output_path, 'w') as embedding_file:
        with ProgressBar() as pb:
            for word in pb(words):
                word = word.strip()
                vectors = elmo.embed_sentence(word)

                # context insensitive - first layer
                embedding = ' '.join(map(str, vectors[layer_idx][0]))
                print(word, embedding, file=embedding_file)
Exemple #5
0
def main():
    title = HTML('Downloading <style bg="yellow" fg="black">4 files...</style>')
    label = HTML('<ansired>some file</ansired>: ')

    with ProgressBar(title=title) as pb:
        for i in pb(range(800), label=label):
            time.sleep(.01)
Exemple #6
0
def main():
    with ProgressBar() as pb:
        # Two parallal tasks.
        def task_1():
            for i in pb(range(100)):
                time.sleep(0.05)

        def task_2():
            for i in pb(range(150)):
                time.sleep(0.08)

        # Start threads.
        t1 = threading.Thread(target=task_1)
        t2 = threading.Thread(target=task_2)
        t1.daemon = True
        t2.daemon = True
        t1.start()
        t2.start()

        # Wait for the threads to finish. We use a timeout for the join() call,
        # because on Windows, join cannot be interrupted by Control-C or any other
        # signal.
        for t in [t1, t2]:
            while t.is_alive():
                t.join(timeout=0.5)
Exemple #7
0
    def loadDataFromExternal(self,
                             dataPath: str = pkg_resources.resource_filename(
                                 'hicity', 'core/citycode.data'),
                             silent=False):
        self.session.query(City).delete()
        logging.info('Database cleared.')

        with open(dataPath, 'r', encoding='UTF-8') as reader:
            logging.info('Started loading data...')
            totalRecord = int(reader.readline())
            cities = []
            if not silent:
                with ProgressBar() as pb:
                    label = 'Loading data'
                    bar = pb(range(1, totalRecord + 1), label=label)
                    for cntRecord in bar:
                        time.sleep(0.0001)  # delay for display effects
                        line = reader.readline()
                        sp = line.strip().split(',')  # 去除行尾换行并分割
                        if len(sp) != 2:
                            continue  # 处理异常数据
                        cities.append(City(code=int(sp[1]), name=sp[0]))
            else:
                for cntRecord in range(1, totalRecord + 1):
                    line = reader.readline()
                    sp = line.strip().split(',')  # 去除行尾换行并分割
                    if len(sp) != 2:
                        continue  # 处理异常数据
                    cities.append(City(code=int(sp[1]), name=sp[0]))
            self.addCities(cities)

            print('Data loaded successfully.\n')
            logging.info('Data loaded successfully.')
def main():
    bottom_toolbar = HTML(
        ' <b>[f]</b> Print "f" <b>[q]</b> Abort  <b>[x]</b> Send Control-C.')

    # Create custom key bindings first.
    kb = KeyBindings()
    cancel = [False]

    @kb.add("f")
    def _(event):
        print("You pressed `f`.")

    @kb.add("q")
    def _(event):
        " Quit by setting cancel flag. "
        cancel[0] = True

    @kb.add("x")
    def _(event):
        " Quit by sending SIGINT to the main thread. "
        os.kill(os.getpid(), signal.SIGINT)

    # Use `patch_stdout`, to make sure that prints go above the
    # application.
    with patch_stdout():
        with ProgressBar(key_bindings=kb, bottom_toolbar=bottom_toolbar) as pb:
            for i in pb(range(800)):
                time.sleep(0.01)

                if cancel[0]:
                    break
Exemple #9
0
def main():
    with ProgressBar(
            title=HTML("<b>Example of many parallel tasks.</b>"),
            bottom_toolbar=HTML(
                "<b>[Control-L]</b> clear  <b>[Control-C]</b> abort"),
    ) as pb:

        def run_task(label, total, sleep_time):
            for i in pb(range(total), label=label):
                time.sleep(sleep_time)

        threads = [
            threading.Thread(target=run_task, args=("First task", 50, 0.1)),
            threading.Thread(target=run_task, args=("Second task", 100, 0.1)),
            threading.Thread(target=run_task, args=("Third task", 8, 3)),
            threading.Thread(target=run_task, args=("Fourth task", 200, 0.1)),
            threading.Thread(target=run_task, args=("Fifth task", 40, 0.2)),
            threading.Thread(target=run_task, args=("Sixth task", 220, 0.1)),
            threading.Thread(target=run_task, args=("Seventh task", 85, 0.05)),
            threading.Thread(target=run_task, args=("Eight task", 200, 0.05)),
        ]

        for t in threads:
            t.daemon = True
            t.start()

        # Wait for the threads to finish. We use a timeout for the join() call,
        # because on Windows, join cannot be interrupted by Control-C or any other
        # signal.
        for t in threads:
            while t.is_alive():
                t.join(timeout=0.5)
Exemple #10
0
    async def main(self):
        bindings = KeyBindings()
        bindings.add("c-x")(self.stop)
        bindings.add("c-c")(self.stop)

        formatters = SCREEN_FORMATTERS.copy()
        formatters[formatters.index("ShowBar")] = ShowBar(self.losses,
                                                          sym_a="_",
                                                          sym_b="🚃 ",
                                                          sym_c="․")

        project = os.path.basename(os.getcwd())
        print_formatted_text(SCREEN_BANNER.format(__version__, project),
                             style=SCREEN_STYLE,
                             flush=True)

        self.progress_bar = ProgressBar(
            bottom_toolbar=SCREEN_TOOLBAR,
            style=SCREEN_STYLE,
            key_bindings=bindings,
            formatters=formatters,
        )

        self.trainer = BasicTrainer(device=self.device)

        scripts = [f for f in self.registry.functions if "main_" in f.name]

        # Old-style hard-coded training procedure.
        if len(scripts) == 0:
            await self._run_stage(stage="N/A", groups=self.registry.groups())

        # New-style user-defined training scripts.
        if len(scripts) == 1:
            await scripts[0].function(self)
Exemple #11
0
def with_progress(title: str,
                  target: Callable[[Callable], None],
                  length: int = None):
    """ A shortcut to displaying a progress bar for various things. It will
    start a prompt_toolkit progress bar with the given title and a counter 
    with the given length. Then, it will call `target` with an `on_progress`
    parameter. This parameter should be called for all progress updates. See
    the `do_upload` and `do_download` for examples w/ copyfileobj """

    with ProgressBar(title) as pb:
        counter = pb(range(length))
        last_update = time.time()

        def on_progress(blocksz):
            """ Update the progress bar """
            if blocksz == -1:
                counter.stopped = True
                counter.done = True
                pb.invalidate()
                return

            counter.items_completed += blocksz
            if counter.items_completed >= counter.total:
                counter.done = True
                counter.stopped = True
            if (time.time() - last_update) > 0.1:
                pb.invalidate()

        target(on_progress)

        # https://github.com/prompt-toolkit/python-prompt-toolkit/issues/964
        time.sleep(0.1)
Exemple #12
0
def main():
    with ProgressBar(
            title=HTML("<b>Example of many parallel tasks.</b>"),
            bottom_toolbar=HTML(
                "<b>[Control-L]</b> clear  <b>[Control-C]</b> abort"),
    ) as pb:

        def run_task(label, total, sleep_time):
            for i in pb(range(total), label=label):
                time.sleep(sleep_time)

        threads = [
            threading.Thread(target=run_task, args=("First task", 50, 0.1)),
            threading.Thread(target=run_task, args=("Second task", 100, 0.1)),
            threading.Thread(target=run_task, args=("Third task", 8, 3)),
            threading.Thread(target=run_task, args=("Fourth task", 200, 0.1)),
            threading.Thread(target=run_task, args=("Fifth task", 40, 0.2)),
            threading.Thread(target=run_task, args=("Sixth task", 220, 0.1)),
            threading.Thread(target=run_task, args=("Seventh task", 85, 0.05)),
            threading.Thread(target=run_task, args=("Eight task", 200, 0.05)),
        ]

        for t in threads:
            t.daemon = True
            t.start()

        for t in threads:
            while t.is_alive():
                t.join(timeout=0.5)
Exemple #13
0
def exec_update_all():
    """
    更新全部rss 内容到数据库
    :return:
    """
    amount_rss = count_all_rss()
    # 已经加入的rss item link 列表
    already_link_list = rss_items.get_link_keys()
    # 标记所有新闻为不是最新
    rss_items.update_all_not_add_new()
    # 获取所有信息
    g = get_all_rss_db(already_link_list)

    list = []

    title = HTML('<style bg="yellow" fg="black">加载RSS最新内容</style>')
    label = HTML('<ansired>加载RSS最新内容</ansired>: ')

    with ProgressBar(title=title) as pb:
        for i in pb(range(amount_rss), label=label):
            time.sleep(.01)
            try:
                result = next(g)
                list.extend(result)
            except StopIteration:
                pass


    if len(list) == 0:
        print('没有新的内容')
    else:
        print('保存到数据库...')
        rss_items.update_all_rss(list)
        print('保存数据库成功,', '共保存:' + str(len(list)))
Exemple #14
0
def main():
    with ProgressBar(
            title=HTML('<b fg="#aa00ff">Nested progress bars</b>'),
            bottom_toolbar=HTML(' <b>[Control-L]</b> clear  <b>[Control-C]</b> abort')) as pb:

        for i in pb(range(6), label='Main task'):
            for j in pb(range(200), label='Subtask <%s>' % (i + 1, ), remove_when_done=True):
                time.sleep(.01)
Exemple #15
0
def main():
    with ProgressBar(
            title='Scrolling task name (make sure the window is not too big).'
    ) as pb:
        for i in pb(
                range(800),
                label=
                'This is a very very very long task that requires horizontal scrolling ...'
        ):
            time.sleep(.01)
Exemple #16
0
 def __init__(self, source_list):
     for source in source_list:
         title = "Fetching news from " + source
         source = feedparser.parse(source)
         with ProgressBar(title=title) as pb:
             for article in pb(source.entries):
                 new_article = Article(article.link)
                 new_article.publish_date = article.published
                 self.article_list.append(new_article)
     self.article_list.sort(key=lambda x: x.publish_date, reverse=True)
Exemple #17
0
    def do_download(self, args):
        """ Download a file from the remote host """

        try:
            # Locate an appropriate downloader class
            DownloaderClass = downloader.find(self, args.method)
        except downloader.DownloadError as exc:
            util.error(f"{exc}")
            return

        # Grab the arguments
        path = args.path
        basename = os.path.basename(args.path)
        outfile = args.output.format(basename=basename)

        download = DownloaderClass(self, remote_path=path, local_path=outfile)

        # Get the remote file size
        size = self.run(
            f'stat -c "%s" {shlex.quote(path)} 2>/dev/null || echo "none"')
        if b"none" in size:
            util.error(f"{path}: no such file or directory")
            return
        size = int(size)

        with ProgressBar([("#888888", "downloading with "),
                          ("fg:ansiyellow", f"{download.NAME}")]) as pb:
            counter = pb(range(size))
            last_update = time.time()

            def on_progress(copied, blocksz):
                """ Update the progress bar """
                if blocksz == -1:
                    counter.stopped = True
                    counter.done = True
                    pb.invalidate()
                    return

                counter.items_completed += blocksz
                if counter.items_completed >= counter.total:
                    counter.done = True
                    counter.stopped = True
                if (time.time() - last_update) > 0.1:
                    pb.invalidate()

            try:
                download.serve(on_progress)
                if download.command():
                    while not counter.done:
                        time.sleep(0.2)
            finally:
                download.shutdown()

            # https://github.com/prompt-toolkit/python-prompt-toolkit/issues/964
            time.sleep(0.1)
Exemple #18
0
    def download_file(self, _old, entry, **kwargs):
        with ProgressBar(formatters=self.progress_bar_formatters) as pb:
            progress_task = pb(label=entry.name, total=entry.size)

            def progress_callback(p_dl_size: int, _p_size: int,
                                  _p_dl_total_size: int, _p_total_size: int):
                progress_task.items_completed = p_dl_size
                pb.invalidate()

            kwargs["progress_callback"] = progress_callback
            return self.pmc.download_file_base(entry, **kwargs)
Exemple #19
0
def AcqProgBar(ctrl, options):
    iface = ctrl.hwInterface()
    info = iface.getHwCtrlObj(Lima.Core.HwCap.DetInfo)
    frame_dim = FrameDim(info.getDetectorImageSize(), info.getCurrImageType())
    exposure_time = options.exposure_time * ur.second
    acq_time = (options.nb_frames * exposure_time).to_compact()
    frame_rate = (1 / exposure_time).to(ur.Hz).to_compact()
    title = f'Acquiring on {info.getDetectorModel()} ({info.getDetectorType()}) | ' \
            f'{options.nb_frames} x {exposure_time:~.4}({frame_rate:~.4}) = {acq_time:~.4}  | ' \
            f'{frame_dim}'
    return ProgressBar(title=title,
                       bottom_toolbar=HTML(" <b>[Control-C]</b> abort"))
Exemple #20
0
def fetch_and_store_orders(db):
    """
    Fetches all the historical orders for the user and saves them in db
    """
    response = session.get(SWIGGY_ORDER_URL)
    if not response.json().get('data', None):
        raise SwiggyAPIError("Unable to fetch orders")

    # get the last order_id to use as offset param for next order fetch call
    orders = response.json().get('data').get('orders', None)
    if not orders:
        raise SwiggyAPIError("Unable to fetch orders")
    offset_id = orders[-1]['order_id']
    count = response.json().get('data')['total_orders']
    pages = ceil(count / 10)

    label = "Fetching {} orders".format(count)

    # Updates the progress bar on every orders fetch call (i.e. after 10 unique orders)
    with ProgressBar(style=PROGRESS_BAR_STYLE,
                     formatters=PROGRESS_BAR_FORMATTER) as pb:
        for i in pb(range(pages), label=label):
            try:
                orders = fetch_orders(offset_id)
            except SwiggyAPIError as e:
                raise SwiggyAPIError(e)
            if len(orders) == 0:
                break

            # extract only the fields required for analytics
            try:
                orders_info = fetch_orders_info(orders)
            except SwiggyAPIError as e:
                raise SwiggyAPIError(e)

            # store the order data in db
            try:
                db.insert_orders_details(orders_info.get('order_details'))
            except SwiggyDBError as e:
                print(e)
            try:
                db.insert_order_items(orders_info.get('order_items'))
            except SwiggyDBError as e:
                print(e)

            # Responsible Scraping. Code word for "dont wanna overload their servers :P" :)
            time.sleep(SWIGGY_API_CALL_INTERVAL)
            # SAD PANDA FACE BEGIN
            # The way it works is that, the first API call returns a paginated set of 10 orders and to fetch the next result, you need
            # to send the last order_id from this result set as an offset parameter. Because the way this offset/cursor
            # is designed it makes it impossible to use any kind of async/await magic.
            # SAD PANDA FACE OVER
            offset_id = orders[-1]['order_id']
def main():
    custom_formatters = [
        formatters.Label(),
        formatters.Text(': [', style='class:percentage'),
        formatters.Percentage(),
        formatters.Text(']', style='class:percentage'),
        formatters.Text(' '),
        formatters.Bar(sym_a='#', sym_b='#', sym_c='.'),
        formatters.Text('  '),
    ]

    with ProgressBar(style=style, formatters=custom_formatters) as pb:
        for i in pb(range(1600), label='Installing'):
            time.sleep(.01)
Exemple #22
0
def main():
    custom_formatters = [
        formatters.Label(),
        formatters.Text(": [", style="class:percentage"),
        formatters.Percentage(),
        formatters.Text("]", style="class:percentage"),
        formatters.Text(" "),
        formatters.Bar(sym_a="#", sym_b="#", sym_c="."),
        formatters.Text("  "),
    ]

    with ProgressBar(style=style, formatters=custom_formatters) as pb:
        for i in pb(range(1600), label="Installing"):
            time.sleep(0.01)
Exemple #23
0
def do_konami(event):
    custom_formatters = [
        formatters.Label(),
        formatters.Text(" "),
        formatters.Rainbow(formatters.Bar()),
        formatters.Text(" left: "),
        formatters.Rainbow(formatters.TimeLeft()),
    ]

    color_depth = ColorDepth.DEPTH_8_BIT
    with ProgressBar(formatters=custom_formatters, color_depth=color_depth) as pb:
        for i in pb(range(1000), label=""):
            time.sleep(0.001)
    print('Downloaded L33t Hax...')
Exemple #24
0
    def do_upload(self, args):
        """ Upload a file to the remote host """

        if not os.path.isfile(args.path):
            util.error(f"{args.path}: no such file or directory")
            return

        try:
            # Locate an appropriate downloader class
            UploaderClass = uploader.find(self, args.method)
        except uploader.UploadError as exc:
            util.error(f"{exc}")
            return

        path = args.path
        basename = os.path.basename(args.path)
        name = basename
        outfile = args.output.format(basename=basename)

        upload = UploaderClass(self, remote_path=outfile, local_path=path)

        with ProgressBar([("#888888", "uploading via "),
                          ("fg:ansiyellow", f"{upload.NAME}")]) as pb:

            counter = pb(range(os.path.getsize(path)))
            last_update = time.time()

            def on_progress(copied, blocksz):
                """ Update the progress bar """
                counter.items_completed += blocksz
                if counter.items_completed >= counter.total:
                    counter.done = True
                    counter.stopped = True
                if (time.time() - last_update) > 0.1:
                    pb.invalidate()

            upload.serve(on_progress)
            upload.command()

            try:
                while not counter.done:
                    time.sleep(0.1)
            except KeyboardInterrupt:
                pass
            finally:
                upload.shutdown()

            # https://github.com/prompt-toolkit/python-prompt-toolkit/issues/964
            time.sleep(0.1)
def main():
    with ProgressBar(
            title=HTML("<b>Example of many parallel tasks.</b>"),
            bottom_toolbar=HTML(
                "<b>[Control-L]</b> clear  <b>[Control-C]</b> abort"),
    ) as pb:

        def run_task(label, total, sleep_time):
            """Complete a normal run."""
            for i in pb(range(total), label=label):
                time.sleep(sleep_time)

        def stop_task(label, total, sleep_time):
            """Stop at some random index.

            Breaking out of iteration at some stop index mimics how progress
            bars behave in cases where errors are raised.
            """
            stop_i = random.randrange(total)
            bar = pb(range(total), label=label)
            for i in bar:
                if stop_i == i:
                    bar.label = f"{label} BREAK"
                    break
                time.sleep(sleep_time)

        threads = []

        for i in range(160):
            label = "Task %i" % i
            total = random.randrange(50, 200)
            sleep_time = random.randrange(5, 20) / 100.0

            threads.append(
                threading.Thread(
                    target=random.choice((run_task, stop_task)),
                    args=(label, total, sleep_time),
                ))

        for t in threads:
            t.daemon = True
            t.start()

        # Wait for the threads to finish. We use a timeout for the join() call,
        # because on Windows, join cannot be interrupted by Control-C or any other
        # signal.
        for t in threads:
            while t.is_alive():
                t.join(timeout=0.5)
Exemple #26
0
def main():
    custom_formatters = [
        formatters.Label(),
        formatters.Text(' '),
        formatters.SpinningWheel(),
        formatters.Text(' '),
        formatters.Text(HTML('<tildes>~~~</tildes>')),
        formatters.Bar(sym_a='#', sym_b='#', sym_c='.'),
        formatters.Text(' left: '),
        formatters.TimeLeft(),
    ]
    with ProgressBar(title='Progress bar example with custom formatter.',
                     formatters=custom_formatters, style=style) as pb:

        for i in pb(range(20), label='Downloading...'):
            time.sleep(1)
Exemple #27
0
    def compareTo(self, filename:str, dstart:float, dend:float, dstep:float, output:str):
        """CompareTo
        Compare the result of the current run of the modelling (with the level you want) and a file 
        that contains expected results.
        This function returns the difference between the expected result and the current run of the modelling

        Usage: compareTo [-h] (--filename <filename>) (delta <dstart> <dend> <dstep>) 
                         [--output <output>]

        Options:
            -h, --help                 Print this help menu.
            -l, --level level          Set the number of layers of the graph [Default: 4].
            -f, --filename <filename>  Csv File containing expected results to compare with.
            -o, --output <output>      File where results will be stored [Default: results.txt].
            delta                      Value used to determine which node acts as a controller.
        """
        try:
            with open(filename, 'r') as csvFile:
                csvData = []
                for line in csvFile.readlines():
                    csvData.append(line.strip())
        except IOError as ioe:
            print(f"CSVFile: {filename}")
            print(f'Error while opening the file...\n{ioe}')
            return False
        except :
            print(f"CSVFile: {filename}")
            print(f'Error while opening into CSV file...')
            return False

        retTab = convert_str_to_array(csvData)

        with open('tests/debug.log', 'w') as outputFile:
            outputFile.write(f"[d] - ExpectedResults\n")
            outputFile.write(f"{retTab}\n")

        with ProgressBar() as pb:
            graphs = {}
            for d in pb(arange(dstart, dend, dstep)):
                current = self.dbc.transGraph(0.6, d.item(), None)
                # current = self.dbc.getResults()
                graphs[d] = current

            # tdelta = get_optimal_delta(retTab.copy(), graphs, plot=True, isT1=True, debug=output)
            plot_controller_delta(retTab.copy(), graphs, plot=True, debug=output)
async def interact(ssh_session: PromptToolkitSSHSession) -> None:
    """
    The application interaction.

    This will run automatically in a prompt_toolkit AppSession, which means
    that any prompt_toolkit application (dialogs, prompts, etc...) will use the
    SSH channel for input and output.
    """
    prompt_session = PromptSession()

    # Alias 'print_formatted_text', so that 'print' calls go to the SSH client.
    print = print_formatted_text

    print("We will be running a few prompt_toolkit applications through this ")
    print("SSH connection.\n")

    # Simple progress bar.
    with ProgressBar() as pb:
        for i in pb(range(50)):
            await asyncio.sleep(0.1)

    # Normal prompt.
    text = await prompt_session.prompt_async("(normal prompt) Type something: ")
    print("You typed", text)

    # Prompt with auto completion.
    text = await prompt_session.prompt_async(
        "(autocompletion) Type an animal: ", completer=animal_completer
    )
    print("You typed", text)

    # prompt with syntax highlighting.
    text = await prompt_session.prompt_async(
        "(HTML syntax highlighting) Type something: ", lexer=PygmentsLexer(HtmlLexer)
    )
    print("You typed", text)

    # Show yes/no dialog.
    await prompt_session.prompt_async("Showing yes/no dialog... [ENTER]")
    await yes_no_dialog("Yes/no dialog", "Running over asyncssh").run_async()

    # Show input dialog
    await prompt_session.prompt_async("Showing input dialog... [ENTER]")
    await input_dialog("Input dialog", "Running over asyncssh").run_async()
def main():
    custom_formatters = [
        formatters.Label(suffix=': '),
        formatters.Percentage(),
        formatters.Bar(start='|', end='|', sym_a=' ', sym_b=' ', sym_c=' '),
        formatters.Text(' '),
        formatters.Progress(),
        formatters.Text(' ['),
        formatters.TimeElapsed(),
        formatters.Text('<'),
        formatters.TimeLeft(),
        formatters.Text(', '),
        formatters.IterationsPerSecond(),
        formatters.Text('it/s]'),
    ]

    with ProgressBar(style=style, formatters=custom_formatters) as pb:
        for i in pb(range(1600), label='Installing'):
            time.sleep(.01)
Exemple #30
0
def main():
    custom_formatters = [
        formatters.Label(suffix=": "),
        formatters.Percentage(),
        formatters.Bar(start="|", end="|", sym_a=" ", sym_b=" ", sym_c=" "),
        formatters.Text(" "),
        formatters.Progress(),
        formatters.Text(" ["),
        formatters.TimeElapsed(),
        formatters.Text("<"),
        formatters.TimeLeft(),
        formatters.Text(", "),
        formatters.IterationsPerSecond(),
        formatters.Text("it/s]"),
    ]

    with ProgressBar(style=style, formatters=custom_formatters) as pb:
        for i in pb(range(1600), label="Installing"):
            time.sleep(0.01)