text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, '__version__'):
d['__version__'] = oldmod.__version__
if hasattr(oldmod, '__loader__'):
d['__loader__'] ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def importobj(modpath, attrname):
"""imports a module, then resolves the attrname on it""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __makeattr(self, name):
"""lazily compute value for name or raise AttributeError if unknown.""" |
# print "makeattr", self.__name__, name
target = None
if '__onfirstaccess__' in self.__map__:
target = self.__map__.pop('__onfirstaccess__')
importobj(*target)()
try:
modpath, attrname = self.__map__[name]
except KeyError:
if targe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _request(self, http_method, relative_url='', **kwargs):
"""Does actual HTTP request using requests library.""" |
# 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_leading_slash(relative_url)
# Add default kwargs with possible custom kwargs returned by
# before_reques... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _new_url(self, relative_url):
"""Create new Url which points to new url.""" |
return Url(
urljoin(self._base_url, relative_url),
**self._default_kwargs
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def roles(self):
"""gets user groups""" |
result = AuthGroup.objects(creator=self.client).only('role')
return json.loads(result.to_json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_permissions(self, role):
"""gets permissions of 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('name')
return json.loads(targets.to_json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_role(self, role):
"""Returns a role object """ |
role = AuthGroup.objects(role=role, creator=self.client).first()
return role |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_role(self, role):
""" deletes a group """ |
target = AuthGroup.objects(role=role, creator=self.client).first()
if target:
target.delete()
return True
else:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_membership(self, user, role):
""" make user a member of a group """ |
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:
target = AuthMembership(user=user, creator=self.client)
if no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_membership(self, user, role):
""" dismember user from a group """ |
if not self.has_membership(user, role):
return True
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if not targetRecord:
return True
for group in targetRecord.groups:
if group.role==role:
targetRecord.grou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_permission(self, role, name):
""" authorize a group for something """ |
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
permission = AuthPermission.objects(name=name).update(
add_to_set__... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_permission(self, role, name):
""" revoke authorization of a group """ |
if not self.has_permission(role, name):
return True
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
target = AuthPermission.objects(groups=targetGroup, name=name, creator=self.client).first()
if not target:
return True
target.delet... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user_has_permission(self, user, name):
""" verify user has permission """ |
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if not targetRecord:
return False
for group in targetRecord.groups:
if self.has_permission(group.role, name):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instantiate(self, scope, args, interp):
"""Create a ParamList instance for actual interpretation :args: TODO :returns: A ParamList object """ |
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 copy of byref params
if getattr(param_cls, "byref", False):
param_instance... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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:
return make_lookup(library,key=key)
return li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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_base = EXPFACTORY_DATA
self.study_id =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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'] = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 clone %s %s' %(url,dest))
if return_code == 0:
return dest
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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()
template_file = "%s/%s" %(base, name)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse( data = None, template = None, data_file = None, template_file = None, interp = None, debug = False, predefines = True, int3 = True, keep_successful = F... |
if data is None and data_file is None:
raise Exception("No input data was specified")
if data is not None and data_file is not None:
raise Exception("Only one input data may be specified")
if isinstance(data, six.string_types):
data = six.StringIO(data)
if data_file i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FindFirst(params, ctxt, scope, stream, coord, interp):
""" This function is identical to the FindAll function except that the return value is the position of... |
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_MATCHES_START_OFFSET
except StopIteration as e:
return -1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FindNext(params, ctxt, scope, stream, coord):
""" This function returns the position of the next occurrence of the target value specified with the FindFirst ... |
if FIND_MATCHES_ITER is None:
raise errors.InvalidState()
direction = 1
if len(params) > 0:
direction = PYVAL(params[0])
if direction != 1:
# TODO maybe instead of storing the iterator in FIND_MATCHES_ITER,
# we should go ahead and find _all the matches in the ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 wi... |
def native_decorator(func):
@functools.wraps(func)
def native_wrapper(*args, **kwargs):
return func(*args, **kwargs)
pfp.interp.PfpInterp.add_native(name, func, ret, interp=interp, send_interp=send_interp)
return native_wrapper
return native_decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_next(self, args):
"""Step over the next statement """ |
self._do_print_from_last_cmd = True
self._interp.step_over()
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_step(self, args):
"""Step INTO the next statement """ |
self._do_print_from_last_cmd = True
self._interp.step_into()
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_continue(self, args):
"""Continue the interpreter """ |
self._do_print_from_last_cmd = True
self._interp.cont()
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
try:
res = self._interp.eval(args)
if res is not None:
if hasattr(res, "_pfp__show"):
print(res._pfp__show())
else:
print(repr(res))
except errors.UnresolvedID as e:
print("ERROR: " + e.message)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_quit(self, args):
"""The quit command """ |
self._interp.set_break(self._interp.BREAK_NONE)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.startswith('http') or not 'github' in url:
bot.error('Test of previe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mask_dict_password(dictionary, secret='***'):
"""Replace passwords with a secret in a dictionary.""" |
d = dictionary.copy()
for k in d:
if 'password' in k:
d[k] = secret
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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')
app.logger.debug('Saving data for %s' %exp_id)
fields = ge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def main(args,parser,subparser=None):
'''this is the main entrypoint for a container based web server, with
most of the variables coming from the environment. See the Dockerfile
template for how this function is executed.
'''
# First priority to args.base
base = args.base
if base is ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
)
subid = session.get('subid')
bot.info('Saving data for subi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = self._endian_transform(raw_bits, endian)
if self._cls_bits is not None:
if num_bits > len(self._cls_bits):
raise errors.PfpError("BitfieldRW reached ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 b... |
if padded:
if left_right:
self._write_bits += raw_bits
else:
self._write_bits = raw_bits + self._write_bits
if len(self._write_bits) == self.reserved_bits:
bits = self._endian_transform(self._write_bits, endian)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 metadata in metadata_info:
if metadata["type"] == "watch":
self._pfp__set_watch(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__watch(self, watcher):
"""Add the watcher to the list of fields that are watching this field """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__set_watch(self, watch_fields, update_func, *func_call_info):
"""Subscribe to update events on each field in ``watch_fields``, using ``update_func`` to ... |
self._pfp__watch_fields = watch_fields
for watch_field in watch_fields:
watch_field._pfp__watch(self)
self._pfp__update_func = update_func
self._pfp__update_func_call_info = func_call_info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__pack_data(self):
"""Pack the nested field """ |
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
unpack_args = []
if self._pfp__packer is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__unpack_data(self, raw_data):
"""Means that the field has already been parsed normally, and that it now needs to be unpacked. :raw_data: A string of the... |
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:
unpack_func = self._pfp__packer
unpack_args = [false(), raw_data]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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?
# could slow things down a bit for large nested structures
# notice the use of _is_ here - 'is' != '=='. '==... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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=recurse) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 in... |
if self._pfp__frozen:
raise errors.UnmodifiableConst()
if len(value) != len(self._pfp__children):
raise errors.PfpError("struct initialization has wrong number of members")
for x in six.moves.range(len(self._pfp__children)):
self._pfp__children[x]._pfp__set_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__add_child(self, name, child, stream=None, overwrite=False):
"""Add a child to the Struct field. If multiple consecutive fields are added with the same ... |
if not overwrite and self._pfp__is_non_consecutive_duplicate(name, child):
return self._pfp__handle_non_consecutive_duplicate(name, child)
elif not overwrite and name in self._pfp__children_map:
return self._pfp__handle_implicit_array(name, child)
else:
child... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__handle_implicit_array(self, name, child):
"""Handle inserting implicit array elements """ |
existing_child = self._pfp__children_map[name]
if isinstance(existing_child, Array):
# I don't think we should check this
#
#if existing_child.field_cls != child.__class__:
# raise errors.PfpError("implicit arrays must be sequential!")
exis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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__children:
res.append("{}{}{:10s} = {}".format(
" "*(level+1),
"{:04... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: ... |
res = super(Union, self)._pfp__add_child(name, child)
self._pfp__buff.seek(0, 0)
child._pfp__build(stream=self._pfp__buff)
size = len(self._pfp__buff.getvalue())
self._pfp__buff.seek(0, 0)
if stream is not None:
curr_pos = stream.tell()
stream.se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.BitwrappedStream(six.BytesIO(new_data))
for other_child in self._pfp__children:
if ot... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__build(self, stream=None, save_offset=False):
"""Build the union and write the result into the stream. :stream: None :returns: None """ |
max_size = -1
if stream is None:
core_stream = six.BytesIO()
new_stream = bitwrap.BitwrappedStream(core_stream)
else:
new_stream = stream
for child in self._pfp__children:
curr_pos = new_stream.tell()
child._pfp__build(new_str... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__parse(self, stream, save_offset=False):
"""Parse the IO stream for this numeric field :stream: An IO stream that can be read from :returns: The number ... |
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 = self.bitfield_rw.read_bits(stream, self.bitsize, self.bitfield_padded, self.bitfield_left_ri... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dom_class(self, obj1, obj2):
"""Return the dominating numeric class between the two :obj1: TODO :obj2: TODO :returns: TODO """ |
if isinstance(obj1, Double) or isinstance(obj2, Double):
return Double
if isinstance(obj1, Float) or isinstance(obj2, Float):
return Float |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__parse(self, stream, save_offset=False):
"""Parse the IO stream for this enum :stream: An IO stream that can be read from :returns: The number of bytes ... |
res = super(Enum, self)._pfp__parse(stream, save_offset)
if self._pfp__value in self.enum_vals:
self.enum_name = self.enum_vals[self._pfp__value]
else:
self.enum_name = "?? UNK_ENUM ??"
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__set_value(self, new_val):
"""Set the value of the String, taking into account escaping and such as well """ |
if not isinstance(new_val, Field):
new_val = utils.binary(utils.string_escape(new_val))
super(String, self)._pfp__set_value(new_val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__parse(self, stream, save_offset=False):
"""Read from the stream until the string is null-terminated :stream: The input stream :returns: None """ |
if save_offset:
self._pfp__offset = stream.tell()
res = utils.binary("")
while True:
byte = utils.binary(stream.read(self.read_size))
if len(byte) < self.read_size:
raise errors.PrematureEOF()
# note that the null terminator must ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pfp__build(self, stream=None, save_offset=False):
"""Build the String field :stream: TODO :returns: TODO """ |
if stream is not None and save_offset:
self._pfp__offset = stream.tell()
data = self._pfp__value + utils.binary("\x00")
if stream is None:
return data
else:
stream.write(data)
return len(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Printf(params, ctxt, scope, stream, coord, interp):
"""Prints format string to stdout :params: TODO :returns: TODO """ |
if len(params) == 1:
if interp._printf:
sys.stdout.write(PYSTR(params[0]))
return len(PYSTR(params[0]))
parts = []
for part in params[1:]:
if isinstance(part, pfp.fields.Array) or isinstance(part, pfp.fields.String):
parts.append(PYSTR(part))
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_strategy(name_or_cls):
"""Return the strategy identified by its name. If ``name_or_class`` is a class, it will be simply returned. """ |
if isinstance(name_or_cls, six.string_types):
if name_or_cls not in STRATS:
raise MutationError("strat is not defined")
return STRATS[name_or_cls]()
return name_or_cls() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mutate(self, field):
"""Mutate the given field, modifying it directly. This is not intended to preserve the value of the field. :field: The pfp.fields.Field ... |
new_val = self.next_val(field)
field._pfp__set_value(new_val)
return field |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def generate_subid(self, token=None, return_user=False):
'''generate a new user in the database, still session based so we
create a new identifier.
'''
from expfactory.database.models import Participant
if not token:
p = Participant()
else:
p = Participant(token=token)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def print_user(self, user):
'''print a relational database user
'''
status = "active"
token = user.token
if token in ['finished', 'revoked']:
status = token
if token is None:
token = ''
subid = "%s\t%s[%s]" %(user.id, token, status)
print(subid)
return subid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_users(self, user=None):
'''list users, each having a model in the database. A headless experiment
will use protected tokens, and interactive will be based on auto-
incremented ids.
'''
from expfactory.database.models import Participant
participants = Participant.query.all()
u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def generate_user(self):
'''generate a new user in the database, 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.
'''
token = str(uuid.uuid4())
return self.generate_subid(token=t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def finish_user(self, subid):
'''finish user will remove a user's token, making the user entry not
accesible if running in headless model'''
p = self.revoke_token(subid)
p.token = "finished"
self.session.commit()
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def restart_user(self, subid):
'''restart a user, which means revoking and issuing a new token.'''
p = self.revoke_token(subid)
p = self.refresh_token(subid)
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def revoke_token(self, subid):
'''revoke a token by removing it. Is done at finish, and also available
as a command line option'''
from expfactory.database.models import Participant
p = Participant.query.filter(Participant.id == subid).first()
if p is not None:
p.token = 'revoked'
self.s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def refresh_token(self, subid):
'''refresh or generate a new token for a user'''
from expfactory.database.models import Participant
p = Participant.query.filter(Participant.id == subid).first()
if p is not None:
p.token = str(uuid.uuid4())
self.session.commit()
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wrap_type_instantiation(self, type_cls):
"""Wrap the creation of the type so that we can provide a null-stream to initialize it""" |
def wrapper(*args, **kwargs):
# use args for struct arguments??
return type_cls(stream=self._null_stream)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def level(self):
"""Return the current scope level """ |
res = len(self._scope_stack)
if self._parent is not None:
res += self._parent.level()
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_local(self, field_name, field):
"""Add a local variable in the current scope :field_name: The field's name :field: The field :returns: None """ |
self._dlog("adding local '{}'".format(field_name))
field._pfp__name = field_name
# TODO do we allow clobbering of locals???
self._curr_scope["vars"][field_name] = field |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_type_struct_or_union(self, name, interp, node):
"""Store the node with the name. When it is instantiated, the node itself will be handled. :name: name of... |
self.add_type_class(name, StructUnionDef(name, interp, node)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_type(self, new_name, orig_names):
"""Record the typedefd name for orig_names. Resolve orig_names to their core names and save those. :new_name: TODO :ori... |
self._dlog("adding a type '{}'".format(new_name))
# TODO do we allow clobbering of types???
res = copy.copy(orig_names)
resolved_names = self._resolve_name(res[-1])
if resolved_names is not None:
res.pop()
res += resolved_names
self._curr_scope["... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_id(self, name, recurse=True):
"""Get the first id matching ``name``. Will either be a local or a var. :name: TODO :returns: TODO """ |
self._dlog("getting id '{}'".format(name))
var = self._search("vars", name, recurse)
return var |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_native(cls, name, func, ret, interp=None, send_interp=False):
"""Add the native python function ``func`` into the pfp interpreter with the name ``name`` ... |
if interp is None:
natives = cls._natives
else:
# the instance's natives
natives = interp._natives
natives[name] = functions.NativeFunction(
name, func, ret, send_interp
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def define_natives(cls):
"""Define the native functions for PFP """ |
if len(cls._natives) > 0:
return
glob_pattern = os.path.join(os.path.dirname(__file__), "native", "*.py")
for filename in glob.glob(glob_pattern):
basename = os.path.basename(filename).replace(".py", "")
if basename == "__init__":
continue
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dlog(self, msg, indent_increase=0):
"""log the message to the log""" |
self._log.debug("interp", msg, indent_increase, filename=self._orig_filename, coord=self._coord) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_break(self, break_type):
"""Set if the interpreter should break. :returns: TODO """ |
self._break_type = break_type
self._break_level = self._scope.level() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_curr_lines(self):
"""Return the current line number in the template, as well as the surrounding source lines """ |
start = max(0, self._coord.line - 5)
end = min(len(self._template_lines), self._coord.line + 4)
lines = [(x, self._template_lines[x]) for x in six.moves.range(start, end, 1)]
return self._coord.line, lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_node(self, node, scope=None, ctxt=None, stream=None):
"""Recursively handle nodes in the 010 AST :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :... |
if scope is None:
if self._scope is None:
self._scope = scope = self._create_scope()
else:
scope = self._scope
if ctxt is None and self._ctxt is not None:
ctxt = self._ctxt
else:
self._ctxt = ctxt
if type(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_cast(self, node, scope, ctxt, stream):
"""Handle cast nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ |
self._dlog("handling cast")
to_type = self._handle_node(node.to_type, scope, ctxt, stream)
val_to_cast = self._handle_node(node.expr, scope, ctxt, stream)
res = to_type()
res._pfp__set_value(val_to_cast)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_node_name(self, node):
"""Get the name of the node - check for node.name and node.type.declname. Not sure why the second one occurs exactly - it happens... |
res = getattr(node, "name", None)
if res is None:
return res
if isinstance(res, AST.TypeDecl):
return res.declname
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_metadata(self, node, scope, ctxt, stream):
"""Handle metadata for the node """ |
self._dlog("handling node metadata {}".format(node.metadata.keyvals))
keyvals = node.metadata.keyvals
metadata_info = []
if "watch" in node.metadata.keyvals or "update" in keyvals:
metadata_info.append(
self._handle_watch_metadata(node, scope, ctxt, stream... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_watch_metadata(self, node, scope, ctxt, stream):
"""Handle watch vars for fields """ |
keyvals = node.metadata.keyvals
if "watch" not in keyvals:
raise errors.PfpError("Packed fields require a packer function set")
if "update" not in keyvals:
raise errors.PfpError("Packed fields require a packer function set")
watch_field_name = keyvals["watch"]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_packed_metadata(self, node, scope, ctxt, stream):
"""Handle packed metadata """ |
keyvals = node.metadata.keyvals
if "packer" not in keyvals and ("pack" not in keyvals or "unpack" not in keyvals):
raise errors.PfpError("Packed fields require a packer function to be set or pack and unpack functions to be set")
if "packtype" not in keyvals:
raise errors... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _str_to_int(self, string):
"""Check for the hex """ |
string = string.lower()
if string.endswith("l"):
string = string[:-1]
if string.lower().startswith("0x"):
# should always match
match = re.match(r'0[xX]([a-fA-F0-9]+)', string)
return int(match.group(1), 0x10)
else:
return int(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_parentof(self, node, scope, ctxt, stream):
"""Handle the parentof unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO ""... |
# if someone does something like parentof(this).blah,
# we'll end up with a StructRef instead of an ID ref
# for node.expr, but we'll also end up with a structref
# if the user does parentof(a.b.c)...
#
# TODO how to differentiate between the two??
#
# t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_exists(self, node, scope, ctxt, stream):
"""Handle the exists unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ |
res = fields.Int()
try:
self._handle_node(node.expr, scope, ctxt, stream)
res._pfp__set_value(1)
except AttributeError:
res._pfp__set_value(0)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_function_exists(self, node, scope, ctxt, stream):
"""Handle the function_exists unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :re... |
res = fields.Int()
try:
func = self._handle_node(node.expr, scope, ctxt, stream)
if isinstance(func, functions.BaseFunction):
res._pfp__set_value(1)
else:
res._pfp__set_value(0)
except errors.UnresolvedID:
res._pfp_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_assignment(self, node, scope, ctxt, stream):
"""Handle assignment nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ |
def add_op(x,y): x += y
def sub_op(x,y): x -= y
def div_op(x,y): x /= y
def mod_op(x,y): x %= y
def mul_op(x,y): x *= y
def xor_op(x,y): x ^= y
def and_op(x,y): x &= y
def or_op(x,y): x |= y
def lshift_op(x,y): x <<= y
def rshift_op(x,y): ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.