output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def _update_activities(self):
"""Update stored activities and update caches as required."""
self._activities = self._activities_request()
_LOGGER.debug("Device Activities Response: %s", self._activities)
if not self._activities:
self._activities = []
elif not isinsta... | How would you implement a function in Python 3 that
updates stored activities and update caches as required. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Update our cached list of latest activity events. | Here you have a function in Python 3, explain what it does
def _update_events(self):
events = self._skybell.dev_cache(self, CONST.EVENT) or {}
for activity in self._activities:
event = activity.get(CONST.EVENT)
created_at = activity.get(CONST.CREATED_AT)
old_event =... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def activities(self, limit=1, event=None):
"""Return device activity information."""
activities = self._activities or []
# Filter our activity array if requested
if event:
activities = list(
filter(
lambda activity:
act... | How would you code a function in Python 3 to
return the requested number of activity information. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _set_setting(self, settings):
"""Validate the settings and then send the PATCH request."""
for key, value in settings.items():
_validate_setting(key, value)
try:
self._settings_request(method="patch", json_data=settings)
self.update(settings_json=setting... | Write a Python 3 script to
validate the settings and then send the PATCH request. | As a python code expert, you are capable of creating scripts from specifications. |
Return lat and lng tuple. | Given the following Python 3 function, write the documentation
def location(self):
location = self._device_json.get(CONST.LOCATION, {})
return (location.get(CONST.LOCATION_LAT, 0),
location.get(CONST.LOCATION_LNG, 0)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def wifi_status(self):
"""Get the wifi status."""
return self._info_json.get(CONST.STATUS, {}).get(CONST.WIFI_LINK) | How would you implement a function in Python 3 that
gets the wifi status. | As a python code expert, you are capable of creating scripts from specifications. |
Get if do not disturb is enabled. | Here you have a function in Python 3, explain what it does
def do_not_disturb(self):
return bool(strtobool(str(self._settings_json.get(
CONST.SETTINGS_DO_NOT_DISTURB)))) | You are a Python code generator, capable of creating scripts from specifications. |
def do_not_disturb(self, enabled):
"""Set do not disturb."""
self._set_setting(
{
CONST.SETTINGS_DO_NOT_DISTURB: str(enabled).lower()
}) | Can you create a Python 3 function that
sets do not disturb. | You are a Python code generator, capable of creating scripts from specifications. |
def motion_sensor(self, enabled):
"""Set the motion sensor state."""
if enabled is True:
value = CONST.SETTINGS_MOTION_POLICY_ON
elif enabled is False:
value = CONST.SETTINGS_MOTION_POLICY_OFF
else:
raise SkybellException(ERROR.INVALID_SETTING_VALUE,
... | Write a Python 3 script to
set the motion sensor state. | As a Python code composer, you craft elegant and concise scripts. |
def led_rgb(self):
"""Get devices LED color."""
return (int(self._settings_json.get(CONST.SETTINGS_LED_R)),
int(self._settings_json.get(CONST.SETTINGS_LED_G)),
int(self._settings_json.get(CONST.SETTINGS_LED_B))) | Write a Python 3 script to
get devices LED color. | You are a Python code analyst, evaluating scripts for potential improvements. |
Set devices LED color. | Can you generate a brief explanation for the following Python 3 code
def led_rgb(self, color):
if (not isinstance(color, (list, tuple)) or
not all(isinstance(item, int) for item in color)):
raise SkybellException(ERROR.COLOR_VALUE_NOT_VALID, color)
self._set_setting(
... | As a python code expert, you are capable of creating scripts from specifications. |
def remote(self, remote_base=None, username=None, password=None):
"""
Configures remote access
Parameters
----------
remote_base : str
base URL path for remote repository
username : str
user name for remote repository
password : str
... | Write a Python 3 function that can
configure remote access to the local repository | You are a Python code generator, capable of creating scripts from specifications. |
def get(self, filetype, **kwargs):
"""Returns file name, downloading if remote access configured.
Parameters
----------
filetype : str
type of file
keyword arguments :
keywords to fully specify path
Notes
-----
Path templates are... | Can you create a Python 3 function that
returns file name downloading if remote access configured. | You are a Python code architect, reviewing and designing scalable and efficient code |
Download a file from url to path and put it at path. | How would you explain what the following Python 3 function does
def download_url_to_path(self, url, path, force=False):
path_exists = isfile(path)
if not path_exists or force:
dir = dirname(path)
if not exists(dir):
if self.verbose:
print("CR... | You are a Python code generator, capable of creating scripts from specifications. |
Reset all the streams and initial streams | Can you generate a brief explanation for the following Python 3 code
def reset(self):
''' Reset all streams '''
# reset the main stream
if self.stream:
self.stream.reset()
# reset the initial stream (otherwise old 'adds' remain in the new stream)
if self.initial_str... | As a Python code analyst, you investigate and solve complex coding mysteries |
def add(self, filetype, **kwargs):
""" Adds a filepath into the list of tasks to download"""
location = self.location(filetype, **kwargs)
source = self.url(filetype, sasdir='sas' if not self.public else '', **kwargs)
if 'full' not in kwargs:
destination = self.full(filetype,... | Write a Python 3 script for
adding a filepath into the list of tasks to download | You are a Python code generator, capable of creating scripts from specifications. |
def set_stream(self):
""" Sets the download streams """
if not self.auth:
raise AccessError("Please use the remote() method to set rsync authorization or use remote(public=True) for public data")
elif not self.initial_stream.task:
raise AccessError("No files to download.... | How would you code a function in Python 3 to
set the download streams | You are a Python code analyst, evaluating scripts for potential improvements. |
Commit the rsync download | Can you generate the documentation for the following Python 3 function
def commit(self, offset=None, limit=None, dryrun=False):
self.stream.command = "rsync -avRK --files-from={path} {source} {destination}"
self.stream.append_tasks_to_streamlets(offset=offset, limit=limit)
self.stream.commit_st... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the balance of this entry after this entry. | How would you explain what the following Python 3 function does
def balance(self) -> Decimal:
return sum_queryset(AccountEntry.objects.filter(account=self.account, timestamp__lte=self.timestamp).exclude(timestamp=self.timestamp, id__gt=self.id)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the balance of all entries in the account before the specified datetime. | Can you generate the documentation for the following Python 3 function
def get_balance(self, t: datetime):
return sum_queryset(self.accountentry_set.all().filter(timestamp__lt=t)) | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns True if the account entry needs settling | Given the following Python 3 function, write the documentation
def needs_settling(self, e: AccountEntry) -> bool:
return e.type and e.type.is_settlement and e.account.id == self.id and e.settled_invoice and AccountEntry.objects.filter(parent=e).count() == 0 | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the account that this invoice was recorded in. | Make a summary of the following Python 3 code
def receivables_account(self) -> Account:
row = AccountEntry.objects.filter(source_invoice=self).order_by('id').first()
return row.account if row else None | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns all entries related to this invoice on specified account. | Make a summary of the following Python 3 code
def get_entries(self, acc: Account, cls=AccountEntry) -> QuerySet:
return cls.objects.filter(Q(account=acc) & (Q(source_invoice=self) | Q(settled_invoice=self))) if acc else cls.objects.none() | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_item_balances(self, acc: Account) -> list:
"""
Returns balances of items of the invoice.
:param acc: Account
:return: list (AccountEntry, Decimal) in item id order
"""
items = []
entries = self.get_entries(acc)
for item in entries.filter(source_inv... | Create a Python 3 function to
return balances of items of the invoice. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the list of unpaid items of the invoice in payback priority order. | Given the following Python 3 function, write the documentation
def get_unpaid_items(self, acc: Account) -> list:
unpaid_items = []
for item, bal in self.get_item_balances(acc):
assert isinstance(item, AccountEntry)
if self.type == INVOICE_DEFAULT:
if bal > Decimal... | You are a Python code analyst, evaluating scripts for potential improvements. |
def MakeRanges(codes):
"""Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]"""
ranges = []
last = -100
for c in codes:
if c == last+1:
ranges[-1][1] = c
else:
ranges.append([c, c])
last = c
return ranges | Can you implement a function in Python 3 that
turns a list like 1 2 3 7 8 9 into a range list | As a Python code analyst, you investigate and solve complex coding mysteries |
def PrintRanges(type, name, ranges):
"""Print the ranges as an array of type named name."""
print "static const %s %s[] = {" % (type, name,)
for lo, hi in ranges:
print "\t{ %d, %d }," % (lo, hi)
print "};" | Implement a function in Python 3 to
print the ranges as an array of type named name. | As a python code expert, you are capable of creating scripts from specifications. |
Print the data structures for the group of codes. | How would you explain what the following Python 3 function does
def PrintGroup(name, codes):
# See unicode_groups.h for a description of the data structure.
# Split codes into 16-bit ranges and 32-bit ranges.
range16 = MakeRanges([c for c in codes if c < 65536])
range32 = MakeRanges([c for c in codes if c >= ... | You are a Python code generator, capable of creating scripts from specifications. |
def settle_assigned_invoice(receivables_account: Account, settlement: AccountEntry, cls, **kwargs) -> list:
"""
Finds unpaid items in the invoice and generates entries to receivables account.
Settlement is matched to invoice items based on entry types payback order.
Generated payment entries have 'paren... | How would you implement a function in Python 3 that
returns a list of unpaid items in the invoice which are assigned to the given account. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def settle_credit_note(credit_note: Invoice, debit_note: Invoice, cls, account: Account, **kwargs) -> list:
"""
Settles credit note. Records settling account entries for both original invoice and the credit note
(negative entries for the credit note).
Default timestamp for account entries is 'created' t... | Implement a Python 3 function for
returning a list of payments for the given credit note. | You are a Python code generator, capable of creating scripts from specifications. |
Read the path template file. | Given the following Python 3 function, write the documentation
def _input_templates(self):
foo = self._config.read([self._pathfile])
if len(foo) == 1:
for k, v in self._config.items('paths'):
self.templates[k] = v
else:
raise ValueError("Could not read {0}... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Lookup the keyword arguments needed for a given path name. | Can you generate a brief explanation for the following Python 3 code
def lookup_keys(self, name):
''' Lookup the keyword arguments needed for a given path name
Parameters:
name (str):
The name of the path
Returns:
A list of keywords needed for filepath g... | As a Python code composer, you craft elegant and concise scripts. |
def _check_special_kwargs(self, name):
''' check special functions for kwargs
Checks the content of the special functions (%methodname) for
any keyword arguments referenced within
Parameters:
name (str):
A path key name
Returns:
... | Write a Python 3 function that can
check special functions for kwargs | As a Python code analyst, you investigate and solve complex coding mysteries |
def _find_source(method):
''' find source code of a given method
Find and extract the source code of a given method in a module.
Uses inspect.findsource to get all source code and performs some
selection magic to identify method source code. Doing it this way
because in... | Write a Python 3 script to
find source code of a given method in a module | As a python code expert, you are capable of creating scripts from specifications. |
Extract keywords from an example path | How would you explain what the following Python 3 function does
def extract(self, name, example):
''' Extract keywords from an example path '''
# if pathlib not available do nothing
if not pathlib:
return None
# ensure example is a string
if isinstance(example, path... | As a Python code analyst, you investigate and solve complex coding mysteries |
def dir(self, filetype, **kwargs):
"""Return the directory containing a file of a given type.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
dir : str
Directory containing the file.
"""
full = k... | Write a Python 3 function that can
return the directory containing a file of a given type. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the name of a file of a given type. | Here you have a function in Python 3, explain what it does
def name(self, filetype, **kwargs):
full = kwargs.get('full', None)
if not full:
full = self.full(filetype, **kwargs)
return os.path.basename(full) | You are a Python code generator, capable of creating scripts from specifications. |
def exists(self, filetype, remote=None, **kwargs):
'''Checks if the given type of file exists locally
Parameters
----------
filetype : str
File type parameter.
remote : bool
If True, checks for remote existence of the file
Returns
------... | Can you create a Python 3 function that
checks if the given type of file exists locally. | As a Python code analyst, you investigate and solve complex coding mysteries |
def expand(self, filetype, **kwargs):
''' Expand a wildcard path locally
Parameters
----------
filetype : str
File type parameter.
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression string to filter the list of fi... | Write a Python 3 script to
expand a wildcard path locally and return a list of SAS urls or a list of files by the given type. | As a Python code composer, you craft elegant and concise scripts. |
def any(self, filetype, **kwargs):
''' Checks if the local directory contains any of the type of file
Parameters
----------
filetype : str
File type parameter.
Returns
-------
any : bool
Boolean indicating if the any files exist in the ex... | Implement a Python 3 function for
checking if the local directory contains any of the type of file | You are a Python code generator, capable of creating scripts from specifications. |
def one(self, filetype, **kwargs):
''' Returns random one of the given type of file
Parameters
----------
filetype : str
File type parameter.
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression string to filter the... | Create a Python 3 function for
returning a random one of the given type of file | As a Python code composer, you craft elegant and concise scripts. |
def random(self, filetype, **kwargs):
''' Returns random number of the given type of file
Parameters
----------
filetype : str
File type parameter.
num : int
The number of files to return
as_url: bool
Boolean to return SAS urls
... | Implement a Python 3 function for
returning a random number of the given type of file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def refine(self, filelist, regex, filterdir='out', **kwargs):
''' Returns a list of files filterd by a regular expression
Parameters
----------
filelist : list
A list of files to filter on.
regex : str
The regular expression string to filter your list
... | Can you create a Python 3 function that
returns a list of files that satisfy a regular expression. | You are a Python code analyst, evaluating scripts for potential improvements. |
def full(self, filetype, **kwargs):
"""Return the full name of a given type of file.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
full : str
The full path to the file.
"""
# check if full alre... | Implement a function in Python 3 to
return the full name of a given type of file. | You are a Python code generator, capable of creating scripts from specifications. |
Calls the special functions found in the path
and returns the expanded template path
| Can you generate a brief explanation for the following Python 3 code
def _call_special_functions(self, filetype, template, **kwargs):
''' Call the special functions found in a template path
Calls special functions indicated by %methodname found in the
sdss_paths.ini template file, and replaces ... | As a Python code composer, you craft elegant and concise scripts. |
def location(self, filetype, base_dir=None, **kwargs):
"""Return the location of the relative sas path of a given type of file.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
full : str
The relative sas path to ... | Write a Python 3 script for
returning the location of the relative SAS path of a given type of file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the url of a given type of file. | Make a summary of the following Python 3 code
def url(self, filetype, base_dir=None, sasdir='sas', **kwargs):
location = self.location(filetype, **kwargs)
return join(self.remote_base, sasdir, location) if self.remote_base and location else None | As a Python code translator, you convert algorithms and pseudocode into Python. |
Print plate ID accounting for 5 - 6 digit plate IDs. | Given the following Python 3 function, write the documentation
def plateid6(self, filetype, **kwargs):
plateid = int(kwargs['plateid'])
if plateid < 10000:
return "{:0>6d}".format(plateid)
else:
return "{:d}".format(plateid) | You are a Python code analyst, evaluating scripts for potential improvements. |
def platedir(self, filetype, **kwargs):
"""Returns plate subdirectory in :envvar:`PLATELIST_DIR` of the form: ``NNNNXX/NNNNNN``.
Parameters
----------
filetype : str
File type parameter.
plateid : int or str
Plate ID number. Will be converted to int inte... | Can you write a function in Python 3 where it
returns the platedir of the current object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def spectrodir(self, filetype, **kwargs):
"""Returns :envvar:`SPECTRO_REDUX` or :envvar:`BOSS_SPECTRO_REDUX`
depending on the value of `run2d`.
Parameters
----------
filetype : str
File type parameter.
run2d : int or str
2D Reduction ID.
... | Implement a function in Python 3 to
return the value of SPECTRO_REDUX or BOSS_SPECTRO_REDUX depending on the value of run2d. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the definition subdirectory in the form NNNNNXX. | Can you generate a brief explanation for the following Python 3 code
def definitiondir(self, filetype, **kwargs):
designid = int(kwargs['designid'])
designid100 = designid // 100
subdir = "{:0>4d}".format(designid100) + "XX"
return subdir | As a Python code translator, you convert algorithms and pseudocode into Python. |
A convenient wrapper to log and perform system calls. | Can you tell what is the following Python 3 function doing
def foreground_run(self, command, test=False, logger=None, logall=False, message=None, outname=None, errname=None):
if logger is not None:
logger.debug(command)
status = 0
out = ''
err = ''
if not test:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def change(ui, repo, *pats, **opts):
"""create, edit or delete a change list
Create, edit or delete a change list.
A change list is a group of files to be reviewed and submitted together,
plus a textual description of the change.
Change lists are referred to by simple alphanumeric names.
Changes must be reviewe... | Implement a function in Python 3 to
create edit or delete a change list | As a Python code composer, you craft elegant and concise scripts. |
def undo(ui, repo, clname, **opts):
"""undo the effect of a CL
Creates a new CL that undoes an earlier CL.
After creating the CL, opens the CL text for editing so that
you can add the reason for the undo to the description.
"""
if repo[None].branch() != "default":
raise hg_util.Abort("cannot run hg undo outsi... | Write a Python 3 function for
undoing the effect of a CL | As a Python code composer, you craft elegant and concise scripts. |
Apply a CL to the release branch. | Make a summary of the following Python 3 code
def release_apply(ui, repo, clname, **opts):
c = repo[None]
if not releaseBranch:
raise hg_util.Abort("no active release branches")
if c.branch() != releaseBranch:
if c.modified() or c.added() or c.removed():
raise hg_util.Abort("uncommitted local changes - cannot... | You are a Python code generator, capable of creating scripts from specifications. |
download a change from the code review server | Here you have a function in Python 3, explain what it does
def download(ui, repo, clname, **opts):
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
cl, vers, patch, err = DownloadCL(ui, repo, clname)
if err != "":
return err
ui.write(cl.EditorText() + "\n")
ui.write(patch + "\n")
return | As a Python code composer, you craft elegant and concise scripts. |
file - change list | How would you explain what the following Python 3 function does
def file(ui, repo, clname, pat, *pats, **opts):
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
pats = tuple([pat] + list(pats))
if not GoodCLName(clname):
return "invalid CL name " + clname
dirty = {}
cl, err = LoadCL(ui, repo,... | You are a Python code architect, reviewing and designing scalable and efficient code |
def gofmt(ui, repo, *pats, **opts):
"""apply gofmt to modified files
Applies gofmt to the modified files in the repository that match
the given patterns.
"""
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
files = ChangedExistingFiles(ui, repo, pats, opts)
files = gofmt_required(files)
if n... | Can you create a Python 3 function that
applies gofmt to modified files in the repository that match the given patterns. | As a Python code translator, you convert algorithms and pseudocode into Python. |
mail a change for review
Uploads a patch to the code review server and sends mail
to the reviewer and CC list asking for a review. | Can you tell what is the following Python 3 function doing
def mail(ui, repo, *pats, **opts):
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
cl, err = CommandLineCL(ui, repo, pats, opts, op="mail", defaultcc=defaultcc)
if err != "":
raise hg_util.Abort(err)
cl.Upload(ui, repo, gofmt_just_warn... | As a Python code composer, you craft elegant and concise scripts. |
alias for hg p | Given the following Python 3 function, write the documentation
def ps(ui, repo, *pats, **opts):
opts['short'] = True
return pending(ui, repo, *pats, **opts) | You are a Python code generator, capable of creating scripts from specifications. |
def pq(ui, repo, *pats, **opts):
"""alias for hg p --quick
"""
opts['quick'] = True
return pending(ui, repo, *pats, **opts) | How would you implement a function in Python 3 that
aliases for hg p | As a Python code analyst, you investigate and solve complex coding mysteries |
def pending(ui, repo, *pats, **opts):
"""show pending changes
Lists pending changes followed by a list of unassigned but modified files.
"""
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
quick = opts.get('quick', False)
short = opts.get('short', False)
m = LoadAllCL(ui, repo, web=not quick... | How would you implement a function in Python 3 that
shows pending changes Lists pending changes followed by a list of unassigned but modified files. | You are a Python code generator, capable of creating scripts from specifications. |
def submit(ui, repo, *pats, **opts):
"""submit change to remote repository
Submits change to remote repository.
Bails out if the local repository is not in sync with the remote one.
"""
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
# We already called this on startup but sometimes Mercurial... | Write a Python 3 function that can
submit change to remote repository | You are a Python code generator, capable of creating scripts from specifications. |
synchronize with remote repository
Incorporates recent changes from the remote repository
into the local repository
if local flag is set to True | Explain what the following Python 3 code does
def sync(ui, repo, **opts):
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
if not opts["local"]:
# If there are incoming CLs, pull -u will do the update.
# If there are no incoming CLs, do hg update to make sure
# that an update always happens r... | As a Python code composer, you craft elegant and concise scripts. |
upload diffs to the code review server | Can you generate the documentation for the following Python 3 function
def upload(ui, repo, name, **opts):
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
repo.ui.quiet = True
cl, err = LoadCL(ui, repo, name, web=True)
if err != "":
raise hg_util.Abort(err)
if not cl.local:
raise hg_util.Ab... | As a Python code analyst, you investigate and solve complex coding mysteries |
Run MySend1 maybe twice because Rietveld is unreliable. | Can you generate the documentation for the following Python 3 function
def MySend(request_path, payload=None,
content_type="application/octet-stream",
timeout=None, force_auth=True,
**kwargs):
"""Run MySend1 maybe twice, because Rietveld is unreliable."""
try:
return MySend1(request_path, payload, content_typ... | As a python code expert, you are capable of creating scripts from specifications. |
def MySend1(request_path, payload=None,
content_type="application/octet-stream",
timeout=None, force_auth=True,
**kwargs):
"""Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body of the request, or None to send an emp... | Write a Python 3 script for
sending a request to the server and return the response body. | As a python code expert, you are capable of creating scripts from specifications. |
Prompts the user for their email address and returns it. | How would you explain what the following Python 3 function does
def GetEmail(prompt):
last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
last_email = ""
if os.path.exists(last_email_file_name):
try:
last_email_file = open(last_email_file_name, "r")
last_email = last_email_file.read... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns an instance of an AbstractRpcServer. | Here you have a function in Python 3, explain what it does
def GetRpcServer(options):
rpc_server_class = HttpRpcServer
def GetUserCredentials():
"""Prompts the user for a username and password."""
# Disable status prints so they don't obscure the password prompt.
global global_status
st = global_status
gl... | As a Python code composer, you craft elegant and concise scripts. |
def EncodeMultipartFormData(fields, files):
"""Encode form fields for multipart/form-data.
Args:
fields: A sequence of (name, value) elements for regular form fields.
files: A sequence of (name, filename, value) elements for data to be
uploaded as files.
Returns:
(content_type, body) ready for httplib.HT... | Create a Python 3 function to
encode form fields for multipart / form - data. | You are a Python code analyst, evaluating scripts for potential improvements. |
def RunShellWithReturnCode(command, print_output=False,
universal_newlines=True, env=os.environ):
"""Executes a command and returns the output from stdout and the return code.
Args:
command: Command to execute.
print_output: If True, the output is printed to stdout.
If False, both stdout and stderr are igno... | Can you implement a function in Python 3 that
executes a command and returns the output from stdout and the return code. | As a Python code analyst, you investigate and solve complex coding mysteries |
Splits a svn diff into separate pieces for each file. | Make a summary of the following Python 3 code
def SplitPatch(data):
patches = []
filename = None
diff = []
for line in data.splitlines(True):
new_filename = None
if line.startswith('Index:'):
unused, new_filename = line.split(':', 1)
new_filename = new_filename.strip()
elif line.startswith('Property cha... | You are a Python code analyst, evaluating scripts for potential improvements. |
Uploads a separate patch for each file in the diff output. | Here you have a function in Python 3, explain what it does
def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
patches = SplitPatch(data)
rv = []
for patch in patches:
set_status("uploading patch for " + patch[0])
if len(patch[1]) > MAX_UPLOAD_SIZE:
print ("Not uploading the patch for " + p... | You are a Python code generator, capable of creating scripts from specifications. |
def _CreateRequest(self, url, data=None):
"""Creates a new urllib request."""
logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
req = urllib2.Request(url, data=data)
if self.host_override:
req.add_header("Host", self.host_override)
for key, value in self.extra_headers.iteritems():
... | Implement a function in Python 3 to
create a new urllib request. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Uses ClientLogin to authenticate the user returning an auth token. | Can you tell what is the following Python 3 function doing
def _GetAuthToken(self, email, password):
account_type = "GOOGLE"
if self.host.endswith(".google.com") and not force_google_account:
# Needed for use inside Google.
account_type = "HOSTED"
req = self._CreateRequest(
url="https://www.google.com/a... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _GetAuthCookie(self, auth_token):
"""Fetches authentication cookies for an authentication token.
Args:
auth_token: The authentication token returned by ClientLogin.
Raises:
HTTPError: If there was an error fetching the authentication cookies.
"""
# This is a dummy value to allow us to identify whe... | Create a Python 3 function to
fetch the authentication cookies for an authentication token. | You are a Python code generator, capable of creating scripts from specifications. |
Authenticates the user.
The authentication process works as follows:
1) We get a username and password from the user
2) We use ClientLogin to obtain an AUTH token for the user
(see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
3) We pass the auth token to /_ah/login on the server to obta... | How would you explain what the following Python 3 function does
def _Authenticate(self):
for i in range(3):
credentials = self.auth_function()
try:
auth_token = self._GetAuthToken(credentials[0], credentials[1])
except ClientLoginError, e:
if e.msg == "BadAuthentication":
print >>sys.stderr, "In... | As a Python code analyst, you investigate and solve complex coding mysteries |
Sends an RPC and returns the response body. | Explain what the following Python 3 code does
def Send(self, request_path, payload=None,
content_type="application/octet-stream",
timeout=None,
**kwargs):
"""Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body... | As a python code expert, you are capable of creating scripts from specifications. |
Save the cookie jar after authentication. | Can you generate the documentation for the following Python 3 function
def _Authenticate(self):
super(HttpRpcServer, self)._Authenticate()
if self.save_cookies:
StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
self.cookie_jar.save() | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _GetOpener(self):
"""Returns an OpenerDirector that supports cookies and ignores redirects.
Returns:
A urllib2.OpenerDirector object.
"""
opener = urllib2.OpenerDirector()
opener.add_handler(urllib2.ProxyHandler())
opener.add_handler(urllib2.UnknownHandler())
opener.add_handler(urllib2.HTTPHandler... | Can you create a Python 3 function that
returns an OpenerDirector that supports cookies and ignores redirects. | You are a Python code generator, capable of creating scripts from specifications. |
def CheckForUnknownFiles(self):
"""Show an "are you sure?" prompt if there are unknown files."""
unknown_files = self.GetUnknownFiles()
if unknown_files:
print "The following files are not added to version control:"
for line in unknown_files:
print line
prompt = "Are you sure to continue?(y/N) "
a... | Write a Python 3 function for
showing an error if there are unknown files. | You are a Python code generator, capable of creating scripts from specifications. |
This method uploads the base files to the server. | Make a summary of the following Python 3 code
def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
files):
"""Uploads the base files (and if necessary, the current ones as well)."""
def UploadFile(filename, file_id, content, is_binary, status, is_base):
"""Uploads a file to the... | You are a Python code analyst, evaluating scripts for potential improvements. |
def IsImage(self, filename):
"""Returns true if the filename has an image extension."""
mimetype = mimetypes.guess_type(filename)[0]
if not mimetype:
return False
return mimetype.startswith("image/") | Write a Python 3 script for
returning true if the filename has an image extension. | As a Python code composer, you craft elegant and concise scripts. |
def IsBinary(self, filename):
"""Returns true if the guessed mimetyped isnt't in text group."""
mimetype = mimetypes.guess_type(filename)[0]
if not mimetype:
return False # e.g. README, "real" binaries usually have an extension
# special case for text files which don't start with text/
if mimetype in TEXT... | Write a Python 3 script to
return true if the guessed mimetype is a text group. | As a Python code composer, you craft elegant and concise scripts. |
def _GetRelPath(self, filename):
"""Get relative path of a file according to the current directory,
given its logical path in the repo."""
assert filename.startswith(self.subdir), (filename, self.subdir)
return filename[len(self.subdir):].lstrip(r"\/") | Write a Python 3 script for
getting relative path of a file according to the current directory. | As a python code expert, you are capable of creating scripts from specifications. |
Return a list of files unknown to the VCS. | Here you have a function in Python 3, explain what it does
def GetUnknownFiles(self):
args = []
status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
silent_ok=True)
unknown_files = []
for line in status.splitlines():
st, fn = line.split(" ", 1)
if st == "?":
unknown_files.append(... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _UInt(s):
"""Converts string to Unicode code point ('263A' => 0x263a).
Args:
s: string to convert
Returns:
Unicode code point
Raises:
InputError: the string is not a valid Unicode value.
"""
try:
v = int(s, 16)
except ValueError:
v = -1
if len(s) < 4 or len(s) > 6 or v < 0 or... | Write a Python 3 function for
converting a Unicode string to Unicode code point. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts a string to Unicode range. | Can you generate a brief explanation for the following Python 3 code
def _URange(s):
a = s.split("..")
if len(a) == 1:
return [_UInt(a[0])]
if len(a) == 2:
lo = _UInt(a[0])
hi = _UInt(a[1])
if lo < hi:
return range(lo, hi + 1)
raise InputError("invalid Unicode range %s" % (s,)) | As a Python code composer, you craft elegant and concise scripts. |
def _ParseContinue(s):
"""Parses a Unicode continuation field.
These are of the form '<Name, First>' or '<Name, Last>'.
Instead of giving an explicit range in a single table entry,
some Unicode tables use two entries, one for the first
code value in the range and one for the last.
The first entry's descrip... | Implement a Python 3 function for
parsing a Unicode continuation field. | As a python code expert, you are capable of creating scripts from specifications. |
Returns list of Unicode code groups equivalent under case folding. | Explain what the following Python 3 code does
def CaseGroups(unicode_dir=_UNICODE_DIR):
# Dict mapping lowercase code point to fold-equivalent group.
togroup = {}
def DoLine(codes, fields):
"""Process single CaseFolding.txt line, updating togroup."""
(_, foldtype, lower, _) = fields
if foldtype not ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def Scripts(unicode_dir=_UNICODE_DIR):
"""Returns dict mapping script names to code lists.
Args:
unicode_dir: Unicode data directory
Returns:
dict mapping script names to code lists
"""
scripts = {}
def DoLine(codes, fields):
"""Process single Scripts.txt line, updating scripts."""
(_, n... | Implement a Python 3 function for
returning dict mapping script names to code lists. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a dict mapping category names to code lists. | Can you generate the documentation for the following Python 3 function
def Categories(unicode_dir=_UNICODE_DIR):
categories = {}
def DoLine(codes, fields):
"""Process single UnicodeData.txt line, updating categories."""
category = fields[2]
categories.setdefault(category, []).extend(codes)
# Add c... | As a Python code analyst, you investigate and solve complex coding mysteries |
def calculate_simple_interest(entries, rate_pct: Decimal, interest_date: date or None=None, begin: date or None=None) -> Decimal:
"""
Calculates simple interest of specified entries over time.
Does not accumulate interest to interest.
:param entries: AccountEntry iterable (e.g. list/QuerySet) ordered by... | How would you implement a function in Python 3 that
calculates simple interest of specified entries over time. | You are a Python code architect, reviewing and designing scalable and efficient code |
Generates a list - table directive that can be used to create a set of environment variables that are defined in the templates dictionary. | Can you generate the documentation for the following Python 3 function
def _format_templates(name, command, templates):
''' Creates a list-table directive
for a set of defined environment variables
Parameters:
name (str):
The name of the config section
command (object):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Generates the relevant Sphinx nodes. | Given the following Python 3 function, write the documentation
def _generate_nodes(self, name, command, templates=None):
# the source name
source_name = name
# Title
section = nodes.section(
'',
nodes.title(text=name),
ids=[nodes.make_id(name)],
... | As a Python code composer, you craft elegant and concise scripts. |
Compute the delta for a and b. | Can you generate a brief explanation for the following Python 3 code
def _Delta(a, b):
if a+1 == b:
if a%2 == 0:
return 'EvenOdd'
else:
return 'OddEven'
if a == b+1:
if a%2 == 0:
return 'OddEven'
else:
return 'EvenOdd'
return b - a | As a python code expert, you are capable of creating scripts from specifications. |
def _AddDelta(a, delta):
"""Return a + delta, handling EvenOdd and OddEven specially."""
if type(delta) == int:
return a+delta
if delta == 'EvenOdd':
if a%2 == 0:
return a+1
else:
return a-1
if delta == 'OddEven':
if a%2 == 1:
return a+1
else:
return a-1
print >>sys... | Can you implement a function in Python 3 that
returns a + delta handling EvenOdd and OddEven specially. | You are a Python code analyst, evaluating scripts for potential improvements. |
Turn a list like [ 65 98... + 32 ) into a list like [ 65 90 + 32 ). | How would you explain what the following Python 3 function does
def _MakeRanges(pairs):
ranges = []
last = -100
def evenodd(last, a, b, r):
if a != last+1 or b != _AddDelta(a, r[2]):
return False
r[1] = a
return True
def evenoddpair(last, a, b, r):
if a != last+2:
return False
... | You are a Python code generator, capable of creating scripts from specifications. |
def align_lines(lines: list, column_separator: str='|') -> list:
"""
Pads lines so that all rows in single column match. Columns separated by '|' in every line.
:param lines: list of lines
:param column_separator: column separator. default is '|'
:return: list of lines
"""
rows = []
col_... | Write a Python 3 script to
align a list of lines so that all rows in single column match. Columns separated by '|' in every line. | You are a Python code analyst, evaluating scripts for potential improvements. |
def resend_invoices(modeladmin, request: HttpRequest, queryset: QuerySet):
"""
Marks invoices with as un-sent.
:param modeladmin:
:param request:
:param queryset:
:return:
"""
user = request.user
assert isinstance(user, User)
for obj in queryset:
assert isinstance(obj, In... | Implement a function in Python 3 to
mark invoices with as un - sent. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.