Exemple #1
0
 def __init__(self,
              initial_address=defaults.default_twc_osmc_address,
              initial_user=defaults.default_twc_osmc_username,
              initial_pw=defaults.default_twc_osmc_password,
              address_label='Address:',
              user_label='User:'******'Password:',
              label_text="OSMC API Access Point",
              auto_display=True):
     self.address_widget = widgets.Text(value=initial_address,
                                        description=address_label)
     self.user_widget = widgets.Text(value=initial_user,
                                     description=user_label)
     self.pw_widget = widgets.Password(value=initial_pw,
                                       description=pw_label)
     self.box = widgets.HBox([
         widgets.VBox([
             widgets.Label(value=label_text),
             widgets.Label(value=""),
             widgets.Label(value="")
         ]),
         widgets.VBox(
             [self.address_widget, self.user_widget, self.pw_widget])
     ])
     if auto_display: self.display()
def decrypt_widget():
    import ipywidgets as widgets
    decrypt_button = widgets.Button(description="decrypt")
    key_text_area = widgets.Password(description="key")

    def do_decrypt(*args):
        key = key_text_area.value
        decrypt(key)

    decrypt_button.on_click(do_decrypt)
    assembly = widgets.VBox(children=[decrypt_button, key_text_area])
    return assembly
Exemple #3
0
 def loginw(self):
     """login widget"""
     user = os.environ['USER']
     self.username = ipywidgets.Text(
         value=user, placeholder=user, description='User:'******'Password:'******'ess password')
     login_interactive = ipywidgets.interactive(
         self.helper1, user=self.username, password=password_widget)
     button = ipywidgets.Button(description="Login")
     self.output = ipywidgets.Output()
     button.on_click(self.on_button_clicked)
Exemple #4
0
def ConstructDataManagementPanel():
    # the main panel
    DataManagementPanel = widgets.VBox() 
    # for separating gui elements
    SeparatorLabel = widgets.HTML(value="<hr>")
    # for explaining the usage of this panel
    UsageLabel = widgets.HTML(value="<p style='line-height:1.4'><b>Usage:</b><br>Here you can select one or several orbit files which will be tranformed from csv to NetCDF files (.nc). If the NetCDF file already exists then it is overwritten. To start the process you have to type the correct password and press the 1st blue button. The 2nd blue button alters the state of the NetCDF file, making Calculated='no' so that all values will be recalculated during a simulation run.</p>")
    # for selecting orbits
    AllOrbitsLabel = widgets.HTML(value="<b>Select one or several orbits:</b>")
    AllOrbitsLabel.layout.margin = '20px 0px 0px 0px'
    AllOrbitFilenames = list()
    for f in os.listdir( DaedalusGlobals.CSV_Files_Path ):
        if f.endswith("csv"):
            AllOrbitFilenames.append( f[:-4] )
    global AllOrbitsSelector
    AllOrbitsSelector = widgets.SelectMultiple( options=AllOrbitFilenames, rows=8, )
    AllOrbitsSelector.layout.min_width='400px'
    # for entering the authorization password 
    PasswordLabel = widgets.HTML(value="<b>Type the authorization password:</b>")
    PasswordBox = widgets.Password()
    PasswordBox.observe(PasswordBox_onValueChange, names='value')
    # for selecting a specific file by typing its full-path name (in order to reset its state)
    SpecificFilenameLabel = widgets.HTML(value="<b>Type a specific full-path filename to reset:<b>")
    SpecificFilenameLabel.layout.margin = '20px 0px 0px 0px'
    # for selecting type of file according to the data stored inside it (in order to reset its state)
    AllStagesLabel = widgets.HTML(value="<b>Or select one/several stages of calculation to reset:</b>")
    AllStagesLabel.layout.margin = '20px 0px 0px 0px'
    AllStages = list()
    for f in os.listdir(DaedalusGlobals.Processed_Files_Path):
        if os.path.isdir(DaedalusGlobals.Processed_Files_Path+f):  
            AllStages.append( f )
    global AllStagesSelector
    AllStagesSelector = widgets.SelectMultiple( options=AllStages, rows=5, )
    AllStagesSelector.layout.min_width='400px'
    # construct the action buttons
    FillNETCDFbutton = widgets.Button(description='Create Orbit NetCDF files', button_style='primary')
    FillNETCDFbutton.layout.margin = '20px 0px 0px 0px'
    FillNETCDFbutton.layout.min_width='220px'
    FillNETCDFbutton.on_click( FillNETCDF_button_clicked )
    ResetNETCDFbutton = widgets.Button(description='Reset state of NetCDF files', button_style='primary')
    ResetNETCDFbutton.layout.margin = '20px 0px 0px 0px'
    ResetNETCDFbutton.layout.min_width='220px'
    ResetNETCDFbutton.on_click( ResetNETCDFbutton_clicked )
    
    # Put all together
    DataManagementPanel.children = [ UsageLabel, SeparatorLabel, PasswordLabel, PasswordBox, AllOrbitsLabel, AllOrbitsSelector, FillNETCDFbutton, SeparatorLabel, SpecificFilenameLabel, SpecificFilename, AllStagesLabel, AllStagesSelector, ResetNETCDFbutton ]
    return DataManagementPanel
    def __init__(self, host="localhost", port=4064):
        """Connects to an omero database.

        Parameters
        ----------
        host: str, the omero server host (default localhost)
        port: int, the connection port (default 4064)

        """
        self.host = host
        self.port = port
        self.logbox = widgets.Text(description="OME loggin")
        self.pwdbox = widgets.Password(description="OME password")
        self.gobtn = widgets.Button(description="Let me in")
        self.gobtn.on_click(self.on_go_clicked)
        self.out = widgets.Output()
        super().__init__((self.logbox, self.pwdbox, self.gobtn, self.out))
        self.conn = None
def decrypt_widget(parent_path, folder_name):
    import ipywidgets as widgets
    decrypt_button = widgets.Button(description="decrypt")
    key_text_area = widgets.Password(description="password")
    out = widgets.Output()

    def do_decrypt(*args):
        with out:
            key = key_text_area.value
            decryptor = Encryption(parent_path, folder_name, key)
            print("now decrypting " + repr(decryptor.crypt_path))
            decryptor.decrypt()
            print("decryption complete.")

    decrypt_button.on_click(do_decrypt)
    assembly = widgets.VBox(children=[decrypt_button, key_text_area, out])
    display(assembly)
    with out:
        print "Please provide password and press the decrypt button to decrypt the data."
Exemple #7
0
def kensu_client_init():
    import ipywidgets as widgets
    api_url = widgets.Text(value='',
                           placeholder='Type the ingestion URL',
                           description='API:',
                           disabled=False)
    display(api_url)

    token = widgets.Password(value='',
                             placeholder='Enter token',
                             description='Token:',
                             disabled=False)
    display(token)

    project = widgets.Text(value='',
                           placeholder='Type a project name',
                           description='Project:',
                           disabled=False)
    display(project)

    def initialization_kensu(button):
        from kensu.utils.kensu_provider import KensuProvider
        kensu = KensuProvider().initKensu(
            api_url=api_url.value,
            auth_token=token.value,
            process_name='demo-monitoring-rules-online',
            user_name='Sammy',
            code_location='https://gitlab.example.com',
            init_context=True,
            project_names=[project.value],
            environment="Production",
            report_to_file=False,
            logical_naming='File')

        print('Kensu Initialization done')

    button = widgets.Button(
        description='Click to initialize',
        disabled=False,
        button_style='',  # 'success', 'info', 'warning', 'danger' or ''
        tooltip='Click me')
    button.on_click(initialization_kensu)
    display(button)
Exemple #8
0
    def __init__(self, serialize_file):
        self._connected = False
        self._serialize_file = serialize_file
        st = {'description_width': 'initial'}
        layout = ipw.Layout(margin='0 100pt 0 0')
        layout1 = ipw.Layout(justify_content='center')

        self.sp = ServerParams()
        self.sp.serialize(serialize_file, {}, True)

        self.text1 = ipw.Text(value=self.sp.server,
                              description='XNAT server:',
                              layout={'width': '200pt'},
                              style=st,
                              disabled=False)
        #        self.text1=ipw.Text(value='https://cnda.wustl.edu', description='XNAT server:',
        #                            layout={'width':'200pt'}, style=st, disabled=False)

        self.text2 = ipw.Text(value=self.sp.user,
                              description='user:'******'width': '120pt'})
        self.text3 = ipw.Password(value='',
                                  description='password:'******'width': '120pt'})
        self.lbl1 = ipw.Label(
            'status: not connected', layout={'width': '120pt'},
            style=st)  #layout={'width':'240px','justify-content':'center'}
        lbl2 = ipw.Label('', layout={'width': '120pt'}, style=st)
        self.btn1 = ipw.Button(description="connect",
                               style={},
                               layout={'width': '200pt'})
        self.btn1.on_click(self.on_connect)
        vb1 = ipw.HBox([self.text1, self.text2, self.text3])
        vb2 = ipw.HBox([self.btn1, lbl2, self.lbl1])
        self.main_box = ipw.VBox([vb1, vb2])
Exemple #9
0
    def __init__(
            self,
            ask_for_user_pw=defaults.default_use_password,
            initial_address=defaults.default_IQS_address,
            initial_user=defaults.default_IQS_username,
            initial_password=defaults.default_IQS_password,
            use_oidc=defaults.default_use_oidc,
            token=defaults.default_IQS_token,
            initial_auth_header_name=defaults.default_IQS_auth_header_name,
            initial_auth_header_value=defaults.default_IQS_auth_header_value,
            use_auth_header=defaults.default_use_auth_header,
            address_label='Address:',
            use_user_pw_label='Login with Username & Password',
            user_label='User:'******'Password:'******'Use OpenID Connect',
            token_label='OIDC Token:',
            label_text="IQS API Access Point",
            auth_header_checkbox_label='Use Authentication Header',
            auth_header_name_label='Header Name:',
            auth_header_value_label='Header Value:',
            login_button=True,
            auto_display=defaults.default_auto_display):

        self.ask_for_user_pw_checkbox = widgets.Checkbox(
            value=ask_for_user_pw, description=use_user_pw_label)
        self.address_field = widgets.Text(value=initial_address,
                                          description=address_label)
        self.user_field = widgets.Text(value=initial_user,
                                       description=user_label)
        self.password_field = widgets.Password(value=initial_password,
                                               description=password_label)

        self.oidc_checkbox = widgets.Checkbox(value=use_oidc,
                                              description=oidc_checkbox_label)
        self.token_field = widgets.Text(value=token, description=token_label)

        self.auth_header_checkbox = widgets.Checkbox(
            value=use_auth_header, description=auth_header_checkbox_label)
        self.auth_header_name_field = widgets.Text(
            value=initial_auth_header_name, description=auth_header_name_label)
        self.auth_header_value_field = widgets.Text(
            value=initial_auth_header_value,
            description=auth_header_value_label)

        self.iqs_client = None

        if ask_for_user_pw:
            fields = [
                self.address_field, self.ask_for_user_pw_checkbox,
                self.user_field, self.password_field, self.oidc_checkbox,
                self.token_field, self.auth_header_checkbox,
                self.auth_header_name_field, self.auth_header_value_field
            ]
        else:
            fields = [self.address_field]

        btn_connect = widgets.Button(description="Test Connection",
                                     disabled=False)
        connection_label = widgets.Label("")

        def test_connection(_):
            try:
                self.iqs_client = self.connect()
                server_status = self.iqs_client.server_management.get_server_status_with_http_info(
                )

                if server_status[1] == 200:
                    if server_status[0].component_statuses["SERVER"] == "UP":
                        connection_label.value = "Connected! IQS is ready to use."
                else:
                    raise Exception(
                        "Error during operation.",
                        "{}: {}".format(server_status.status_code,
                                        server_status.reason))

            except Exception as error:
                connection_label.value = f"Connection failed: {error}"

        btn_connect.on_click(test_connection)

        if login_button:
            fields.append(btn_connect)
            fields.append(connection_label)

        self.box = widgets.HBox(
            [widgets.Label(value=label_text),
             widgets.VBox(fields)])
        if auto_display:
            self.display()
Exemple #10
0
    # value='John',
    placeholder='Choose Someone',
    options=['Paul', 'John', 'George', 'Ringo'],
    description='Combobox:',
    ensure_option=True,
    disabled=False)

# ### Password
#
# The `Password` widget hides user input on the screen. **This widget is not a secure way to collect sensitive information because:**
#
# + The contents of the `Password` widget are transmitted unencrypted.
# + If the widget state is saved in the notebook the contents of the `Password` widget is stored as plain text.

widgets.Password(value='password',
                 placeholder='Enter password',
                 description='Password:',
                 disabled=False)

# + [markdown] slideshow={"slide_type": "slide"}
# ### Label
#
# The `Label` widget is useful if you need to build a custom description next to a control using similar styling to the built-in control descriptions.
# -

widgets.HBox(
    [widgets.Label(value="The $m$ in $E=mc^2$:"),
     widgets.FloatSlider()])

# ### HTML

widgets.HTML(
Exemple #11
0
    def __init__(self, **kwargs):
        computer_image = ipw.HTML(
            '<img width="200px" src="./miscellaneous/images/computer.png">')

        # Username.
        inp_username = ipw.Text(description="SSH username:"******"350px"),
                                style=STYLE)
        link((inp_username, 'value'), (self, 'username'))

        # Port.
        inp_port = ipw.IntText(description="SSH port:",
                               value=22,
                               layout=ipw.Layout(width="350px"),
                               style=STYLE)
        link((inp_port, 'value'), (self, 'port'))

        # Hostname.
        inp_computer_hostname = ipw.Text(description="Computer hostname:",
                                         layout=ipw.Layout(width="350px"),
                                         style=STYLE)
        link((inp_computer_hostname, 'value'), (self, 'hostname'))

        # Upload private key directly.
        self._inp_password = ipw.Password(description="SSH password:"******"150px"),
                                          style=STYLE,
                                          disabled=False)
        self._inp_private_key = ipw.FileUpload(
            accept='',
            layout=ipw.Layout(width="350px"),
            style=STYLE,
            description='Private key',
            multiple=False,
            disabled=True)
        self._verification_mode = ipw.Dropdown(
            options=['password', 'private_key'],
            layout=ipw.Layout(width="350px"),
            style=STYLE,
            value='password',
            description='verification mode:',
            disabled=False)
        self._verification_mode.observe(self.on_use_verification_mode_change,
                                        names='value')

        # Proxy ssh settings.
        inp_use_proxy = ipw.Checkbox(value=False, description='Use proxy')
        inp_use_proxy.observe(self.on_use_proxy_change, names='value')
        link((inp_use_proxy, 'value'), (self, 'use_proxy'))

        inp_proxy_hostname = ipw.Text(description="Proxy server address:",
                                      layout=ipw.Layout(width="350px"),
                                      style=STYLE)
        link((inp_proxy_hostname, 'value'), (self, 'proxy_hostname'))

        self._use_diff_proxy_username = ipw.Checkbox(
            value=False,
            description='Use different username and password',
            layout={'width': 'initial'})
        self._use_diff_proxy_username.observe(
            self.on_use_diff_proxy_username_change, names='value')
        inp_proxy_username = ipw.Text(value='',
                                      description="Proxy server username:"******"350px"),
                                      style=STYLE)
        link((inp_proxy_username, 'value'), (self, 'proxy_username'))

        self._inp_proxy_password = ipw.Password(
            value='',
            description="Proxy server password:"******"138px"),
            style=STYLE)

        # Setup ssh button and output.
        btn_setup_ssh = ipw.Button(description="Setup ssh")
        btn_setup_ssh.on_click(self.on_setup_ssh)
        self._setup_ssh_out = ipw.Output()

        # Defining widgets positions.
        computer_ssh_box = ipw.VBox([
            inp_computer_hostname, inp_port, inp_username,
            self._verification_mode, self._inp_password, self._inp_private_key,
            inp_use_proxy
        ],
                                    layout=ipw.Layout(width="400px"))
        self._proxy_user_password_box = ipw.VBox(
            [inp_proxy_username, self._inp_proxy_password],
            layout={'visibility': 'hidden'})
        self._proxy_ssh_box = ipw.VBox([
            inp_proxy_hostname, self._use_diff_proxy_username,
            self._proxy_user_password_box
        ],
                                       layout={
                                           'visibility': 'hidden',
                                           'width': '400px'
                                       })

        children = [
            ipw.HBox([computer_image, computer_ssh_box, self._proxy_ssh_box]),
            btn_setup_ssh, self._setup_ssh_out
        ]
        super(SshComputerSetup, self).__init__(children, **kwargs)
Exemple #12
0
    def __init__(self, **kwargs):
        computer_image = ipw.HTML(
            '<img width="200px" src="./miscellaneous/images/computer.png">')

        # Computer ssh settings
        self._inp_username = ipw.Text(description="SSH username:"******"350px"),
                                      style=STYLE)
        self._inp_password = ipw.Password(description="SSH password:"******"130px"),
                                          style=STYLE)
        self._inp_computer_hostname = ipw.Text(
            description="Computer name:",
            layout=ipw.Layout(width="350px"),
            style=STYLE)

        # Proxy ssh settings
        self._use_proxy = ipw.Checkbox(value=False, description='Use proxy')
        self._use_proxy.observe(self.on_use_proxy_change, names='value')
        self._inp_proxy_address = ipw.Text(description="Proxy server address:",
                                           layout=ipw.Layout(width="350px"),
                                           style=STYLE)
        self._use_diff_proxy_username = ipw.Checkbox(
            value=False,
            description='Use different username and password',
            layout={'width': 'initial'})
        self._use_diff_proxy_username.observe(
            self.on_use_diff_proxy_username_change, names='value')
        self._inp_proxy_username = ipw.Text(
            value='',
            description="Proxy server username:"******"350px"),
            style=STYLE)
        self._inp_proxy_password = ipw.Password(
            value='',
            description="Proxy server password:"******"138px"),
            style=STYLE)

        # Setup ssh button and output
        self._btn_setup_ssh = ipw.Button(description="Setup ssh")
        self._btn_setup_ssh.on_click(self.on_setup_ssh)
        self._setup_ssh_out = ipw.Output()

        # Check whether some settings were already provided
        predefine_settings(self, **kwargs)

        # Defining widgets positions
        computer_ssh_box = ipw.VBox([
            self._inp_computer_hostname, self._inp_username,
            self._inp_password, self._use_proxy
        ],
                                    layout=ipw.Layout(width="400px"))
        self._proxy_user_password_box = ipw.VBox(
            [self._inp_proxy_username, self._inp_proxy_password],
            layout={'visibility': 'hidden'})
        self._proxy_ssh_box = ipw.VBox([
            self._inp_proxy_address, self._use_diff_proxy_username,
            self._proxy_user_password_box
        ],
                                       layout={
                                           'visibility': 'hidden',
                                           'width': '400px'
                                       })

        children = [
            ipw.HBox([computer_image, computer_ssh_box, self._proxy_ssh_box]),
            self._btn_setup_ssh, self._setup_ssh_out
        ]
        super(SshComputerSetup, self).__init__(children, **kwargs)
Exemple #13
0
def main():
    '''The main function that runs the mastermind game.'''
    max_num_guesses = code_length = code = num_guesses_left = None
    is_game_ended = True
    colors = 'ROYGBP'
    color_code = {
        "R": "#F88,#F00,#800",
        "O": "#FD8,#F80,#840",
        "Y": "#FF8,#FF0,#AA0",
        "G": "#8F8,#0F0,#080",
        "B": "#88F,#00F,#008",
        "P": "#F8F,#F0F,#808",
        "b": "#888,#000,#000",
        "w": "#FFF,#EEE,#888"
    }

    # returns the HTML code for a colored peg.
    def getPeg(color, size=30):
        return '''<div style='display:inline-block;
                              background-image: radial-gradient(circle, {0}); 
                              width:{1}px; height:{1}px; border-radius:50%;'>
                  </div>'''.format(color_code[color], size)

    colors_display = widgets.HBox([widgets.Label(value='Color codes:')] + [
        widgets.HBox([widgets.Label(value=color),
                      widgets.HTML(getPeg(color))]) for color in colors
    ])

    max_num_guesses_input = widgets.IntSlider(min=5,
                                              max=15,
                                              value=10,
                                              description="# guesses:")
    code_length_input = widgets.IntSlider(min=2,
                                          max=10,
                                          value=4,
                                          description="Code length:")
    code_input = widgets.Password(description="Code:")
    start_new_game_button = widgets.Button(description="Start a new game")

    guess_input = widgets.Text(description="Guess:")
    submit_guess_button = widgets.Button(description="Submit guess")
    board = widgets.Output()
    message = widgets.Output()

    display(
        widgets.VBox([
            max_num_guesses_input, code_length_input, colors_display,
            widgets.HBox([code_input, start_new_game_button]),
            widgets.HBox([guess_input, submit_guess_button]), board, message
        ]))

    # A listener that starts a new game
    def start_new_game(button):
        nonlocal code, num_guesses_left, is_game_ended, max_num_guesses, code_length
        max_num_guesses = max_num_guesses_input.value
        code_length = code_length_input.value
        board.clear_output()
        message.clear_output()
        code = code_input.value or get_code(colors, code_length)
        with message:
            if not valid_code(colors, code_length, code):
                display(
                    HTML('''<p>The code {} is invalid.<br>
                        Leave the code box empty to randomly generated a code.
                        </p>'''.format(code)))
                is_game_ended = True
            else:
                num_guesses_left = max_num_guesses
                is_game_ended = num_guesses_left <= 0
                display(
                    HTML('<p>Game started! {} Guesses left.</p>'.format(
                        num_guesses_left)))

    # A listener that submits a guess
    def submit_guess(button):
        nonlocal num_guesses_left, is_game_ended
        guess = guess_input.value
        with message:
            message.clear_output()
            if is_game_ended:
                display(
                    HTML('''<p>Game has not started.<br> 
                        Please start a new game.</p>'''))
                return
            if not valid_code(colors, code_length, guess):
                display(HTML('<p>Invalid guess.</p>'))
                return
        feedback = get_feedback(code, guess)
        num_guesses_left -= 1
        with board:
            content = ""
            for k in guess:
                content += getPeg(k)
            content += '''<div style='display:inline-block; 
                             margin: 0px 5px 0px 30px; 
                             position:relative; top:5px;'>Feeback:</div>
                          <div style='display:inline-block; 
                             border: 1px solid; width:120px; height:30px;'>'''
            for k in feedback:
                content += getPeg(k, 28)
            content += "</div>"
            display(HTML(content))

        with message:
            message.clear_output()
            if feedback == 'b' * code_length:
                is_game_ended = True
                display(
                    HTML('<p>You won with {} guesses left!</p>'.format(
                        num_guesses_left)))
                return
            is_game_ended = num_guesses_left <= 0
            if is_game_ended:
                display(HTML('<p>Game over...</p>'))
                return
            display(HTML('<p>{} Guesses left.</p>'.format(num_guesses_left)))

    start_new_game_button.on_click(start_new_game)
    submit_guess_button.on_click(submit_guess)
Exemple #14
0
    def __init__(self):
        self.out = widgets.Output(layout={'border': '1px solid black'})
        self.iceflow = IceflowClient()
        self.last_orders = None
        self.current_projection = 'north'
        self.clear = True
        self.controls = []
        self.credentials = None
        self.start_date = datetime(1993, 1, 1)
        self.end_date = datetime.now()
        slider_dates = [(date.strftime(' %Y-%m-%d '), date) for date in
                        pd.date_range(datetime(1993, 1, 1),
                                      datetime.now(),
                                      freq='D')]
        slider_index = (0, len(slider_dates) - 1)

        self.username = widgets.Text(
            value='',
            description='User:'******'Your NASA EarthData username ',
            disabled=False
        )
        self.password = widgets.Password(
            value='',
            placeholder='Enter password',
            description='Password:'******'',
            description='Email:',
            placeholder='Your EarthData e-mail',
            disabled=False
        )
        self.credentials_button = widgets.Button(description='Set Credentials', )
        self.projection = widgets.Dropdown(
            options=['global', 'south', 'north'],
            description='Hemisphere:',
            disabled=False,
            value='north'
        )
        self.dataset = widgets.SelectMultiple(
            options=['ATM1B', 'GLAH06', 'ILVIS2'],
            value=['ATM1B'],
            rows=4,
            description='Datasets',
            disabled=False
        )
        self.itrf = widgets.Dropdown(
            options=[None, 'ITRF2000', 'ITRF2008', 'ITRF2014'],
            disabled=False,
            description='ITRF:',
            layout={'width': 'max-content',
                    'display': 'flex',
                    'description_width': 'initial'}
        )
        self.epoch = widgets.Text(
            value='',
            description='Epoch:',
            placeholder='i.e. 2008.1',
            disabled=False
        )
        self.is2 = widgets.Dropdown(
            options=['None', 'ATL03', 'ATL06', 'ATL07', 'ATL08'],
            description='ICESat 2:',
            disabled=False,
        )
        self.dates_range = widgets.SelectionRangeSlider(
            options=slider_dates,
            index=slider_index,
            continuous_update=False,
            description='Date Range',
            orientation='horizontal',
            layout={'width': '90%'})

        self.granule_count = widgets.Button(description="Get Raw Granule Count",
                                            display='flex',
                                            flex_flow='column',
                                            align_items='stretch', )
        self.granule_count.style.button_color = 'lightgreen'
        self.granule_count.layout.width = 'auto'
        self.print_parameters = widgets.Button(description="Print Current Parameters",
                                               display='flex',
                                               flex_flow='column',
                                               align_items='stretch', )
        self.print_parameters.style.button_color = 'lightgreen'
        self.print_parameters.layout.width = 'auto'

        self.post_order = widgets.Button(description="Place Data Order",
                                         display='flex',
                                         flex_flow='column',
                                         align_items='stretch', )
        self.post_order.style.button_color = 'lightblue'
        self.post_order.layout.width = 'auto'

        self.check_order_status = widgets.Button(description="Order status",
                                                 display='flex',
                                                 flex_flow='column',
                                                 align_items='stretch', )
        self.check_order_status.style.button_color = 'lightblue'
        self.check_order_status.layout.width = 'auto'

        self.download_button = widgets.Button(description="Download completed orders",
                                              display='flex',
                                              flex_flow='column',
                                              align_items='stretch', )
        self.download_button.style.button_color = 'lightblue'
        self.download_button.layout.width = 'auto'

        self.selection_buttons = widgets.HBox([self.granule_count,
                                               self.print_parameters,
                                               self.post_order,
                                               self.check_order_status,
                                               self.download_button])
        self.selection_controls = widgets.VBox([self.projection,
                                                self.dataset,
                                                self.itrf,
                                                self.epoch,
                                                self.is2,
                                                self.dates_range,
                                                self.selection_buttons])
        self.controls.append(self.selection_controls)
        self.layers_control = LayersControl(position='topright')
        # Map Components
        place_marker = Marker(icon=AwesomeIcon(name="check", marker_color='green', icon_color='darkgreen'))
        self.search_control = SearchControl(
            position="topleft",
            url='https://nominatim.openstreetmap.org/search?format=json&q={s}',
            zoom=5,
            marker=place_marker
        )
        self.dc = DrawControl(
            circlemarker={},
            polyline={},
            rectangle={
                "shapeOptions": {
                    "fillColor": "#cc00cc",
                    "color": "#cc00cc",
                    "fillOpacity": 0.5
                }
            })
        self.file_upload = widgets.FileUpload(
            accept='.json,.geojson,.shp',
            multiple=False  # True to accept multiple files upload else False
        )

        # Now we are going to link the controls to the relevant events
        self.dates_range.observe(self.dates_changed, 'value')
        self.projection.observe(self.hemisphere_change)
        self.credentials_button.on_click(self.set_credentials)
        self.granule_count.on_click(self.query_cmr)
        self.print_parameters.on_click(self.get_parameters)
        self.post_order.on_click(self.place_data_orders)
        self.check_order_status.on_click(self.order_statuses)
        self.download_button.on_click(self.download_orders)
Exemple #15
0
from netCDF4 import Dataset  # https://unidata.github.io/netcdf4-python/netCDF4/index.html
from netCDF4 import MFDataset
from netCDF4 import stringtochar
from datetime import datetime
import SourceCode.DaedalusGlobals as DaedalusGlobals
import hashlib
import ipywidgets as widgets
import traceback
import numpy as np
import csv
import os


AuthPassword = "" # global - Necessary to remember password from the widgets.Password() widget.
PasswordBox = widgets.Password( ) # global
SpecificFilename = widgets.Text( )  # global

# Constructs the GUI which allows the user manage the NetCDF files.
def ConstructDataManagementPanel():
    # the main panel
    DataManagementPanel = widgets.VBox() 
    # for separating gui elements
    SeparatorLabel = widgets.HTML(value="<hr>")
    # for explaining the usage of this panel
    UsageLabel = widgets.HTML(value="<p style='line-height:1.4'><b>Usage:</b><br>Here you can select one or several orbit files which will be tranformed from csv to NetCDF files (.nc). If the NetCDF file already exists then it is overwritten. To start the process you have to type the correct password and press the 1st blue button. The 2nd blue button alters the state of the NetCDF file, making Calculated='no' so that all values will be recalculated during a simulation run.</p>")
    # for selecting orbits
    AllOrbitsLabel = widgets.HTML(value="<b>Select one or several orbits:</b>")
    AllOrbitsLabel.layout.margin = '20px 0px 0px 0px'
    AllOrbitFilenames = list()
    for f in os.listdir( DaedalusGlobals.CSV_Files_Path ):
    def __init__(self,
                 hostname='bigred3.uits.iu.edu',
                 username='******',
                 server_password=None,
                 ssh_private_key=None,
                 port=22):

        self.ssh = None

        self.hostname = widgets.Text(
            value=hostname,
            description='Hostname: ',
            style=style,
        )

        self.username = widgets.Text(
            value=username,
            description='Username: '******'Password: '******'********',
            style=style,
        )

        self.ssh_private_key = widgets.Dropdown(
            options=['None'],
            value='None',
            description='ssh key: ',
            style=style,
        )

        self.port = widgets.BoundedIntText(
            value=port,
            description='Port: ',
            style=style,
        )

        self.connect_btn = widgets.Button(description='Connect')
        self.connect_btn.on_click(self.onclick_coonect_btn)

        self.attribute_widget = widgets.HBox([
            self.hostname, self.username, self.server_password,
            self.ssh_private_key, self.port, self.connect_btn
        ])

        self.command_line = widgets.Text(value='',
                                         description='Enter Command: ',
                                         style=style,
                                         layout=Layout(flex='0 1 auto',
                                                       width='100%'))

        self.execute_btn = widgets.Button(description='Execute')
        self.execute_btn.on_click(self.onclick_execute_btn)

        self.clear_btn = widgets.Button(description='Clear')
        self.clear_btn.on_click(self.onclick_clear_btn)

        self.command_exe_widget = widgets.HBox(
            [self.command_line, self.execute_btn, self.clear_btn])

        self.ssh_log = widgets.Textarea(value='',
                                        placeholder='',
                                        disabled=True,
                                        layout=Layout(flex='0 1 auto',
                                                      height='100px',
                                                      min_height='100px',
                                                      width='100%'))

        group_area_layout = Layout(display='flex',
                                   border='solid 1px',
                                   align_items='stretch',
                                   padding='5px',
                                   width='100%')

        self.textlog_widget = widgets.HBox([self.ssh_log])

        self.wigetbox = widgets.VBox([
            self.attribute_widget, self.command_exe_widget, self.textlog_widget
        ],
                                     layout=group_area_layout)

        self.populate_ssh_key_drop()
Exemple #17
0
#Log-in page

#importing the necessary packages
import ipywidgets as widgets  #to get the widgets
from IPython.display import display  #to display the created widgets

#to direct our widgets
e_add = widgets.Text(
    description="E-mail")  #to allow the user to type the e-mail
e_pass = widgets.Password(
    description="Password"
)  #to allow the user to type the password(it is in dots)
c = widgets.Button(description="Log in",
                   button_style="info")  #to prompt the user to log-in
val = widgets.Text(
    description=e_pass.value, disabled=True
)  #to show the password entered by the user(disabling it so that he cannot make changes to it)
mylink = widgets.jslink(
    (e_pass, 'value'),
    (val, 'value'))  #to link the password entered with 'val'
display(e_add, e_pass, val, c)  #to display all the values


#to define a function which checks for the entered values
def on_button_clicked(b):  #defining a function to check for the credentials
    if (a.value == ''):  #in case the e-mail box is left empty
        print("There must be some address. It cannot be empty"
              )  #giving a suitable message
        c.button_style = 'danger'  #changing the button colour to red(indicating wrong)
    else:  #else if the value isn't empty
        if (val.value == "pass@123" and e_add.value == "*****@*****.**"
Exemple #18
0
#account_selector = widgets.Dropdown(
#    options = w3.eth.accounts,
#    value = w3.eth.accounts[1],
#    description = 'Account: '
#)

# Must input account address and private key manually on live testnet
account_selector = widgets.Text(
    value = '',
    description = 'Account: ',
    placeholder = 'Enter account address'
)

key_input = widgets.Password(
    value = '',
    description = 'Private Key: ',
    placeholder = 'Enter private key'
)


# Input token amount for purchase
coin_text = widgets.IntText(
    value = 0,
    description = f'{coin_name}s :',
    style = {'description_width': 'initial'},
    disabled = False
)

# Purchase button
coin_button = widgets.Button(
    description = 'Buy!',
Exemple #19
0
    config = json.load(open(config_file))
    config_user_file = Path('config_user.json')
    if config_user_file.exists():
        config_user = json.load(open(config_user_file))
        if "Rafal.urls" in config_user:
            config["Rafal.urls"].update(config_user["Rafal.urls"])

    user = config['Rafal.user']
    urls = config['Rafal.urls']

    # UI connect
    myPwd = config.get('Rafal.password', environ.get('jpwd', None))

    pwd_exists = bool(myPwd)
    wPwd = widgets.Password(
        value='',
        placeholder='from config' if pwd_exists else 'Enter password',
        disabled=pwd_exists)

    # proxy parameters
    proxies = (config['proxies'] if config['proxies']['http']
               or config['proxies']['https'] else None)

    wServer = widgets.Dropdown(
        options=urls.items(),
        value=urls['review_master'],
        disabled=False,
    )
    button = widgets.Button(
        description='Connect',
        button_style='info',
    )
Exemple #20
0
def widget_emso_qc(wf,
                   depth_range: List[float] = [-10, 10000],
                   range_test: List[float] = [-1000, 1000],
                   spike_window: int = 100,
                   spike_threshold: float = 3.5,
                   spike_influence: float = 0.5,
                   user: str = '',
                   password: str = '',
                   token: str = ''):
    """
    It makes a Jupyter Notebook Widget used to download EMSO data and make data
    quality control tests.

    Parameters
    ----------
        wf: WaterFrame
        depth_range: List[float]
            Range of depth
        user: str
            User for the EMSO ERIC API
        password: str
            Password for the EMSO ERIC API
        token: str
            Token for the EMSO ERIC API
        parameter: str
            Parameter
        range_test: List[float]
            Limits for the range test [min value, max value]
        spike_window: int
            Window for the spike test
        spike_threshold: float
            Float for the spike test
        spike_influence: float
            Influence of the bad data on the spike test

    Returns
    -------
        main_box: ipwidgets.VBox
            Jupyter notebook widget 
    """
    pyo.init_notebook_mode()

    # Layout config
    label_width = '7rem'
    sublabel_width = '5rem'
    checkbox_width = '8rem'

    def show_result(wf, parameter_in, chart_title=''):
        # Change name of flags
        wf2 = wf.copy()
        qc_labels = {0: 'No QC', 1: 'Good data', 4: 'Bad data'}
        wf2.data[f'{parameter_in}_QC'].replace(qc_labels, inplace=True)

        fig = wf2.iplot_line(
            parameter_in,
            # color=f'{parameter_in}_QC',
            marginal_y=None,
            line_shape='linear',
            rangeslider_visible=False,
            line_dash_sequence=['dot', 'dot'],
            title=chart_title,
        )
        # line_group='DEPTH')
        fig.show()

    # Sing in
    authentification_title = widgets.HTML('<b>Authentification</b>')
    user_label = widgets.Label('User:'******'Password:'******'or', layout=widgets.Layout(width=label_width))
    token_label = widgets.Label('Token:',
                                layout=widgets.Layout(width=label_width))
    input_token = widgets.Text(value=token)

    # map
    emso = mooda.EMSO(user=input_user.value,
                      password=input_password.value,
                      token=input_token.value)
    map_dict = emso.get_fig_map()
    pio.show(map_dict)

    # Platform code
    data_title = widgets.HTML('<b>Downloading data</b>')
    platform_label = widgets.Label('Platform code:',
                                   layout=widgets.Layout(width=label_width))
    platform_codes = emso.get_info_platform_code()
    input_platform = widgets.Dropdown(options=platform_codes,
                                      value=platform_codes[0],
                                      disabled=False)

    # Get metadata
    metadata_list = emso.get_metadata(platform_codes=[platform_codes[0]])
    try:
        metadata = metadata_list[0]
        parameter_list = metadata.get('parameters')
        if parameter_list is None:
            parameter_list = emso.get_info_parameter()
        depth_min = metadata.get('geospatial_vertical_min', depth_range[0])
        depth_max = metadata.get('geospatial_vertical_max', depth_range[1])
        start_date = metadata.get('time_coverage_start')
        if start_date:
            start_date = start_date.split('T')[0]
        end_date = metadata.get('time_coverage_end')
        if end_date:
            end_date = end_date.split('T')[0]
    except:
        parameter_list = emso.get_info_parameter()
        depth_min = depth_range[0]
        depth_max = depth_range[1]
        start_date = None
        end_date = None

    # Parameters
    parameters_label = widgets.Label('Parameters:',
                                     layout=widgets.Layout(width=label_width))
    input_parameters = widgets.SelectMultiple(options=parameter_list,
                                              rows=10,
                                              disabled=False,
                                              value=[parameter_list[0]])

    # Size
    size_label = widgets.Label('Size:',
                               layout=widgets.Layout(width=label_width))
    input_size = widgets.BoundedIntText(value=10, min=1, max=100000, step=1)

    # Depth
    depth_label = widgets.Label('Depth:',
                                layout=widgets.Layout(width=label_width))
    input_depth = widgets.FloatRangeSlider(value=[depth_min, depth_max],
                                           min=depth_min,
                                           max=depth_max,
                                           step=0.1,
                                           disabled=False,
                                           continuous_update=False,
                                           orientation='horizontal',
                                           readout=True,
                                           readout_format='.1f')

    # Time
    start_date_label = widgets.Label('Start date:',
                                     layout=widgets.Layout(width=label_width))
    input_start_date = widgets.DatePicker(
        disabled=False,
        min_date=date(int(start_date.split('-')[0]),
                      int(start_date.split('-')[1]),
                      int(start_date.split('-')[2])),
        max_date=date(int(end_date.split('-')[0]), int(end_date.split('-')[1]),
                      int(end_date.split('-')[2])),
        value=date(int(start_date.split('-')[0]),
                   int(start_date.split('-')[1]),
                   int(start_date.split('-')[2])))

    end_date_label = widgets.Label('End date:',
                                   layout=widgets.Layout(width=label_width))
    input_end_date = widgets.DatePicker(
        disabled=False,
        min_date=date(int(start_date.split('-')[0]),
                      int(start_date.split('-')[1]),
                      int(start_date.split('-')[2])),
        max_date=date(int(end_date.split('-')[0]), int(end_date.split('-')[1]),
                      int(end_date.split('-')[2])),
        value=date(int(end_date.split('-')[0]), int(end_date.split('-')[1]),
                   int(end_date.split('-')[2])))

    qc_label = widgets.HTML('<b>Data QC Tests - Select the test to run</b>')

    # Layout config
    checkbox_width = '8rem'
    # Reset flags
    # reset_label = widgets.Label('Reset flags:')
    reset_checkbox = widgets.Checkbox(
        description='Reset flags',
        style={'description_width': '0'},
        layout=widgets.Layout(width=checkbox_width))

    # Flat test
    flat_checkbox = widgets.Checkbox(
        description='Flat test',
        style={'description_width': '0'},
        layout=widgets.Layout(width=checkbox_width))
    window_label = widgets.Label('Window:',
                                 layout=widgets.Layout(width=sublabel_width))
    window_flat = widgets.IntText(value=2, disabled=False, color='black')

    # Range test
    # range_label = widgets.Label('Range test:')
    range_checkbox = widgets.Checkbox(
        description='Range test',
        style={'description_width': '0'},
        layout=widgets.Layout(width=checkbox_width))
    limit_label = widgets.Label('Limits:',
                                layout=widgets.Layout(width=sublabel_width))
    limits = widgets.FloatRangeSlider(value=[range_test[0], range_test[1]],
                                      min=range_test[0],
                                      max=range_test[1],
                                      step=0.1,
                                      disabled=False,
                                      continuous_update=False,
                                      orientation='horizontal',
                                      readout=True,
                                      readout_format='.1f')

    # Spike test
    # spike_label = widgets.Label('Spike test:')
    spike_checkbox = widgets.Checkbox(
        description='Spike test',
        style={'description_width': '0'},
        layout=widgets.Layout(width=checkbox_width))
    window_spike = widgets.IntText(value=spike_window,
                                   disabled=False,
                                   color='black')
    threshold_label = widgets.Label(
        'Threshold:', layout=widgets.Layout(width=sublabel_width))
    threshold = widgets.FloatText(value=spike_threshold,
                                  disabled=False,
                                  color='black')
    influence_label = widgets.Label(
        'Influence:', layout=widgets.Layout(width=sublabel_width))
    influence = widgets.FloatSlider(value=spike_influence,
                                    min=0,
                                    max=1,
                                    step=0.1,
                                    disabled=False,
                                    continuous_update=False,
                                    orientation='horizontal',
                                    readout=True,
                                    readout_format='.1f',
                                    slider_color='white')

    # Replace
    # replace_label = widgets.Label('Replace QC:')
    replace_checkbox = widgets.Checkbox(description='Replace flags',
                                        style={'description_width': '0'})

    def update_components(_):
        # Update all components
        emso = mooda.EMSO(user=input_user.value,
                          password=input_password.value,
                          token=input_token.value)
        # Get metadata
        metadata_list = emso.get_metadata(
            platform_codes=[input_platform.value])

        try:
            metadata = metadata_list[0]
            parameter_list = metadata.get('parameters')
            if parameter_list is None:
                parameter_list = emso.get_info_parameter()
            depth_min = metadata.get('geospatial_vertical_min', depth_range[0])
            depth_max = metadata.get('geospatial_vertical_max', depth_range[1])
            start_date = metadata.get('time_coverage_start')
            if start_date:
                start_date = start_date.split('T')[0]
            end_date = metadata.get('time_coverage_end')
            if end_date:
                end_date = end_date.split('T')[0]
        except:
            parameter_list = emso.get_info_parameter()
            depth_min = depth_range[0]
            depth_max = depth_range[1]
            start_date = None
            end_date = None

        # Parameters
        input_parameters.options = parameter_list

        # Depth
        input_depth.min = depth_min
        input_depth.max = depth_max
        input_depth.value = [depth_min, depth_max]

        # Time
        input_start_date.min_date = date(int(start_date.split('-')[0]),
                                         int(start_date.split('-')[1]),
                                         int(start_date.split('-')[2]))
        input_start_date.max_date = date(int(end_date.split('-')[0]),
                                         int(end_date.split('-')[1]),
                                         int(end_date.split('-')[2]))
        input_start_date.value = date(int(start_date.split('-')[0]),
                                      int(start_date.split('-')[1]),
                                      int(start_date.split('-')[2]))
        input_end_date.min_date = date(int(start_date.split('-')[0]),
                                       int(start_date.split('-')[1]),
                                       int(start_date.split('-')[2]))
        input_end_date.max_date = date(int(end_date.split('-')[0]),
                                       int(end_date.split('-')[1]),
                                       int(end_date.split('-')[2]))
        input_end_date.value = date(int(end_date.split('-')[0]),
                                    int(end_date.split('-')[1]),
                                    int(end_date.split('-')[2]))

    input_platform.observe(update_components, names='value')

    # Button
    button = widgets.Button(description='Get data')
    out = widgets.Output()
    out2 = widgets.Output()

    def on_button_clicked(_):
        # "linking function with output"
        with out:
            # what happens when we press the button
            clear_output()

            parameters = []
            for input_parameter in input_parameters.value:
                parameters.append(input_parameter.split('-')[0].strip())

            if input_start_date.value is None:
                start_time = ''
            else:
                start_time = str(input_start_date.value) + ' 00:00:00'

            if input_end_date.value is None:
                end_time = ''
            else:
                end_time = str(input_end_date.value) + ' 00:00:00'

            if input_token.value is None:
                token = ''
            else:
                token = input_token.value

            print('Downloading data, please wait')

            wf2 = mooda.from_emso(platform_code=input_platform.value,
                                  parameters=parameters,
                                  start_time=start_time,
                                  end_time=end_time,
                                  depth_min=input_depth.value[0],
                                  depth_max=input_depth.value[1],
                                  user=input_user.value,
                                  password=input_password.value,
                                  size=input_size.value,
                                  token=token)

            wf.data = wf2.data.copy()
            wf.metadata = wf2.metadata.copy()
            wf.vocabulary = wf2.vocabulary.copy()

            clear_output()
            display(wf)

        with out2:
            # what happens when we press the button
            clear_output()
            print('Making tests')

            for parameter_one in wf.parameters:

                if reset_checkbox.value:
                    wf.qc_replace(parameters=[parameter_one],
                                  to_replace=1,
                                  value=0)
                    wf.qc_replace(parameters=[parameter_one],
                                  to_replace=4,
                                  value=0)
                if flat_checkbox.value:
                    wf.qc_flat_test(window=window_flat.value,
                                    parameters=[parameter_one])
                if range_checkbox.value:
                    wf.qc_range_test(limits=limits.value,
                                     parameters=[parameter_one])
                if spike_checkbox.value:
                    wf.qc_spike_test(window=window_spike.value,
                                     influence=influence.value,
                                     threshold=threshold.value,
                                     parameters=[parameter_one])
                if replace_checkbox.value:
                    start = 0
                    if spike_checkbox.value:
                        start = window_spike.value
                    wf.qc_replace(parameters=[parameter_one], start=start)

                show_result(wf, parameter_one, f'Final result')

    # linking button and function together using a button's method
    button.on_click(on_button_clicked)
    user_box = widgets.HBox([user_label, input_user])
    password_box = widgets.HBox([password_label, input_password])
    token_box = widgets.HBox([token_label, input_token])
    platform_box = widgets.HBox([platform_label, input_platform])
    parameters_box = widgets.HBox([parameters_label, input_parameters])
    size_box = widgets.HBox([size_label, input_size])
    depth_box = widgets.HBox([depth_label, input_depth])
    start_date_box = widgets.HBox([start_date_label, input_start_date])
    end_date_box = widgets.HBox([end_date_label, input_end_date])
    reset_box = widgets.HBox([reset_checkbox])
    flat_box = widgets.HBox([flat_checkbox, window_label, window_flat])
    range_box = widgets.HBox([range_checkbox, limit_label, limits])
    spike_window_column = widgets.HBox([window_label, window_spike])
    spike_threshold_column = widgets.HBox([threshold_label, threshold])
    spike_influence_column = widgets.HBox([influence_label, influence])
    spike_column = widgets.VBox(
        [spike_window_column, spike_threshold_column, spike_influence_column])
    spike_box = widgets.HBox([spike_checkbox, spike_column])
    replace_box = widgets.HBox([replace_checkbox])

    main_box = widgets.VBox([
        authentification_title, user_box, password_box, or_label, token_box,
        data_title, platform_box, parameters_box, size_box, depth_box,
        start_date_box, end_date_box, qc_label, reset_box, flat_box, range_box,
        spike_box, replace_box, button, out, out2
    ])

    return main_box
Exemple #21
0
run_flag_widget = widgets.Dropdown(
    options=['Sample Data', 'Downloaded Data'],
    description='Analyses Run Mode',
    disabled=False,
)
indate = widgets.DatePicker(description='Start Date', disabled=False)

outdate = widgets.DatePicker(description='End Date', disabled=False)

username = widgets.Text(value='',
                        placeholder='Meteoam username',
                        description='Username:'******'Meteoam Password',
                            description='Password:'******'Downloaded Data',
                            selected_date=None):
    if product == 'h10' or product == 'h34':
        ext = 'H5'
Exemple #22
0
    tasks = pickle.load(f)

prohibited_words = ['order by', 'desc', 'asc', 'group by']

###############################################################################
# Now the single elements like textboxes, buttons are initialized.
###############################################################################

tab_nest = widgets.Tab(layout={
    'border': '2px solid tomato',
    'width': '100%',
    'height': '100%'
})

user_name = widgets.Text(description='Username:'******'width': '30%'})
user_pw = widgets.Password(description='Password:'******'width': '30%'})

tab_login = widgets.VBox(children=[user_name, user_pw],
                         layout={'height': '100%'})

logo = widgets.Image(value=image, format='png', width='90%', height=350)

logo_box = widgets.VBox(children=[logo])

welcome_text = widgets.HTML(
    value='''Hi, melde dich einfach mit deiner Ora- Kennung
    + Passwort an und es kann los gehen!''',
    width='100%',
    height=400)
welcome_box = widgets.VBox(children=[welcome_text])
Exemple #23
0
    def __init__(self, textbox_upload=True, **kwargs):
        """Initializes ASKLBWidget by creating all widget components."""

        # TODO hack since FileUpload widgets do not work on any notebook hosting services (Azure, Colab)
        self.textbox_upload = textbox_upload

        # Set up authentication to the database
        client = pymongo.MongoClient(MONGO_URI)
        self.db = client.asklb_test
        self.username = None

        self.queries = 0
        # We make the assumption that the first column are the labels.
        # TODO can add "checksum" for the y's for the data to be in the same order
        self.data = []
        self.filenames = []
        self.models = []
        # We make the assumption that the data are uploaded in the same order.
        self.train_idxs = []
        self.test_idxs = []

        # Widgets for user authentication
        self.user_text_widget = widgets.Text(placeholder='Username',
                                             description='Username:'******'Password',
                                                     description='Password:'******'auto'),
            button_style='primary',
            disabled=False)
        self.sign_in_widget.on_click(self.on_sign_in_widget_click)

        self.register_widget = widgets.Button(
            description="Register",
            layout=widgets.Layout(width='auto'),
            button_style='primary',
            disabled=False)
        self.register_widget.on_click(self.on_register_widget_click)

        self.auth_label_widget = widgets.Label(
            value="Please sign in or register")

        self.is_signed_in = False  #Boolean for being signed in

        # Widgets for automl runtime
        self.runtime_widget = widgets.IntSlider(value=1, min=1, max=MAX_TIME)

        self.budget_widget = widgets.IntSlider(value=int(MAX_BUDGET / 2),
                                               min=1,
                                               max=MAX_BUDGET)

        if self.textbox_upload:
            self.upload_text = widgets.Text(placeholder="CSV filename here")
            self.test_size_text = widgets.Text(
                placeholder="Input test set size here")
            self.upload_button = widgets.Button(
                description="Upload Data",
                layout=widgets.Layout(width='auto'),
                button_style='primary',
                disabled=False)
            self.upload_button.on_click(self.on_upload_button_clicked)

            self.upload_widget = widgets.HBox(
                [self.upload_text, self.test_size_text, self.upload_button])

        else:
            self.upload_widget = widgets.FileUpload(
                accept='.csv',  # Accepted file extension
                multiple=False  # Only accept a single file
            )
            self.upload_widget.observe(self.on_data_upload_begin,
                                       names="_counter")
            self.upload_widget.observe(self.on_data_upload_completion,
                                       names="value")

        self.progress_widget = widgets.IntProgress(value=0,
                                                   min=0,
                                                   description="Progress")

        self.fit_button_widget = widgets.Button(
            description="Fit Data to AutoML Model",
            layout=widgets.Layout(width='auto'),
            button_style='primary',
            disabled=True)  # init with fit button disabled
        self.fit_button_widget.on_click(self.on_fit_button_clicked)

        self.event_output_widget = widgets.Output(
            layout={'border': '1px solid black'})
        self.model_output_widget = widgets.Output()
        self.metrics_output_widget = widgets.Output()

        self.assemble_widget(**kwargs)
    def __init__(self, **kwargs):
        computer_image = ipw.HTML(
            '<img width="200px" src="../miscellaneous/images/computer.png">'
        )

        # Username.
        inp_username = ipw.Text(
            description="SSH username:"******"350px"), style=STYLE
        )
        link((inp_username, "value"), (self, "username"))

        # Port.
        inp_port = ipw.IntText(
            description="SSH port:",
            value=22,
            layout=ipw.Layout(width="350px"),
            style=STYLE,
        )
        link((inp_port, "value"), (self, "port"))

        # Hostname.
        inp_computer_hostname = ipw.Text(
            description="Computer hostname:",
            layout=ipw.Layout(width="350px"),
            style=STYLE,
        )
        link((inp_computer_hostname, "value"), (self, "hostname"))

        # Upload private key directly.
        self._inp_password = ipw.Password(
            description="SSH password:"******"150px"),
            style=STYLE,
            disabled=False,
        )
        self._inp_private_key = ipw.FileUpload(
            accept="",
            layout=ipw.Layout(width="350px"),
            style=STYLE,
            description="Private key",
            multiple=False,
            disabled=True,
        )
        self._verification_mode = ipw.Dropdown(
            options=["password", "private_key"],
            layout=ipw.Layout(width="350px"),
            style=STYLE,
            value="password",
            description="verification mode:",
            disabled=False,
        )
        self._verification_mode.observe(
            self.on_use_verification_mode_change, names="value"
        )

        # Proxy ssh settings.
        inp_use_proxy = ipw.Checkbox(value=False, description="Use proxy")
        inp_use_proxy.observe(self.on_use_proxy_change, names="value")
        link((inp_use_proxy, "value"), (self, "use_proxy"))

        inp_proxy_hostname = ipw.Text(
            description="Proxy server address:",
            layout=ipw.Layout(width="350px"),
            style=STYLE,
        )
        link((inp_proxy_hostname, "value"), (self, "proxy_hostname"))

        self._use_diff_proxy_username = ipw.Checkbox(
            value=False,
            description="Use different username and password",
            layout={"width": "initial"},
        )
        self._use_diff_proxy_username.observe(
            self.on_use_diff_proxy_username_change, names="value"
        )
        inp_proxy_username = ipw.Text(
            value="",
            description="Proxy server username:"******"350px"),
            style=STYLE,
        )
        link((inp_proxy_username, "value"), (self, "proxy_username"))

        self._inp_proxy_password = ipw.Password(
            value="",
            description="Proxy server password:"******"138px"),
            style=STYLE,
        )

        # Setup ssh button and output.
        btn_setup_ssh = ipw.Button(description="Setup ssh")
        btn_setup_ssh.on_click(self.on_setup_ssh)
        self._setup_ssh_out = ipw.Output()

        # Defining widgets positions.
        computer_ssh_box = ipw.VBox(
            [
                inp_computer_hostname,
                inp_port,
                inp_username,
                self._verification_mode,
                self._inp_password,
                self._inp_private_key,
                inp_use_proxy,
            ],
            layout=ipw.Layout(width="400px"),
        )
        self._proxy_user_password_box = ipw.VBox(
            [inp_proxy_username, self._inp_proxy_password],
            layout={"visibility": "hidden"},
        )
        self._proxy_ssh_box = ipw.VBox(
            [
                inp_proxy_hostname,
                self._use_diff_proxy_username,
                self._proxy_user_password_box,
            ],
            layout={"visibility": "hidden", "width": "400px"},
        )

        children = [
            ipw.HBox([computer_image, computer_ssh_box, self._proxy_ssh_box]),
            btn_setup_ssh,
            self._setup_ssh_out,
        ]
        super().__init__(children, **kwargs)
    def manage_log(self, line):
        line = line or ""
        if line or not __CAN_USE_WIDGET__:
            params = line.split(" ")
            if len(params) == 5:
                print(u"连接中...")
                endpoint, key_id, key_val, project, logstore = params
                result, detail = self.verify_sls_connection(
                    endpoint, key_id, key_val, project, logstore)

                if result:
                    clear_output()
                    print(u"连接成功.")
                    _save_config(endpoint, key_id, key_val, project, logstore)
                    self.client(reset=True)
                else:
                    print(detail)
            else:
                print(
                    u"参数错误,请使用GUI配置(无参)或遵循格式:%manage_log <endpoint> <ak_id> <ak_key> <project> <logstore>"
                )

            return

        import ipywidgets as widgets
        w_1 = widgets.ToggleButtons(options=[u'基本配置', u"高级配置"])

        w_endpoint = widgets.Text(description=u'服务入口', value=g_default_region)
        w_key_id = widgets.Password(description=u'秘钥ID', value=g_default_ak_id)
        w_key_val = widgets.Password(description=u'秘钥Key',
                                     value=g_default_ak_key)
        w_project = widgets.Text(description=u'默认项目', value=g_default_project)
        w_logstore = widgets.Text(description=u'默认日志库',
                                  value=g_default_logstore)
        w_confirm = widgets.Button(
            description=u'修改' if g_default_region else u'确认',
            button_style='info',
            icon='confirm')
        w_result = widgets.Label(value='')
        hide_layout = widgets.Layout(height="0px")
        show_layout = widgets.Layout(height='auto')
        progress = widgets.FloatProgress(description="",
                                         value=0.0,
                                         min=0.0,
                                         max=1.0,
                                         layout=hide_layout)

        def work(progress):
            global result
            total = 100
            for i in range(total):
                time.sleep(0.2)
                if result is None:
                    progress.value = float(i + 1) / total
                else:
                    progress.value = 100
                    progress.description = u"完成" if result else u"失败"
                    break

        def on_button_clicked(b):
            global result, detail
            progress.layout = show_layout
            progress.description = u"连接中..."
            progress.value = 0
            w_result.value = ""

            result = None
            detail = ""
            thread = threading.Thread(target=work, args=(progress, ))
            thread.start()

            result, detail = self.verify_sls_connection(
                w_endpoint.value, w_key_id.value, w_key_val.value,
                w_project.value, w_logstore.value)

            if result:
                w_result.value = u"连接成功."
                _save_config(w_endpoint.value, w_key_id.value, w_key_val.value,
                             w_project.value, w_logstore.value)
                self.client(reset=True)
            else:
                w_result.value = str(detail)

        w_confirm.on_click(on_button_clicked)

        p = widgets.VBox(children=[
            w_1, w_endpoint, w_key_id, w_key_val, w_project, w_logstore,
            w_confirm, progress, w_result
        ])

        return p
Exemple #26
0
            def ssh_copy_id():
                timeout = 30
                print(f"Sending public key to {self.hostname.value}... ",
                      end="")
                str_ssh = f"ssh-copy-id {self.hostname.value}"
                child = pexpect.spawn(str_ssh)

                expectations = [
                    "assword:",  # 0
                    "Now try logging into",  # 1
                    "All keys were skipped because they already exist on the remote system",  # 2
                    "Are you sure you want to continue connecting (yes/no)?",  # 3
                    "ERROR: No identities found",  # 4
                    "Could not resolve hostname",  # 5
                    "Connection refused",  # 6
                    pexpect.EOF,
                ]

                previous_message, message = None, None
                while True:
                    try:
                        index = child.expect(
                            expectations,
                            timeout=timeout,
                        )

                    except pexpect.TIMEOUT:
                        print(f"Exceeded {timeout} s timeout")
                        return False

                    if index == 0:
                        message = child.before.splitlines()[-1] + child.after
                        if previous_message != message:
                            previous_message = message
                            pwd = ipw.Password(layout={"width": "100px"})
                            display(
                                ipw.HBox([
                                    ipw.HTML(message),
                                    pwd,
                                    self._continue_button,
                                ]))
                            yield
                        child.sendline(pwd.value)

                    elif index == 1:
                        print("Success.")
                        if on_success:
                            on_success()
                        break

                    elif index == 2:
                        print(
                            "Keys are already present on the remote machine.")
                        if on_success:
                            on_success()
                        break

                    elif index == 3:  # Adding a new host.
                        child.sendline("yes")

                    elif index == 4:
                        print(
                            "Failed\nLooks like the key pair is not present in ~/.ssh folder."
                        )
                        break

                    elif index == 5:
                        print("Failed\nUnknown hostname.")
                        break

                    elif index == 6:
                        print("Failed\nConnection refused.")
                        break

                    else:
                        print("Failed\nUnknown problem.")
                        print(child.before, child.after)
                        break
                child.close()
                yield