signature:
def url ( ctx ) :
    """Prints the tensorboard url for project / experiment / experiment group .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples for project tensorboards :
 ` ` ` bash
 $ polyaxon tensorboard url
 ` ` ` bash
 $ polyaxon tensorboard - p mnist url
 Examples for experiment tensorboards :
 ` ` ` bash
 $ polyaxon tensorboard - xp 1 url
 Examples for experiment group tensorboards :
 ` ` ` bash
 $ polyaxon tensorboard - g 1 url"""

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
group = ctx . obj . get ( 'group' )
experiment = ctx . obj . get ( 'experiment' )
if experiment :
    try :
        response = PolyaxonClient ( ) . experiment . get_experiment ( username = user , project_name = project_name , experiment_id = experiment )
        obj = 'experiment {}' . format ( experiment )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not get experiment `{}`.' . format ( experiment ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
elif group :
    try :
        response = PolyaxonClient ( ) . experiment_group . get_experiment_group ( username = user , project_name = project_name , group_id = group )
        obj = 'group `{}`.' . format ( group )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not get group `{}`.' . format ( group ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
else :
    try :
        response = PolyaxonClient ( ) . project . get_project ( username = user , project_name = project_name )
        obj = 'project `{}`.' . format ( project_name )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not get project `{}`.' . format ( project_name ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
if response . has_tensorboard :
    click . echo ( get_tensorboard_url ( user = user , project_name = project_name , experiment = experiment , group = group ) )
else :
    Printer . print_warning ( 'This `{}` does not have a running tensorboard' . format ( obj ) )
    click . echo ( 'You can start tensorboard with this command: polyaxon tensorboard start --help' )


signature:
def start ( ctx , file ) : # pylint : disable = redefined - builtin
    """Start a tensorboard deployment for project / experiment / experiment group .
 Project tensorboard will aggregate all experiments under the project .
 Experiment group tensorboard will aggregate all experiments under the group .
 Experiment tensorboard will show all metrics for an experiment .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example : using the default tensorflow image 1.4.1.
 ` ` ` bash
 $ polyaxon tensorboard start
 Example : with custom image and resources
 ` ` ` bash
 $ polyaxon tensorboard start - f file - f file _ override . . .
 Example : starting a tensorboard for an experiment group
 ` ` ` bash
 $ polyaxon tensorboard - g 1 start - f file
 Example : starting a tensorboard for an experiment
 ` ` ` bash
 $ polyaxon tensorboard - xp 112 start - f file"""

implementation:
specification = None
job_config = None
if file :
    specification = check_polyaxonfile ( file , log = False ) . specification
if specification : # pylint : disable = protected - access
    check_polyaxonfile_kind ( specification = specification , kind = specification . _TENSORBOARD )
    job_config = specification . parsed_data
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
group = ctx . obj . get ( 'group' )
experiment = ctx . obj . get ( 'experiment' )
if experiment :
    try :
        response = PolyaxonClient ( ) . experiment . start_tensorboard ( username = user , project_name = project_name , experiment_id = experiment , job_config = job_config )
        obj = 'experiment `{}`' . format ( experiment )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not start tensorboard experiment `{}`.' . format ( experiment ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
elif group :
    try :
        response = PolyaxonClient ( ) . experiment_group . start_tensorboard ( username = user , project_name = project_name , group_id = group , job_config = job_config )
        obj = 'group `{}`' . format ( group )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not start tensorboard group `{}`.' . format ( group ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
else :
    try :
        response = PolyaxonClient ( ) . project . start_tensorboard ( username = user , project_name = project_name , job_config = job_config )
        obj = 'project `{}`' . format ( project_name )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not start tensorboard project `{}`.' . format ( project_name ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
if response . status_code == 200 :
    Printer . print_header ( "A tensorboard for this {} is already running on:" . format ( obj ) )
    click . echo ( get_tensorboard_url ( user = user , project_name = project_name , experiment = experiment , group = group ) )
    sys . exit ( 0 )
if response . status_code != 201 :
    Printer . print_error ( 'Something went wrong, Tensorboard was not created.' )
    sys . exit ( 1 )
Printer . print_success ( 'Tensorboard is being deployed for {}' . format ( obj ) )
clint . textui . puts ( "It may take some time before you can access tensorboard.\n" )
clint . textui . puts ( "Your tensorboard will be available on:\n" )
with clint . textui . indent ( 4 ) :
    clint . textui . puts ( get_tensorboard_url ( user , project_name , experiment , group ) )


signature:
def stop ( ctx , yes ) :
    """Stops the tensorboard deployment for project / experiment / experiment group if it exists .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples : stopping project tensorboard
 ` ` ` bash
 $ polyaxon tensorboard stop
 Examples : stopping experiment group tensorboard
 ` ` ` bash
 $ polyaxon tensorboard - g 1 stop
 Examples : stopping experiment tensorboard
 ` ` ` bash
 $ polyaxon tensorboard - xp 112 stop"""

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
group = ctx . obj . get ( 'group' )
experiment = ctx . obj . get ( 'experiment' )
if experiment :
    obj = 'experiment `{}`' . format ( experiment )
elif group :
    obj = 'group `{}`' . format ( group )
else :
    obj = 'project `{}/{}`' . format ( user , project_name )
if not yes and not click . confirm ( "Are sure you want to stop tensorboard " "for {}" . format ( obj ) ) :
    click . echo ( 'Existing without stopping tensorboard.' )
    sys . exit ( 1 )
if experiment :
    try :
        PolyaxonClient ( ) . experiment . stop_tensorboard ( username = user , project_name = project_name , experiment_id = experiment )
        Printer . print_success ( 'Tensorboard is being deleted' )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not stop tensorboard {}.' . format ( obj ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
elif group :
    try :
        PolyaxonClient ( ) . experiment_group . stop_tensorboard ( username = user , project_name = project_name , group_id = group )
        Printer . print_success ( 'Tensorboard is being deleted' )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not stop tensorboard {}.' . format ( obj ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
else :
    try :
        PolyaxonClient ( ) . project . stop_tensorboard ( username = user , project_name = project_name )
        Printer . print_success ( 'Tensorboard is being deleted' )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not stop tensorboard {}.' . format ( obj ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )


signature:
def check_cli_version ( ) :
    """Check if the current cli version satisfies the server requirements"""

implementation:
if not CliConfigManager . should_check ( ) :
    return
server_version = get_server_version ( )
current_version = get_current_version ( )
CliConfigManager . reset ( current_version = current_version , min_version = server_version . min_version )
if LooseVersion ( current_version ) < LooseVersion ( server_version . min_version ) :
    click . echo ( """Your version of CLI ({}) is no longer compatible with server.""" . format ( current_version ) )
    if click . confirm ( "Do you want to upgrade to " "version {} now?" . format ( server_version . latest_version ) ) :
        pip_upgrade ( )
        sys . exit ( 0 )
    else :
        clint . textui . puts ( "Your can manually run:" )
        with clint . textui . indent ( 4 ) :
            clint . textui . puts ( "pip install -U polyaxon-cli" )
        clint . textui . puts ( "to upgrade to the latest version `{}`" . format ( server_version . latest_version ) )
        sys . exit ( 0 )
elif LooseVersion ( current_version ) < LooseVersion ( server_version . latest_version ) :
    clint . textui . puts ( "New version of CLI ({}) is now available. To upgrade run:" . format ( server_version . latest_version ) )
    with clint . textui . indent ( 4 ) :
        clint . textui . puts ( "pip install -U polyaxon-cli" )
elif LooseVersion ( current_version ) > LooseVersion ( server_version . latest_version ) :
    clint . textui . puts ( "You version of CLI ({}) is ahead of the latest version " "supported by Polyaxon Platform ({}) on your cluster, " "and might be incompatible." . format ( current_version , server_version . latest_version ) )


signature:
def version ( cli , platform ) :
    """Print the current version of the cli and platform ."""

implementation:
version_client = PolyaxonClient ( ) . version
cli = cli or not any ( [ cli , platform ] )
if cli :
    try :
        server_version = version_client . get_cli_version ( )
    except AuthorizationError :
        session_expired ( )
        sys . exit ( 1 )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not get cli version.' )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
    cli_version = get_version ( PROJECT_CLI_NAME )
    Printer . print_header ( 'Current cli version: {}.' . format ( cli_version ) )
    Printer . print_header ( 'Supported cli versions:' )
    dict_tabulate ( server_version . to_dict ( ) )
if platform :
    try :
        platform_version = version_client . get_platform_version ( )
    except AuthorizationError :
        session_expired ( )
        sys . exit ( 1 )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not get platform version.' )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
    chart_version = version_client . get_chart_version ( )
    Printer . print_header ( 'Current platform version: {}.' . format ( chart_version . version ) )
    Printer . print_header ( 'Supported platform versions:' )
    dict_tabulate ( platform_version . to_dict ( ) )


signature:
def dashboard ( yes , url ) :
    """Open dashboard in browser ."""

implementation:
dashboard_url = "{}/app" . format ( PolyaxonClient ( ) . api_config . http_host )
if url :
    click . echo ( dashboard_url )
    sys . exit ( 0 )
if not yes :
    click . confirm ( 'Dashboard page will now open in your browser. Continue?' , abort = True , default = True )
click . launch ( dashboard_url )


signature:
def grant ( username ) :
    """Grant superuser role to a user .
 Example :
 ` ` ` bash
 $ polyaxon superuser grant david"""

implementation:
try :
    PolyaxonClient ( ) . user . grant_superuser ( username )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not grant superuser role to user `{}`.' . format ( username ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "Superuser role was granted successfully to user `{}`." . format ( username ) )


signature:
def revoke ( username ) :
    """Revoke superuser role to a user .
 Example :
 ` ` ` bash
 $ polyaxon superuser revoke david"""

implementation:
try :
    PolyaxonClient ( ) . user . revoke_superuser ( username )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not revoke superuser role from user `{}`.' . format ( username ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "Superuser role was revoked successfully from user `{}`." . format ( username ) )


signature:
def url ( ctx ) :
    """Prints the notebook url for this project .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon notebook url"""

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
try :
    response = PolyaxonClient ( ) . project . get_project ( user , project_name )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not get project `{}`.' . format ( project_name ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
if response . has_notebook :
    click . echo ( get_notebook_url ( user , project_name ) )
else :
    Printer . print_warning ( 'This project `{}` does not have a running notebook.' . format ( project_name ) )
    click . echo ( 'You can start a notebook with this command: polyaxon notebook start --help' )


signature:
def start ( ctx , file , u ) : # pylint : disable = redefined - builtin
    """Start a notebook deployment for this project .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon notebook start - f file - f file _ override . . .
 Example : upload before running
 ` ` ` bash
 $ polyaxon - p user12 / mnist notebook start - f file - u"""

implementation:
specification = None
job_config = None
if file :
    specification = check_polyaxonfile ( file , log = False ) . specification
# Check if we need to upload
if u :
    ctx . invoke ( upload , sync = False )
if specification : # pylint : disable = protected - access
    check_polyaxonfile_kind ( specification = specification , kind = specification . _NOTEBOOK )
    job_config = specification . parsed_data
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
try :
    response = PolyaxonClient ( ) . project . start_notebook ( user , project_name , job_config )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not start notebook project `{}`.' . format ( project_name ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
if response . status_code == 200 :
    Printer . print_header ( "A notebook for this project is already running on:" )
    click . echo ( get_notebook_url ( user , project_name ) )
    sys . exit ( 0 )
if response . status_code != 201 :
    Printer . print_error ( 'Something went wrong, Notebook was not created.' )
    sys . exit ( 1 )
Printer . print_success ( 'Notebook is being deployed for project `{}`' . format ( project_name ) )
clint . textui . puts ( "It may take some time before you can access the notebook.\n" )
clint . textui . puts ( "Your notebook will be available on:\n" )
with clint . textui . indent ( 4 ) :
    clint . textui . puts ( get_notebook_url ( user , project_name ) )


signature:
def stop ( ctx , commit , yes ) :
    """Stops the notebook deployment for this project if it exists .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )"""

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
if not yes and not click . confirm ( "Are sure you want to stop notebook " "for project `{}/{}`" . format ( user , project_name ) ) :
    click . echo ( 'Existing without stopping notebook.' )
    sys . exit ( 1 )
if commit is None :
    commit = True
try :
    PolyaxonClient ( ) . project . stop_notebook ( user , project_name , commit )
    Printer . print_success ( 'Notebook is being deleted' )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not stop notebook project `{}`.' . format ( project_name ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )


signature:
def cli ( context , verbose ) :
    """Polyaxon CLI tool to :
 * Parse , Validate , and Check Polyaxonfiles .
 * Interact with Polyaxon server .
 * Run and Monitor experiments .
 Check the help available for each command listed below ."""

implementation:
configure_logger ( verbose or GlobalConfigManager . get_value ( 'verbose' ) )
non_check_cmds = [ 'config' , 'version' , 'login' , 'logout' , 'deploy' , 'admin' , 'teardown' ]
if context . invoked_subcommand not in non_check_cmds :
    check_cli_version ( )


signature:
def check ( self ) :
    """Add platform specific checks"""

implementation:
if not self . is_valid :
    raise PolyaxonDeploymentConfigError ( 'Deployment type `{}` not supported' . format ( self . deployment_type ) )
check = False
if self . is_kubernetes :
    check = self . check_for_kubernetes ( )
elif self . is_docker_compose :
    check = self . check_for_docker_compose ( )
elif self . is_docker :
    check = self . check_for_docker ( )
elif self . is_heroku :
    check = self . check_for_heroku ( )
if not check :
    raise PolyaxonDeploymentConfigError ( 'Deployment `{}` is not valid' . format ( self . deployment_type ) )


signature:
def install ( self ) :
    """Install polyaxon using the current config to the correct platform ."""

implementation:
if not self . is_valid :
    raise PolyaxonDeploymentConfigError ( 'Deployment type `{}` not supported' . format ( self . deployment_type ) )
if self . is_kubernetes :
    self . install_on_kubernetes ( )
elif self . is_docker_compose :
    self . install_on_docker_compose ( )
elif self . is_docker :
    self . install_on_docker ( )
elif self . is_heroku :
    self . install_on_heroku ( )


signature:
def upgrade ( self ) :
    """Upgrade deployment ."""

implementation:
if not self . is_valid :
    raise PolyaxonDeploymentConfigError ( 'Deployment type `{}` not supported' . format ( self . deployment_type ) )
if self . is_kubernetes :
    self . upgrade_on_kubernetes ( )
elif self . is_docker_compose :
    self . upgrade_on_docker_compose ( )
elif self . is_docker :
    self . upgrade_on_docker ( )
elif self . is_heroku :
    self . upgrade_on_heroku ( )


signature:
def teardown ( self , hooks = True ) :
    """Teardown Polyaxon ."""

implementation:
if not self . is_valid :
    raise PolyaxonDeploymentConfigError ( 'Deployment type `{}` not supported' . format ( self . deployment_type ) )
if self . is_kubernetes :
    self . teardown_on_kubernetes ( hooks = hooks )
elif self . is_docker_compose :
    self . teardown_on_docker_compose ( )
elif self . is_docker :
    self . teardown_on_docker ( hooks = hooks )
elif self . is_heroku :
    self . teardown_on_heroku ( hooks = hooks )


signature:
def project ( ctx , project ) : # pylint : disable = redefined - outer - name
    """Commands for projects ."""

implementation:
if ctx . invoked_subcommand not in [ 'create' , 'list' ] :
    ctx . obj = ctx . obj or { }
    ctx . obj [ 'project' ] = project


signature:
def create ( ctx , name , description , tags , private , init ) :
    """Create a new project .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon project create - - name = cats - vs - dogs - - description = " Image Classification with DL " """

implementation:
try :
    tags = tags . split ( ',' ) if tags else None
    project_dict = dict ( name = name , description = description , is_public = not private , tags = tags )
    project_config = ProjectConfig . from_dict ( project_dict )
except ValidationError :
    Printer . print_error ( 'Project name should contain only alpha numerical, "-", and "_".' )
    sys . exit ( 1 )
try :
    _project = PolyaxonClient ( ) . project . create_project ( project_config )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not create project `{}`.' . format ( name ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "Project `{}` was created successfully." . format ( _project . name ) )
if init :
    ctx . obj = { }
    ctx . invoke ( init_project , project = name )


signature:
def list ( page ) : # pylint : disable = redefined - builtin
    """List projects .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )"""

implementation:
user = AuthConfigManager . get_value ( 'username' )
if not user :
    Printer . print_error ( 'Please login first. `polyaxon login --help`' )
page = page or 1
try :
    response = PolyaxonClient ( ) . project . list_projects ( user , page = page )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not get list of projects.' )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
meta = get_meta_response ( response )
if meta :
    Printer . print_header ( 'Projects for current user' )
    Printer . print_header ( 'Navigation:' )
    dict_tabulate ( meta )
else :
    Printer . print_header ( 'No projects found for current user' )
objects = list_dicts_to_tabulate ( [ o . to_light_dict ( humanize_values = True , exclude_attrs = [ 'uuid' , 'experiment_groups' , 'experiments' , 'description' , 'num_experiments' , 'num_independent_experiments' , 'num_experiment_groups' , 'num_jobs' , 'num_builds' , 'unique_name' ] ) for o in response [ 'results' ] ] )
if objects :
    Printer . print_header ( "Projects:" )
    dict_tabulate ( objects , is_list_dict = True )


signature:
def get ( ctx ) :
    """Get info for current project , by project _ name , or user / project _ name .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 To get current project :
 ` ` ` bash
 $ polyaxon project get
 To get a project by name
 ` ` ` bash
 $ polyaxon project get user / project"""

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
try :
    response = PolyaxonClient ( ) . project . get_project ( user , project_name )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not get project `{}`.' . format ( project_name ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
get_project_details ( response )


signature:
def delete ( ctx ) :
    """Delete project .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )"""

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
if not click . confirm ( "Are sure you want to delete project `{}/{}`" . format ( user , project_name ) ) :
    click . echo ( 'Existing without deleting project.' )
    sys . exit ( 1 )
try :
    response = PolyaxonClient ( ) . project . delete_project ( user , project_name )
    local_project = ProjectManager . get_config ( )
    if local_project and ( user , project_name ) == ( local_project . user , local_project . name ) : # Purge caching
        ProjectManager . purge ( )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not delete project `{}/{}`.' . format ( user , project_name ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
if response . status_code == 204 :
    Printer . print_success ( "Project `{}/{}` was delete successfully" . format ( user , project_name ) )


signature:
def update ( ctx , name , description , tags , private ) :
    """Update project .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon update foobar - - description = " Image Classification with DL using TensorFlow "
 ` ` ` bash
 $ polyaxon update mike1 / foobar - - description = " Image Classification with DL using TensorFlow "
 ` ` ` bash
 $ polyaxon update - - tags = " foo , bar " """

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
update_dict = { }
if name :
    update_dict [ 'name' ] = name
if description :
    update_dict [ 'description' ] = description
if private is not None :
    update_dict [ 'is_public' ] = not private
tags = validate_tags ( tags )
if tags :
    update_dict [ 'tags' ] = tags
if not update_dict :
    Printer . print_warning ( 'No argument was provided to update the project.' )
    sys . exit ( 1 )
try :
    response = PolyaxonClient ( ) . project . update_project ( user , project_name , update_dict )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not update project `{}`.' . format ( project_name ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "Project updated." )
get_project_details ( response )


signature:
def groups ( ctx , query , sort , page ) :
    """List experiment groups for this project .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 Get all groups :
 ` ` ` bash
 $ polyaxon project groups
 Get all groups with with status { created or running } , and
 creation date between 2018-01-01 and 2018-01-02,
 and search algorithm not in { grid or random search }
 ` ` ` bash
 $ polyaxon project groups - q " status : created | running , started _ at : 2018-01-01 . . 2018-01-02 , search _ algorithm : ~ grid | random "
 Get all groups sorted by update date
 ` ` ` bash
 $ polyaxon project groups - s " - updated _ at " """

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
page = page or 1
try :
    response = PolyaxonClient ( ) . project . list_experiment_groups ( username = user , project_name = project_name , query = query , sort = sort , page = page )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not get experiment groups for project `{}`.' . format ( project_name ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
meta = get_meta_response ( response )
if meta :
    Printer . print_header ( 'Experiment groups for project `{}/{}`.' . format ( user , project_name ) )
    Printer . print_header ( 'Navigation:' )
    dict_tabulate ( meta )
else :
    Printer . print_header ( 'No experiment groups found for project `{}/{}`.' . format ( user , project_name ) )
objects = [ Printer . add_status_color ( o . to_light_dict ( humanize_values = True ) ) for o in response [ 'results' ] ]
objects = list_dicts_to_tabulate ( objects )
if objects :
    Printer . print_header ( "Experiment groups:" )
    objects . pop ( 'project' , None )
    objects . pop ( 'user' , None )
    dict_tabulate ( objects , is_list_dict = True )


signature:
def experiments ( ctx , metrics , declarations , independent , group , query , sort , page ) :
    """List experiments for this project .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 Get all experiments :
 ` ` ` bash
 $ polyaxon project experiments
 Get all experiments with with status { created or running } , and
 creation date between 2018-01-01 and 2018-01-02 , and declarations activation equal to sigmoid
 and metric loss less or equal to 0.2
 ` ` ` bash
 $ polyaxon project experiments - q " status : created | running , started _ at : 2018-01-01 . . 2018-01-02 , declarations . activation : sigmoid , metric . loss : < = 0.2"
 Get all experiments sorted by update date
 ` ` ` bash
 $ polyaxon project experiments - s " - updated _ at " """

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
page = page or 1
try :
    response = PolyaxonClient ( ) . project . list_experiments ( username = user , project_name = project_name , independent = independent , group = group , metrics = metrics , declarations = declarations , query = query , sort = sort , page = page )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not get experiments for project `{}`.' . format ( project_name ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
meta = get_meta_response ( response )
if meta :
    Printer . print_header ( 'Experiments for project `{}/{}`.' . format ( user , project_name ) )
    Printer . print_header ( 'Navigation:' )
    dict_tabulate ( meta )
else :
    Printer . print_header ( 'No experiments found for project `{}/{}`.' . format ( user , project_name ) )
if metrics :
    objects = get_experiments_with_metrics ( response )
elif declarations :
    objects = get_experiments_with_declarations ( response )
else :
    objects = [ Printer . add_status_color ( o . to_light_dict ( humanize_values = True ) ) for o in response [ 'results' ] ]
objects = list_dicts_to_tabulate ( objects )
if objects :
    Printer . print_header ( "Experiments:" )
    objects . pop ( 'project_name' , None )
    dict_tabulate ( objects , is_list_dict = True )


signature:
def git ( ctx , url , private , sync ) : # pylint : disable = assign - to - new - keyword
    """Set / Sync git repo on this project .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon project git - - url = https : / / github . com / polyaxon / polyaxon - quick - start
 ` ` ` bash
 $ polyaxon project git - - url = https : / / github . com / polyaxon / polyaxon - quick - start - - private"""

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
def git_set_url ( ) :
    if private :
        click . echo ( '\nSetting a private git repo "{}" on project: {} ...\n' . format ( url , project_name ) )
    else :
        click . echo ( '\nSetting a public git repo "{}" on project: {} ...\n' . format ( url , project_name ) )
    try :
        PolyaxonClient ( ) . project . set_repo ( user , project_name , url , not private )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not set git repo on project `{}`.' . format ( project_name ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
    Printer . print_success ( 'Project was successfully initialized with `{}`.' . format ( url ) )
def git_sync_repo ( ) :
    try :
        response = PolyaxonClient ( ) . project . sync_repo ( user , project_name )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not sync git repo on project `{}`.' . format ( project_name ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
    click . echo ( response . status_code )
    Printer . print_success ( 'Project was successfully synced with latest changes.' )
if url :
    git_set_url ( )
if sync :
    git_sync_repo ( )


signature:
def ci ( ctx , enable , disable ) : # pylint : disable = assign - to - new - keyword
    """Enable / Disable CI on this project .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon project ci - - enable
 ` ` ` bash
 $ polyaxon project ci - - disable"""

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
def enable_ci ( ) :
    try :
        PolyaxonClient ( ) . project . enable_ci ( user , project_name )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not enable CI on project `{}`.' . format ( project_name ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
    Printer . print_success ( 'Polyaxon CI was successfully enabled on project: `{}`.' . format ( project_name ) )
def disable_ci ( ) :
    try :
        PolyaxonClient ( ) . project . disable_ci ( user , project_name )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not disable CI on project `{}`.' . format ( project_name ) )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
    Printer . print_success ( 'Polyaxon CI was successfully disabled on project: `{}`.' . format ( project_name ) )
if enable :
    enable_ci ( )
if disable :
    disable_ci ( )


signature:
def download ( ctx ) :
    """Download code of the current project ."""

implementation:
user , project_name = get_project_or_local ( ctx . obj . get ( 'project' ) )
try :
    PolyaxonClient ( ) . project . download_repo ( user , project_name )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not download code for project `{}`.' . format ( project_name ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( 'Files downloaded.' )


signature:
def write ( self , file , optstring = "" , quote = False ) :
    """write the ' object ' line ; additional args are packed in string"""

implementation:
classid = str ( self . id )
if quote :
    classid = '"' + classid + '"'
# Only use a * single * space between tokens ; both chimera ' s and pymol ' s DX parser
# does not properly implement the OpenDX specs and produces garbage with multiple
# spaces . ( Chimera 1.4.1 , PyMOL 1.3)
file . write ( 'object ' + classid + ' class ' + str ( self . name ) + ' ' + optstring + '\n' )


signature:
def edges ( self ) :
    """Edges of the grid cells , origin at centre of 0,0 , . . , 0 grid cell .
 Only works for regular , orthonormal grids ."""

implementation: return [ self . delta [ d , d ] * numpy . arange ( self . shape [ d ] + 1 ) + self . origin [ d ] - 0.5 * self . delta [ d , d ] for d in range ( self . rank ) ]


signature:
def write ( self , file ) :
    """Write the * class array * section .
 Parameters
 file : file
 Raises
 ValueError
 If the ` dxtype ` is not a valid type , : exc : ` ValueError ` is
 raised ."""

implementation:
if self . type not in self . dx_types :
    raise ValueError ( ( "DX type {} is not supported in the DX format. \n" "Supported valus are: {}\n" "Use the type=<type> keyword argument." ) . format ( self . type , list ( self . dx_types . keys ( ) ) ) )
typelabel = ( self . typequote + self . type + self . typequote )
DXclass . write ( self , file , 'type {0} rank 0 items {1} data follows' . format ( typelabel , self . array . size ) )
# grid data , serialized as a C array ( z fastest varying )
# ( flat iterator is equivalent to : for x : for y : for z : grid [ x , y , z ] )
# VMD ' s DX reader requires exactly 3 values per line
fmt_string = "{:d}"
if ( self . array . dtype . kind == 'f' or self . array . dtype . kind == 'c' ) :
    precision = numpy . finfo ( self . array . dtype ) . precision
    fmt_string = "{:." + "{:d}" . format ( precision ) + "f}"
values_per_line = 3
values = self . array . flat
while 1 :
    try :
        for i in range ( values_per_line ) :
            file . write ( fmt_string . format ( next ( values ) ) + "\t" )
        file . write ( '\n' )
    except StopIteration :
        file . write ( '\n' )
        break
file . write ( 'attribute "dep" string "positions"\n' )


signature:
def write ( self , filename ) :
    """Write the complete dx object to the file .
 This is the simple OpenDX format which includes the data into
 the header via the ' object array . . . data follows ' statement .
 Only simple regular arrays are supported .
 The format should be compatible with VMD ' s dx reader plugin ."""

implementation:
# comments ( VMD chokes on lines of len > 80 , so truncate )
maxcol = 80
with open ( filename , 'w' ) as outfile :
    for line in self . comments :
        comment = '# ' + str ( line )
        outfile . write ( comment [ : maxcol ] + '\n' )
    # each individual object
    for component , object in self . sorted_components ( ) :
        object . write ( outfile )
    # the field object itself
    DXclass . write ( self , outfile , quote = True )
    for component , object in self . sorted_components ( ) :
        outfile . write ( 'component "%s" value %s\n' % ( component , str ( object . id ) ) )


signature:
def read ( self , file ) :
    """Read DX field from file .
 dx = OpenDX . field . read ( dxfile )
 The classid is discarded and replaced with the one from the file ."""

implementation:
DXfield = self
p = DXParser ( file )
p . parse ( DXfield )


signature:
def sorted_components ( self ) :
    """iterator that returns ( component , object ) in id order"""

implementation:
for component , object in sorted ( self . components . items ( ) , key = lambda comp_obj : comp_obj [ 1 ] . id ) :
    yield component , object


signature:
def histogramdd ( self ) :
    """Return array data as ( edges , grid ) , i . e . a numpy nD histogram ."""

implementation:
shape = self . components [ 'positions' ] . shape
edges = self . components [ 'positions' ] . edges ( )
hist = self . components [ 'data' ] . array . reshape ( shape )
return ( hist , edges )


signature:
def value ( self , ascode = None ) :
    """Return text cast to the correct type or the selected type"""

implementation:
if ascode is None :
    ascode = self . code
return self . cast [ ascode ] ( self . text )


signature:
def initialize ( self ) :
    """Initialize the corresponding DXclass from the data .
 class = DXInitObject . initialize ( )"""

implementation: return self . DXclasses [ self . type ] ( self . id , ** self . args )


signature:
def parse ( self , DXfield ) :
    """Parse the dx file and construct a DX field object with component classes .
 A : class : ` field ` instance * DXfield * must be provided to be
 filled by the parser : :
 DXfield _ object = OpenDX . field ( * args )
 parse ( DXfield _ object )
 A tokenizer turns the dx file into a stream of tokens . A
 hierarchy of parsers examines the stream . The level - 0 parser
 ( ' general ' ) distinguishes comments and objects ( level - 1 ) . The
 object parser calls level - 3 parsers depending on the object
 found . The basic idea is that of a ' state machine ' . There is
 one parser active at any time . The main loop is the general
 parser .
 * Constructing the dx objects with classtype and classid is
 not implemented yet .
 * Unknown tokens raise an exception ."""

implementation:
self . DXfield = DXfield
# OpenDX . field ( used by comment parser )
self . currentobject = None
# containers for data
self . objects = [ ]
self . tokens = [ ]
# token buffer
with open ( self . filename , 'r' ) as self . dxfile :
    self . use_parser ( 'general' )
# parse the whole file and populate self . objects
# assemble field from objects
for o in self . objects :
    if o . type == 'field' : # Almost ignore the field object ; VMD , for instance ,
    # does not write components . To make this work
    # seamlessly I have to think harder how to organize
    # and use the data , eg preping the field object
    # properly and the initializing . Probably should also
    # check uniqueness of ids etc .
        DXfield . id = o . id
        continue
    c = o . initialize ( )
    self . DXfield . add ( c . component , c )
# free space
del self . currentobject , self . objects


signature:
def __general ( self ) :
    """Level - 0 parser and main loop .
 Look for a token that matches a level - 1 parser and hand over control ."""

implementation:
while 1 : # main loop
    try :
        tok = self . __peek ( )
        # only peek , apply _ parser ( ) will consume
    except DXParserNoTokens : # save previous DXInitObject
    # ( kludge in here as the last level - 2 parser usually does not return
    # via the object parser )
        if self . currentobject and self . currentobject not in self . objects :
            self . objects . append ( self . currentobject )
        return
        # stop parsing and finish
    # decision branches for all level - 1 parsers :
    # ( the only way to get out of the lower level parsers ! )
    if tok . iscode ( 'COMMENT' ) :
        self . set_parser ( 'comment' )
        # switch the state
    elif tok . iscode ( 'WORD' ) and tok . equals ( 'object' ) :
        self . set_parser ( 'object' )
        # switch the state
    elif self . __parser is self . __general : # Either a level - 2 parser screwed up or some level - 1
    # construct is not implemented . ( Note : this elif can
    # be only reached at the beginning or after comments ;
    # later we never formally switch back to _ _ general
    # ( would create inifinite loop )
        raise DXParseError ( 'Unknown level-1 construct at ' + str ( tok ) )
    self . apply_parser ( )


signature:
def __comment ( self ) :
    """Level - 1 parser for comments .
 pattern : # . *
 Append comment ( with initial ' # ' stripped ) to all comments ."""

implementation:
tok = self . __consume ( )
self . DXfield . add_comment ( tok . value ( ) )
self . set_parser ( 'general' )


signature:
def __object ( self ) :
    """Level - 1 parser for objects .
 pattern : ' object ' id ' class ' type . . .
 id : : = integer | string | ' " ' white space string ' " '
 type : : = string"""

implementation:
self . __consume ( )
# ' object '
classid = self . __consume ( ) . text
word = self . __consume ( ) . text
if word != "class" :
    raise DXParseError ( "reserved word %s should have been 'class'." % word )
# save previous DXInitObject
if self . currentobject :
    self . objects . append ( self . currentobject )
# setup new DXInitObject
classtype = self . __consume ( ) . text
self . currentobject = DXInitObject ( classtype = classtype , classid = classid )
self . use_parser ( classtype )


signature:
def __gridpositions ( self ) :
    """Level - 2 parser for gridpositions .
 pattern :
 object 1 class gridpositions counts 97 93 99
 origin - 46.5 - 45.5 - 48.5
 delta 1 0 0
 delta 0 1 0
 delta 0 0 1"""

implementation:
try :
    tok = self . __consume ( )
except DXParserNoTokens :
    return
if tok . equals ( 'counts' ) :
    shape = [ ]
    try :
        while True : # raises exception if not an int
            self . __peek ( ) . value ( 'INTEGER' )
            tok = self . __consume ( )
            shape . append ( tok . value ( 'INTEGER' ) )
    except ( DXParserNoTokens , ValueError ) :
        pass
    if len ( shape ) == 0 :
        raise DXParseError ( 'gridpositions: no shape parameters' )
    self . currentobject [ 'shape' ] = shape
elif tok . equals ( 'origin' ) :
    origin = [ ]
    try :
        while ( self . __peek ( ) . iscode ( 'INTEGER' ) or self . __peek ( ) . iscode ( 'REAL' ) ) :
            tok = self . __consume ( )
            origin . append ( tok . value ( ) )
    except DXParserNoTokens :
        pass
    if len ( origin ) == 0 :
        raise DXParseError ( 'gridpositions: no origin parameters' )
    self . currentobject [ 'origin' ] = origin
elif tok . equals ( 'delta' ) :
    d = [ ]
    try :
        while ( self . __peek ( ) . iscode ( 'INTEGER' ) or self . __peek ( ) . iscode ( 'REAL' ) ) :
            tok = self . __consume ( )
            d . append ( tok . value ( ) )
    except DXParserNoTokens :
        pass
    if len ( d ) == 0 :
        raise DXParseError ( 'gridpositions: missing delta parameters' )
    try :
        self . currentobject [ 'delta' ] . append ( d )
    except KeyError :
        self . currentobject [ 'delta' ] = [ d ]
else :
    raise DXParseError ( 'gridpositions: ' + str ( tok ) + ' not recognized.' )


signature:
def __gridconnections ( self ) :
    """Level - 2 parser for gridconnections .
 pattern :
 object 2 class gridconnections counts 97 93 99"""

implementation:
try :
    tok = self . __consume ( )
except DXParserNoTokens :
    return
if tok . equals ( 'counts' ) :
    shape = [ ]
    try :
        while True : # raises exception if not an int
            self . __peek ( ) . value ( 'INTEGER' )
            tok = self . __consume ( )
            shape . append ( tok . value ( 'INTEGER' ) )
    except ( DXParserNoTokens , ValueError ) :
        pass
    if len ( shape ) == 0 :
        raise DXParseError ( 'gridconnections: no shape parameters' )
    self . currentobject [ 'shape' ] = shape
else :
    raise DXParseError ( 'gridconnections: ' + str ( tok ) + ' not recognized.' )


signature:
def __array ( self ) :
    """Level - 2 parser for arrays .
 pattern :
 object 3 class array type double rank 0 items 12 data follows
 0 2 0
 0 0 3.6
 0 - 2.0 1e - 12
 + 4.534e + 01 . 34534 0.43654
 attribute " dep " string " positions " """

implementation:
try :
    tok = self . __consume ( )
except DXParserNoTokens :
    return
if tok . equals ( 'type' ) :
    tok = self . __consume ( )
    if not tok . iscode ( 'STRING' ) :
        raise DXParseError ( 'array: type was "%s", not a string.' % tok . text )
    self . currentobject [ 'type' ] = tok . value ( )
elif tok . equals ( 'rank' ) :
    tok = self . __consume ( )
    try :
        self . currentobject [ 'rank' ] = tok . value ( 'INTEGER' )
    except ValueError :
        raise DXParseError ( 'array: rank was "%s", not an integer.' % tok . text )
elif tok . equals ( 'items' ) :
    tok = self . __consume ( )
    try :
        self . currentobject [ 'size' ] = tok . value ( 'INTEGER' )
    except ValueError :
        raise DXParseError ( 'array: items was "%s", not an integer.' % tok . text )
elif tok . equals ( 'data' ) :
    tok = self . __consume ( )
    if not tok . iscode ( 'STRING' ) :
        raise DXParseError ( 'array: data was "%s", not a string.' % tok . text )
    if tok . text != 'follows' :
        raise NotImplementedError ( 'array: Only the "data follows header" format is supported.' )
    if not self . currentobject [ 'size' ] :
        raise DXParseError ( "array: missing number of items" )
    # This is the slow part . Once we get here , we are just
    # reading in a long list of numbers . Conversion to floats
    # will be done later when the numpy array is created .
    # Don ' t assume anything about whitespace or the number of elements per row
    self . currentobject [ 'array' ] = [ ]
    while len ( self . currentobject [ 'array' ] ) < self . currentobject [ 'size' ] :
        self . currentobject [ 'array' ] . extend ( self . dxfile . readline ( ) . strip ( ) . split ( ) )
    # If you assume that there are three elements per row
    # ( except the last ) the following version works and is a little faster .
    # for i in range ( int ( numpy . ceil ( self . currentobject [ ' size ' ] / 3 ) ) ) :
    # self . currentobject [ ' array ' ] . append ( self . dxfile . readline ( ) )
    # self . currentobject [ ' array ' ] = ' ' . join ( self . currentobject [ ' array ' ] ) . split ( )
elif tok . equals ( 'attribute' ) : # not used at the moment
    attribute = self . __consume ( ) . value ( )
    if not self . __consume ( ) . equals ( 'string' ) :
        raise DXParseError ( 'array: "string" expected.' )
    value = self . __consume ( ) . value ( )
else :
    raise DXParseError ( 'array: ' + str ( tok ) + ' not recognized.' )


signature:
def __field ( self ) :
    """Level - 2 parser for a DX field object .
 pattern :
 object " site map 1 " class field
 component " positions " value 1
 component " connections " value 2
 component " data " value 3"""

implementation:
try :
    tok = self . __consume ( )
except DXParserNoTokens :
    return
if tok . equals ( 'component' ) :
    component = self . __consume ( ) . value ( )
    if not self . __consume ( ) . equals ( 'value' ) :
        raise DXParseError ( 'field: "value" expected' )
    classid = self . __consume ( ) . value ( )
    try :
        self . currentobject [ 'components' ] [ component ] = classid
    except KeyError :
        self . currentobject [ 'components' ] = { component : classid }
else :
    raise DXParseError ( 'field: ' + str ( tok ) + ' not recognized.' )


signature:
def use_parser ( self , parsername ) :
    """Set parsername as the current parser and apply it ."""

implementation:
self . __parser = self . parsers [ parsername ]
self . __parser ( )


signature:
def __tokenize ( self , string ) :
    """Split s into tokens and update the token buffer .
 _ _ tokenize ( string )
 New tokens are appended to the token buffer , discarding white
 space . Based on http : / / effbot . org / zone / xml - scanner . htm"""

implementation:
for m in self . dx_regex . finditer ( string . strip ( ) ) :
    code = m . lastgroup
    text = m . group ( m . lastgroup )
    tok = Token ( code , text )
    if not tok . iscode ( 'WHITESPACE' ) :
        self . tokens . append ( tok )


signature:
def __refill_tokenbuffer ( self ) :
    """Add a new tokenized line from the file to the token buffer .
 _ _ refill _ tokenbuffer ( )
 Only reads a new line if the buffer is empty . It is safe to
 call it repeatedly .
 At end of file , method returns empty strings and it is up to
 _ _ peek and _ _ consume to flag the end of the stream ."""

implementation:
if len ( self . tokens ) == 0 :
    self . __tokenize ( self . dxfile . readline ( ) )


signature:
def read ( self , filename ) :
    """Populate the instance from the plt file * filename * ."""

implementation:
from struct import calcsize , unpack
if not filename is None :
    self . filename = filename
with open ( self . filename , 'rb' ) as plt :
    h = self . header = self . _read_header ( plt )
    nentries = h [ 'nx' ] * h [ 'ny' ] * h [ 'nz' ]
    # quick and dirty . . . slurp it all in one go
    datafmt = h [ 'bsaflag' ] + str ( nentries ) + self . _data_bintype
    a = numpy . array ( unpack ( datafmt , plt . read ( calcsize ( datafmt ) ) ) )
self . header [ 'filename' ] = self . filename
self . array = a . reshape ( h [ 'nz' ] , h [ 'ny' ] , h [ 'nx' ] ) . transpose ( )
# unpack plt in reverse ! !
self . delta = self . _delta ( )
self . origin = numpy . array ( [ h [ 'xmin' ] , h [ 'ymin' ] , h [ 'zmin' ] ] ) + 0.5 * numpy . diagonal ( self . delta )
self . rank = h [ 'rank' ]


signature:
def _read_header ( self , pltfile ) :
    """Read header bytes , try all possibilities for byte order / size / alignment ."""

implementation:
nheader = struct . calcsize ( self . _headerfmt )
names = [ r . key for r in self . _header_struct ]
binheader = pltfile . read ( nheader )
def decode_header ( bsaflag = '@' ) :
    h = dict ( zip ( names , struct . unpack ( bsaflag + self . _headerfmt , binheader ) ) )
    h [ 'bsaflag' ] = bsaflag
    return h
for flag in '@=<>' : # try all endinaness and alignment options until we find something that looks sensible
    header = decode_header ( flag )
    if header [ 'rank' ] == 3 :
        break
        # only legal value according to spec
    header = None
if header is None :
    raise TypeError ( "Cannot decode header --- corrupted or wrong format?" )
for rec in self . _header_struct :
    if not rec . is_legal_dict ( header ) :
        warnings . warn ( "Key %s: Illegal value %r" % ( rec . key , header [ rec . key ] ) )
return header


signature:
def ndmeshgrid ( * arrs ) :
    """Return a mesh grid for N dimensions .
 The input are N arrays , each of which contains the values along one axis of
 the coordinate system . The arrays do not have to have the same number of
 entries . The function returns arrays that can be fed into numpy functions
 so that they produce values for * all * points spanned by the axes * arrs * .
 Original from
 http : / / stackoverflow . com / questions / 1827489 / numpy - meshgrid - in - 3d and fixed .
 . . SeeAlso : : func : ` numpy . meshgrid ` for the 2D case ."""

implementation:
# arrs = tuple ( reversed ( arrs ) ) < - - wrong on stackoverflow . com
arrs = tuple ( arrs )
lens = list ( map ( len , arrs ) )
dim = len ( arrs )
sz = 1
for s in lens :
    sz *= s
ans = [ ]
for i , arr in enumerate ( arrs ) :
    slc = [ 1 ] * dim
    slc [ i ] = lens [ i ]
    arr2 = numpy . asanyarray ( arr ) . reshape ( slc )
    for j , sz in enumerate ( lens ) :
        if j != i :
            arr2 = arr2 . repeat ( sz , axis = j )
    ans . append ( arr2 )
return tuple ( ans )


signature:
def resample ( self , edges ) :
    """Resample data to a new grid with edges * edges * .
 This method creates a new grid with the data from the current
 grid resampled to a regular grid specified by * edges * . The
 order of the interpolation is set by
 : attr : ` Grid . interpolation _ spline _ order ` : change the value
 * before * calling : meth : ` resample ` .
 Parameters
 edges : tuple of arrays or Grid
 edges of the new grid or a : class : ` Grid ` instance that
 provides : attr : ` Grid . edges `
 Returns
 Grid
 a new : class : ` Grid ` with the data interpolated over the
 new grid cells
 Examples
 Providing * edges * ( a tuple of three arrays , indicating the
 boundaries of each grid cell ) : :
 g = grid . resample ( edges )
 As a convenience , one can also supply another : class : ` Grid ` as
 the argument for this method : :
 g = grid . resample ( othergrid )
 and the edges are taken from : attr : ` Grid . edges ` ."""

implementation:
try :
    edges = edges . edges
    # can also supply another Grid
except AttributeError :
    pass
midpoints = self . _midpoints ( edges )
coordinates = ndmeshgrid ( * midpoints )
# feed a meshgrid to generate all points
newgrid = self . interpolated ( * coordinates )
return self . __class__ ( newgrid , edges )


signature:
def resample_factor ( self , factor ) :
    """Resample to a new regular grid .
 Parameters
 factor : float
 The number of grid cells are scaled with ` factor ` in each
 dimension , i . e . , ` ` factor * N _ i ` ` cells along each
 dimension i .
 Returns
 Grid
 See Also
 resample"""

implementation:
# new number of edges N ' = ( N - 1 ) * f + 1
newlengths = [ ( N - 1 ) * float ( factor ) + 1 for N in self . _len_edges ( ) ]
edges = [ numpy . linspace ( start , stop , num = int ( N ) , endpoint = True ) for ( start , stop , N ) in zip ( self . _min_edges ( ) , self . _max_edges ( ) , newlengths ) ]
return self . resample ( edges )


signature:
def _update ( self ) :
    """compute / update all derived data
 Can be called without harm and is idem - potent .
 Updates these attributes and methods :
 : attr : ` origin `
 the center of the cell with index 0,0,0
 : attr : ` midpoints `
 centre coordinate of each grid cell
 : meth : ` interpolated `
 spline interpolation function that can generated a value for
 coordinate"""

implementation:
self . delta = numpy . array ( list ( map ( lambda e : ( e [ - 1 ] - e [ 0 ] ) / ( len ( e ) - 1 ) , self . edges ) ) )
self . midpoints = self . _midpoints ( self . edges )
self . origin = numpy . array ( list ( map ( lambda m : m [ 0 ] , self . midpoints ) ) )
if self . __interpolated is not None : # only update if we are using it
    self . __interpolated = self . _interpolationFunctionFactory ( )


signature:
def interpolated ( self ) :
    """B - spline function over the data grid ( x , y , z ) .
 The : func : ` interpolated ` function allows one to obtain data
 values for any values of the coordinates : :
 interpolated ( [ x1 , x2 , . . . ] , [ y1 , y2 , . . . ] , [ z1 , z2 , . . . ] ) - > F [ x1 , y1 , z1 ] , F [ x2 , y2 , z2 ] , . . .
 The interpolation order is set in
 : attr : ` Grid . interpolation _ spline _ order ` .
 The interpolated function is computed once and is cached for better
 performance . Whenever : attr : ` ~ Grid . interpolation _ spline _ order ` is
 modified , : meth : ` Grid . interpolated ` is recomputed .
 The value for unknown data is set in : attr : ` Grid . interpolation _ cval `
 ( TODO : also recompute when ` ` interpolation _ cval ` ` value is changed . )
 Example
 Example usage for resampling : :
 XX , YY , ZZ = numpy . mgrid [ 40:75:0.5 , 96:150:0.5 , 20:50:0.5]
 FF = interpolated ( XX , YY , ZZ )
 Note
 Values are interpolated with a spline function . It is possible
 that the spline will generate values that would not normally
 appear in the data . For example , a density is non - negative but
 a cubic spline interpolation can generate negative values ,
 especially at the boundary between 0 and high values ."""

implementation:
if self . __interpolated is None :
    self . __interpolated = self . _interpolationFunctionFactory ( )
return self . __interpolated


signature:
def load ( self , filename , file_format = None ) :
    """Load saved ( pickled or dx ) grid and edges from < filename > . pickle
 Grid . load ( < filename > . pickle )
 Grid . load ( < filename > . dx )
 The load ( ) method calls the class ' s constructor method and
 completely resets all values , based on the loaded data ."""

implementation:
loader = self . _get_loader ( filename , file_format = file_format )
loader ( filename )


signature:
def _load_cpp4 ( self , filename ) :
    """Initializes Grid from a CCP4 file ."""

implementation:
ccp4 = CCP4 . CCP4 ( )
ccp4 . read ( filename )
grid , edges = ccp4 . histogramdd ( )
self . __init__ ( grid = grid , edges = edges , metadata = self . metadata )


signature:
def _load_dx ( self , filename ) :
    """Initializes Grid from a OpenDX file ."""

implementation:
dx = OpenDX . field ( 0 )
dx . read ( filename )
grid , edges = dx . histogramdd ( )
self . __init__ ( grid = grid , edges = edges , metadata = self . metadata )


signature:
def _load_plt ( self , filename ) :
    """Initialize Grid from gOpenMol plt file ."""

implementation:
g = gOpenMol . Plt ( )
g . read ( filename )
grid , edges = g . histogramdd ( )
self . __init__ ( grid = grid , edges = edges , metadata = self . metadata )


signature:
def export ( self , filename , file_format = None , type = None , typequote = '"' ) :
    """export density to file using the given format .
 The format can also be deduced from the suffix of the filename
 though the * format * keyword takes precedence .
 The default format for export ( ) is ' dx ' . Use ' dx ' for
 visualization .
 Implemented formats :
 dx
 : mod : ` OpenDX `
 pickle
 pickle ( use : meth : ` Grid . load ` to restore ) ; : meth : ` Grid . save `
 is simpler than ` ` export ( format = ' python ' ) ` ` .
 Parameters
 filename : str
 name of the output file
 file _ format : { ' dx ' , ' pickle ' , None } ( optional )
 output file format , the default is " dx "
 type : str ( optional )
 for DX , set the output DX array type , e . g . , " double " or " float " .
 By default ( ` ` None ` ` ) , the DX type is determined from the numpy
 dtype of the array of the grid ( and this will typically result in
 " double " ) .
 . . versionadded : : 0.4.0
 typequote : str ( optional )
 For DX , set the character used to quote the type string ;
 by default this is a double - quote character , ' " ' .
 Custom parsers like the one from NAMD - GridForces ( backend for MDFF )
 expect no quotes , and typequote = ' ' may be used to appease them .
 . . versionadded : : 0.5.0"""

implementation:
exporter = self . _get_exporter ( filename , file_format = file_format )
exporter ( filename , type = type , typequote = typequote )


signature:
def _export_python ( self , filename , ** kwargs ) :
    """Pickle the Grid object
 The object is dumped as a dictionary with grid and edges : This
 is sufficient to recreate the grid object with _ _ init _ _ ( ) ."""

implementation:
data = dict ( grid = self . grid , edges = self . edges , metadata = self . metadata )
with open ( filename , 'wb' ) as f :
    cPickle . dump ( data , f , cPickle . HIGHEST_PROTOCOL )


signature:
def _export_dx ( self , filename , type = None , typequote = '"' , ** kwargs ) :
    """Export the density grid to an OpenDX file .
 The file format is the simplest regular grid array and it is
 also understood by VMD ' s and Chimera ' s DX reader ; PyMOL
 requires the dx ` type ` to be set to " double " .
 For the file format see
 http : / / opendx . sdsc . edu / docs / html / pages / usrgu068 . htm # HDREDF"""

implementation:
root , ext = os . path . splitext ( filename )
filename = root + '.dx'
comments = [ 'OpenDX density file written by gridDataFormats.Grid.export()' , 'File format: http://opendx.sdsc.edu/docs/html/pages/usrgu068.htm#HDREDF' , 'Data are embedded in the header and tied to the grid positions.' , 'Data is written in C array order: In grid[x,y,z] the axis z is fastest' , 'varying, then y, then finally x, i.e. z is the innermost loop.' ]
# write metadata in comments section
if self . metadata :
    comments . append ( 'Meta data stored with the python Grid object:' )
for k in self . metadata :
    comments . append ( '   ' + str ( k ) + ' = ' + str ( self . metadata [ k ] ) )
comments . append ( '(Note: the VMD dx-reader chokes on comments below this line)' )
components = dict ( positions = OpenDX . gridpositions ( 1 , self . grid . shape , self . origin , self . delta ) , connections = OpenDX . gridconnections ( 2 , self . grid . shape ) , data = OpenDX . array ( 3 , self . grid , type = type , typequote = typequote ) , )
dx = OpenDX . field ( 'density' , components = components , comments = comments )
dx . write ( filename )


signature:
def centers ( self ) :
    """Returns the coordinates of the centers of all grid cells as an
 iterator ."""

implementation:
for idx in numpy . ndindex ( self . grid . shape ) :
    yield self . delta * numpy . array ( idx ) + self . origin


signature:
def check_compatible ( self , other ) :
    """Check if * other * can be used in an arithmetic operation .
 1 ) * other * is a scalar
 2 ) * other * is a grid defined on the same edges
 : Raises : : exc : ` TypeError ` if not compatible ."""

implementation:
if not ( numpy . isreal ( other ) or self == other ) :
    raise TypeError ( "The argument can not be arithmetically combined with the grid. " "It must be a scalar or a grid with identical edges. " "Use Grid.resample(other.edges) to make a new grid that is " "compatible with other." )
return True


signature:
def read ( self , filename ) :
    """Populate the instance from the ccp4 file * filename * ."""

implementation:
if filename is not None :
    self . filename = filename
with open ( self . filename , 'rb' ) as ccp4 :
    h = self . header = self . _read_header ( ccp4 )
    nentries = h [ 'nc' ] * h [ 'nr' ] * h [ 'ns' ]
    # Quick and dirty . . . slurp it all in one go .
    datafmt = h [ 'bsaflag' ] + str ( nentries ) + self . _data_bintype
    a = np . array ( struct . unpack ( datafmt , ccp4 . read ( struct . calcsize ( datafmt ) ) ) )
self . header [ 'filename' ] = self . filename
# TODO : Account for the possibility that y - axis is fastest or
# slowest index , which unfortunately is possible in CCP4.
order = 'C' if h [ 'mapc' ] == 'z' else 'F'
self . array = a . reshape ( h [ 'nc' ] , h [ 'nr' ] , h [ 'ns' ] , order = order )
self . delta = self . _delta ( )
self . origin = np . zeros ( 3 )
self . rank = 3


signature:
def _detect_byteorder ( ccp4file ) :
    """Detect the byteorder of stream ` ccp4file ` and return format character .
 Try all endinaness and alignment options until we find
 something that looks sensible ( " MAPS " in the first 4 bytes ) .
 ( The ` ` machst ` ` field could be used to obtain endianness , but
 it does not specify alignment . )
 . . SeeAlso : :
 : mod : ` struct `"""

implementation:
bsaflag = None
ccp4file . seek ( 52 * 4 )
mapbin = ccp4file . read ( 4 )
for flag in '@=<>' :
    mapstr = struct . unpack ( flag + '4s' , mapbin ) [ 0 ] . decode ( 'utf-8' )
    if mapstr . upper ( ) == 'MAP ' :
        bsaflag = flag
        break
        # Only possible value according to spec .
else :
    raise TypeError ( "Cannot decode header --- corrupted or wrong format?" )
ccp4file . seek ( 0 )
return bsaflag


signature:
def _read_header ( self , ccp4file ) :
    """Read header bytes"""

implementation:
bsaflag = self . _detect_byteorder ( ccp4file )
# Parse the top of the header ( 4 - byte words , 1 to 25 ) .
nheader = struct . calcsize ( self . _headerfmt )
names = [ r . key for r in self . _header_struct ]
bintopheader = ccp4file . read ( 25 * 4 )
def decode_header ( header , bsaflag = '@' ) :
    h = dict ( zip ( names , struct . unpack ( bsaflag + self . _headerfmt , header ) ) )
    h [ 'bsaflag' ] = bsaflag
    return h
header = decode_header ( bintopheader , bsaflag )
for rec in self . _header_struct :
    if not rec . is_legal_dict ( header ) :
        warnings . warn ( "Key %s: Illegal value %r" % ( rec . key , header [ rec . key ] ) )
# Parse the latter half of the header ( 4 - byte words , 26 to 256 ) .
if ( header [ 'lskflg' ] ) :
    skewmatrix = np . fromfile ( ccp4file , dtype = np . float32 , count = 9 )
    header [ 'skwmat' ] = skewmatrix . reshape ( ( 3 , 3 ) )
    header [ 'skwtrn' ] = np . fromfile ( ccp4file , dtype = np . float32 , count = 3 )
else :
    header [ 'skwmat' ] = header [ 'skwtrn' ] = None
    ccp4file . seek ( 12 * 4 , 1 )
ccp4file . seek ( 15 * 4 , 1 )
# Skip future use section .
ccp4file . seek ( 4 , 1 )
# Skip map text , already used above to verify format .
# TODO : Compare file specified endianness to one obtained above .
endiancode = struct . unpack ( bsaflag + '4b' , ccp4file . read ( 4 ) )
header [ 'endianness' ] = 'little' if endiancode == ( 0x44 , 0x41 , 0 , 0 ) else 'big'
header [ 'arms' ] = struct . unpack ( bsaflag + 'f' , ccp4file . read ( 4 ) ) [ 0 ]
header [ 'nlabl' ] = struct . unpack ( bsaflag + 'I' , ccp4file . read ( 4 ) ) [ 0 ]
if header [ 'nlabl' ] :
    binlabel = ccp4file . read ( 80 * header [ 'nlabl' ] )
    flag = bsaflag + str ( 80 * header [ 'nlabl' ] ) + 's'
    label = struct . unpack ( flag , binlabel ) [ 0 ]
    header [ 'label' ] = label . decode ( 'utf-8' ) . rstrip ( '\x00' )
else :
    header [ 'label' ] = None
ccp4file . seek ( 256 * 4 )
# TODO : Parse symmetry records , if any .
return header


signature:
def get_data ( self , ** kwargs ) :
    """Get the data for a specific device for a specific end date
 Keyword Arguments :
 limit - max 288
 end _ date - is Epoch in milliseconds
 : return :"""

implementation:
limit = int ( kwargs . get ( 'limit' , 288 ) )
end_date = kwargs . get ( 'end_date' , False )
if end_date and isinstance ( end_date , datetime . datetime ) :
    end_date = self . convert_datetime ( end_date )
if self . mac_address is not None :
    service_address = 'devices/%s' % self . mac_address
    self . api_instance . log ( 'SERVICE ADDRESS: %s' % service_address )
    data = dict ( limit = limit )
    # If endDate is left blank ( not passed in ) , the most recent results will be returned .
    if end_date :
        data . update ( { 'endDate' : end_date } )
    self . api_instance . log ( 'DATA:' )
    self . api_instance . log ( data )
    return self . api_instance . api_call ( service_address , ** data )


signature:
def get_devices ( self ) :
    """Get all devices
 : return :
 A list of AmbientWeatherStation instances ."""

implementation:
retn = [ ]
api_devices = self . api_call ( 'devices' )
self . log ( 'DEVICES:' )
self . log ( api_devices )
for device in api_devices :
    retn . append ( AmbientWeatherStation ( self , device ) )
self . log ( 'DEVICE INSTANCE LIST:' )
self . log ( retn )
return retn


signature:
def create_url ( self , path , params = { } , opts = { } ) :
    """Create URL with supplied path and ` opts ` parameters dict .
 Parameters
 path : str
 opts : dict
 Dictionary specifying URL parameters . Non - imgix parameters are
 added to the URL unprocessed . For a complete list of imgix
 supported parameters , visit https : / / docs . imgix . com / apis / url .
 ( default { } )
 Returns
 str
 imgix URL"""

implementation:
if opts :
    warnings . warn ( '`opts` has been deprecated. Use `params` instead.' , DeprecationWarning , stacklevel = 2 )
params = params or opts
if self . _shard_strategy == SHARD_STRATEGY_CRC :
    crc = zlib . crc32 ( path . encode ( 'utf-8' ) ) & 0xffffffff
    index = crc % len ( self . _domains )
    # Deterministically choose domain
    domain = self . _domains [ index ]
elif self . _shard_strategy == SHARD_STRATEGY_CYCLE :
    domain = self . _domains [ self . _shard_next_index ]
    self . _shard_next_index = ( self . _shard_next_index + 1 ) % len ( self . _domains )
else :
    domain = self . _domains [ 0 ]
scheme = "https" if self . _use_https else "http"
url_obj = UrlHelper ( domain , path , scheme , sign_key = self . _sign_key , include_library_param = self . _include_library_param , params = params )
return str ( url_obj )


signature:
def set_parameter ( self , key , value ) :
    """Set a url parameter .
 Parameters
 key : str
 If key ends with ' 64 ' , the value provided will be automatically
 base64 encoded ."""

implementation:
if value is None or isinstance ( value , ( int , float , bool ) ) :
    value = str ( value )
if key . endswith ( '64' ) :
    value = urlsafe_b64encode ( value . encode ( 'utf-8' ) )
    value = value . replace ( b ( '=' ) , b ( '' ) )
self . _parameters [ key ] = value


signature:
async def rt_connect ( self , loop ) :
    """Start subscription manager for real time data ."""

implementation:
if self . sub_manager is not None :
    return
self . sub_manager = SubscriptionManager ( loop , "token={}" . format ( self . _access_token ) , SUB_ENDPOINT )
self . sub_manager . start ( )


signature:
async def execute ( self , document , variable_values = None ) :
    """Execute gql ."""

implementation:
res = await self . _execute ( document , variable_values )
if res is None :
    return None
return res . get ( "data" )


signature:
async def _execute ( self , document , variable_values = None , retry = 2 ) :
    """Execute gql ."""

implementation:
query_str = print_ast ( document )
payload = { "query" : query_str , "variables" : variable_values or { } }
post_args = { "headers" : { "Authorization" : "Bearer " + self . _access_token } , "data" : payload , }
try :
    with async_timeout . timeout ( self . _timeout ) :
        resp = await self . websession . post ( API_ENDPOINT , ** post_args )
    if resp . status != 200 :
        _LOGGER . error ( "Error connecting to Tibber, resp code: %s" , resp . status )
        return None
    result = await resp . json ( )
except aiohttp . ClientError as err :
    _LOGGER . error ( "Error connecting to Tibber: %s " , err , exc_info = True )
    if retry > 0 :
        return await self . _execute ( document , variable_values , retry - 1 )
    raise
except asyncio . TimeoutError as err :
    _LOGGER . error ( "Timed out when connecting to Tibber: %s " , err , exc_info = True )
    if retry > 0 :
        return await self . _execute ( document , variable_values , retry - 1 )
    raise
errors = result . get ( "errors" )
if errors :
    _LOGGER . error ( "Received non-compatible response %s" , errors )
return result


signature:
def sync_update_info ( self , * _ ) :
    """Update home info ."""

implementation:
loop = asyncio . get_event_loop ( )
task = loop . create_task ( self . update_info ( ) )
loop . run_until_complete ( task )


signature:
async def update_info ( self , * _ ) :
    """Update home info async ."""

implementation:
query = gql ( """
        {
          viewer {
            name
            homes {
              subscriptions {
                status
              }
              id
            }
          }
        }
        """ )
res = await self . _execute ( query )
if res is None :
    return
errors = res . get ( "errors" , [ ] )
if errors :
    msg = errors [ 0 ] . get ( "message" , "failed to login" )
    _LOGGER . error ( msg )
    raise InvalidLogin ( msg )
data = res . get ( "data" )
if not data :
    return
viewer = data . get ( "viewer" )
if not viewer :
    return
self . _name = viewer . get ( "name" )
homes = viewer . get ( "homes" , [ ] )
self . _home_ids = [ ]
for _home in homes :
    home_id = _home . get ( "id" )
    self . _all_home_ids += [ home_id ]
    subs = _home . get ( "subscriptions" )
    if subs :
        status = subs [ 0 ] . get ( "status" , "ended" ) . lower ( )
        if not home_id or status != "running" :
            continue
    self . _home_ids += [ home_id ]


signature:
def get_homes ( self , only_active = True ) :
    """Return list of Tibber homes ."""

implementation: return [ self . get_home ( home_id ) for home_id in self . get_home_ids ( only_active ) ]


signature:
def get_home ( self , home_id ) :
    """Retun an instance of TibberHome for given home id ."""

implementation:
if home_id not in self . _all_home_ids :
    _LOGGER . error ( "Could not find any Tibber home with id: %s" , home_id )
    return None
if home_id not in self . _homes . keys ( ) :
    self . _homes [ home_id ] = TibberHome ( home_id , self )
return self . _homes [ home_id ]


signature:
async def send_notification ( self , title , message ) :
    """Send notification ."""

implementation:
query = gql ( """
        mutation{
          sendPushNotification(input: {
            title: "%s",
            message: "%s",
          }){
            successful
            pushedToNumberOfDevices
          }
        }
        """ % ( title , message ) )
res = await self . execute ( query )
if not res :
    return False
noti = res . get ( "sendPushNotification" , { } )
successful = noti . get ( "successful" , False )
pushed_to_number_of_devices = noti . get ( "pushedToNumberOfDevices" , 0 )
_LOGGER . debug ( "send_notification: status %s, send to %s devices" , successful , pushed_to_number_of_devices , )
return successful


signature:
async def update_info ( self ) :
    """Update current price info async ."""

implementation:
query = gql ( """
        {
          viewer {
            home(id: "%s") {
              appNickname
              features {
                  realTimeConsumptionEnabled
                }
              currentSubscription {
                status
              }
              address {
                address1
                address2
                address3
                city
                postalCode
                country
                latitude
                longitude
              }
              meteringPointData {
                consumptionEan
                energyTaxType
                estimatedAnnualConsumption
                gridCompany
                productionEan
                vatType
              }
              owner {
                name
                isCompany
                language
                contactInfo {
                  email
                  mobile
                }
              }
              timeZone
              subscriptions {
                id
                status
                validFrom
                validTo
                statusReason
              }
             currentSubscription {
                    priceInfo {
                      current {
                        currency
                      }
                    }
                  }
                }
              }
            }
        """ % self . _home_id )
self . info = await self . _tibber_control . execute ( query )


signature:
def sync_update_current_price_info ( self ) :
    """Update current price info ."""

implementation:
loop = asyncio . get_event_loop ( )
task = loop . create_task ( self . update_current_price_info ( ) )
loop . run_until_complete ( task )


signature:
async def update_current_price_info ( self ) :
    """Update current price info async ."""

implementation:
query = gql ( """
        {
          viewer {
            home(id: "%s") {
              currentSubscription {
                priceInfo {
                  current {
                    energy
                    tax
                    total
                    startsAt
                  }
                }
              }
            }
          }
        }
        """ % self . home_id )
price_info_temp = await self . _tibber_control . execute ( query )
if not price_info_temp :
    _LOGGER . error ( "Could not find current price info." )
    return
try :
    home = price_info_temp [ "viewer" ] [ "home" ]
    current_subscription = home [ "currentSubscription" ]
    price_info = current_subscription [ "priceInfo" ] [ "current" ]
except ( KeyError , TypeError ) :
    _LOGGER . error ( "Could not find current price info." )
    return
if price_info :
    self . _current_price_info = price_info


signature:
def sync_update_price_info ( self ) :
    """Update current price info ."""

implementation:
loop = asyncio . get_event_loop ( )
task = loop . create_task ( self . update_price_info ( ) )
loop . run_until_complete ( task )


signature:
async def update_price_info ( self ) :
    """Update price info async ."""

implementation:
query = gql ( """
        {
          viewer {
            home(id: "%s") {
              currentSubscription {
                priceInfo {
                  current {
                    energy
                    tax
                    total
                    startsAt
                    level
                  }
                  today {
                    total
                    startsAt
                    level
                  }
                  tomorrow {
                    total
                    startsAt
                    level
                  }
                }
              }
            }
          }
        }
        """ % self . home_id )
price_info_temp = await self . _tibber_control . execute ( query )
if not price_info_temp :
    _LOGGER . error ( "Could not find price info." )
    return
self . _price_info = { }
self . _level_info = { }
for key in [ "current" , "today" , "tomorrow" ] :
    try :
        home = price_info_temp [ "viewer" ] [ "home" ]
        current_subscription = home [ "currentSubscription" ]
        price_info = current_subscription [ "priceInfo" ] [ key ]
    except ( KeyError , TypeError ) :
        _LOGGER . error ( "Could not find price info for %s." , key )
        continue
    if key == "current" :
        self . _current_price_info = price_info
        continue
    for data in price_info :
        self . _price_info [ data . get ( "startsAt" ) ] = data . get ( "total" )
        self . _level_info [ data . get ( "startsAt" ) ] = data . get ( "level" )


signature:
def currency ( self ) :
    """Return the currency ."""

implementation:
try :
    current_subscription = self . info [ "viewer" ] [ "home" ] [ "currentSubscription" ]
    return current_subscription [ "priceInfo" ] [ "current" ] [ "currency" ]
except ( KeyError , TypeError , IndexError ) :
    _LOGGER . error ( "Could not find currency." )
return ""


signature:
def price_unit ( self ) :
    """Return the price unit ."""

implementation:
currency = self . currency
consumption_unit = self . consumption_unit
if not currency or not consumption_unit :
    _LOGGER . error ( "Could not find price_unit." )
    return " "
return currency + "/" + consumption_unit


signature:
async def rt_subscribe ( self , loop , async_callback ) :
    """Connect to Tibber and subscribe to Tibber rt subscription ."""

implementation:
if self . _subscription_id is not None :
    _LOGGER . error ( "Already subscribed." )
    return
await self . _tibber_control . rt_connect ( loop )
document = gql ( """
            subscription{
              liveMeasurement(homeId:"%s"){
                timestamp
                power
                powerProduction
                accumulatedProduction
                accumulatedConsumption
                accumulatedCost
                currency
                minPower
                averagePower
                maxPower
                voltagePhase1
                voltagePhase2
                voltagePhase3
                currentPhase1
                currentPhase2
                currentPhase3
                lastMeterConsumption
                lastMeterProduction
            }
           }
        """ % self . home_id )
sub_query = print_ast ( document )
self . _subscription_id = await self . _tibber_control . sub_manager . subscribe ( sub_query , async_callback )


signature:
async def rt_unsubscribe ( self ) :
    """Unsubscribe to Tibber rt subscription ."""

implementation:
if self . _subscription_id is None :
    _LOGGER . error ( "Not subscribed." )
    return
await self . _tibber_control . sub_manager . unsubscribe ( self . _subscription_id )


signature:
def rt_subscription_running ( self ) :
    """Is real time subscription running ."""

implementation: return ( self . _tibber_control . sub_manager is not None and self . _tibber_control . sub_manager . is_running and self . _subscription_id is not None )


signature:
async def get_historic_data ( self , n_data ) :
    """Get historic data ."""

implementation:
query = gql ( """
                {
                  viewer {
                    home(id: "%s") {
                      consumption(resolution: HOURLY, last: %s) {
                        nodes {
                          from
                          totalCost
                          consumption
                        }
                      }
                    }
                  }
                }
          """ % ( self . home_id , n_data ) )
data = await self . _tibber_control . execute ( query )
if not data :
    _LOGGER . error ( "Could not find current the data." )
    return
data = data [ "viewer" ] [ "home" ] [ "consumption" ]
if data is None :
    self . _data = [ ]
    return
self . _data = data [ "nodes" ]


signature:
def sync_get_historic_data ( self , n_data ) :
    """get _ historic _ data ."""

implementation:
loop = asyncio . get_event_loop ( )
task = loop . create_task ( self . get_historic_data ( n_data ) )
loop . run_until_complete ( task )
return self . _data


signature:
def cleanup_none ( self ) :
    """Removes the temporary value set for None attributes ."""

implementation:
for ( prop , default ) in self . defaults . items ( ) :
    if getattr ( self , prop ) == '_None' :
        setattr ( self , prop , None )


signature:
def build_environ ( self , sock_file , conn ) :
    """Build the execution environment ."""

implementation:
# Grab the request line
request = self . read_request_line ( sock_file )
# Copy the Base Environment
environ = self . base_environ . copy ( )
# Grab the headers
for k , v in self . read_headers ( sock_file ) . items ( ) :
    environ [ str ( 'HTTP_' + k ) ] = v
# Add CGI Variables
environ [ 'REQUEST_METHOD' ] = request [ 'method' ]
environ [ 'PATH_INFO' ] = request [ 'path' ]
environ [ 'SERVER_PROTOCOL' ] = request [ 'protocol' ]
environ [ 'SERVER_PORT' ] = str ( conn . server_port )
environ [ 'REMOTE_PORT' ] = str ( conn . client_port )
environ [ 'REMOTE_ADDR' ] = str ( conn . client_addr )
environ [ 'QUERY_STRING' ] = request [ 'query_string' ]
if 'HTTP_CONTENT_LENGTH' in environ :
    environ [ 'CONTENT_LENGTH' ] = environ [ 'HTTP_CONTENT_LENGTH' ]
if 'HTTP_CONTENT_TYPE' in environ :
    environ [ 'CONTENT_TYPE' ] = environ [ 'HTTP_CONTENT_TYPE' ]
# Save the request method for later
self . request_method = environ [ 'REQUEST_METHOD' ]
# Add Dynamic WSGI Variables
if conn . ssl :
    environ [ 'wsgi.url_scheme' ] = 'https'
    environ [ 'HTTPS' ] = 'on'
else :
    environ [ 'wsgi.url_scheme' ] = 'http'
if environ . get ( 'HTTP_TRANSFER_ENCODING' , '' ) == 'chunked' :
    environ [ 'wsgi.input' ] = ChunkedReader ( sock_file )
else :
    environ [ 'wsgi.input' ] = sock_file
return environ


signature:
def write ( self , data , sections = None ) :
    """Write the data to the output socket ."""

implementation:
if self . error [ 0 ] :
    self . status = self . error [ 0 ]
    data = b ( self . error [ 1 ] )
if not self . headers_sent :
    self . send_headers ( data , sections )
if self . request_method != 'HEAD' :
    try :
        if self . chunked :
            self . conn . sendall ( b ( '%x\r\n%s\r\n' % ( len ( data ) , data ) ) )
        else :
            self . conn . sendall ( data )
    except socket . timeout :
        self . closeConnection = True
    except socket . error : # But some clients will close the connection before that
    # resulting in a socket error .
        self . closeConnection = True


signature:
def start_response ( self , status , response_headers , exc_info = None ) :
    """Store the HTTP status and headers to be sent when self . write is
 called ."""

implementation:
if exc_info :
    try :
        if self . headers_sent : # Re - raise original exception if headers sent
        # because this violates WSGI specification .
            raise
    finally :
        exc_info = None
elif self . header_set :
    raise AssertionError ( "Headers already set!" )
if PY3K and not isinstance ( status , str ) :
    self . status = str ( status , 'ISO-8859-1' )
else :
    self . status = status
# Make sure headers are bytes objects
try :
    self . header_set = Headers ( response_headers )
except UnicodeDecodeError :
    self . error = ( '500 Internal Server Error' , 'HTTP Headers should be bytes' )
    self . err_log . error ( 'Received HTTP Headers from client that contain' ' invalid characters for Latin-1 encoding.' )
return self . write_warning


signature:
def CherryPyWSGIServer ( bind_addr , wsgi_app , numthreads = 10 , server_name = None , max = - 1 , request_queue_size = 5 , timeout = 10 , shutdown_timeout = 5 ) :
    """A Cherrypy wsgiserver - compatible wrapper ."""

implementation:
max_threads = max
if max_threads < 0 :
    max_threads = 0
return Rocket ( bind_addr , 'wsgi' , { 'wsgi_app' : wsgi_app } , min_threads = numthreads , max_threads = max_threads , queue_size = request_queue_size , timeout = timeout )


signature:
def aggregate ( l ) :
    """Aggregate a ` list ` of prefixes .
 Keyword arguments :
 l - - a python list of prefixes
 Example use :
 > > > aggregate ( [ " 10.0.0.0/8 " , " 10.0.0.0/24 " ] )
 [ ' 10.0.0.0/8 ' ]"""

implementation:
tree = radix . Radix ( )
for item in l :
    try :
        tree . add ( item )
    except ( ValueError ) as err :
        raise Exception ( "ERROR: invalid IP prefix: {}" . format ( item ) )
return aggregate_tree ( tree ) . prefixes ( )


signature:
def aggregate_tree ( l_tree ) :
    """Walk a py - radix tree and aggregate it .
 Arguments
 l _ tree - - radix . Radix ( ) object"""

implementation:
def _aggregate_phase1 ( tree ) : # phase1 removes any supplied prefixes which are superfluous because
# they are already included in another supplied prefix . For example ,
# 2001:67c : 208c : 10 : : / 64 would be removed if 2001:67c : 208c : : / 48 was
# also supplied .
    n_tree = radix . Radix ( )
    for prefix in tree . prefixes ( ) :
        if tree . search_worst ( prefix ) . prefix == prefix :
            n_tree . add ( prefix )
    return n_tree
def _aggregate_phase2 ( tree ) : # phase2 identifies adjacent prefixes that can be combined under a
# single , shorter - length prefix . For example , 2001:67c : 208c : : / 48 and
# 2001:67c : 208d : : / 48 can be combined into the single prefix
# 2001:67c : 208c : : / 47.
    n_tree = radix . Radix ( )
    for rnode in tree :
        p = text ( ip_network ( text ( rnode . prefix ) ) . supernet ( ) )
        r = tree . search_covered ( p )
        if len ( r ) == 2 :
            if r [ 0 ] . prefixlen == r [ 1 ] . prefixlen == rnode . prefixlen :
                n_tree . add ( p )
            else :
                n_tree . add ( rnode . prefix )
        else :
            n_tree . add ( rnode . prefix )
    return n_tree
l_tree = _aggregate_phase1 ( l_tree )
if len ( l_tree . prefixes ( ) ) == 1 :
    return l_tree
while True :
    r_tree = _aggregate_phase2 ( l_tree )
    if l_tree . prefixes ( ) == r_tree . prefixes ( ) :
        break
    else :
        l_tree = r_tree
        del r_tree
return l_tree


signature:
def _ordinal_metric ( _v1 , _v2 , i1 , i2 , n_v ) :
    """Metric for ordinal data ."""


signature:
def _ratio_metric ( v1 , v2 , ** _kwargs ) :
    """Metric for ratio data ."""


signature:
def _coincidences ( value_counts , value_domain , dtype = np . float64 ) :
    """Coincidence matrix .
 Parameters
 value _ counts : ndarray , with shape ( N , V )
 Number of coders that assigned a certain value to a determined unit , where N is the number of units
 and V is the value count .
 value _ domain : array _ like , with shape ( V , )
 Possible values V the units can take .
 If the level of measurement is not nominal , it must be ordered .
 dtype : data - type
 Result and computation data - type .
 Returns
 o : ndarray , with shape ( V , V )
 Coincidence matrix ."""

implementation:
value_counts_matrices = value_counts . reshape ( value_counts . shape + ( 1 , ) )
pairable = np . maximum ( np . sum ( value_counts , axis = 1 ) , 2 )
diagonals = np . tile ( np . eye ( len ( value_domain ) ) , ( len ( value_counts ) , 1 , 1 ) ) * value_counts . reshape ( ( value_counts . shape [ 0 ] , 1 , value_counts . shape [ 1 ] ) )
unnormalized_coincidences = value_counts_matrices * value_counts_matrices . transpose ( ( 0 , 2 , 1 ) ) - diagonals
return np . sum ( np . divide ( unnormalized_coincidences , ( pairable - 1 ) . reshape ( ( - 1 , 1 , 1 ) ) , dtype = dtype ) , axis = 0 )


signature:
def _random_coincidences ( value_domain , n , n_v ) :
    """Random coincidence matrix .
 Parameters
 value _ domain : array _ like , with shape ( V , )
 Possible values V the units can take .
 If the level of measurement is not nominal , it must be ordered .
 n : scalar
 Number of pairable values .
 n _ v : ndarray , with shape ( V , )
 Number of pairable elements for each value .
 Returns
 e : ndarray , with shape ( V , V )
 Random coincidence matrix ."""

implementation:
n_v_column = n_v . reshape ( - 1 , 1 )
return ( n_v_column . dot ( n_v_column . T ) - np . eye ( len ( value_domain ) ) * n_v_column ) / ( n - 1 )


signature:
def _distances ( value_domain , distance_metric , n_v ) :
    """Distances of the different possible values .
 Parameters
 value _ domain : array _ like , with shape ( V , )
 Possible values V the units can take .
 If the level of measurement is not nominal , it must be ordered .
 distance _ metric : callable
 Callable that return the distance of two given values .
 n _ v : ndarray , with shape ( V , )
 Number of pairable elements for each value .
 Returns
 d : ndarray , with shape ( V , V )
 Distance matrix for each value pair ."""

implementation: return np . array ( [ [ distance_metric ( v1 , v2 , i1 = i1 , i2 = i2 , n_v = n_v ) for i2 , v2 in enumerate ( value_domain ) ] for i1 , v1 in enumerate ( value_domain ) ] )


signature:
def _reliability_data_to_value_counts ( reliability_data , value_domain ) :
    """Return the value counts given the reliability data .
 Parameters
 reliability _ data : ndarray , with shape ( M , N )
 Reliability data matrix which has the rate the i coder gave to the j unit , where M is the number of raters
 and N is the unit count .
 Missing rates are represented with ` np . nan ` .
 value _ domain : array _ like , with shape ( V , )
 Possible values the units can take .
 Returns
 value _ counts : ndarray , with shape ( N , V )
 Number of coders that assigned a certain value to a determined unit , where N is the number of units
 and V is the value count ."""

implementation: return np . array ( [ [ sum ( 1 for rate in unit if rate == v ) for v in value_domain ] for unit in reliability_data . T ] )


signature:
def alpha ( reliability_data = None , value_counts = None , value_domain = None , level_of_measurement = 'interval' , dtype = np . float64 ) :
    """Compute Krippendorff ' s alpha .
 See https : / / en . wikipedia . org / wiki / Krippendorff % 27s _ alpha for more information .
 Parameters
 reliability _ data : array _ like , with shape ( M , N )
 Reliability data matrix which has the rate the i coder gave to the j unit , where M is the number of raters
 and N is the unit count .
 Missing rates are represented with ` np . nan ` .
 If it ' s provided then ` value _ counts ` must not be provided .
 value _ counts : ndarray , with shape ( N , V )
 Number of coders that assigned a certain value to a determined unit , where N is the number of units
 and V is the value count .
 If it ' s provided then ` reliability _ data ` must not be provided .
 value _ domain : array _ like , with shape ( V , )
 Possible values the units can take .
 If the level of measurement is not nominal , it must be ordered .
 If ` reliability _ data ` is provided , then the default value is the ordered list of unique rates that appear .
 Else , the default value is ` list ( range ( V ) ) ` .
 level _ of _ measurement : string or callable
 Steven ' s level of measurement of the variable .
 It must be one of ' nominal ' , ' ordinal ' , ' interval ' , ' ratio ' or a callable .
 dtype : data - type
 Result and computation data - type .
 Returns
 alpha : ` dtype `
 Scalar value of Krippendorff ' s alpha of type ` dtype ` .
 Examples
 > > > reliability _ data = [ [ np . nan , np . nan , np . nan , np . nan , np . nan , 3 , 4 , 1 , 2 , 1 , 1 , 3 , 3 , np . nan , 3 ] ,
 . . . [ 1 , np . nan , 2 , 1 , 3 , 3 , 4 , 3 , np . nan , np . nan , np . nan , np . nan , np . nan , np . nan , np . nan ] ,
 . . . [ np . nan , np . nan , 2 , 1 , 3 , 4 , 4 , np . nan , 2 , 1 , 1 , 3 , 3 , np . nan , 4 ] ]
 > > > print ( round ( alpha ( reliability _ data = reliability _ data , level _ of _ measurement = ' nominal ' ) , 6 ) )
 0.691358
 > > > print ( round ( alpha ( reliability _ data = reliability _ data , level _ of _ measurement = ' interval ' ) , 6 ) )
 0.810845
 > > > value _ counts = np . array ( [ [ 1 , 0 , 0 , 0 ] ,
 . . . [ 0 , 0 , 0 , 0 ] ,
 . . . [ 0 , 2 , 0 , 0 ] ,
 . . . [ 2 , 0 , 0 , 0 ] ,
 . . . [ 0 , 0 , 2 , 0 ] ,
 . . . [ 0 , 0 , 2 , 1 ] ,
 . . . [ 0 , 0 , 0 , 3 ] ,
 . . . [ 1 , 0 , 1 , 0 ] ,
 . . . [ 0 , 2 , 0 , 0 ] ,
 . . . [ 2 , 0 , 0 , 0 ] ,
 . . . [ 2 , 0 , 0 , 0 ] ,
 . . . [ 0 , 0 , 2 , 0 ] ,
 . . . [ 0 , 0 , 2 , 0 ] ,
 . . . [ 0 , 0 , 0 , 0 ] ,
 . . . [ 0 , 0 , 1 , 1 ] ] )
 > > > print ( round ( alpha ( value _ counts = value _ counts , level _ of _ measurement = ' nominal ' ) , 6 ) )
 0.691358
 > > > # The following examples were extracted from
 > > > # https : / / www . statisticshowto . datasciencecentral . com / wp - content / uploads / 2016/07 / fulltext . pdf , page 8.
 > > > reliability _ data = [ [ 1 , 2 , 3 , 3 , 2 , 1 , 4 , 1 , 2 , np . nan , np . nan , np . nan ] ,
 . . . [ 1 , 2 , 3 , 3 , 2 , 2 , 4 , 1 , 2 , 5 , np . nan , 3 . ] ,
 . . . [ np . nan , 3 , 3 , 3 , 2 , 3 , 4 , 2 , 2 , 5 , 1 , np . nan ] ,
 . . . [ 1 , 2 , 3 , 3 , 2 , 4 , 4 , 1 , 2 , 5 , 1 , np . nan ] ]
 > > > print ( round ( alpha ( reliability _ data , level _ of _ measurement = ' ordinal ' ) , 3 ) )
 0.815
 > > > print ( round ( alpha ( reliability _ data , level _ of _ measurement = ' ratio ' ) , 3 ) )
 0.797"""

implementation:
if ( reliability_data is None ) == ( value_counts is None ) :
    raise ValueError ( "Either reliability_data or value_counts must be provided, but not both." )
# Don ' t know if it ' s a list or numpy array . If it ' s the latter , the truth value is ambiguous . So , ask for None .
if value_counts is None :
    if type ( reliability_data ) is not np . ndarray :
        reliability_data = np . array ( reliability_data )
    value_domain = value_domain or np . unique ( reliability_data [ ~ np . isnan ( reliability_data ) ] )
    value_counts = _reliability_data_to_value_counts ( reliability_data , value_domain )
else : # elif reliability _ data is None
    if value_domain :
        assert value_counts . shape [ 1 ] == len ( value_domain ) , "The value domain should be equal to the number of columns of value_counts."
    else :
        value_domain = tuple ( range ( value_counts . shape [ 1 ] ) )
distance_metric = _distance_metric ( level_of_measurement )
o = _coincidences ( value_counts , value_domain , dtype = dtype )
n_v = np . sum ( o , axis = 0 )
n = np . sum ( n_v )
e = _random_coincidences ( value_domain , n , n_v )
d = _distances ( value_domain , distance_metric , n_v )
return 1 - np . sum ( o * d ) / np . sum ( e * d )


signature:
def inquire ( self ) :
    """Maps to fortran CDF _ Inquire .
 Assigns parameters returned by CDF _ Inquire
 to pysatCDF instance . Not intended
 for regular direct use by user ."""

implementation:
name = copy . deepcopy ( self . fname )
stats = fortran_cdf . inquire ( name )
# break out fortran output into something meaningful
status = stats [ 0 ]
if status == 0 :
    self . _num_dims = stats [ 1 ]
    self . _dim_sizes = stats [ 2 ]
    self . _encoding = stats [ 3 ]
    self . _majority = stats [ 4 ]
    self . _max_rec = stats [ 5 ]
    self . _num_r_vars = stats [ 6 ]
    self . _num_z_vars = stats [ 7 ]
    self . _num_attrs = stats [ 8 ]
else :
    raise IOError ( fortran_cdf . statusreporter ( status ) )


signature:
def _read_all_z_variable_info ( self ) :
    """Gets all CDF z - variable information , not data though .
 Maps to calls using var _ inquire . Gets information on
 data type , number of elements , number of dimensions , etc ."""

implementation:
self . z_variable_info = { }
self . z_variable_names_by_num = { }
# call Fortran that grabs all of the basic stats on all of the
# zVariables in one go .
info = fortran_cdf . z_var_all_inquire ( self . fname , self . _num_z_vars , len ( self . fname ) )
status = info [ 0 ]
data_types = info [ 1 ]
num_elems = info [ 2 ]
rec_varys = info [ 3 ]
dim_varys = info [ 4 ]
num_dims = info [ 5 ]
dim_sizes = info [ 6 ]
rec_nums = info [ 7 ]
var_nums = info [ 8 ]
var_names = info [ 9 ]
if status == 0 :
    for i in np . arange ( len ( data_types ) ) :
        out = { }
        out [ 'data_type' ] = data_types [ i ]
        out [ 'num_elems' ] = num_elems [ i ]
        out [ 'rec_vary' ] = rec_varys [ i ]
        out [ 'dim_varys' ] = dim_varys [ i ]
        out [ 'num_dims' ] = num_dims [ i ]
        # only looking at first possible extra dimension
        out [ 'dim_sizes' ] = dim_sizes [ i , : 1 ]
        if out [ 'dim_sizes' ] [ 0 ] == 0 :
            out [ 'dim_sizes' ] [ 0 ] += 1
        out [ 'rec_num' ] = rec_nums [ i ]
        out [ 'var_num' ] = var_nums [ i ]
        var_name = '' . join ( var_names [ i ] . astype ( 'U' ) )
        out [ 'var_name' ] = var_name . rstrip ( )
        self . z_variable_info [ out [ 'var_name' ] ] = out
        self . z_variable_names_by_num [ out [ 'var_num' ] ] = var_name
else :
    raise IOError ( fortran_cdf . statusreporter ( status ) )