output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def variations(word):
"""Create variations of the word based on letter combinations like oo,
sh, etc."""
if len(word) == 1:
return [[word[0]]]
elif word == 'aa':
return [['A']]
elif word == 'ee':
return [['i']]
elif word == 'ei':
return [['ei']]
elif word in ['oo... | How would you implement a function in Python 3 that
creates variations of the word based on letter combinations like oo ou etc. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert a single word from Finglish to Persian. | Explain what the following Python 3 code does
def f2p_word(word, max_word_size=15, cutoff=3):
original_word = word
word = word.lower()
c = dictionary.get(word)
if c:
return [(c, 1.0)]
if word == '':
return []
elif len(word) > max_word_size:
return [(original_word, 1.0)... | You are a Python code architect, reviewing and designing scalable and efficient code |
def f2p_list(phrase, max_word_size=15, cutoff=3):
"""Convert a phrase from Finglish to Persian.
phrase: The phrase to convert.
max_word_size: Maximum size of the words to consider. Words larger
than this will be kept unchanged.
cutoff: The cut-off point. For each word, there could be many
pos... | Write a Python 3 script for
converting a phrase from Finglish to Persian. | As a python code expert, you are capable of creating scripts from specifications. |
def f2p(phrase, max_word_size=15, cutoff=3):
"""Convert a Finglish phrase to the most probable Persian phrase.
"""
results = f2p_list(phrase, max_word_size, cutoff)
return ' '.join(i[0][0] for i in results) | How would you code a function in Python 3 to
convert a Finglish phrase to the most probable Persian phrase. | You are a Python code generator, capable of creating scripts from specifications. |
def distribution_version(name):
"""try to get the version of the named distribution,
returs None on failure"""
from pkg_resources import get_distribution, DistributionNotFound
try:
dist = get_distribution(name)
except DistributionNotFound:
pass
else:
return dist.version | Implement a Python 3 function for
trying to get the version of the named distribution returs None on failure | As a python code expert, you are capable of creating scripts from specifications. |
def initpkg(pkgname, exportdefs, attr=None, eager=False):
""" initialize given package from the export definitions. """
attr = attr or {}
oldmod = sys.modules.get(pkgname)
d = {}
f = getattr(oldmod, '__file__', None)
if f:
f = _py_abspath(f)
d['__file__'] = f
if hasattr(oldmod, '... | Create a Python 3 function for
initializing given package from the export definitions. | As a python code expert, you are capable of creating scripts from specifications. |
imports a module then resolves the attrname on it | Here you have a function in Python 3, explain what it does
def importobj(modpath, attrname):
module = __import__(modpath, None, None, ['__doc__'])
if not attrname:
return module
retval = module
names = attrname.split(".")
for x in names:
retval = getattr(retval, x)
return retval | As a Python code composer, you craft elegant and concise scripts. |
Does actual HTTP request using requests library. | Can you tell what is the following Python 3 function doing
def _request(self, http_method, relative_url='', **kwargs):
# It could be possible to call api.resource.get('/index')
# but it would be non-intuitive that the path would resolve
# to root of domain
relative_url = self._remove_lea... | As a Python code analyst, you investigate and solve complex coding mysteries |
Create new Url which points to new url. | Here you have a function in Python 3, explain what it does
def _new_url(self, relative_url):
return Url(
urljoin(self._base_url, relative_url),
**self._default_kwargs
) | As a Python code composer, you craft elegant and concise scripts. |
gets permissions of role | How would you explain what the following Python 3 function does
def get_permissions(self, role):
target_role = AuthGroup.objects(role=role, creator=self.client).first()
if not target_role:
return '[]'
targets = AuthPermission.objects(groups=target_role, creator=self.client).only('nam... | You are a Python code generator, capable of creating scripts from specifications. |
get permissions of a user | How would you explain what the following Python 3 function does
def get_user_permissions(self, user):
memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups')
results = []
for each in memberShipRecords:
for group in each.groups:
target... | You are a Python code analyst, evaluating scripts for potential improvements. |
get permissions of a user | Can you tell what is the following Python 3 function doing
def get_user_roles(self, user):
memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups')
results = []
for each in memberShipRecords:
for group in each.groups:
results.append({'... | As a python code expert, you are capable of creating scripts from specifications. |
get permissions of a user | Can you generate the documentation for the following Python 3 function
def get_role_members(self, role):
targetRoleDb = AuthGroup.objects(creator=self.client, role=role)
members = AuthMembership.objects(groups__in=targetRoleDb).only('user')
return json.loads(members.to_json()) | As a Python code composer, you craft elegant and concise scripts. |
Returns a role object | How would you explain what the following Python 3 function does
def get_role(self, role):
role = AuthGroup.objects(role=role, creator=self.client).first()
return role | As a Python code translator, you convert algorithms and pseudocode into Python. |
Adds a role to the group | Given the following Python 3 function, write the documentation
def add_role(self, role, description=None):
new_group = AuthGroup(role=role, creator=self.client)
try:
new_group.save()
return True
except NotUniqueError:
return False | You are a Python code analyst, evaluating scripts for potential improvements. |
add a user to a group | Make a summary of the following Python 3 code
def add_membership(self, user, role):
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
if not targetGroup:
return False
target = AuthMembership.objects(user=user, creator=self.client).first()
if not target:... | You are a Python code architect, reviewing and designing scalable and efficient code |
delete a user from a group | Can you generate a brief explanation for the following Python 3 code
def del_membership(self, user, role):
if not self.has_membership(user, role):
return True
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if not targetRecord:
return True
... | As a python code expert, you are capable of creating scripts from specifications. |
def has_membership(self, user, role):
""" checks if user is member of a group"""
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if targetRecord:
return role in [i.role for i in targetRecord.groups]
return False | Implement a function in Python 3 to
check if user is member of a group | You are a Python code architect, reviewing and designing scalable and efficient code |
authorize a group for something | Explain what the following Python 3 code does
def add_permission(self, role, name):
if self.has_permission(role, name):
return True
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
if not targetGroup:
return False
# Create or update
... | As a Python code composer, you craft elegant and concise scripts. |
revoke authorization of a group | Given the following Python 3 function, write the documentation
def del_permission(self, role, name):
if not self.has_permission(role, name):
return True
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
target = AuthPermission.objects(groups=targetGroup, name=na... | You are a Python code architect, reviewing and designing scalable and efficient code |
verify user has permission | Can you tell what is the following Python 3 function doing
def user_has_permission(self, user, name):
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if not targetRecord:
return False
for group in targetRecord.groups:
if self.has_permission(g... | As a Python code analyst, you investigate and solve complex coding mysteries |
Bump the current version of the current language. | Explain what the following Python 3 code does
def bump_version(version, bump='patch'):
try:
parts = map(int, version.split('.'))
except ValueError:
fail('Current version is not numeric')
if bump == 'patch':
parts[2] += 1
elif bump == 'minor':
parts[1] += 1
parts[... | As a python code expert, you are capable of creating scripts from specifications. |
def handler(event):
"""Signal decorator to allow use of callback functions as class decorators."""
def decorator(fn):
def apply(cls):
event.connect(fn, sender=cls)
return cls
fn.apply = apply
return fn
return decorator | Write a Python 3 script for
signaling decorator to allow use of callback functions as class decorators. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def stringify(req, resp):
"""
dumps all valid jsons
This is the latest after hook
"""
if isinstance(resp.body, dict):
try:
resp.body = json.dumps(resp.body)
except(nameError):
resp.status = falcon.HTTP_500 | Write a Python 3 function that can
dump all valid jsons This is the latest after hook | You are a Python code analyst, evaluating scripts for potential improvements. |
Post - processing of the response. | Given the following Python 3 function, write the documentation
def process_response(self, req, resp, resource):
if isinstance(resp.body, dict):
try:
resp.body = json.dumps(resp.body)
except(nameError):
resp.status = falcon.HTTP_500 | As a Python code analyst, you investigate and solve complex coding mysteries |
def run(command=None, *arguments):
"""
Run the given command.
Parameters:
:param command: A string describing a command.
:param arguments: A list of strings describing arguments to the command.
"""
if command is None:
sys.exit('django-shortcuts: No argument was supplied, please spe... | Can you create a Python 3 function that
runs the given command. | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a ParamList instance for actual interpretation of the parameters. | Here you have a function in Python 3, explain what it does
def instantiate(self, scope, args, interp):
param_instances = []
BYREF = "byref"
# TODO are default values for function parameters allowed in 010?
for param_name, param_cls in self._params:
# we don't instantiate a ... | You are a Python code analyst, evaluating scripts for potential improvements. |
load_experiments
a wrapper for load_experiment to read multiple experiments
| Make a summary of the following Python 3 code
def load_experiments(folders):
'''load_experiments
a wrapper for load_experiment to read multiple experiments
:param experiment_folders: a list of experiment folders to load, full paths
'''
experiments = []
if isinstance(folders,str):
folders... | You are a Python code generator, capable of creating scripts from specifications. |
load_experiment reads in the config. json for a folder returns None if not found. | Can you generate a brief explanation for the following Python 3 code
def load_experiment(folder, return_path=False):
'''load_experiment:
reads in the config.json for a folder, returns None if not found.
:param folder: full path to experiment folder
:param return_path: if True, don't load the config.json... | As a python code expert, you are capable of creating scripts from specifications. |
we compare the basename of the exp_id of the selection and available and
regardless of parent directories | Given the following Python 3 function, write the documentation
def get_selection(available, selection, base='/scif/apps'):
'''we compare the basename (the exp_id) of the selection and available,
regardless of parent directories'''
if isinstance(selection, str):
selection = selection.split(',')
... | As a Python code composer, you craft elegant and concise scripts. |
validate
:param folder: full path to experiment folder with config.json. If path begins
with https, we assume to be starting from a repository. | Can you generate the documentation for the following Python 3 function
def validate(folder=None, cleanup=False):
'''validate
:param folder: full path to experiment folder with config.json. If path begins
with https, we assume to be starting from a repository.
'''
from expfactory.valid... | As a Python code analyst, you investigate and solve complex coding mysteries |
return the raw library without parsing | Explain what the following Python 3 code does
def get_library(lookup=True, key='exp_id'):
''' return the raw library, without parsing'''
library = None
response = requests.get(EXPFACTORY_LIBRARY)
if response.status_code == 200:
library = response.json()
if lookup is True:
ret... | You are a Python code analyst, evaluating scripts for potential improvements. |
Int3 is a wrapper around the Int2 function in the interpreter. | Given the following Python 3 function, write the documentation
def int3(params, ctxt, scope, stream, coord, interp):
if interp._no_debug:
return
if interp._int3:
interp.debugger = PfpDbg(interp)
interp.debugger.cmdloop() | As a Python code analyst, you investigate and solve complex coding mysteries |
initdb will check for writability of the data folder and meaning that it is bound to the local machine. | Explain what the following Python 3 code does
def initdb(self):
'''initdb will check for writability of the data folder, meaning
that it is bound to the local machine. If the folder isn't bound,
expfactory runs in demo mode (not saving data)
'''
self.database = EXPFACTORY_... | You are a Python code generator, capable of creating scripts from specifications. |
setup the internal variables and database preferences | Make a summary of the following Python 3 code
def setup(self):
''' obtain database and filesystem preferences from defaults,
and compare with selection in container.
'''
self.selection = EXPFACTORY_EXPERIMENTS
self.ordered = len(EXPFACTORY_EXPERIMENTS) > 0
self.data_... | As a python code expert, you are capable of creating scripts from specifications. |
return the name of the next experiment depending on the user s is
choice to randomize. | Can you generate a brief explanation for the following Python 3 code
def get_next(self, session):
'''return the name of the next experiment, depending on the user's
choice to randomize. We don't remove any experiments here, that is
done on finish, in the case the user doesn't submit data (... | As a Python code analyst, you investigate and solve complex coding mysteries |
def finish_experiment(self, session, exp_id):
'''remove an experiment from the list after completion.
'''
self.logger.debug('Finishing %s' %exp_id)
experiments = session.get('experiments', [])
experiments = [x for x in experiments if x != exp_id]
session['experiments'] = ... | Write a Python 3 function that can
remove an experiment from the list after completion. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return directories and sub directories starting from a basepath | Given the following Python 3 function, write the documentation
def find_subdirectories(basepath):
'''
Return directories (and sub) starting from a base
'''
directories = []
for root, dirnames, filenames in os.walk(basepath):
new_directories = [d for d in dirnames if d not in directories]
... | You are a Python code generator, capable of creating scripts from specifications. |
def find_directories(root,fullpath=True):
'''
Return directories at one level specified by user
(not recursive)
'''
directories = []
for item in os.listdir(root):
# Don't include hidden directories
if not re.match("^[.]",item):
if os.path.isdir(os.path.join(root, item... | Write a Python 3 script for
finding all directories in a user s directory tree. | You are a Python code analyst, evaluating scripts for potential improvements. |
def copy_directory(src, dest, force=False):
''' Copy an entire directory recursively
'''
if os.path.exists(dest) and force is True:
shutil.rmtree(dest)
try:
shutil.copytree(src, dest)
except OSError as e:
# If the error was caused because the source wasn't a directory
... | Write a Python 3 script to
copy a directory recursively. | As a Python code composer, you craft elegant and concise scripts. |
clone a repository from Github | Can you generate a brief explanation for the following Python 3 code
def clone(url, tmpdir=None):
'''clone a repository from Github'''
if tmpdir is None:
tmpdir = tempfile.mkdtemp()
name = os.path.basename(url).replace('.git', '')
dest = '%s/%s' %(tmpdir,name)
return_code = os.system('git cl... | As a python code expert, you are capable of creating scripts from specifications. |
run_command uses subprocess to send a command to the terminal. | Explain what the following Python 3 code does
def run_command(cmd):
'''run_command uses subprocess to send a command to the terminal.
:param cmd: the command to send, should be a list for subprocess
'''
output = Popen(cmd,stderr=STDOUT,stdout=PIPE)
t = output.communicate()[0],output.returncode
o... | You are a Python code analyst, evaluating scripts for potential improvements. |
read in and return a template file
| Explain what the following Python 3 code does
def get_template(name, base=None):
'''read in and return a template file
'''
# If the file doesn't exist, assume relative to base
template_file = name
if not os.path.exists(template_file):
if base is None:
base = get_templatedir()
... | As a python code expert, you are capable of creating scripts from specifications. |
def sub_template(template,template_tag,substitution):
'''make a substitution for a template_tag in a template
'''
template = template.replace(template_tag,substitution)
return template | Write a Python 3 function for
making a substitution for a template_tag in a template | You are a Python code analyst, evaluating scripts for potential improvements. |
parse through a request and return fields from post in a dictionary
| Can you generate the documentation for the following Python 3 function
def get_post_fields(request):
'''parse through a request, and return fields from post in a dictionary
'''
fields = dict()
for field,value in request.form.items():
fields[field] = value
return fields | As a Python code translator, you convert algorithms and pseudocode into Python. |
Parse the data stream using the supplied template. | Here you have a function in Python 3, explain what it does
def parse(
data = None,
template = None,
data_file = None,
template_file = None,
interp = None,
debug = False,
predefines = True,
int3 =... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function runs a simple checksum on a file and returns the result as an int64. | Can you tell what is the following Python 3 function doing
def Checksum(params, ctxt, scope, stream, coord):
checksum_types = {
0: "CHECKSUM_BYTE", # Treats the file as a set of unsigned bytes
1: "CHECKSUM_SHORT_LE", # Treats the file as a set of unsigned little-endian shorts
2: "CHECKSUM_SH... | As a python code expert, you are capable of creating scripts from specifications. |
This function is identical to the FindAll function except that the return value is the position of the first occurrence of the target
. | Can you tell what is the following Python 3 function doing
def FindFirst(params, ctxt, scope, stream, coord, interp):
global FIND_MATCHES_ITER
FIND_MATCHES_ITER = _find_helper(params, ctxt, scope, stream, coord, interp)
try:
first = six.next(FIND_MATCHES_ITER)
return first.start() + FIND_MA... | As a Python code composer, you craft elegant and concise scripts. |
This function returns the position of the next occurrence of the target value specified with the FindFirst function. | Can you generate the documentation for the following Python 3 function
def FindNext(params, ctxt, scope, stream, coord):
if FIND_MATCHES_ITER is None:
raise errors.InvalidState()
direction = 1
if len(params) > 0:
direction = PYVAL(params[0])
if direction != 1:
# TODO ma... | You are a Python code generator, capable of creating scripts from specifications. |
generate a unique id for the current object | Explain what the following Python 3 code does
def generate_subid(self, token=None):
'''assumes a flat (file system) database, organized by experiment id, and
subject id, with data (json) organized by subject identifier
'''
# Not headless auto-increments
if not token:
token = str(uuid.uu... | As a Python code composer, you craft elegant and concise scripts. |
list users each associated with a filesystem folder | Given the following Python 3 function, write the documentation
def list_users(self):
'''list users, each associated with a filesystem folder
'''
folders = glob('%s/*' %(self.database))
folders.sort()
return [self.print_user(x) for x in folders] | As a python code expert, you are capable of creating scripts from specifications. |
def print_user(self, user):
'''print a filesystem database user. A "database" folder that might end with
the participant status (e.g. _finished) is extracted to print in format
[folder] [identifier][studyid]
/scif/data/expfactory/xxxx-xxxx xxxx-xxxx[studyid]
... | Write a Python 3 function for
printing a filesystem database user | You are a Python code analyst, evaluating scripts for potential improvements. |
def generate_user(self, subid=None):
'''generate a new user on the filesystem, still session based so we
create a new identifier. This function is called from the users new
entrypoint, and it assumes we want a user generated with a token.
since we don't have a database proper, we write the fol... | Implement a Python 3 function for
generating a new user on the filesystem | You are a Python code generator, capable of creating scripts from specifications. |
def finish_user(self, subid, ext='finished'):
'''finish user will append "finished" (or other) to the data folder when
the user has completed (or been revoked from) the battery.
For headless, this means that the session is ended and the token
will not work again to rewrite the result. If the ... | Write a Python 3 script for
finishing user and return the path to the finished file | As a Python code translator, you convert algorithms and pseudocode into Python. |
def restart_user(self, subid):
'''restart user will remove any "finished" or "revoked" extensions from
the user folder to restart the session. This command always comes from
the client users function, so we know subid does not start with the
study identifer first
'''
if os.path.exists(s... | How would you implement a function in Python 3 that
restarts user will remove any "finished" or "revoked" extensions from the user folder to restart the session. This command always comes from the client users function, so we know subid does not start with the study identifer first | As a Python code composer, you craft elegant and concise scripts. |
retrieve a subject based on a token. Valid means we return a participant
invalid means we return None
| Explain what the following Python 3 code does
def validate_token(self, token):
'''retrieve a subject based on a token. Valid means we return a participant
invalid means we return None
'''
# A token that is finished or revoked is not valid
subid = None
if not token.endswith(('finished','revoke... | You are a Python code generator, capable of creating scripts from specifications. |
def refresh_token(self, subid):
'''refresh or generate a new token for a user. If the user is finished,
this will also make the folder available again for using.'''
if os.path.exists(self.data_base): # /scif/data
data_base = "%s/%s" %(self.data_base, subid)
if os.path.exists(data_base)... | Write a Python 3 script for
refreshing or generate a new token for a user. | As a Python code composer, you craft elegant and concise scripts. |
save data will obtain the current subid from the session and save it as json | Here you have a function in Python 3, explain what it does
def save_data(self, session, exp_id, content):
'''save data will obtain the current subid from the session, and save it
depending on the database type. Currently we just support flat files'''
subid = session.get('subid')
# We only attempt s... | As a python code expert, you are capable of creating scripts from specifications. |
def native(name, ret, interp=None, send_interp=False):
"""Used as a decorator to add the decorated function to the
pfp interpreter so that it can be used from within scripts.
:param str name: The name of the function as it will be exposed in template scripts.
:param pfp.fields.Field ret: The return typ... | Write a Python 3 function for
using as a decorator to add the decorated function to the pfp interpreter so that it can be used from within scripts. :param str name: The name of the function as it will be exposed in template scripts. :param pfp.fields.Field ret: The return type of the function (a class) :param pfp.inter... | As a python code expert, you are capable of creating scripts from specifications. |
Peek at the next 16 hex bytes in the input stream::
| Given the following Python 3 function, write the documentation
def do_peek(self, args):
s = self._interp._stream
# make a copy of it
pos = s.tell()
saved_bits = collections.deque(s._bits)
data = s.read(0x10)
s.seek(pos, 0)
s._bits = saved_bits
parts = ["{... | As a python code expert, you are capable of creating scripts from specifications. |
Step over the next statement in the log | Explain what the following Python 3 code does
def do_next(self, args):
self._do_print_from_last_cmd = True
self._interp.step_over()
return True | You are a Python code analyst, evaluating scripts for potential improvements. |
Step into the next statement | Make a summary of the following Python 3 code
def do_step(self, args):
self._do_print_from_last_cmd = True
self._interp.step_into()
return True | As a Python code translator, you convert algorithms and pseudocode into Python. |
def do_eval(self, args):
"""Eval the user-supplied statement. Note that you can do anything with
this command that you can do in a template.
The resulting value of your statement will be displayed.
"""
try:
res = self._interp.eval(args)
if res is not None... | Write a Python 3 function that can
evaluate the user - supplied statement. | You are a Python code analyst, evaluating scripts for potential improvements. |
Show the current structure of __root or show the result of the expression. | Can you generate the documentation for the following Python 3 function
def do_show(self, args):
args = args.strip()
to_show = self._interp._root
if args != "":
try:
to_show = self._interp.eval(args)
except Exception as e:
print("ERROR: " +... | You are a Python code architect, reviewing and designing scalable and efficient code |
Validate the URL of a Github repository and return True if validation passes False otherwise | Can you generate the documentation for the following Python 3 function
def validate(self, url):
''' takes in a Github repository for validation of preview and
runtime (and possibly tests passing?
'''
# Preview must provide the live URL of the repository
if not url.startswit... | You are a Python code architect, reviewing and designing scalable and efficient code |
Replace passwords with a secret in a dictionary. | Make a summary of the following Python 3 code
def mask_dict_password(dictionary, secret='***'):
d = dictionary.copy()
for k in d:
if 'password' in k:
d[k] = secret
return d | As a Python code analyst, you investigate and solve complex coding mysteries |
save is a view to save data. We need to adjust this to allow for
updating saved data but we need to adjust this to allow for
updating saved data but we need to adjust this to allow for
updating saved data | Can you generate a brief explanation for the following Python 3 code
def save():
'''save is a view to save data. We might want to adjust this to allow for
updating saved data, but given single file is just one post for now
'''
if request.method == 'POST':
exp_id = session.get('exp_id')
... | As a Python code analyst, you investigate and solve complex coding mysteries |
save data for the current subject | Can you generate a brief explanation for the following Python 3 code
def save_data(self,session, exp_id, content):
'''save data will obtain the current subid from the session, and save it
depending on the database type.'''
from expfactory.database.models import (
Participant,
Result
)... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def init_db(self):
'''initialize the database, with the default database path or custom of
the format sqlite:////scif/data/expfactory.db
'''
# Database Setup, use default if uri not provided
if self.database == 'sqlite':
db_path = os.path.join(EXPFACTORY_DATA, '%s.db' % EXPFACTORY_SUBID... | Create a Python 3 function for
initializing the database, with the default database path or custom of the format sqlite:////scif/data/expfactory.db | You are a Python code generator, capable of creating scripts from specifications. |
Used to reserve num_bits amount of bits in the track
. | Here you have a function in Python 3, explain what it does
def reserve_bits(self, num_bits, stream):
padded = self.interp.get_bitfield_padded()
num_bits = PYVAL(num_bits)
if padded:
num_bits = PYVAL(num_bits)
if num_bits + self.reserved_bits > self.max_bits:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def read_bits(self, stream, num_bits, padded, left_right, endian):
"""Return ``num_bits`` bits, taking into account endianness and
left-right bit directions
"""
if self._cls_bits is None and padded:
raw_bits = stream.read_bits(self.cls.width*8)
self._cls_bits = s... | How would you code a function in Python 3 to
read num_bits bits from the given stream. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def write_bits(self, stream, raw_bits, padded, left_right, endian):
"""Write the bits. Once the size of the written bits is equal
to the number of the reserved bits, flush it to the stream
"""
if padded:
if left_right:
self._write_bits += raw_bits
... | Write a Python 3 function for
writing the bits to the stream. | As a Python code analyst, you investigate and solve complex coding mysteries |
Save off the current value of the field
| How would you explain what the following Python 3 function does
def _pfp__snapshot(self, recurse=True):
if hasattr(self, "_pfp__value"):
self._pfp__snapshot_value = self._pfp__value | As a python code expert, you are capable of creating scripts from specifications. |
def _pfp__process_metadata(self):
"""Process the metadata once the entire struct has been
declared.
"""
if self._pfp__metadata_processor is None:
return
metadata_info = self._pfp__metadata_processor()
if isinstance(metadata_info, list):
for metada... | Create a Python 3 function to
process the metadata once the entire struct has been declared. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add the watcher to the list of fields that are watching this field
| Can you tell what is the following Python 3 function doing
def _pfp__watch(self, watcher):
if self._pfp__parent is not None and isinstance(self._pfp__parent, Union):
self._pfp__parent._pfp__watch(watcher)
else:
self._pfp__watchers.append(watcher) | You are a Python code analyst, evaluating scripts for potential improvements. |
Subscribe to update events on each field in watch_fields using update_func to update self s value when watch_field changes | Given the following Python 3 function, write the documentation
def _pfp__set_watch(self, watch_fields, update_func, *func_call_info):
self._pfp__watch_fields = watch_fields
for watch_field in watch_fields:
watch_field._pfp__watch(self)
self._pfp__update_func = update_func
se... | As a Python code composer, you craft elegant and concise scripts. |
Set the packer and unpack functions for this field as
. | Can you generate a brief explanation for the following Python 3 code
def _pfp__set_packer(self, pack_type, packer=None, pack=None, unpack=None, func_call_info=None):
self._pfp__pack_type = pack_type
self._pfp__unpack = unpack
self._pfp__pack = pack
self._pfp__packer = packer
self... | As a Python code composer, you craft elegant and concise scripts. |
Pack the nested field containing the data | Make a summary of the following Python 3 code
def _pfp__pack_data(self):
if self._pfp__pack_type is None:
return
tmp_stream = six.BytesIO()
self._._pfp__build(bitwrap.BitwrappedStream(tmp_stream))
raw_data = tmp_stream.getvalue()
unpack_func = self._pfp__packer
... | As a Python code composer, you craft elegant and concise scripts. |
Parses the raw data into a set of attributes. | Explain what the following Python 3 code does
def _pfp__unpack_data(self, raw_data):
if self._pfp__pack_type is None:
return
if self._pfp__no_unpack:
return
unpack_func = self._pfp__packer
unpack_args = []
if self._pfp__packer is not None:
unp... | You are a Python code generator, capable of creating scripts from specifications. |
def _pfp__handle_updated(self, watched_field):
"""Handle the watched field that was updated
"""
self._pfp__no_notify = True
# nested data has been changed, so rebuild the
# nested data to update the field
# TODO a global setting to determine this behavior?
# coul... | Write a Python 3 script for
handling the watched field that was updated | You are a Python code generator, capable of creating scripts from specifications. |
Return the width of the field | Given the following Python 3 function, write the documentation
def _pfp__width(self):
raw_output = six.BytesIO()
output = bitwrap.BitwrappedStream(raw_output)
self._pfp__build(output)
output.flush()
return len(raw_output.getvalue()) | You are a Python code generator, capable of creating scripts from specifications. |
Set the new value if type checking is passes potentially
| Can you generate the documentation for the following Python 3 function
def _pfp__set_value(self, new_val):
if self._pfp__frozen:
raise errors.UnmodifiableConst()
self._pfp__value = self._pfp__get_root_value(new_val)
self._pfp__notify_parent() | As a Python code translator, you convert algorithms and pseudocode into Python. |
Save off the current value of the field
| Can you tell what is the following Python 3 function doing
def _pfp__snapshot(self, recurse=True):
super(Struct, self)._pfp__snapshot(recurse=recurse)
if recurse:
for child in self._pfp__children:
child._pfp__snapshot(recurse=recurse) | You are a Python code analyst, evaluating scripts for potential improvements. |
def _pfp__restore_snapshot(self, recurse=True):
"""Restore the snapshotted value without triggering any events
"""
super(Struct, self)._pfp__restore_snapshot(recurse=recurse)
if recurse:
for child in self._pfp__children:
child._pfp__restore_snapshot(recurse=r... | Write a Python 3 script to
restore the snapshotted value without triggering any events. | As a Python code composer, you craft elegant and concise scripts. |
def _pfp__set_value(self, value):
"""Initialize the struct. Value should be an array of
fields, one each for each struct member.
:value: An array of fields to initialize the struct with
:returns: None
"""
if self._pfp__frozen:
raise errors.UnmodifiableConst()... | Create a Python 3 function to
initialize the struct. Value should be an array of fields one each for each struct member. | As a Python code analyst, you investigate and solve complex coding mysteries |
Add a child to the Struct field. | How would you explain what the following Python 3 function does
def _pfp__add_child(self, name, child, stream=None, overwrite=False):
if not overwrite and self._pfp__is_non_consecutive_duplicate(name, child):
return self._pfp__handle_non_consecutive_duplicate(name, child)
elif not overwrite ... | You are a Python code generator, capable of creating scripts from specifications. |
This method handles a non - consecutive duplicate of a new child and potentially one already existing child. | How would you explain what the following Python 3 function does
def _pfp__handle_non_consecutive_duplicate(self, name, child, insert=True):
if name in self._pfp__children_map:
previous_child = self._pfp__children_map[name]
# DO NOT cause __eq__ to be called, we want to test actual objec... | As a Python code composer, you craft elegant and concise scripts. |
def _pfp__is_non_consecutive_duplicate(self, name, child):
"""Return True/False if the child is a non-consecutive duplicately named
field. Consecutive duplicately-named fields are stored in an implicit array,
non-consecutive duplicately named fields have a numeric suffix appended to their name""... | How would you implement a function in Python 3 that
returns True if the child is a non - consecutive duplicate of the named field. | You are a Python code analyst, evaluating scripts for potential improvements. |
Handle inserting implicit array elements. | Can you generate the documentation for the following Python 3 function
def _pfp__handle_implicit_array(self, name, child):
existing_child = self._pfp__children_map[name]
if isinstance(existing_child, Array):
# I don't think we should check this
#
#if existing_child.fi... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Parse the incoming stream containing the n - bit tag and return the number of bytes parsed. | Explain what the following Python 3 code does
def _pfp__parse(self, stream, save_offset=False):
if save_offset:
self._pfp__offset = stream.tell()
res = 0
for child in self._pfp__children:
res += child._pfp__parse(stream, save_offset)
return res | You are a Python code analyst, evaluating scripts for potential improvements. |
Builds the field and writes the result into the stream | Can you generate a brief explanation for the following Python 3 code
def _pfp__build(self, stream=None, save_offset=False):
if save_offset and stream is not None:
self._pfp__offset = stream.tell()
# returns either num bytes written or total data
res = utils.binary("") if stream is N... | As a python code expert, you are capable of creating scripts from specifications. |
def _pfp__show(self, level=0, include_offset=False):
"""Show the contents of the struct
"""
res = []
res.append("{}{} {{".format(
"{:04x} ".format(self._pfp__offset) if include_offset else "",
self._pfp__show_name
))
for child in self._pfp__childre... | Implement a Python 3 function for
showing the contents of the struct | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _pfp__add_child(self, name, child, stream=None):
"""Add a child to the Union field
:name: The name of the child
:child: A :class:`.Field` instance
:returns: The resulting field
"""
res = super(Union, self)._pfp__add_child(name, child)
self._pfp__buff.seek(0, ... | Can you create a Python 3 function that
adds a child to the Union field | As a Python code composer, you craft elegant and concise scripts. |
def _pfp__notify_update(self, child=None):
"""Handle a child with an updated value
"""
if getattr(self, "_pfp__union_update_other_children", True):
self._pfp__union_update_other_children = False
new_data = child._pfp__build()
new_stream = bitwrap.BitwrappedS... | Implement a Python 3 function for
handling a child with an updated value | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse the incoming stream containing the current set of entries. | Here you have a function in Python 3, explain what it does
def _pfp__parse(self, stream, save_offset=False):
if save_offset:
self._pfp__offset = stream.tell()
max_res = 0
for child in self._pfp__children:
child_res = child._pfp__parse(stream, save_offset)
if ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Builds the union and writes the result into the stream. | Can you generate the documentation for the following Python 3 function
def _pfp__build(self, stream=None, save_offset=False):
max_size = -1
if stream is None:
core_stream = six.BytesIO()
new_stream = bitwrap.BitwrappedStream(core_stream)
else:
new_stream = str... | As a Python code composer, you craft elegant and concise scripts. |
Parse the data for the numeric field. | Explain what the following Python 3 code does
def _pfp__parse(self, stream, save_offset=False):
if save_offset:
self._pfp__offset = stream.tell()
if self.bitsize is None:
raw_data = stream.read(self.width)
data = utils.binary(raw_data)
else:
bits... | As a Python code composer, you craft elegant and concise scripts. |
Builds the field and writes the result into the stream | Explain what the following Python 3 code does
def _pfp__build(self, stream=None, save_offset=False):
if stream is not None and save_offset:
self._pfp__offset = stream.tell()
if self.bitsize is None:
data = struct.pack(
"{}{}".format(self.endian, self.format),
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the dominating numeric class between the two objects. | Given the following Python 3 function, write the documentation
def _dom_class(self, obj1, obj2):
if isinstance(obj1, Double) or isinstance(obj2, Double):
return Double
if isinstance(obj1, Float) or isinstance(obj2, Float):
return Float | As a Python code analyst, you investigate and solve complex coding mysteries |
Set the value of the internal field. | Can you generate a brief explanation for the following Python 3 code
def _pfp__set_value(self, new_val):
if self._pfp__frozen:
raise errors.UnmodifiableConst()
if isinstance(new_val, IntBase):
# will automatically convert correctly between ints of
# different sizes, ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.