# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # 5.10. Interacting with asynchronous parallel tasks in IPython

# #### This notebook requires an ipcluster to be executed before start

# + magic_args="bash --bg" language="script"
# ipcluster start -n 4
# -

# !sleep 5

import sys
import time
import ipyparallel
import ipywidgets
from IPython.display import clear_output, display

rc = ipyparallel.Client()

view = rc.load_balanced_view()


def f(x):
    import time
    time.sleep(.1)
    return x * x


numbers = list(range(100))

ar = view.map_async(f, numbers)

ar.metadata[0]

for i in ar:
    print(i, end=', ')


def progress_bar(ar):
    # We create a progress bar.
    w = ipywidgets.IntProgress()
    # The maximum value is the number of tasks.
    w.max = len(ar.msg_ids)
    # We display the widget in the output area.
    display(w)
    # Repeat:
    while not ar.ready():
        # Update the widget's value with the
        # number of tasks that have finished
        # so far.
        w.value = ar.progress
        time.sleep(.1)
    w.value = w.max


ar = view.map_async(f, numbers)

# + podoc={"output_text": "Progress bar"}
progress_bar(ar)
# -

# ## Cleanup

# !ipcluster stop

# %killbgscripts

StarcoderdataJupyterScriptsDedupFiltered