output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Add common list options to commands. | Make a summary of the following Python 3 code
def common_cli_list_options(f):
@click.option(
"-p",
"--page",
default=1,
type=int,
help="The page to view for lists, where 1 is the first page",
callback=validators.validate_page,
)
@click.option(
"-l",
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Add common API authentication options to commands. | Can you tell what is the following Python 3 function doing
def common_api_auth_options(f):
@click.option(
"-k",
"--api-key",
hide_input=True,
envvar="CLOUDSMITH_API_KEY",
help="The API key for authenticating with the API.",
)
@click.pass_context
@functools.wraps(... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Initialise the Cloudsmith API for use. | Can you generate the documentation for the following Python 3 function
def initialise_api(f):
@click.option(
"--api-host", envvar="CLOUDSMITH_API_HOST", help="The API host to connect to."
)
@click.option(
"--api-proxy",
envvar="CLOUDSMITH_API_PROXY",
help="The API proxy to c... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get a list of entitlements on a repository. | Can you generate the documentation for the following Python 3 function
def list_entitlements(owner, repo, page, page_size, show_tokens):
client = get_entitlements_api()
with catch_raise_api_exception():
data, _, headers = client.entitlements_list_with_http_info(
owner=owner,
rep... | As a Python code composer, you craft elegant and concise scripts. |
Create an entitlement in a repository. | Can you generate the documentation for the following Python 3 function
def create_entitlement(owner, repo, name, token, show_tokens):
client = get_entitlements_api()
data = {}
if name is not None:
data["name"] = name
if token is not None:
data["token"] = token
with catch_raise_api... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Delete an entitlement from a repository. | Can you generate a brief explanation for the following Python 3 code
def delete_entitlement(owner, repo, identifier):
client = get_entitlements_api()
with catch_raise_api_exception():
_, _, headers = client.entitlements_delete_with_http_info(
owner=owner, repo=repo, identifier=identifier
... | As a Python code composer, you craft elegant and concise scripts. |
Update an entitlement in a repository. | Make a summary of the following Python 3 code
def update_entitlement(owner, repo, identifier, name, token, show_tokens):
client = get_entitlements_api()
data = {}
if name is not None:
data["name"] = name
if token is not None:
data["token"] = token
with catch_raise_api_exception():... | You are a Python code architect, reviewing and designing scalable and efficient code |
def refresh_entitlement(owner, repo, identifier, show_tokens):
"""Refresh an entitlement in a repository."""
client = get_entitlements_api()
with catch_raise_api_exception():
data, _, headers = client.entitlements_refresh_with_http_info(
owner=owner, repo=repo, identifier=identifier, sh... | Can you write a function in Python 3 where it
refreshes an entitlement in a repository. | As a python code expert, you are capable of creating scripts from specifications. |
Get an API client with configuration. | Can you generate a brief explanation for the following Python 3 code
def get_api_client(cls):
config = cloudsmith_api.Configuration()
client = cls()
client.config = config
client.api_client.rest_client = RestClient()
user_agent = getattr(config, "user_agent", None)
if user_agent:
client... | As a python code expert, you are capable of creating scripts from specifications. |
def set_api_key(config, key):
"""Configure a new API key."""
if not key and "X-Api-Key" in config.api_key:
del config.api_key["X-Api-Key"]
else:
config.api_key["X-Api-Key"] = key | Write a Python 3 function that can
configure a new API key. | You are a Python code generator, capable of creating scripts from specifications. |
def validate_request_file_upload(owner, repo, filepath, md5_checksum=None):
"""Validate parameters for requesting a file upload."""
client = get_files_api()
md5_checksum = md5_checksum or calculate_file_md5(filepath)
with catch_raise_api_exception():
_, _, headers = client.files_validate_with_h... | Write a Python 3 script for
validating parameters for requesting a file upload. | As a Python code analyst, you investigate and solve complex coding mysteries |
Request a new file upload. | Here you have a function in Python 3, explain what it does
def request_file_upload(owner, repo, filepath, md5_checksum=None):
client = get_files_api()
md5_checksum = md5_checksum or calculate_file_md5(filepath)
with catch_raise_api_exception():
data, _, headers = client.files_create_with_http_info(... | As a Python code analyst, you investigate and solve complex coding mysteries |
Upload a pre - signed file to Cloudsmith. | Make a summary of the following Python 3 code
def upload_file(upload_url, upload_fields, filepath, callback=None):
upload_fields = list(six.iteritems(upload_fields))
upload_fields.append(
("file", (os.path.basename(filepath), click.open_file(filepath, "rb")))
)
encoder = MultipartEncoder(upload_... | You are a Python code architect, reviewing and designing scalable and efficient code |
Context manager that handles API exceptions. | Given the following Python 3 function, write the documentation
def handle_api_exceptions(
ctx, opts, context_msg=None, nl=False, exit_on_error=True, reraise_on_error=False
):
"""Context manager that handles API exceptions."""
# flake8: ignore=C901
# Use stderr for messages if the output is something els... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_details(exc):
"""Get the details from the exception."""
detail = None
fields = collections.OrderedDict()
if exc.detail:
detail = exc.detail
if exc.fields:
for k, v in six.iteritems(exc.fields):
try:
field_detail = v["detail"]
except (... | Write a Python 3 function for
getting the details from the exception. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get a hint to show to the user if any. | Can you tell what is the following Python 3 function doing
def get_error_hint(ctx, opts, exc):
module = sys.modules[__name__]
get_specific_error_hint = getattr(module, "get_%s_error_hint" % exc.status, None)
if get_specific_error_hint:
return get_specific_error_hint(ctx, opts, exc)
return None | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates an environment key - equivalent for the given key | Given the following Python 3 function, write the documentation
def make_env_key(app_name, key):
key = key.replace('-', '_').replace(' ', '_')
return str("_".join((x.upper() for x in (app_name, key)))) | You are a Python code generator, capable of creating scripts from specifications. |
def set_env(self, key, value):
"""Sets environment variables by prepending the app_name to `key`. Also registers the
environment variable with the instance object preventing an otherwise-required call to
`reload()`.
"""
os.environ[make_env_key(self.appname, key)] = str(value) # ... | Create a Python 3 function for
setting the environment variable by prepending the app_name to key. | As a python code expert, you are capable of creating scripts from specifications. |
def unset_env(self, key):
"""Removes an environment variable using the prepended app_name convention with `key`."""
os.environ.pop(make_env_key(self.appname, key), None)
self._registered_env_keys.discard(key)
self._clear_memoization() | Write a Python 3 function for
removing an environment variable using the prepended app_name convention with key. | You are a Python code analyst, evaluating scripts for potential improvements. |
Reloads the configuration from the file and environment variables. Useful if using
os. environ instead of this class s set_env method. | Here you have a function in Python 3, explain what it does
def _reload(self, force=False):
self._config_map = dict()
self._registered_env_keys = set()
self.__reload_sources(force)
self.__load_environment_keys()
self.verify()
self._clear_memoization() | You are a Python code analyst, evaluating scripts for potential improvements. |
def move(
ctx,
opts,
owner_repo_package,
destination,
skip_errors,
wait_interval,
no_wait_for_sync,
sync_attempts,
yes,
):
"""
Move (promote) a package to another repo.
This requires appropriate permissions for both the source
repository/package and the destination r... | Create a Python 3 function to
promote a package from one repository to another repository. | As a python code expert, you are capable of creating scripts from specifications. |
def create_requests_session(
retries=None,
backoff_factor=None,
status_forcelist=None,
pools_size=4,
maxsize=4,
ssl_verify=None,
ssl_cert=None,
proxy=None,
session=None,
):
"""Create a requests session that retries some errors."""
# pylint: disable=too-many-branches
confi... | Create a Python 3 function for
creating a requests session that retries some errors. | As a Python code composer, you craft elegant and concise scripts. |
Get the content for the response. | Make a summary of the following Python 3 code
def data(self):
if self._data is None:
self._data = self.response.content.decode("utf-8")
return self._data | You are a Python code generator, capable of creating scripts from specifications. |
def getheader(self, name, default=None):
"""
Return a given response header.
"""
return self.response.headers.get(name, default) | Write a Python 3 script for
getting a given response header. | You are a Python code analyst, evaluating scripts for potential improvements. |
This method is used to make a request to the API. | How would you explain what the following Python 3 function does
def request(
self,
method,
url,
query_params=None,
headers=None,
body=None,
post_params=None,
_preload_content=True,
_request_timeout=None,
):
"""
:param method: ht... | You are a Python code generator, capable of creating scripts from specifications. |
Get the root directory for the application. | How would you explain what the following Python 3 function does
def get_root_path():
return os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir)) | As a Python code composer, you craft elegant and concise scripts. |
Read the specific file into a string in its entirety. | Can you generate the documentation for the following Python 3 function
def read_file(*path):
real_path = os.path.realpath(os.path.join(*path))
with click.open_file(real_path, "r") as fp:
return fp.read() | You are a Python code architect, reviewing and designing scalable and efficient code |
def calculate_file_md5(filepath, blocksize=2 ** 20):
"""Calculate an MD5 hash for a file."""
checksum = hashlib.md5()
with click.open_file(filepath, "rb") as f:
def update_chunk():
"""Add chunk to checksum."""
buf = f.read(blocksize)
if buf:
chec... | Create a Python 3 function for
calculating an MD5 hash for a file. | As a Python code composer, you craft elegant and concise scripts. |
def get_page_kwargs(**kwargs):
"""Construct page and page size kwargs (if present)."""
page_kwargs = {}
page = kwargs.get("page")
if page is not None and page > 0:
page_kwargs["page"] = page
page_size = kwargs.get("page_size")
if page_size is not None and page_size > 0:
page_kw... | How would you implement a function in Python 3 that
constructs page and page size kwargs (if present ). | As a python code expert, you are capable of creating scripts from specifications. |
Construct page and page size kwargs. | Here you have a function in Python 3, explain what it does
def get_query_kwargs(**kwargs):
query_kwargs = {}
query = kwargs.pop("query")
if query:
query_kwargs["query"] = query
return query_kwargs | As a Python code composer, you craft elegant and concise scripts. |
def _get_version_from_git_tag(path):
"""Return a PEP440-compliant version derived from the git status.
If that fails for any reason, return the changeset hash.
"""
m = GIT_DESCRIBE_REGEX.match(_git_describe_tags(path) or '')
if m is None:
return None
version, post_commit, hash = m.groups... | How would you implement a function in Python 3 that
returns a PEP440 - compliant version derived from the git tag. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a version string for the current package derived
from git or from a. version file. | Can you generate a brief explanation for the following Python 3 code
def get_version(dunder_file):
path = abspath(expanduser(dirname(dunder_file)))
try:
return _get_version_from_version_file(path) or _get_version_from_git_tag(path)
except CalledProcessError as e:
log.warn(repr(e))
re... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def ctime(message=None):
"Counts the time spent in some context"
global t_elapsed
t_elapsed = 0.0
print('\n')
t = time.time()
yield
if message:
print(message + ": ", end='')
t_elapsed = time.time() - t
print(round(t_elapsed, 4), "sec") | Write a Python 3 function that can
count the time spent in some context | As a Python code analyst, you investigate and solve complex coding mysteries |
Euler rotation about first axis | Here you have a function in Python 3, explain what it does
def rot1(angle, form='c'):
cos_a = np.cos(angle)
sin_a = np.sin(angle)
rot_mat = np.identity(3)
if form=='c':
rot_mat[1, 1] = cos_a
rot_mat[1, 2] = -sin_a
rot_mat[2, 1] = sin_a
rot_mat[2, 2] = cos_a
elif form... | As a python code expert, you are capable of creating scripts from specifications. |
def dcm2body313(dcm):
"""Convert DCM to body Euler 3-1-3 angles
"""
theta = np.zeros(3)
theta[0] = np.arctan2(dcm[2, 0], dcm[2, 1])
theta[1] = np.arccos(dcm[2, 2])
theta[2] = np.arctan2(dcm[0, 2], -dcm[1, 2])
return theta | Implement a Python 3 function for
converting DCM to body Euler 3 - 1 - 3 angles | You are a Python code architect, reviewing and designing scalable and efficient code |
Return that hat map of a vector | Can you generate the documentation for the following Python 3 function
def hat_map(vec):
vec = np.squeeze(vec)
skew = np.array([
[0, -vec[2], vec[1]],
[vec[2], 0, -vec[0]],
[-vec[1], vec[0], 0]])
return skew | As a Python code composer, you craft elegant and concise scripts. |
Return the vee map of a vector
| Make a summary of the following Python 3 code
def vee_map(skew):
vec = 1/2 * np.array([skew[2,1] - skew[1,2],
skew[0,2] - skew[2,0],
skew[1,0] - skew[0,1]])
return vec | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert DCM to quaternion | Given the following Python 3 function, write the documentation
def dcmtoquat(dcm):
quat = np.zeros(4)
quat[-1] = 1/2*np.sqrt(np.trace(dcm)+1)
quat[0:3] = 1/4/quat[-1]*vee_map(dcm-dcm.T)
return quat | As a Python code translator, you convert algorithms and pseudocode into Python. |
def quattodcm(quat):
"""Convert quaternion to DCM
This function will convert a quaternion to the equivalent rotation matrix,
or direction cosine matrix.
Parameters:
----------
quat - (4,) numpy array
Array defining a quaterion where the quaternion is defined in terms of
a vecto... | Can you write a function in Python 3 where it
converts quaternion to DCM | You are a Python code generator, capable of creating scripts from specifications. |
def dcmdottoang_vel(R,Rdot):
"""Convert a rotation matrix to angular velocity
w - angular velocity in inertial frame
Omega - angular velocity in body frame
"""
w = vee_map(Rdot.dot(R.T))
Omega = vee_map(R.T.dot(Rdot))
return (w, Omega) | Implement a function in Python 3 to
convert a rotation matrix to angular velocity w Omega | As a Python code composer, you craft elegant and concise scripts. |
def ang_veltoaxisangledot(angle, axis, Omega):
"""Compute kinematics for axis angle representation
"""
angle_dot = axis.dot(Omega)
axis_dot = 1/2*(hat_map(axis) - 1/np.tan(angle/2) * hat_map(axis).dot(hat_map(axis))).dot(Omega)
return angle_dot, axis_dot | Write a Python 3 script for
computing kinematics for axis angle representation | As a python code expert, you are capable of creating scripts from specifications. |
def axisangledottoang_vel(angle,axis, angle_dot,axis_dot):
"""Convert axis angle represetnation to angular velocity in body frame
"""
Omega = angle_dot*axis + np.sin(angle)*axis_dot - (1-np.cos(angle))*hat_map(axis).dot(axis_dot)
return Omega | How would you code a function in Python 3 to
convert axis angle represetnation to angular velocity in body frame | As a Python code translator, you convert algorithms and pseudocode into Python. |
Normalizes a number to range [ lower upper ) or [ lower upper ). | Explain what the following Python 3 code does
def normalize(num_in, lower=0, upper=360, b=False):
if lower >= upper:
ValueError("lower must be lesser than upper")
if not b:
if not ((lower + upper == 0) or (lower == 0)):
raise ValueError('When b=False lower=0 or range must be symmetri... | You are a Python code architect, reviewing and designing scalable and efficient code |
List repositories in a namespace. | How would you explain what the following Python 3 function does
def list_repos(owner=None, **kwargs):
client = get_repos_api()
api_kwargs = {}
api_kwargs.update(utils.get_page_kwargs(**kwargs))
# pylint: disable=fixme
# FIXME: Compatibility code until we work out how to conflate
# the overlapp... | You are a Python code architect, reviewing and designing scalable and efficient code |
def copy(
ctx,
opts,
owner_repo_package,
destination,
skip_errors,
wait_interval,
no_wait_for_sync,
sync_attempts,
):
"""
Copy a package to another repository.
This requires appropriate permissions for both the source
repository/package and the destination repository.
... | Implement a function in Python 3 to
copy a package from one repository to another. | As a Python code analyst, you investigate and solve complex coding mysteries |
Helper function to remove a certain filepath from the system. | Explain what the following Python 3 code does
def rm_file_or_dir(path, ignore_errors=True):
if os.path.exists(path):
if os.path.isdir(path):
if os.path.islink(path):
os.unlink(path)
else:
shutil.rmtree(path, ignore_errors=ignore_errors)
else:
... | As a python code expert, you are capable of creating scripts from specifications. |
def cache_valid(self, col):
"""
Checks whether the column has a factorization that exists and is not older than the source
:param col:
:return:
"""
cache_valid = False
if self.rootdir:
col_org_file_check = self[col].rootdir + '/__attrs__'
... | Write a Python 3 function for
checking whether the column has a factorization that exists and is not older than the source | As a Python code analyst, you investigate and solve complex coding mysteries |
Checks whether the group has a factorization that exists and is not older than the source ArcGIS group. | How would you explain what the following Python 3 function does
def group_cache_valid(self, col_list):
cache_valid = False
if self.rootdir:
col_values_file_check = os.path.join(self.rootdir, self.create_group_base_name(col_list)) + \
'.values/__attrs__'
... | You are a Python code generator, capable of creating scripts from specifications. |
def cache_factor(self, col_list, refresh=False):
"""
Existing todos here are: these should be hidden helper carrays
As in: not normal columns that you would normally see as a user
The factor (label index) carray is as long as the original carray
(and the rest of the table theref... | Create a Python 3 function for
existing todos here are: these should be hidden helper carrays As in: not normal columns that you would normally see as a user The factor (label index) carray is as long as the original carray (and the rest of the table therefore) But the (unique) values carray is not as long (as long as ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a list of unique values of a column or a list of lists of column list
| Can you tell what is the following Python 3 function doing
def unique(self, col_or_col_list):
if isinstance(col_or_col_list, list):
col_is_list = True
col_list = col_or_col_list
else:
col_is_list = False
col_list = [col_or_col_list]
output = []
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Perform aggregation and place the result in the given ctable. | Make a summary of the following Python 3 code
def aggregate_groups(self, ct_agg, nr_groups, skip_key,
carray_factor, groupby_cols, agg_ops,
dtype_dict, bool_arr=None):
'''Perform aggregation and place the result in the given ctable.
Args:
ct... | You are a Python code generator, capable of creating scripts from specifications. |
factorizes all columns that are used in the groupby
| Given the following Python 3 function, write the documentation
def factorize_groupby_cols(self, groupby_cols):
# first check if the factorized arrays already exist
# unless we need to refresh the cache
factor_list = []
values_list = []
# factorize the groupby columns
for... | You are a Python code generator, capable of creating scripts from specifications. |
Create a unique factorized column out of several individual columns. | How would you explain what the following Python 3 function does
def create_group_column_factor(self, factor_list, groupby_cols, cache=False):
if not self.rootdir:
# in-memory scenario
input_rootdir = None
col_rootdir = None
col_factor_rootdir = None
co... | You are a Python code architect, reviewing and designing scalable and efficient code |
def make_group_index(self, groupby_cols, bool_arr):
'''Create unique groups for groupby loop
Args:
factor_list:
values_list:
groupby_cols:
bool_arr:
Returns:
carray: (carray_factor)
int: (nr... | Create a Python 3 function to
create unique groups for groupby loop | As a python code expert, you are capable of creating scripts from specifications. |
def create_tmp_rootdir(self):
"""
create a rootdir that we can destroy later again
Returns
-------
"""
if self.rootdir:
tmp_rootdir = tempfile.mkdtemp(prefix='bcolz-')
self._dir_clean_list.append(tmp_rootdir)
else:
tmp_rootdir... | Write a Python 3 script to
create a temporary rootdir that we can destroy later again | You are a Python code architect, reviewing and designing scalable and efficient code |
def clean_tmp_rootdir(self):
"""
clean up all used temporary rootdirs
Returns
-------
"""
for tmp_rootdir in list(self._dir_clean_list):
rm_file_or_dir(tmp_rootdir)
self._dir_clean_list.remove(tmp_rootdir) | Write a Python 3 function that can
clean up all used temporary rootdirs | You are a Python code generator, capable of creating scripts from specifications. |
def create_agg_ctable(self, groupby_cols, agg_list, expectedlen, rootdir):
'''Create a container for the output table, a dictionary describing it's
columns and a list of tuples describing aggregation
operations to perform.
Args:
groupby_cols (list): a list of columns... | Implement a Python 3 function for
creating a container for the output table a dictionary describing it s columns and a list of tuples describing aggregation operations to perform. | You are a Python code analyst, evaluating scripts for potential improvements. |
def where_terms(self, term_list, cache=False):
"""
Create a boolean array where `term_list` is true.
A terms list has a [(col, operator, value), ..] construction.
Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])]
:param term_list:
:param outcols:
:param limi... | Can you create a Python 3 function that
creates a boolean array where the terms in term_list are true. | As a Python code analyst, you investigate and solve complex coding mysteries |
def where_terms_factorization_check(self, term_list):
"""
check for where terms if they are applicable
Create a boolean array where `term_list` is true.
A terms list has a [(col, operator, value), ..] construction.
Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])]
:... | Create a Python 3 function for
checking for where terms are applicable | As a Python code composer, you craft elegant and concise scripts. |
Returns True if the entry is in the ordered subgroups of the entry. | Explain what the following Python 3 code does
def is_in_ordered_subgroups(self, basket_col=None, bool_arr=None,
_max_len_subgroup=1000):
"""
Expands the filter using a specified column
Parameters
----------
basket_col
bool_arr
_max... | You are a Python code architect, reviewing and designing scalable and efficient code |
Class decorator to set metaclass for base classes. | Given the following Python 3 function, write the documentation
def with_metaclass(Type, skip_attrs=set(('__dict__', '__weakref__'))):
def _clone_with_metaclass(Class):
attrs = dict((key, value) for key, value in items(vars(Class))
if key not in skip_attrs)
return Type(Class.__n... | You are a Python code generator, capable of creating scripts from specifications. |
def ensure_tuple(length, tuples):
"""Yield `length`-sized tuples from the given collection.
Will truncate longer tuples to the desired length, and pad using the leading element if shorter.
"""
for elem in tuples:
# Handle non-tuples and non-lists as a single repeated element.
if not isinstance(elem, (tuple,... | Write a Python 3 script for
yielding length - sized tuples from the given collection. | As a python code expert, you are capable of creating scripts from specifications. |
def print_version():
"""Print the environment versions."""
click.echo("Versions:")
click.secho(
"CLI Package Version: %(version)s"
% {"version": click.style(get_cli_version(), bold=True)}
)
click.secho(
"API Package Version: %(version)s"
% {"version": click.style(get_... | Implement a Python 3 function for
printing the environment versions. | As a python code expert, you are capable of creating scripts from specifications. |
def main(ctx, opts, version):
"""Handle entrypoint to CLI."""
# pylint: disable=unused-argument
if version:
print_version()
elif ctx.invoked_subcommand is None:
click.echo(ctx.get_help()) | How would you code a function in Python 3 to
handle entrypoint to CLI. | As a python code expert, you are capable of creating scripts from specifications. |
Validate parameters for requesting a file upload. | Explain what the following Python 3 code does
def validate_upload_file(ctx, opts, owner, repo, filepath, skip_errors):
filename = click.format_filename(filepath)
basename = os.path.basename(filename)
click.echo(
"Checking %(filename)s file upload parameters ... "
% {"filename": click.style(... | As a Python code analyst, you investigate and solve complex coding mysteries |
def upload_file(ctx, opts, owner, repo, filepath, skip_errors, md5_checksum):
"""Upload a package file via the API."""
filename = click.format_filename(filepath)
basename = os.path.basename(filename)
click.echo(
"Requesting file upload for %(filename)s ... "
% {"filename": click.style(b... | Can you write a function in Python 3 where it
uploads a file via the API. | You are a Python code analyst, evaluating scripts for potential improvements. |
Check new package parameters via the API. | Here you have a function in Python 3, explain what it does
def validate_create_package(
ctx, opts, owner, repo, package_type, skip_errors, **kwargs
):
"""Check new package parameters via the API."""
click.echo(
"Checking %(package_type)s package upload parameters ... "
% {"package_type": cli... | As a Python code composer, you craft elegant and concise scripts. |
Create a new package via the API. | Make a summary of the following Python 3 code
def create_package(ctx, opts, owner, repo, package_type, skip_errors, **kwargs):
click.echo(
"Creating a new %(package_type)s package ... "
% {"package_type": click.style(package_type, bold=True)},
nl=False,
)
context_msg = "Failed to cr... | You are a Python code generator, capable of creating scripts from specifications. |
def wait_for_package_sync(
ctx, opts, owner, repo, slug, wait_interval, skip_errors, attempts=3
):
"""Wait for a package to synchronise (or fail)."""
# pylint: disable=too-many-locals
attempts -= 1
click.echo()
label = "Synchronising %(package)s:" % {"package": click.style(slug, fg="green")}
... | Create a Python 3 function for
waiting for a package to be synced. | As a Python code analyst, you investigate and solve complex coding mysteries |
Upload files and create a new package. | How would you explain what the following Python 3 function does
def upload_files_and_create_package(
ctx,
opts,
package_type,
owner_repo,
dry_run,
no_wait_for_sync,
wait_interval,
skip_errors,
sync_attempts,
**kwargs
):
"""Upload package files and create a new package."""
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a handler for uploading a new package from each of the package formats. | Here you have a function in Python 3, explain what it does
def create_push_handlers():
# pylint: disable=fixme
# HACK: hacky territory - Dynamically generate a handler for each of the
# package formats, until we have slightly more clever 'guess type'
# handling. :-)
handlers = create_push_handlers.h... | As a Python code composer, you craft elegant and concise scripts. |
Memoize a function to return the cached result on subsequent calls. | Given the following Python 3 function, write the documentation
def memoize(func):
func._result_cache = {} # pylint: disable-msg=W0212
@wraps(func)
def _memoized_func(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key in func._result_cache: # pylint: disable-msg=W0212
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def clear_memoized_methods(obj, *method_names):
"""
Clear the memoized method or @memoizedproperty results for the given
method names from the given object.
>>> v = [0]
>>> def inc():
... v[0] += 1
... return v[0]
...
>>> class Foo(object):
... @memoizemethod
... ... | Create a Python 3 function to
clear the memoized method or memoized property results for the given method names from the given object. | As a Python code composer, you craft elegant and concise scripts. |
Encrypt data with AES - CBC and sign it with HMAC - SHA256 | Make a summary of the following Python 3 code
def aes_encrypt(base64_encryption_key, data):
if isinstance(data, text_type):
data = data.encode("UTF-8")
aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key)
data = _pad(data)
iv_bytes = os.urandom(AES_BLOCK_SIZE)
cipher = AES.ne... | You are a Python code generator, capable of creating scripts from specifications. |
Verify HMAC - SHA256 signature and decrypt data with AES - CBC | Explain what the following Python 3 code does
def aes_decrypt(base64_encryption_key, base64_data):
data = from_base64(base64_data)
aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key)
data, hmac_signature = data[:-HMAC_SIG_SIZE], data[-HMAC_SIG_SIZE:]
if hmac.new(hmac_key_bytes, data, ha... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Retrieve your current authentication status. | Given the following Python 3 function, write the documentation
def whoami(ctx, opts):
click.echo("Retrieving your authentication status from the API ... ", nl=False)
context_msg = "Failed to retrieve your authentication status!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
w... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _clean(self, value):
"""Perform a standardized pipline of operations across an iterable."""
value = (str(v) for v in value)
if self.strip:
value = (v.strip() for v in value)
if not self.empty:
value = (v for v in value if v)
return value | Can you write a function in Python 3 where it
performs a standardized pipline of operations across an iterable. | You are a Python code architect, reviewing and designing scalable and efficient code |
def native(self, value, context=None):
"""Convert the given string into a list of substrings."""
separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator
value = super().native(value, context)
if value is None:
return self.cast()
if hasattr(value, '... | Can you write a function in Python 3 where it
converts the given string into a list of substrings. | You are a Python code analyst, evaluating scripts for potential improvements. |
def foreign(self, value, context=None):
"""Construct a string-like representation for an iterable of string-like objects."""
if self.separator is None:
separator = ' '
else:
separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator
value = self._clean(... | Can you create a Python 3 function that
constructs a string - like representation for an iterable of string - like objects. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return provided 32 bit value as a string of four bytes. | Can you tell what is the following Python 3 function doing
def tob32(val):
ret = bytearray(4)
ret[0] = (val>>24)&M8
ret[1] = (val>>16)&M8
ret[2] = (val>>8)&M8
ret[3] = val&M8
return ret | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert binary buffer to ihex and return as string. | Explain what the following Python 3 code does
def bintoihex(buf, spos=0x0000):
c = 0
olen = len(buf)
ret = ""
# 16 byte lines
while (c+0x10) <= olen:
adr = c + spos
l = ':10{0:04X}00'.format(adr)
sum = 0x10+((adr>>8)&M8)+(adr&M8)
for j in range(0,0x10):
nb... | As a python code expert, you are capable of creating scripts from specifications. |
Generate a machine instruction using the op gen table. | How would you explain what the following Python 3 function does
def op_gen(mcode):
gen = op_tbl[mcode[0]]
ret = gen[0] # opcode
nargs = len(gen)
i = 1
while i < nargs:
if i < len(mcode): # or assume they are same len
ret |= (mcode[i]&gen[i][0]) << gen[i][1]
i += 1
ret... | As a Python code analyst, you investigate and solve complex coding mysteries |
def scanerror(self, msg):
"""Emit scan error and abort assembly."""
error('scan error: ' + msg + ' on line {}'.format(self.sline))
sys.exit(-1) | How would you implement a function in Python 3 that
emits scan error and abort assembly. | You are a Python code analyst, evaluating scripts for potential improvements. |
def parseerror(self, msg, line=None):
"""Emit parse error and abort assembly."""
if line is None:
line = self.sline
error('parse error: ' + msg + ' on line {}'.format(line))
sys.exit(-2) | Write a Python 3 function for
emitting parse error and abort assembly. | As a Python code composer, you craft elegant and concise scripts. |
def make_create_payload(**kwargs):
"""Create payload for upload/check-upload operations."""
payload = {}
# Add non-empty arguments
for k, v in six.iteritems(kwargs):
if v is not None:
payload[k] = v
return payload | Can you implement a function in Python 3 that
creates payload for upload or check - upload operations. | You are a Python code analyst, evaluating scripts for potential improvements. |
def create_package(package_format, owner, repo, **kwargs):
"""Create a new package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
upload = getattr(client, "packages_upload_%s_with_http_info" % package_format)
data, _, headers = upload(
owner=o... | Write a Python 3 function for
creating a new package in a repository. | You are a Python code analyst, evaluating scripts for potential improvements. |
Validate parameters for creating a package. | Explain what the following Python 3 code does
def validate_create_package(package_format, owner, repo, **kwargs):
client = get_packages_api()
with catch_raise_api_exception():
check = getattr(
client, "packages_validate_upload_%s_with_http_info" % package_format
)
_, _, hea... | As a Python code analyst, you investigate and solve complex coding mysteries |
Copy a package to another repository. | Can you tell what is the following Python 3 function doing
def copy_package(owner, repo, identifier, destination):
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_copy_with_http_info(
owner=owner,
repo=repo,
identifier... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def move_package(owner, repo, identifier, destination):
"""Move a package to another repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_move_with_http_info(
owner=owner,
repo=repo,
identifier=identifier... | Can you implement a function in Python 3 that
moves a package to another repository. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def delete_package(owner, repo, identifier):
"""Delete a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
_, _, headers = client.packages_delete_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratelimits.maybe_rate_li... | Write a Python 3 script to
delete a package in a repository. | As a Python code composer, you craft elegant and concise scripts. |
Get the status of a package in a repository. | Can you tell what is the following Python 3 function doing
def get_package_status(owner, repo, identifier):
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_status_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ra... | As a python code expert, you are capable of creating scripts from specifications. |
def list_packages(owner, repo, **kwargs):
"""List packages for a repository."""
client = get_packages_api()
api_kwargs = {}
api_kwargs.update(utils.get_page_kwargs(**kwargs))
api_kwargs.update(utils.get_query_kwargs(**kwargs))
with catch_raise_api_exception():
data, _, headers = client... | Write a Python 3 script to
list packages for a repository. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the list of available package formats and parameters. | Explain what the following Python 3 code does
def get_package_formats():
# pylint: disable=fixme
# HACK: This obviously isn't great, and it is subject to change as
# the API changes, but it'll do for now as a interim method of
# introspection to get the parameters we need.
def get_parameters(cls):
... | As a python code expert, you are capable of creating scripts from specifications. |
def get_package_format_names(predicate=None):
"""Get names for available package formats."""
return [
k
for k, v in six.iteritems(get_package_formats())
if not predicate or predicate(k, v)
] | Create a Python 3 function for
getting names for available package formats. | As a python code expert, you are capable of creating scripts from specifications. |
Start a new timer. | Here you have a function in Python 3, explain what it does
def start(opts, bot, event):
name = opts['--name']
now = datetime.datetime.now()
bot.timers[name] = now
return bot.start_fmt.format(now) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Retrieve user token from the API via authentication. | Here you have a function in Python 3, explain what it does
def get_user_token(login, password):
client = get_user_api()
# Never use API key for the token endpoint
config = cloudsmith_api.Configuration()
set_api_key(config, None)
with catch_raise_api_exception():
data, _, headers = client.u... | You are a Python code generator, capable of creating scripts from specifications. |
Retrieve brief for current user. | How would you explain what the following Python 3 function does
def get_user_brief():
client = get_user_api()
with catch_raise_api_exception():
data, _, headers = client.user_self_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
return data.authenticated, data.slug, data.email, da... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_default_filepath(cls):
"""Get the default filepath for the configuratin file."""
if not cls.config_files:
return None
if not cls.config_searchpath:
return None
filename = cls.config_files[0]
filepath = cls.config_searchpath[0]
return os.pat... | Write a Python 3 function for
getting the default filepath for the configuratin file. | As a python code expert, you are capable of creating scripts from specifications. |
Create a config file and override data if specified. | Here you have a function in Python 3, explain what it does
def create_default_file(cls, data=None, mode=None):
filepath = cls.get_default_filepath()
if not filepath:
return False
filename = os.path.basename(filepath)
config = read_file(get_data_path(), filename)
# F... | You are a Python code architect, reviewing and designing scalable and efficient code |
Check if a configuration file exists. | Here you have a function in Python 3, explain what it does
def has_default_file(cls):
for filename in cls.config_files:
for searchpath in cls.config_searchpath:
path = os.path.join(searchpath, filename)
if os.path.exists(path):
return True
... | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.