예제 #1
0
파일: nmtools.py 프로젝트: usnair/georad
 def getCP(self):
     self.setLabel()
     self.usrTW = Text(value='',
                       placeholder='',
                       description='Username:'******'values')
     self.pwdPW = Password(value='',
                           placeholder='',
                           description='Password:'******'value')
     self.st = widgets.DatePicker(description='Start Date',
                                  value=datetime(2020, 4, 20),
                                  disabled=False,
                                  layout=Layout(width='220px'))
     self.et = widgets.DatePicker(description='End Date',
                                  value=datetime(2020, 4, 30),
                                  disabled=False,
                                  layout=Layout(width='220px'))
     self.st.observe(self.startDate)
     self.et.observe(self.endDate)
     self.latitude = Text(value='24.42',
                          description='Latitude:',
                          disabled=False,
                          layout=Layout(width='220px'))
     self.longitude = Text(value='54.43',
                           description='Longitude:',
                           disabled=False,
                           layout=Layout(width='220px'))
     self.latitude.observe(self.set_lat_val, names='value')
     self.longitude.observe(self.set_lon_val, names='value')
     self.plotms = Button(description='Plot in m/s',
                          disabled=False,
                          layout={
                              'width': 'auto',
                              'border': '3px outset'
                          })
     self.plotms.on_click(self.plotWindRose_ms)
     self.plotkt = Button(description='Plot in kt',
                          disabled=False,
                          layout={
                              'width': 'auto',
                              'border': '3px outset'
                          })
     self.plotkt.on_click(self.plotWindRose_kt)
     self.inpUSR.children += (HBox([
         VBox([self.st, self.latitude, self.longitude]),
         VBox([self.et, self.plotms, self.plotkt])
     ],
                                   layout={'overflow': 'visible'}), )
     with self.out_cp:
         self.out_cp.clear_output()
         display(self.getCP)
     return self.cp
예제 #2
0
    def __init__(self,
                 url=None,
                 token=None,
                 regexpr=None,
                 fields=None,
                 callbacks=None):
        """Instantiate a UI controller.
        """
        super().__init__()

        self.fields = fields
        self.callbacks = callbacks or []

        # toolbar
        self.ht = HTML("<b>Host/Owner:</b>")
        self.tx_desc = "Repo owner URL, eg. https://github.com/python"
        self.tx = Text(
            url or "",
            placeholder=self.tx_desc,
            description_tooltip="Repo owner URL, press enter to scan!",
            layout=Layout(width="200px"))
        self.tx.on_submit(self.start_scan)
        tok_desc = "GitHub API Access Token"
        self.tok = Password(token,
                            placeholder=tok_desc,
                            description_tooltip=tok_desc,
                            layout=Layout(width="175px"))
        self.tok.on_submit(self.start_scan)
        self.btn = Button(description="Scan",
                          button_style="info",
                          layout=Layout(width="100px"))
        self.btn.on_click(self.start_scan)
        rx_desc = "Regex to match repo names"
        self.rx = Text(regexpr,
                       placeholder=rx_desc,
                       description_tooltip=rx_desc,
                       layout=Layout(width="60px"))
        self.rx.on_submit(self.start_scan)
        self.toolbar = HBox([self.ht, self.tx, self.tok, self.rx, self.btn])

        # content area
        self.sx = HTML(layout=Layout(width="100pc"))
        self.tabout = VBox()
        self.pbout = Output()
        self.out = Output()
        self.cont = VBox([self.sx, self.tabout, self.pbout, self.out])

        # entire area
        self.children = [self.toolbar, self.cont]

        self.scanner = None
예제 #3
0
    def __init__(self):

        # Add the required widgets
        self.wt_url = Text(placeholder='Add URL',
                           description='API URL:',
                           disabled=False)
        self.wt_user = Text(placeholder='Username',
                            description='API User:'******'******',
                                description='API Password:'******'Member State',
                          description='Member State:',
                          disabled=False)

        self.wdd_year = Dropdown(options=['2020', '2019', '2018'],
                                 placeholder='Year',
                                 description='Year:',
                                 disabled=False)

        self.wdd_ptype = Dropdown(options=['', 'm', 'g', 'b'],
                                  placeholder='Type',
                                  description='Type:',
                                  disabled=False)

        super().__init__([self.wt_url, self.wt_user, self.wt_pass, self.wt_ms, \
                         self.wdd_year, self.wdd_ptype])
예제 #4
0
    def register(self):
        username_box = Text(value=None,
                            placeholder="username",
                            description="Username: "******"Suggested password : "******"Password: "******"")
        conf_password_box = Password(description="Confirm: ", placeholder="")
        register_button = Button(description="Register",
                                 button_style="primary",
                                 layout=Layout(width="10%"))

        status_text = HTML(value="<font color='blue'>Enter credentials</font>")
        output_box = Output()

        base_url = "https://hugs.acquire-aaai.com/t"

        def register_user(a):
            if password_box.value != conf_password_box.value:
                with output_box:
                    status_text.value = (
                        "<font color='red'>Passwords do not match</font>")
            else:
                result = User.register(
                    username=username_box.value,
                    password=password_box.value,
                    identity_url=f"{base_url}/identity",
                )

                with output_box:
                    status_text.value = "<font color='green'>Please scan QR code with authenticator app</font>"
                    display(result["qrcode"])

        register_button.on_click(register_user)

        return VBox(children=[
            username_box,
            suggested_password,
            password_box,
            conf_password_box,
            register_button,
            status_text,
            output_box,
        ])
예제 #5
0
def api(mode=None):
    """"""
    values = config.read()

    wt_url = Text(
        value=values['api']['url'],
        placeholder='Add URL',
        description='API URL:',
        disabled=False
    )
    wt_user = Text(
        value=values['api']['user'],
        placeholder='Username',
        description='API User:'******'api']['pass'],
        placeholder='******',
        description='API Password:'******'Save',
        disabled=False,
        icon='save'
    )

    progress = Output()

    def outlog(*text):
        with progress:
            print(*text)

    @wb_save.on_click
    def wb_save_on_click(b):
        progress.clear_output()
        config.set_value(['api', 'url'], str(wt_url.value).replace(' ', ''))
        config.set_value(['api', 'user'], str(wt_user.value).replace(' ', ''))
        if wt_pass.value != '':
            config.set_value(['api', 'pass'], str(
                wt_pass.value).replace(' ', ''))
        outlog("The RESTful API credentials are saved.")

    wbox = VBox([HBox([wt_url,
                       Label("Format: http://0.0.0.0/ or https://0.0.0.0/")]),
                 wt_user, wt_pass,
                 HBox([wb_save, progress])])

    return wbox
예제 #6
0
def rest_api(mode=None):
    """"""
    values = config.read()

    wt_url = Text(
        value=values['api']['url'],
        placeholder='Add URL',
        description='API URL:',
        disabled=False
    )
    wt_user = Text(
        value=values['api']['user'],
        placeholder='Username',
        description='API User:'******'api']['pass'],
        placeholder='******',
        description='API Password:'******'Save',
        disabled=False,
        icon='save'
    )

    progress = Output()

    def outlog(*text):
        with progress:
            print(*text)

    @wb_save.on_click
    def wb_save_on_click(b):
        config.update(['api', 'url'], str(wt_url.value))
        config.update(['api', 'user'], str(wt_user.value))
        if wt_pass.value != '':
            config.update(['api', 'pass'], str(wt_pass.value))
        outlog("API information is updated")

    wbox = VBox([wt_url, wt_user, wt_pass, wb_save, progress])

    return wbox
예제 #7
0
    def __init__(self):
        # Add the required widgets
        self.wt_url = Text(placeholder='Add Database Host',
                           description='Host:',
                           disabled=False)

        self.wt_port = IntText(value=5432, description='Port:', disabled=False)

        self.wt_name = Text(placeholder='Add Database Name',
                            description='DB Name:',
                            disabled=False)

        self.wt_user = Text(placeholder='Username',
                            description='DB User:'******'******',
                                description='DB Password:'******'Schema',
                              description='DB Schema:',
                              disabled=False)

        self.wt_table = Text(placeholder='Table',
                             description='Parcel Table:',
                             disabled=False)

        self.wt_foiid = Text(placeholder='Attribute',
                             description='FOI Attribute:',
                             disabled=False)

        self.wa_sql = Textarea(placeholder='SQL Additional Conditions',
                               description='SQL Additional Conditions:',
                               disabled=False)

        super().__init__([self.wt_url, self.wt_port, self.wt_name, self.wt_user,\
                          self.wt_pass, self.wt_schema, self.wt_table, self.wt_foiid,\
                          self.wa_sql])
예제 #8
0
 def get_password(**kwargs):
     return Password(**kwargs)
예제 #9
0
 def __init__(self, name, value, **kwargs):
     self.dd = Password(value=value)
     FormValue.__init__(self, name, **kwargs)
예제 #10
0
 def get_password(**kwargs):
     """
         Get Password Widget.
     """
     return Password(**kwargs)
예제 #11
0
def widget_box():
    """Update the repository.
    Args:
        None
    Returns:
        update_widget : A widget for general settings.
    Raises:
        Error:
    Example:

    """

    # User settings
    user_info = Label("General settings.")

    values = config.read()

    user_name = Text(value=values['set']['user'],
                     placeholder='user name',
                     description='User:'******'set']['email'],
                      placeholder='[email protected]',
                      description='email:',
                      disabled=False)
    user_institution = Text(value=values['set']['institution'],
                            placeholder='EU-',
                            description='Institution:',
                            disabled=False)
    ms_list = data_options.eu_ms()
    ms = Dropdown(
        options=[(ms_list[m], m) for m in ms_list] + [('', '')],
        value=values['set']['member_state'],
        description='Member state:',
        disabled=False,
    )
    wbox_user = VBox([user_info, user_name, user_email, user_institution, ms],
                     layout=Layout(border='1px solid black'))

    # System settings
    sys_info = Label("System settings.")
    paths_info = Label(
        "Select the personal data folder and the temporary folder.")

    jupyterlab = Checkbox(
        value=eval(values['set']['jupyterlab']),
        description=
        'Workin in Jupyter Lab (Uncheck for Voila and classical jupyter environment)',
        disabled=False,
        indent=False)

    def on_jupyterlab_change(change):
        config.update(['set', 'jupyterlab'], str(jupyterlab.value))

    jupyterlab.observe(on_jupyterlab_change, 'value')

    path_data = Text(value=values['paths']['data'], description='Data path:')

    path_temp = Text(value=values['paths']['temp'], description='Temp path:')

    files_info = Label("Select where to store the parcel IDs list file from:")

    file_pids_poly = Text(value=values['files']['pids_poly'],
                          description='Polygon:')
    file_pids_dist = Text(value=values['files']['pids_dist'],
                          description='Distance:')

    plimit_info = Label(
        "Warning: No more than 25 parcels are tested, unexpected results may occur."
    )
    plimit = BoundedIntText(value=int(values['set']['plimit']),
                            max=100_000_000,
                            min=1,
                            step=1,
                            description='Max parcels that can be downloaded:',
                            disabled=False)

    wbox_sys = VBox([
        sys_info, jupyterlab, plimit_info, plimit, paths_info, path_data,
        path_temp, files_info, file_pids_poly, file_pids_dist
    ],
                    layout=Layout(border='1px solid black'))

    # Git settings
    git_info = Label(
        "Git Settings. (To easily get the latest version of notebooks and scripts.)"
    )

    git_url, git_user, git_pass = config.credentials('git')

    git_url = Text(value=git_url, description='Url:')
    git_user = Text(value=git_user, description='User name:')
    git_pass = Password(value=git_pass,
                        placeholder='******',
                        description='Password:'******'1px solid black'))

    btn_save = Button(description='Save', disabled=False, icon='save')

    progress = Output()

    def outlog(*text):
        with progress:
            print(*text)

    @btn_save.on_click
    def btn_save_on_click(b):
        progress.clear_output()
        config.update(['set', 'user'], str(user_name.value))
        config.update(['set', 'email'], str(user_email.value))
        config.update(['set', 'institution'], str(user_institution.value))
        config.update(['set', 'member_state'], str(user_email.value))
        config.update(['set', 'plimit'], str(plimit.value))
        config.update(['git', 'url'], str(git_url.value))
        config.update(['git', 'user'], str(git_user.value))
        config.update(['paths', 'data'], str(path_data.value))
        config.update(['paths', 'temp'], str(path_temp.value))
        config.update(['files', 'pids_poly'], str(file_pids_poly.value))
        config.update(['files', 'pids_dist'], str(file_pids_dist.value))
        if git_pass.value != '':
            config.update(['git', 'pass'], str(git_pass.value))
        outlog("The new settings are saved.")

    wbox = VBox([
        config.clean_temp(), wbox_user, wbox_sys, wbox_git,
        HBox([btn_save, update.btn_update()]), progress
    ])

    return wbox
예제 #12
0
def direct_conn(db='1'):
    values = config.read()

    info_db = Label("Database connection settings.")

    db_host = Text(value=values['db'][db]['conn']['host'],
                   placeholder='Database host',
                   description='db Host:',
                   disabled=False)
    db_port = Text(value=values['db'][db]['conn']['port'],
                   placeholder='Database port',
                   description='db Port:',
                   disabled=False)
    db_name = Text(value=values['db'][db]['conn']['name'],
                   placeholder='Database name',
                   description='db Name:',
                   disabled=False)
    db_user = Text(value=values['db'][db]['conn']['user'],
                   placeholder='Database user',
                   description='db User:'******'db'][db]['conn']['pass'],
                       placeholder='******',
                       description='db Pass:'******'EOSC', 'CREODIAS', 'SOBLOO', 'MUNDI', 'ONDA', 'WEKEO', ''],
        value=values['obst']['osdias'],
        description='DIAS:',
        disabled=False,
    )
    os_host = Text(value=values['obst']['oshost'],
                   placeholder='Storage host',
                   description='s3 Host:',
                   disabled=False)
    os_bucket = Text(value=values['obst']['bucket'],
                     placeholder='Bucket name',
                     description='Bucket name:',
                     disabled=False)
    os_access_key = Text(value=values['obst']['access_key'],
                         placeholder='Access key',
                         description='Access Key:',
                         disabled=False)
    os_secret_key = Password(value=values['obst']['secret_key'],
                             placeholder='Secret key',
                             description='Secret Key:',
                             disabled=False)

    wb_save = Button(description='Save', disabled=False, icon='save')

    progress = Output()

    def outlog(*text):
        with progress:
            print(*text)

    @wb_save.on_click
    def wb_save_on_click(b):
        progress.clear_output()
        # Save database connection information
        config.update(['db', db, 'conn', 'host'], str(db_host.value))
        config.update(['db', db, 'conn', 'port'], str(db_port.value))
        config.update(['db', db, 'conn', 'name'], str(db_name.value))
        config.update(['db', db, 'conn', 'user'], str(db_user.value))
        if db_pass.value != '':
            config.update(['db', db, 'conn', 'pass'], str(db_pass.value))
        # Save Object storage connection information
        config.update(['obst', 'osdias'], str(os_dias.value))
        config.update(['obst', 'oshost'], str(os_host.value))
        config.update(['obst', 'bucket'], str(os_bucket.value))
        config.update(['obst', 'access_key'], str(os_access_key.value))
        if os_secret_key.value != '':
            config.update(['obst', 'secret_key'], str(os_secret_key.value))

        outlog("All changes are saved.")

    wbox = VBox([
        info_db, db_host, db_port, db_name, db_user, db_pass, info_os, os_dias,
        os_host, os_bucket, os_access_key, os_secret_key, wb_save, progress
    ])

    return wbox
예제 #13
0
파일: radboard.py 프로젝트: usnair/georad
  def configDBCB(self,b):

    self.out_cp.clear_output()

    self.objList = [*(self.objDict)]

    pw = self.panelWidth[0]

    lw = (pw*self.nx)+((self.nx-1)*self.gridGap)+(self.gridPad*2)

    gw = lw + (2*self.dbBorder)

    lw1 = lw-2

    self.topLabel.layout = {'width': str(lw-2)+'px'}

    gap = str(self.gridGap)+'px'

    pd = str(self.gridPad)

    pad = pd+'px '+pd+'px '+pd+'px '+pd+'px'

    self.gridDB1 = GridspecLayout(self.ny,self.nx,
                                  layout={
                                          'scroll':'False',
                                          'grid_gap':gap,
                                          'padding':pad
                                          }
                                  )
    self.objSW = [ ([0] * self.nx) for y in range(self.ny) ]
    self.objinfoTW = [ ([0] * self.nx) for y in range(self.ny) ]
    self.pwTW = [ ([0] * self.nx) for y in range(self.ny) ]
    self.phTW = [ ([0] * self.nx) for y in range(self.ny) ]

    txw = str(int(0.96*float(self.panelWidth[0])))+'px'
    pw = str(self.panelWidth[0])+'px'
    ph = str(self.panelHeight[0])+'px'
    pb = str(self.panelBorder)+'px groove'

    for i in range(0,self.ny):
      for j in range(0,self.nx):
        desc = 'Panel('+str(i+1)+','+str(j+1)+'):'
        self.objSW[i][j]  = Dropdown(options=self.objList,value=self.objList[0],
                                    description=desc,disabled=False,
                                    layout={'width':txw})
        objinfo = self.objinfoDict[self.objList[0]]
        self.objinfoTW[i][j] = Textarea(value=objinfo,placeholder='',description='',
                                    disabled=False,layout={'width':txw,'border':'2px inset'})
        self.pwTW[i][j] = Text(value=str(self.panelWidth[1]),placeholder='',description='Panel Width:',
                                    disabled=False,layout={'width':txw,'border':'2px inset'})
        self.phTW[i][j] = Text(value=str(self.panelHeight[1]),placeholder='',description='Panel Height',
                                    disabled=False,layout={'width':txw,'border':'2px inset'})
        
        self.gridDB1[i,j] = VBox([self.objSW[i][j],self.pwTW[i][j],self.phTW[i][j],self.objinfoTW[i][j]],layout={'border':'2px solid black'})

        self.objSW[i][j].observe(functools.partial(self.objSWCB, irow_=i, jcol_=j),names='value')
        self.phTW[i][j].observe(functools.partial(self.phTWCB, irow_=i, jcol_=j),names='value')

    gp  = str(self.gridPad)+'px'
    dbb = str(self.dbBorder)+'px groove'
    dbw = str(gw)+'px'

    self.pmLabel = HTML(disabled=False,layout={'width': 'auto','flex_flow':'column'})
    
    self.pmLabel.value = ( '<div style="background-color: #C0C0C0 ;'+ 
                           'border-top-style:groove;border-width:3px'
                           'padding: 1em 0em 0em 0em;border-bottom-style:groove;border-width:3px">'+
                           '<b><font size="4"><center><h3>Password Manager</h3></center></font></b></div>')
    self.accSW = Dropdown(options=self.accList,value=self.accList[0],
                                    description='Account:',disabled=False,
                                    layout={'width':txw})
    self.usrTW = Text(value='',placeholder='',description='Username:'******'width':txw})
    
    self.pwdPW = Password(value='',placeholder='',description='Password:'******'width':txw})
    self.addPWD = Button(description='Add Account',disabled=False,
                        layout={'width':'150px','border':'3px outset'}
                        )
    self.createDB = Button(description='Create Dashboard',disabled=False,
                        layout={'width':'150px','border':'3px outset'}
                        )
    self.addPWD.on_click(self.addPWDCB)
    self.createDB.on_click(self.createDBCB)
    self.reconfigDB = Button(description='Reconfigure Dashboard',disabled=False,
                        layout={'width':'180px','border':'3px outset'}
                        )
    self.reconfigDB.on_click(self.reconfigDBCB)
    
    self.cp   = VBox([ 
                       HBox([self.topLabel],layout={'flex_flow':'column'}),
                       HBox([self.gridDB1]),
                       HBox([self.pmLabel],layout={'flex_flow':'column'}),
                       VBox([self.accSW,self.usrTW,self.pwdPW]),
                       HBox([self.addPWD],layout={'justify_content':'center'}),
                       self.rule,
                       HBox([self.reconfigDB,self.createDB],layout={'justify_content':'center','padding':gp})
                     ],layout={'border':dbb,'width':dbw}
                    )
    with self.out_cp:
      self.out_cp.clear_output()
      display(self.cp)
예제 #14
0
class ReposheetUI(VBox):
    """ReposheetUI returns stats about multiple code repositories.
    
    This will create an interactive spreadsheet-like overview of high-level
    key values for repositories of some user or organization.

    To do that it needs the repo URL and an API key for the repository hoster
    (for now GitHub). So far it works only for github.com, but support for
    gitlab.com is coming!
    """
    def __init__(self,
                 url=None,
                 token=None,
                 regexpr=None,
                 fields=None,
                 callbacks=None):
        """Instantiate a UI controller.
        """
        super().__init__()

        self.fields = fields
        self.callbacks = callbacks or []

        # toolbar
        self.ht = HTML("<b>Host/Owner:</b>")
        self.tx_desc = "Repo owner URL, eg. https://github.com/python"
        self.tx = Text(
            url or "",
            placeholder=self.tx_desc,
            description_tooltip="Repo owner URL, press enter to scan!",
            layout=Layout(width="200px"))
        self.tx.on_submit(self.start_scan)
        tok_desc = "GitHub API Access Token"
        self.tok = Password(token,
                            placeholder=tok_desc,
                            description_tooltip=tok_desc,
                            layout=Layout(width="175px"))
        self.tok.on_submit(self.start_scan)
        self.btn = Button(description="Scan",
                          button_style="info",
                          layout=Layout(width="100px"))
        self.btn.on_click(self.start_scan)
        rx_desc = "Regex to match repo names"
        self.rx = Text(regexpr,
                       placeholder=rx_desc,
                       description_tooltip=rx_desc,
                       layout=Layout(width="60px"))
        self.rx.on_submit(self.start_scan)
        self.toolbar = HBox([self.ht, self.tx, self.tok, self.rx, self.btn])

        # content area
        self.sx = HTML(layout=Layout(width="100pc"))
        self.tabout = VBox()
        self.pbout = Output()
        self.out = Output()
        self.cont = VBox([self.sx, self.tabout, self.pbout, self.out])

        # entire area
        self.children = [self.toolbar, self.cont]

        self.scanner = None

    def start_scan(self, widget):
        """Callback for the scan button or name text line.
        """
        self.sx.value = ""
        if not self.tx.value.startswith(
                "github.com/") or not "/" in self.tx.value:
            self.sx.value = "Expected: github.com/&lt;owner&gt;"
            return

        # toolbar
        with self.out:
            btn_desc = self.btn.description
            self.btn.description = "Scanning..."
            self.btn.disabled = True
            token = self.tok.value or None
            if self.scanner is None:
                self.scanner = GitHubRepoScanner(Github(token))
            fields = self.fields or [
                "name", "created_at", "fork", "contributors", "subscribers",
                "forks_count", "issues", "pulls", "stargazers_count",
                "get_commits", "commits_1y", "commit_activity"
            ]
            repo_name_pat = self.rx.value
            owner_name = self.tx.value.split("/")[1]
            data = []
            df = pd.DataFrame(data, columns=fields)
            opts = {"enableColumnReorder": True}
            self.tab = show_grid(df, show_toolbar=False, grid_options=opts)
            kwargs = dict(owner_name=owner_name,
                          repo_name_pat=repo_name_pat,
                          fields=fields,
                          callbacks=self.callbacks,
                          use_tqdm=False)
            try:
                gen = self.scanner.scan_repos(**kwargs)
                repos = next(gen)
                num_repos = len(repos)
            except UnknownObjectException:
                self.sx.value = "Unknown Object"
            except RateLimitExceededException:
                self.sx.value = "Rate Limit Exceeded"
            except BadCredentialsException:
                self.sx.value = "Bad Credentials"

        # progress bar
        with self.pbout:
            pb = tqdm_notebook(initial=0, total=num_repos)

        # table
        with self.out:
            try:
                for i, row in enumerate(gen):
                    if i == 0:
                        self.tabout.children = [self.tab]
                    # tab.add_row(row=row.items())  # not working
                    self.tab.df = self.tab.df.append(row, ignore_index=True)
                    pb.update(1)
                self.pbout.clear_output()
            except RateLimitExceededException:
                self.sx.value = "Rate Limit Exceeded"
                pb.close()
            except KeyboardInterrupt:
                pb.close()

        # toolbar
        self.btn.disabled = False
        self.btn.description = btn_desc
예제 #15
0
파일: nmtools.py 프로젝트: usnair/georad
class MERRA_WindRose(PanelObject):
    def __init__(self, *args, **kwargs):
        self.title = "MERRA2 Wind Rose"
        self.accList = ['NASA Earth Data']
        PanelObject.__init__(self, *args, **kwargs)
        self.windms = []
        self.windkt = []
        self.winddir = []
        self.times = []
        self.latv = 24.42
        self.lonv = 54.43
        self.start_date = datetime(2020, 4, 20)
        self.end_date = datetime(2020, 4, 30)

    def getCP(self):
        self.setLabel()
        self.usrTW = Text(value='',
                          placeholder='',
                          description='Username:'******'values')
        self.pwdPW = Password(value='',
                              placeholder='',
                              description='Password:'******'value')
        self.st = widgets.DatePicker(description='Start Date',
                                     value=datetime(2020, 4, 20),
                                     disabled=False,
                                     layout=Layout(width='220px'))
        self.et = widgets.DatePicker(description='End Date',
                                     value=datetime(2020, 4, 30),
                                     disabled=False,
                                     layout=Layout(width='220px'))
        self.st.observe(self.startDate)
        self.et.observe(self.endDate)
        self.latitude = Text(value='24.42',
                             description='Latitude:',
                             disabled=False,
                             layout=Layout(width='220px'))
        self.longitude = Text(value='54.43',
                              description='Longitude:',
                              disabled=False,
                              layout=Layout(width='220px'))
        self.latitude.observe(self.set_lat_val, names='value')
        self.longitude.observe(self.set_lon_val, names='value')
        self.plotms = Button(description='Plot in m/s',
                             disabled=False,
                             layout={
                                 'width': 'auto',
                                 'border': '3px outset'
                             })
        self.plotms.on_click(self.plotWindRose_ms)
        self.plotkt = Button(description='Plot in kt',
                             disabled=False,
                             layout={
                                 'width': 'auto',
                                 'border': '3px outset'
                             })
        self.plotkt.on_click(self.plotWindRose_kt)
        self.inpUSR.children += (HBox([
            VBox([self.st, self.latitude, self.longitude]),
            VBox([self.et, self.plotms, self.plotkt])
        ],
                                      layout={'overflow': 'visible'}), )
        with self.out_cp:
            self.out_cp.clear_output()
            display(self.getCP)
        return self.cp

    def username(self, t):
        username = t.value

    def password(self, t):
        password = self.pwdPW.value

    def startDate(self, date):
        self.start_date = datetime(self.st.value.year, self.st.value.month,
                                   self.st.value.day)

        return self.start_date

    def endDate(self, date):
        self.end_date = datetime(self.et.value.year, self.et.value.month,
                                 self.et.value.day)
        return self.end_date

    def lonlatToIndex(self, plon, plat):
        self.ilat = int(
            np.interp(plat, (self.lat.data.min(), self.lat.data.max()),
                      (0, self.lat.shape[0] - 1)))
        self.ilon = int(
            np.interp(plon, (self.lon.data.min(), self.lon.data.max()),
                      (0, self.lon.shape[0] - 1)))

    def get_data(self):
        url1 = 'https://goldsmr4.gesdisc.eosdis.nasa.gov:443/opendap/MERRA2/M2I1NXASM.5.12.4/'
        url2 = '/MERRA2_'
        url3 = '.inst1_2d_asm_Nx.'
        zero = '0'
        slash = '/'
        nc = '.nc4'
        for dt in rrule.rrule(rrule.DAILY,
                              dtstart=self.start_date,
                              until=self.end_date):
            #print('Getting data for',dt)
            self.times.append(dt)
            if dt.year >= 2011:
                val = 400
            if dt.year < 2011 and dt.year >= 2001:
                val = 300
            if dt.year < 2001 and dt.year >= 1992:
                val = 200
            if dt.year < 1992:
                val = 100
            if dt.month > 9 and dt.day < 10:
                opendap_url = url1 + str(dt.year) + slash + str(
                    dt.month) + url2 + str(val) + url3 + str(dt.year) + str(
                        dt.month) + zero + str(dt.day) + nc
            if dt.month > 9 and dt.day >= 10:
                opendap_url = url1 + str(dt.year) + slash + str(
                    dt.month) + url2 + str(val) + url3 + str(dt.year) + str(
                        dt.month) + str(dt.day) + nc
            if dt.month < 10 and dt.day < 10:
                opendap_url = url1 + str(dt.year) + slash + zero + str(
                    dt.month) + url2 + str(val) + url3 + str(
                        dt.year) + zero + str(dt.month) + zero + str(
                            dt.day) + nc
            if dt.month < 10 and dt.day >= 10:
                opendap_url = url1 + str(dt.year) + slash + zero + str(
                    dt.month) + url2 + str(val) + url3 + str(
                        dt.year) + zero + str(dt.month) + str(dt.day) + nc
            username = self.pwdDict['NASA Earth Data']['user']
            password = self.pwdDict['NASA Earth Data']['password']
            with self.out_cp:
                print('user='******'lon'][:]
            self.lat = dataset['lat'][:]
            self.time = dataset['time'][:]
            self.uwind = np.squeeze(dataset['U10M'][:, :, :])
            self.vwind = np.squeeze(dataset['V10M'][:, :, :])

            self.lons, self.lats = np.meshgrid(self.lon, self.lat)
            self.lonlatToIndex(self.lonv, self.latv)

            uwind = self.uwind[:, self.ilat, self.ilon].mean()
            vwind = self.vwind[:, self.ilat, self.ilon].mean()
            wind_speed = np.sqrt(uwind**2 + vwind**2)
            self.windms.append(wind_speed)
            ws_to_kt = wind_speed * 0.514444
            self.windkt.append(ws_to_kt)
            wind_dir_trig_to = (np.arctan2((uwind / wind_speed),
                                           (vwind / wind_speed)))
            wind_dir_trig_to_degrees = (wind_dir_trig_to * (180 / np.pi))
            wind_dir = wind_dir_trig_to_degrees + 180
            self.winddir.append(wind_dir)

    def set_lat_val(self, value):
        self.latv = float(self.latitude.value)

    def set_lon_val(self, value):
        self.lonv = float(self.longitude.value)

    def plotWindRose_kt(self, b):
        plt.ioff()
        with self.out_cp:
            self.out_cp.clear_output()
            print("Getting data ...")
            self.get_data()
            print("Finished")
            fig = plt.figure(figsize=(10, 5))
            ax = WindroseAxes.from_ax()

            ax.bar(self.winddir,
                   self.windkt,
                   normed=True,
                   opening=0.8,
                   edgecolor='white')
            ax.set_legend()
            title = 'MERRA2 Wind Rose (kt) from ' + str(
                self.start_date) + ' to ' + str(
                    self.end_date) + ' at Latitude ' + str(
                        self.latitude.value) + ' and Longitude ' + str(
                            self.longitude.value)
            ax.set_title(title)

            plt.show()

    def plotWindRose_ms(self, b):
        plt.ioff()
        with self.out_cp:
            self.out_cp.clear_output()
            print("Getting data ...")
            self.get_data()
            print("Finished")
            self.out_cp.clear_output()
            fig = plt.figure(figsize=(10, 5))
            ax = WindroseAxes.from_ax()
            ax.bar(self.winddir,
                   self.windms,
                   normed=True,
                   opening=0.8,
                   edgecolor='white')
            title = 'MERRA2 Wind Rose (m/s) from ' + str(
                self.start_date) + ' to ' + str(
                    self.end_date) + ' at Latitude ' + str(
                        self.latitude.value) + ' and Longitude ' + str(
                            self.longitude.value)
            ax.set_title(title)
            ax.set_legend()
            plt.show()