Instruction:
Can you create a Python 3 function that
commands for build jobs.

Response:
def build(ctx, project, build):  # pylint:disable=redefined-outer-name
    """Commands for build jobs."""
    ctx.obj = ctx.obj or {}
    ctx.obj['project'] = project
    ctx.obj['build'] = build


Instruction:
Write a Python 3 script for
getting a build job.

Response:
def get(ctx):
    """Get build job.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Examples:

    \b
    ```bash
    $ polyaxon build -b 1 get
    ```

    \b
    ```bash
    $ polyaxon build --build=1 --project=project_name get
    ```
    """
    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))
    try:
        response = PolyaxonClient().build_job.get_build(user, project_name, _build)
        cache.cache(config_manager=BuildJobManager, response=response)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not get build job `{}`.'.format(_build))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    get_build_details(response)


Instruction:
Create a Python 3 function to
delete a build job.

Response:
def delete(ctx):
    """Delete build job.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Example:

    \b
    ```bash
    $ polyaxon build delete
    ```

    \b
    ```bash
    $ polyaxon build -b 2 delete
    ```
    """
    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))
    if not click.confirm("Are sure you want to delete build job `{}`".format(_build)):
        click.echo('Existing without deleting build job.')
        sys.exit(1)

    try:
        response = PolyaxonClient().build_job.delete_build(
            user, project_name, _build)
        # Purge caching
        BuildJobManager.purge()
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not delete job `{}`.'.format(_build))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    if response.status_code == 204:
        Printer.print_success("Build job `{}` was deleted successfully".format(_build))


Instruction:
Write a Python 3 script to
update build. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon build -b 2 update --description="new description for my build" ```

Response:
def update(ctx, name, description, tags):
    """Update build.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Example:

    \b
    ```bash
    $ polyaxon build -b 2 update --description="new description for my build"
    ```
    """
    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))
    update_dict = {}

    if name:
        update_dict['name'] = name

    if description:
        update_dict['description'] = description

    tags = validate_tags(tags)
    if tags:
        update_dict['tags'] = tags

    if not update_dict:
        Printer.print_warning('No argument was provided to update the build.')
        sys.exit(0)

    try:
        response = PolyaxonClient().build_job.update_build(
            user, project_name, _build, update_dict)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not update build `{}`.'.format(_build))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    Printer.print_success("Build updated.")
    get_build_details(response)


Instruction:
Can you implement a function in Python 3 that
stops a build job.

Response:
def stop(ctx, yes):
    """Stop build job.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Examples:

    \b
    ```bash
    $ polyaxon build stop
    ```

    \b
    ```bash
    $ polyaxon build -b 2 stop
    ```
    """
    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))
    if not yes and not click.confirm("Are sure you want to stop "
                                     "job `{}`".format(_build)):
        click.echo('Existing without stopping build job.')
        sys.exit(0)

    try:
        PolyaxonClient().build_job.stop(user, project_name, _build)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not stop build job `{}`.'.format(_build))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    Printer.print_success("Build job is being stopped.")


Instruction:
Write a Python 3 function that can
bookmark build job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon build bookmark ``` \b ```bash $ polyaxon build -b 2 bookmark ```

Response:
def bookmark(ctx):
    """Bookmark build job.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Examples:

    \b
    ```bash
    $ polyaxon build bookmark
    ```

    \b
    ```bash
    $ polyaxon build -b 2 bookmark
    ```
    """
    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))
    try:
        PolyaxonClient().build_job.bookmark(user, project_name, _build)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not bookmark build job `{}`.'.format(_build))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    Printer.print_success("Build job bookmarked.")


Instruction:
How would you code a function in Python 3 to
get build job resources.

Response:
def resources(ctx, gpu):
    """Get build job resources.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Examples:

    \b
    ```bash
    $ polyaxon build -b 2 resources
    ```

    For GPU resources

    \b
    ```bash
    $ polyaxon build -b 2 resources --gpu
    ```
    """
    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))
    try:
        message_handler = Printer.gpu_resources if gpu else Printer.resources
        PolyaxonClient().build_job.resources(user,
                                             project_name,
                                             _build,
                                             message_handler=message_handler)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not get resources for build job `{}`.'.format(_build))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)


Instruction:
How would you explain what the following Python 3 function does
def init(project, polyaxonfile):
    user, project_name = get_project_or_local(project)
    try:
        project_config = PolyaxonClient().project.get_project(user, project_name)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Make sure you have a project with this name `{}`'.format(project))
        Printer.print_error(
            'You can a create new project with this command: '
            'polyaxon project create '
            '--name={} [--description=...] [--tags=...]'.format(project_name))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    init_project = False
    if ProjectManager.is_initialized():
        local_project = ProjectManager.get_config()
        click.echo('Warning! This project is already initialized with the following project:')
        with clint.textui.indent(4):
            clint.textui.puts('User: {}'.format(local_project.user))
            clint.textui.puts('Project: {}'.format(local_project.name))
        if click.confirm('Would you like to override this current config?', default=False):
            init_project = True
    else:
        init_project = True

    if init_project:
        ProjectManager.purge()
        ProjectManager.set_config(project_config, init=True)
        Printer.print_success('Project was initialized')
    else:
        Printer.print_header('Project config was not changed.')

    init_ignore = False
    if IgnoreManager.is_initialized():
        click.echo('Warning! Found a .polyaxonignore file.')
        if click.confirm('Would you like to override it?', default=False):
            init_ignore = True
    else:
        init_ignore = True

    if init_ignore:
        IgnoreManager.init_config()
        Printer.print_success('New .polyaxonignore file was created.')
    else:
        Printer.print_header('.polyaxonignore file was not changed.')

    if polyaxonfile:
        create_polyaxonfile()

Response: Initialize a new polyaxonfile specification.


Instruction:
How would you explain what the following Python 3 function does
def run(ctx, project, file, name, tags, description, ttl, u, l):  # pylint:disable=redefined-builtin
    if not file:
        file = PolyaxonFile.check_default_path(path='.')
    if not file:
        file = ''
    specification = check_polyaxonfile(file, log=False).specification

    spec_cond = (specification.is_experiment or
                 specification.is_group or
                 specification.is_job or
                 specification.is_build)
    if not spec_cond:
        Printer.print_error(
            'This command expects an experiment, a group, a job, or a build specification,'
            'received instead a `{}` specification'.format(specification.kind))
        if specification.is_notebook:
            click.echo('Please check "polyaxon notebook --help" to start a notebook.')
        elif specification.is_tensorboard:
            click.echo('Please check: "polyaxon tensorboard --help" to start a tensorboard.')
        sys.exit(1)

    # Check if we need to upload
    if u:
        if project:
            Printer.print_error('Uploading is not supported when switching project context!')
            click.echo('Please, either omit the `-u` option or `-p` / `--project=` option.')
            sys.exit(1)
        ctx.invoke(upload, sync=False)

    user, project_name = get_project_or_local(project)
    project_client = PolyaxonClient().project

    tags = validate_tags(tags)

    def run_experiment():
        click.echo('Creating an independent experiment.')
        experiment = ExperimentConfig(
            name=name,
            description=description,
            tags=tags,
            config=specification.parsed_data,
            ttl=ttl)
        try:
            response = PolyaxonClient().project.create_experiment(user,
                                                                  project_name,
                                                                  experiment)
            cache.cache(config_manager=ExperimentManager, response=response)
            Printer.print_success('Experiment `{}` was created'.format(response.id))
        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
            Printer.print_error('Could not create experiment.')
            Printer.print_error('Error message `{}`.'.format(e))
            sys.exit(1)

    def run_group():
        click.echo('Creating an experiment group with the following definition:')
        experiments_def = specification.experiments_def
        get_group_experiments_info(**experiments_def)
        experiment_group = ExperimentGroupConfig(
            name=name,
            description=description,
            tags=tags,
            content=specification._data)  # pylint:disable=protected-access
        try:
            response = project_client.create_experiment_group(user,
                                                              project_name,
                                                              experiment_group)
            cache.cache(config_manager=GroupManager, response=response)
            Printer.print_success('Experiment group {} was created'.format(response.id))
        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
            Printer.print_error('Could not create experiment group.')
            Printer.print_error('Error message `{}`.'.format(e))
            sys.exit(1)

    def run_job():
        click.echo('Creating a job.')
        job = JobConfig(
            name=name,
            description=description,
            tags=tags,
            config=specification.parsed_data,
            ttl=ttl)
        try:
            response = project_client.create_job(user,
                                                 project_name,
                                                 job)
            cache.cache(config_manager=JobManager, response=response)
            Printer.print_success('Job {} was created'.format(response.id))
        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
            Printer.print_error('Could not create job.')
            Printer.print_error('Error message `{}`.'.format(e))
            sys.exit(1)

    def run_build():
        click.echo('Creating a build.')
        job = JobConfig(
            name=name,
            description=description,
            tags=tags,
            config=specification.parsed_data,
            ttl=ttl)
        try:
            response = project_client.create_build(user,
                                                   project_name,
                                                   job)
            cache.cache(config_manager=BuildJobManager, response=response)
            Printer.print_success('Build {} was created'.format(response.id))
        except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
            Printer.print_error('Could not create build.')
            Printer.print_error('Error message `{}`.'.format(e))
            sys.exit(1)

    logs = None
    if specification.is_experiment:
        run_experiment()
        logs = experiment_logs
    elif specification.is_group:
        run_group()
    elif specification.is_job:
        run_job()
        logs = job_logs
    elif specification.is_build:
        run_build()
        logs = build_logs

    # Check if we need to invoke logs
    if l and logs:
        ctx.obj = {'project': '{}/{}'.format(user, project_name)}
        ctx.invoke(logs)

Response: Run a single polyaxon file.


Instruction:
Make a summary of the following Python 3 code
def projects(ctx, page):
    user = get_username_or_local(ctx.obj.get('username'))

    page = page or 1
    try:
        response = PolyaxonClient().bookmark.projects(username=user, page=page)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error(
            'Could not get bookmarked projects for user `{}`.'.format(user))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    meta = get_meta_response(response)
    if meta:
        Printer.print_header('Bookmarked projects for user `{}`.'.format(user))
        Printer.print_header('Navigation:')
        dict_tabulate(meta)
    else:
        Printer.print_header('No bookmarked projects found for user `{}`.'.format(user))

    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("Projects:")
        dict_tabulate(objects, is_list_dict=True)

Response: List bookmarked projects for a user.


Instruction:
Write a Python 3 function for
removing trailing spaces unless they are quoted with a backslash.

Response:
def _remove_trailing_spaces(line):
        """Remove trailing spaces unless they are quoted with a backslash."""
        while line.endswith(' ') and not line.endswith('\\ '):
            line = line[:-1]
        return line.replace('\\ ', ' ')


Instruction:
Can you write a function in Python 3 where it
yields all matching patterns for path.

Response:
def find_matching(cls, path, patterns):
        """Yield all matching patterns for path."""
        for pattern in patterns:
            if pattern.match(path):
                yield pattern


Instruction:
How would you implement a function in Python 3 that
checks whether a path is ignored. For directories include a trailing slash.

Response:
def is_ignored(cls, path, patterns):
        """Check whether a path is ignored. For directories, include a trailing slash."""
        status = None
        for pattern in cls.find_matching(path, patterns):
            status = pattern.is_exclude
        return status


Instruction:
Explain what the following Python 3 code does
def _matches_patterns(path, patterns):
        for glob in patterns:
            try:
                if PurePath(path).match(glob):
                    return True
            except TypeError:
                pass
        return False

Response: Returns a if a path matches any pattern.


Instruction:
Implement a Python 3 function for
returning a whether a path should be ignored or not.

Response:
def _ignore_path(cls, path, ignore_list=None, white_list=None):
        """Returns a whether a path should be ignored or not."""
        ignore_list = ignore_list or []
        white_list = white_list or []
        return (cls._matches_patterns(path, ignore_list) and
                not cls._matches_patterns(path, white_list))


Instruction:
Here you have a function in Python 3, explain what it does
def group(ctx, project, group):  # pylint:disable=redefined-outer-name
    ctx.obj = ctx.obj or {}
    ctx.obj['project'] = project
    ctx.obj['group'] = group

Response: Commands for experiment groups.


Instruction:
How would you implement a function in Python 3 that
gets an experiment group by uuid.

Response:
def get(ctx):
    """Get experiment group by uuid.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Examples:

    \b
    ```bash
    $ polyaxon group -g 13 get
    ```
    """
    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),
                                                            ctx.obj.get('group'))
    try:
        response = PolyaxonClient().experiment_group.get_experiment_group(
            user, project_name, _group)
        cache.cache(config_manager=GroupManager, response=response)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not get experiment group `{}`.'.format(_group))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    get_group_details(response)


Instruction:
Can you tell what is the following Python 3 function doing
def delete(ctx):
    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),
                                                            ctx.obj.get('group'))

    if not click.confirm("Are sure you want to delete experiment group `{}`".format(_group)):
        click.echo('Existing without deleting experiment group.')
        sys.exit(0)

    try:
        response = PolyaxonClient().experiment_group.delete_experiment_group(
            user, project_name, _group)
        # Purge caching
        GroupManager.purge()
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not delete experiment group `{}`.'.format(_group))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    if response.status_code == 204:
        Printer.print_success("Experiment group `{}` was delete successfully".format(_group))

Response: Delete an experiment group.


Instruction:
Implement a Python 3 function for
updating an existing group.

Response:
def update(ctx, name, description, tags):
    """Update experiment group.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Example:

    \b
    ```bash
    $ polyaxon group -g 2 update --description="new description for this group"
    ```

    \b
    ```bash
    $ polyaxon update --tags="foo, bar"
    ```
    """
    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),
                                                            ctx.obj.get('group'))
    update_dict = {}

    if name:
        update_dict['name'] = name

    if description:
        update_dict['description'] = description

    tags = validate_tags(tags)
    if tags:
        update_dict['tags'] = tags

    if not update_dict:
        Printer.print_warning('No argument was provided to update the experiment group.')
        sys.exit(0)

    try:
        response = PolyaxonClient().experiment_group.update_experiment_group(
            user, project_name, _group, update_dict)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not update experiment group `{}`.'.format(_group))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    Printer.print_success("Experiment group updated.")
    get_group_details(response)


Instruction:
Can you generate the documentation for the following Python 3 function
def stop(ctx, yes, pending):
    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),
                                                            ctx.obj.get('group'))

    if not yes and not click.confirm("Are sure you want to stop experiments "
                                     "in group `{}`".format(_group)):
        click.echo('Existing without stopping experiments in group.')
        sys.exit(0)

    try:
        PolyaxonClient().experiment_group.stop(user, project_name, _group, pending=pending)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not stop experiments in group `{}`.'.format(_group))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    Printer.print_success("Experiments in group are being stopped.")

Response: Stop all experiments in the specified group.


Instruction:
How would you explain what the following Python 3 function does
def bookmark(ctx):
    user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),
                                                            ctx.obj.get('group'))

    try:
        PolyaxonClient().experiment_group.bookmark(user, project_name, _group)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not bookmark group `{}`.'.format(_group))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    Printer.print_success("Experiments group is bookmarked.")

Response: Bookmark the current group.


Instruction:
How would you code a function in Python 3 to
set and get the global configurations.

Response:
def config(list):  # pylint:disable=redefined-builtin
    """Set and get the global configurations."""
    if list:
        _config = GlobalConfigManager.get_config_or_default()
        Printer.print_header('Current config:')
        dict_tabulate(_config.to_dict())


Instruction:
How would you code a function in Python 3 to
get the global config values by keys.

Response:
def get(keys):
    """Get the global config values by keys.

    Example:

    \b
    ```bash
    $ polyaxon config get host http_port
    ```
    """
    _config = GlobalConfigManager.get_config_or_default()

    if not keys:
        return

    print_values = {}
    for key in keys:
        if hasattr(_config, key):
            print_values[key] = getattr(_config, key)
        else:
            click.echo('Key `{}` is not recognised.'.format(key))

    dict_tabulate(print_values, )


Instruction:
Here you have a function in Python 3, explain what it does
def set(verbose,  # pylint:disable=redefined-builtin
        host,
        http_port,
        ws_port,
        use_https,
        verify_ssl):
    """Set the global config values.

    Example:

    \b
    ```bash
    $ polyaxon config set --hots=localhost http_port=80
    ```
    """
    _config = GlobalConfigManager.get_config_or_default()

    if verbose is not None:
        _config.verbose = verbose

    if host is not None:
        _config.host = host

    if http_port is not None:
        _config.http_port = http_port

    if ws_port is not None:
        _config.ws_port = ws_port

    if use_https is not None:
        _config.use_https = use_https

    if verify_ssl is False:
        _config.verify_ssl = verify_ssl

    GlobalConfigManager.set_config(_config)
    Printer.print_success('Config was updated.')
    # Reset cli config
    CliConfigManager.purge()

Response: Set the global config values.


Instruction:
Write a Python 3 script for
activating a user. Example: \b ```bash $ polyaxon user activate david ```

Response:
def activate(username):
    """Activate a user.

    Example:

    \b
    ```bash
    $ polyaxon user activate david
    ```
    """
    try:
        PolyaxonClient().user.activate_user(username)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not activate user `{}`.'.format(username))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    Printer.print_success("User `{}` was activated successfully.".format(username))


Instruction:
Write a Python 3 function that can
delete a user. Example: \b ```bash $ polyaxon user delete david ```

Response:
def delete(username):
    """Delete a user.

    Example:

    \b
    ```bash
    $ polyaxon user delete david
    ```
    """
    try:
        PolyaxonClient().user.delete_user(username)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not delete user `{}`.'.format(username))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)

    Printer.print_success("User `{}` was deleted successfully.".format(username))


Instruction:
Explain what the following Python 3 code does
def teardown(file):  # pylint:disable=redefined-builtin
    config = read_deployment_config(file)
    manager = DeployManager(config=config, filepath=file)
    exception = None
    try:
        if click.confirm('Would you like to execute pre-delete hooks?', default=True):
            manager.teardown(hooks=True)
        else:
            manager.teardown(hooks=False)
    except Exception as e:
        Printer.print_error('Polyaxon could not teardown the deployment.')
        exception = e

    if exception:
        Printer.print_error('Error message `{}`.'.format(exception))

Response: Teardown a polyaxon deployment given a config file.


Instruction:
Can you generate the documentation for the following Python 3 function
def create_tarfile(files, project_name):
    fd, filename = tempfile.mkstemp(prefix="polyaxon_{}".format(project_name), suffix='.tar.gz')
    with tarfile.open(filename, "w:gz") as tar:
        for f in files:
            tar.add(f)

    yield filename

    # clear
    os.close(fd)
    os.remove(filename)

Response: Create a tar file based on the list of files passed


Instruction:
Create a Python 3 function to
print the tensorboard url for project group and experiment.

Response:
def url(ctx):
    """Prints the tensorboard url for project/experiment/experiment group.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Examples for project tensorboards:

    \b
    ```bash
    $ polyaxon tensorboard url
    ```

    \b
    ```bash
    $ polyaxon tensorboard -p mnist url
    ```

    Examples for experiment tensorboards:

    \b
    ```bash
    $ polyaxon tensorboard -xp 1 url
    ```

    Examples for experiment group tensorboards:

    \b
    ```bash
    $ polyaxon tensorboard -g 1 url
    ```
    """
    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')


Instruction:
Can you generate the documentation for the following Python 3 function
def start(ctx, file):  # pylint:disable=redefined-builtin
    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))

Response: Start a tensorboard deployment for project group and resource.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def stop(ctx, yes):
    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)

Response: Stops the tensorboard for the current project and experiment.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def check_cli_version():
    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))

Response: Check if the current CLI version satisfies the server requirements


Instruction:
Implement a function in Python 3 to
print the current version of the cli and platform.

Response:
def version(cli, platform):
    """Print the current version of the cli and platform."""
    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())


Instruction:
Can you implement a function in Python 3 that
opens dashboard in browser.

Response:
def dashboard(yes, url):
    """Open dashboard in browser."""
    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)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def grant(username):
    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))

Response: Grant superuser role to a user.


Instruction:
Here you have a function in Python 3, explain what it does
def revoke(username):
    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))

Response: Revoke superuser role from a user.


Instruction:
Can you implement a function in Python 3 that
prints the url for this project.

Response:
def url(ctx):
    """Prints the notebook url for this project.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Example:

    \b
    ```bash
    $ polyaxon notebook url
    ```
    """
    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')


Instruction:
Can you create a Python 3 function that
starts a new notebook for this project.

Response:
def start(ctx, file, u):  # pylint:disable=redefined-builtin
    """Start a notebook deployment for this project.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Example:

    \b
    ```bash
    $ polyaxon notebook start -f file -f file_override ...
    ```

    Example: upload before running

    \b
    ```bash
    $ polyaxon -p user12/mnist notebook start -f file -u
    ```
    """
    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))


Instruction:
How would you code a function in Python 3 to
stop the notebook deployment for this project.

Response:
def stop(ctx, commit, yes):
    """Stops the notebook deployment for this project if it exists.

    Uses [Caching](/references/polyaxon-cli/#caching)
    """
    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)


Instruction:
Create a Python 3 function to
add platform specific checks

Response:
def check(self):
        """Add platform specific checks"""
        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))


Instruction:
Here you have a function in Python 3, explain what it does
def install(self):
        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()

Response: Install polyaxon using the current config to the correct platform.


Instruction:
Implement a Python 3 function for
upgrading the specified resource.

Response:
def upgrade(self):
        """Upgrade deployment."""
        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()


Instruction:
Can you generate the documentation for the following Python 3 function
def create(ctx, name, description, tags, private, init):
    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)

Response: Create a new project.


Instruction:
Explain what the following Python 3 code does
def list(page):  # pylint:disable=redefined-builtin
    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)

Response:
List projects.

    Uses [Caching](/references/polyaxon-cli/#caching)


Instruction:
How would you explain what the following Python 3 function does
def get(ctx):
    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)

Response: Get current project by project_name or user or project_name.


Instruction:
Make a summary of the following Python 3 code
def delete(ctx):
    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))

Response:
Delete project.

    Uses [Caching](/references/polyaxon-cli/#caching)


Instruction:
Write a Python 3 script for
updating project. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon update foobar --description="Image Classification with DL using TensorFlow" ``` \b ```bash $ polyaxon update mike1/foobar --description="Image Classification with DL using TensorFlow" ``` \b ```bash $ polyaxon update --tags="foo, bar" ```

Response:
def update(ctx, name, description, tags, private):
    """Update project.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Example:

    \b
    ```bash
    $ polyaxon update foobar --description="Image Classification with DL using TensorFlow"
    ```

    \b
    ```bash
    $ polyaxon update mike1/foobar --description="Image Classification with DL using TensorFlow"
    ```

    \b
    ```bash
    $ polyaxon update --tags="foo, bar"
    ```
    """
    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)


Instruction:
Can you tell what is the following Python 3 function doing
def groups(ctx, query, sort, page):
    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)

Response: List experiment groups for this project.


Instruction:
Create a Python 3 function to
list all experiments for this project.

Response:
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:

    \b
    ```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

    \b
    ```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

    \b
    ```bash
    $ polyaxon project experiments -s "-updated_at"
    ```
    """
    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)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def git(ctx, url, private, sync):  # pylint:disable=assign-to-new-keyword
    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()

Response: Set or sync git repo on this project.


Instruction:
Explain what the following Python 3 code does
def ci(ctx, enable, disable):  # pylint:disable=assign-to-new-keyword
    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()

Response: Enables or disables the CI on this project.


Instruction:
Given the following Python 3 function, write the documentation
def download(ctx):
    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.')

Response: Download code of the current project.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write(self,file,optstring="",quote=False):
        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')

Response: write the object line ; additional args are packed in string


Instruction:
Explain what the following Python 3 code does
def edges(self):
        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)]

Response: Edges of the grid cells origin at centre of 0.. 0 grid cell.


Instruction:
How would you code a function in Python 3 to
write the class array section to a file.

Response:
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.

        """
        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')


Instruction:
Implement a Python 3 function for
writing the complete dx object to the file.

Response:
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.
        """
        # 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)))


Instruction:
Write a Python 3 script to
read the classid from file.

Response:
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.
        """
        DXfield = self
        p = DXParser(file)
        p.parse(DXfield)


Instruction:
Can you generate the documentation for the following Python 3 function
def histogramdd(self):
        shape = self.components['positions'].shape
        edges = self.components['positions'].edges()
        hist = self.components['data'].array.reshape(shape)
        return (hist,edges)

Response: Return array data as ( edges grid ) i. e. a numpy nD histogram.


Instruction:
Can you generate the documentation for the following Python 3 function
def value(self,ascode=None):
        if ascode is None:
            ascode = self.code
        return self.cast[ascode](self.text)

Response: Return text cast to the correct type or the selected type


Instruction:
Write a Python 3 script for
initializing the corresponding DXclass from the data.

Response:
def initialize(self):
        """Initialize the corresponding DXclass from the data.

        class = DXInitObject.initialize()
        """
        return self.DXclasses[self.type](self.id,**self.args)


Instruction:
Can you tell what is the following Python 3 function doing
def parse(self,DXfield):

        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

Response: Parse the dx file and construct a DXField object with component classes.


Instruction:
Here you have a function in Python 3, explain what it does
def __general(self):
        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()

Response: Level - 1 parser and main loop.


Instruction:
How would you implement a function in Python 3 that
levels - 1 parser for comments. pattern

Response:
def __comment(self):
        """Level-1 parser for comments.

        pattern: #.*
        Append comment (with initial '# ' stripped) to all comments.
        """
        tok = self.__consume()
        self.DXfield.add_comment(tok.value())
        self.set_parser('general')


Instruction:
Given the following Python 3 function, write the documentation
def __object(self):
        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)

Response:
Level-1 parser for objects.

        pattern: 'object' id 'class' type ...

        id ::=   integer|string|'"'white space string'"'
        type ::= string


Instruction:
Write a Python 3 function for
leveling - 2 parser for gridpositions.

Response:
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
        """
        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.')


Instruction:
Can you create a Python 3 function that
levels - 2 parser for gridconnections.

Response:
def __gridconnections(self):
        """Level-2 parser for gridconnections.

        pattern:
        object 2 class gridconnections counts 97 93 99
        """
        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.')


Instruction:
Can you tell what is the following Python 3 function doing
def __array(self):
        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.')

Response: Level - 2 parser for arrays.


Instruction:
How would you code a function in Python 3 to
parse a DX Field object.

Response:
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
        """
        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.')


Instruction:
Write a Python 3 script for
setting parsername as the current parser and apply it.

Response:
def use_parser(self,parsername):
        """Set parsername as the current parser and apply it."""
        self.__parser = self.parsers[parsername]
        self.__parser()


Instruction:
How would you explain what the following Python 3 function does
def __tokenize(self,string):
        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)

Response: Splits s into tokens and update the token buffer.


Instruction:
Here you have a function in Python 3, explain what it does
def __refill_tokenbuffer(self):
        if len(self.tokens) == 0:
            self.__tokenize(self.dxfile.readline())

Response: Add a new tokenized line from the file to the token buffer.


Instruction:
Write a Python 3 script for
populating the instance from the plt file filename.

Response:
def read(self, filename):
        """Populate the instance from the plt file *filename*."""
        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']


Instruction:
How would you explain what the following Python 3 function does
def _read_header(self, pltfile):
        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

Response: Read the header bytes and return a dictionary of the header values.


Instruction:
Can you tell what is the following Python 3 function doing
def ndmeshgrid(*arrs):
    #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)

Response: Return a meshgrid for N dimensions.


Instruction:
Here you have a function in Python 3, explain what it does
def resample(self, edges):
        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)

Response: Resample data to a new grid with the given edges.


Instruction:
Implement a function in Python 3 to
compute and update all derived data for a specific entry.

Response:
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
        """
        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()


Instruction:
Explain what the following Python 3 code does
def interpolated(self):
        if self.__interpolated is None:
            self.__interpolated = self._interpolationFunctionFactory()
        return self.__interpolated

Response: A function that returns the interpolated function over the data grid.


Instruction:
How would you explain what the following Python 3 function does
def load(self, filename, file_format=None):
        loader = self._get_loader(filename, file_format=file_format)
        loader(filename)

Response: Load a saved ( pickled or dx grid and edges from a file.


Instruction:
Here you have a function in Python 3, explain what it does
def _load_cpp4(self, filename):
        ccp4 = CCP4.CCP4()
        ccp4.read(filename)
        grid, edges = ccp4.histogramdd()
        self.__init__(grid=grid, edges=edges, metadata=self.metadata)

Response: Initializes Grid from a CCP4 file.


Instruction:
How would you code a function in Python 3 to
initialize a Grid from a OpenDX file.

Response:
def _load_dx(self, filename):
        """Initializes Grid from a OpenDX file."""
        dx = OpenDX.field(0)
        dx.read(filename)
        grid, edges = dx.histogramdd()
        self.__init__(grid=grid, edges=edges, metadata=self.metadata)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _load_plt(self, filename):
        g = gOpenMol.Plt()
        g.read(filename)
        grid, edges = g.histogramdd()
        self.__init__(grid=grid, edges=edges, metadata=self.metadata)

Response: Initialize Grid from gOpenMol plt file.


Instruction:
Write a Python 3 script to
export density to file using the given format.

Response:
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

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


Instruction:
Create a Python 3 function to
export the grid object to a file.

Response:
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__().
        """
        data = dict(grid=self.grid, edges=self.edges, metadata=self.metadata)
        with open(filename, 'wb') as f:
            cPickle.dump(data, f, cPickle.HIGHEST_PROTOCOL)


Instruction:
How would you implement a function in Python 3 that
exports the density grid to an OpenDX file.

Response:
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

        """
        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)


Instruction:
Implement a function in Python 3 to
return the coordinates of the centers of all grid cells as an an iterator.

Response:
def centers(self):
        """Returns the coordinates of the centers of all grid cells as an
        iterator."""
        for idx in numpy.ndindex(self.grid.shape):
            yield self.delta * numpy.array(idx) + self.origin


Instruction:
Can you generate a brief explanation for the following Python 3 code
def check_compatible(self, other):
        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

Response: Checks if self and other are compatible with the grid.


Instruction:
Can you tell what is the following Python 3 function doing
def _interpolationFunctionFactory(self, spline_order=None, cval=None):
        # for scipy >=0.9: should use scipy.interpolate.griddata
        # http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html#scipy.interpolate.griddata
        # (does it work for nD?)
        import scipy.ndimage

        if spline_order is None:
            # must be compatible with whatever :func:`scipy.ndimage.spline_filter` takes.
            spline_order = self.interpolation_spline_order
        if cval is None:
            cval = self.interpolation_cval

        data = self.grid
        if cval is None:
            cval = data.min()
        try:
            # masked arrays, fill with min: should keep spline happy
            _data = data.filled(cval)
        except AttributeError:
            _data = data

        coeffs = scipy.ndimage.spline_filter(_data, order=spline_order)
        x0 = self.origin
        dx = self.delta

        def _transform(cnew, c0, dc):
            return (numpy.atleast_1d(cnew) - c0) / dc

        def interpolatedF(*coordinates):
            """B-spline function over the data grid(x,y,z).

            interpolatedF([x1,x2,...],[y1,y2,...],[z1,z2,...]) -> F[x1,y1,z1],F[x2,y2,z2],...

            Example usage for resampling::
              >>> XX,YY,ZZ = numpy.mgrid[40:75:0.5, 96:150:0.5, 20:50:0.5]
              >>> FF = _interpolationFunction(XX,YY,ZZ)
            """
            _coordinates = numpy.array(
                [_transform(coordinates[i], x0[i], dx[i]) for i in range(len(
                    coordinates))])
            return scipy.ndimage.map_coordinates(coeffs,
                                                 _coordinates,
                                                 prefilter=False,
                                                 mode='nearest',
                                                 cval=cval)
        # mode='wrap' would be ideal but is broken: https://github.com/scipy/scipy/issues/1323
        return interpolatedF

Response: Returns a function F that interpolates any values on the grid.


Instruction:
How would you explain what the following Python 3 function does
def read(self, filename):
        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

Response: Populate the instance from the ccp4 file filename.


Instruction:
How would you explain what the following Python 3 function does
def _detect_byteorder(ccp4file):
        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

Response: Detect the byteorder of stream ccp4file and return format character.


Instruction:
Given the following Python 3 function, write the documentation
def _read_header(self, ccp4file):

        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

Response: Read the header bytes and return a tuple of the class ID and the header bytes.


Instruction:
Can you tell what is the following Python 3 function doing
def get_data(self, **kwargs):
        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)

Response: Get the data for a specific device for a specific end date


Instruction:
Can you generate the documentation for the following Python 3 function
def get_devices(self):
        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

Response: Get all devices in the system


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_url(self, path, params={}, opts={}):

        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)

Response: Create URL with supplied path and opts parameters dict.


Instruction:
How would you implement a function in Python 3 that
sets a url parameter.

Response:
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.
        """
        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


Instruction:
Write a Python 3 script for
starting subscription manager for real time data.

Response:
async def rt_connect(self, loop):
        """Start subscription manager for real time data."""
        if self.sub_manager is not None:
            return
        self.sub_manager = SubscriptionManager(
            loop, "token={}".format(self._access_token), SUB_ENDPOINT
        )
        self.sub_manager.start()


Instruction:
Explain what the following Python 3 code does
async def update_info(self, *_):
        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]

Response: Update home info async.