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 resolve_pattern(pattern):
'''Resolve a glob pattern into a filelist'''
if os.path.exists(pattern) and os.path.isdir(pattern):
pattern = os.path.join(pattern, '**/*.bench.py')
return recursive_glob(pattern) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def cli(patterns, times, json, csv, rst, md, ref, unit, precision, debug):
'''Execute minibench benchmarks'''
if ref:
ref = JSON.load(ref)
filenames = []
reporters = [CliReporter(ref=ref, debug=debug, unit=unit, precision=precision)]
kwargs = {}
for pattern in patterns or ['**/*.bench.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 load_json(self):
"""Load JSON from the request body and store them in self.request.arguments, like Tornado does by default for POSTed form parameters. If JSO... |
try:
self.request.arguments = json.loads(self.request.body)
except ValueError:
msg = "Could not decode JSON: %s" % self.request.body
self.logger.debug(msg)
self.raise_error(400, msg) |
<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_dict_of_all_args(self):
"""Generates a dictionary from a handler paths query string and returns it :returns: Dictionary of all key/values in arguments li... |
dictionary = {}
for arg in [arg for arg in self.request.arguments if arg not in self.settings.get("reserved_query_string_params", [])]:
val = self.get_argument(arg, default=None)
if val:
dictionary[arg] = val
return dictionary |
<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_arg_value_as_type(self, key, default=None, convert_int=False):
"""Allow users to pass through truthy type values like true, yes, no and get to a typed va... |
val = self.get_query_argument(key, default)
if isinstance(val, int):
return val
if val.lower() in ['true', 'yes']:
return True
if val.lower() in ['false', 'no']:
return False
return 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 get_mongo_query_from_arguments(self, reserved_attributes=[]):
"""Generate a mongo query from the given URL query parameters, handles OR query via multiples :... |
query = {}
for arg in self.request.arguments:
if arg not in reserved_attributes:
if len(self.request.arguments.get(arg)) > 1:
query["$or"] = []
for val in self.request.arguments.get(arg):
query["$or"].append({a... |
<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_meta_data(self):
"""Creates the meta data dictionary for a revision""" |
return {
"comment": self.request.headers.get("comment", ""),
"author": self.get_current_user() or self.settings.get('annonymous_user')
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def arg_as_array(self, arg, split_char="|"):
"""Turns an argument into an array, split by the splitChar :param str arg: The name of the query param you want to t... |
valuesString = self.get_argument(arg, default=None)
if valuesString:
valuesArray = valuesString.split(split_char)
return valuesArray
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
""" Sets an error status and returns a message to the user in JSON format :param int status: The status code to use :param str message: The message to return in t... |
self.set_status(status)
self.write({"message" : message,
"status" : status}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def return_resource(self, resource, status=200, statusMessage="OK"):
"""Return a resource response :param str resource: The JSON String representation of a resou... |
self.set_status(status, statusMessage)
self.write(json.loads(json_util.dumps(resource))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def group_objects_by(self, list, attr, valueLabel="value", childrenLabel="children"):
""" Generates a group object based on the attribute value on of the given a... |
groups = []
for obj in list:
val = obj.get(attr)
if not val:
pass
newGroup = {"attribute": attr, valueLabel: val, childrenLabel: [obj]}
found = False
for i in range(0,len(groups)):
if val == groups[i].get(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 write_hyper_response(self, links=[], meta={}, entity_name=None, entity=None, notifications=[], actions=[]):
"""Writes a hyper media response object :param li... |
assert entity_name is not None
assert entity is not None
meta.update({
"status": self.get_status()
})
self.write({
"links": links,
"meta": meta,
entity_name: entity,
"notifications": notifications,
"action... |
<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(self, id):
""" Get an by object by unique identifier :id string id: the bson id of an object :rtype: JSON """ |
try:
if self.request.headers.get("Id"):
object_ = yield self.client.find_one({self.request.headers.get("Id"): id})
else:
object_ = yield self.client.find_one_by_id(id)
if object_:
self.write(object_)
return
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, id):
""" Update a resource by bson ObjectId :returns: json string representation :rtype: JSON """ |
try:
#Async update flow
object_ = json_util.loads(self.request.body)
toa = self.request.headers.get("Caesium-TOA", None)
obj_check = yield self.client.find_one_by_id(id)
if not obj_check:
self.raise_error(404, "Resource not found: %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 post(self, id=None):
""" Create a new object resource :json: Object to create :returns: json string representation :rtype: JSON """ |
try:
try:
base_object = json_util.loads(self.request.body)
except TypeError:
base_object = json_util.loads(self.request.body.decode())
#assert not hasattr(base_object, "_id")
toa = self.request.headers.get("Caesium-TOA", 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 initialize(self):
"""Initializer for the Search Handler""" |
self.logger = logging.getLogger(self.__class__.__name__)
self.client = 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 __lazy_migration(self, master_id):
""" Creates a revision for a master id that didn't previously have a revision, this allows you to easily turn on revisioni... |
collection_name = self.request.headers.get("collection")
if collection_name:
stack = AsyncSchedulableDocumentRevisionStack(collection_name,
self.settings,
master_id=master_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 get(self, master_id):
""" Get a list of revisions by master ID :param master_id: :return: """ |
collection_name = self.request.headers.get("collection")
self.client = BaseAsyncMotorDocument("%s_revisions" % collection_name)
limit = self.get_query_argument("limit", 2)
add_current_revision = self.get_arg_value_as_type("addCurrent",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, id):
""" Update a revision by ID :param id: BSON id :return: """ |
collection_name = self.request.headers.get("collection")
if not collection_name:
self.raise_error(400, "Missing a collection name header")
self.client = BaseAsyncMotorDocument("%s_revisions" % collection_name)
super(self.__class__, self).put(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 get(self, id):
""" Get revision based on the stack preview algorithm :param id: BSON id :return: JSON """ |
collection_name = self.request.headers.get("collection")
if not collection_name:
self.raise_error(400, "Missing a collection name for stack")
self.stack = AsyncSchedulableDocumentRevisionStack(collection_name, self.settings)
revision = yield self.stack.preview(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 get(self):
""" Standard search end point for a resource of any type, override this get method as necessary in any specifc sub class. This is mostly here as a... |
objects = yield self.client.find(self.get_mongo_query_from_arguments())
self.write({
"count" : len(objects),
"results": objects
})
self.finish() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, id=None):
"""Update many objects with a single PUT. Example Request:: { "ids": ["52b0ede98ac752b358b1bd69", "52b0ede98ac752b358b1bd70"], "patch": {... |
toa = self.request.headers.get("Caesium-TOA")
if not toa:
self.raise_error(400, "Caesium-TOA header is required, none found")
self.finish(self.request.headers.get("Caesium-TOA"))
meta = self._get_meta_data()
meta["bulk_id"] = uuid.uuid4().get_hex()
ids... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, bulk_id):
"""Update many objects with a single toa :param str bulk_id: The bulk id for the job you want to delete """ |
collection_name = self.request.headers.get("collection")
if not collection_name:
self.raise_error(400, "Missing a collection name header")
self.revisions = BaseAsyncMotorDocument("%s_revisions" % collection_name)
self.logger.info("Deleting revisions with bulk_id %s" % (b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def author_from_git(self):
""" Get the author name from git information. """ |
self.author = None
try:
encoding = locale.getdefaultlocale()[1]
# launch git command and get answer
cmd = Popen(["git", "config", "--get", "user.name"], stdout=PIPE)
stdoutdata = cmd.communicate().decode(encoding)
if (stdoutdata[0]):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _getframe(level=0):
'''
A reimplementation of `sys._getframe`.
`sys._getframe` is a private function, and isn't guaranteed to exist in all
versions and implementations of Python.
This function is about 2 times slower than the native implementation. It
relies on the asumption that the trace... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def graft(func=None, *, namespace=None):
"""Decorator for marking a function as a graft. Parameters: namespace (str):
namespace of data, same format as targetin... |
if not func:
return functools.partial(graft, namespace=namespace)
if isinstance(func, Graft):
return func
return Graft(func, namespace=namespace) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(force=False):
"""Magical loading of all grafted functions. Parameters: force (bool):
force reload """ |
if GRAFTS and not force:
return GRAFTS
# insert missing paths
# this could be a configurated item
userpath = settings.userpath
if os.path.isdir(userpath) and userpath not in __path__:
__path__.append(userpath)
def notify_error(name):
logging.error('unable to load %s 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 _write_buildproc_yaml(build_data, env, user, cmd, volumes, app_folder):
""" Write a proc.yaml for the container and return the container path """ |
buildproc = ProcData({
'app_folder': str(app_folder),
'app_name': build_data.app_name,
'app_repo_url': '',
'app_repo_type': '',
'buildpack_url': '',
'buildpack_version': '',
'config_name': 'build',
'env': env,
'host': '',
'port': 0,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assert_compile_finished(app_folder):
""" Once builder.sh has invoked the compile script, it should return and we should set a flag to the script returned. If... |
fpath = os.path.join(app_folder, '.postbuild.flag')
if not os.path.isfile(fpath):
msg = ('No postbuild flag set, LXC container may have crashed while '
'building. Check compile logs for build.')
raise AssertionError(msg)
try:
os.remove(fpath)
except OSError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recover_release_data(app_folder):
""" Given the path to an app folder where an app was just built, return a dictionary containing the data emitted from runni... |
with open(os.path.join(app_folder, '.release.yaml'), 'rb') as f:
return yaml.safe_load(f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recover_buildpack(app_folder):
""" Given the path to an app folder where an app was just built, return a BuildPack object pointing to the dir for the buildpa... |
filepath = os.path.join(app_folder, '.buildpack')
with open(filepath) as f:
buildpack_picked = f.read()
buildpack_picked = buildpack_picked.lstrip('/')
buildpack_picked = buildpack_picked.rstrip('\n')
buildpack_picked = os.path.join(os.getcwd(), buildpack_picked)
return BuildPack(buildp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pull_buildpack(url):
""" Update a buildpack in its shared location, then make a copy into the current directory, using an md5 of the url. """ |
defrag = _defrag(urllib.parse.urldefrag(url))
with lock_or_wait(defrag.url):
bp = update_buildpack(url)
dest = bp.basename + '-' + hash_text(defrag.url)
shutil.copytree(bp.folder, dest)
# Make the buildpack dir writable, per
# https://bitbucket.org/yougov/velociraptor/issues/178... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_tarball(self, app_folder, build_data):
""" Following a successful build, create a tarball and build result. """ |
# slugignore
clean_slug_dir(app_folder)
# tar up the result
with tarfile.open('build.tar.gz', 'w:gz') as tar:
tar.add(app_folder, arcname='')
build_data.build_md5 = file_md5('build.tar.gz')
tardest = os.path.join(self.outfolder, 'build.tar.gz')
shut... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def process_request(self, request):
'''
checks if the host domain is one of the site objects
and sets request.site_id
'''
site_id = 0
domain = request.get_host().lower()
if hasattr(settings, 'SITE_ID'):
site_id = settings.SITE_ID
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign(self, request, authheaders, secret):
"""Returns the v2 signature appropriate for the request. The request is not changed by this function. Keyword argum... |
if "id" not in authheaders or authheaders["id"] == '':
raise KeyError("id required in authorization headers.")
if "nonce" not in authheaders or authheaders["nonce"] == '':
raise KeyError("nonce required in authorization headers.")
if "realm" not in authheaders or authhea... |
<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_response_signer(self):
"""Returns the response signer for this version of the signature. """ |
if not hasattr(self, "response_signer"):
self.response_signer = V2ResponseSigner(self.digest, orig=self)
return self.response_signer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self, request, secret):
"""Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature. This ver... |
if request.get_header("Authorization") == "":
return False
ah = self.parse_auth_headers(request.get_header("Authorization"))
if "signature" not in ah:
return False
if request.get_header('x-authorization-timestamp') == '':
raise KeyError("X-Authorizati... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unroll_auth_headers(self, authheaders, exclude_signature=False, sep=",", quote=True):
"""Converts an authorization header dict-like object into a string repr... |
res = ""
ordered = collections.OrderedDict(sorted(authheaders.items()))
form = '{0}=\"{1}\"' if quote else '{0}={1}'
if exclude_signature:
return sep.join([form.format(k, urlquote(str(v), safe='')) for k, v in ordered.items() if k != 'signature'])
else:
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign_direct(self, request, authheaders, secret):
"""Signs a request directly with a v2 signature. The request's Authorization header will change. This functi... |
if request.get_header('x-authorization-timestamp') == '':
request.with_header("X-Authorization-Timestamp", str(time.time()))
if request.body is not None and request.body != b'':
if request.get_header("x-authorization-content-sha256") == '':
sha256 = hashlib.sha25... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self, request, response, secret):
"""Checks the response for the appropriate signature. Returns True if the signature matches the expected value. Keywo... |
auth = request.get_header('Authorization')
if auth == '':
raise KeyError('Authorization header is required for the request.')
ah = self.orig.parse_auth_headers(auth)
act = response.headers['X-Server-Authorization-HMAC-SHA256']
if act == '':
raise KeyError... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signable(self, request, authheaders, response_body):
"""Creates the signable string for a response and returns it. Keyword arguments: request -- A request ob... |
nonce = authheaders["nonce"]
timestamp = request.get_header("x-authorization-timestamp")
try:
body_str = response_body.decode('utf-8')
except:
body_str = response_body
return '{0}\n{1}\n{2}'.format(nonce, timestamp, body_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 sign(self, request, authheaders, response_body, secret):
"""Returns the response signature for the response to the request. Keyword arguments: request -- A r... |
if "nonce" not in authheaders or authheaders["nonce"] == '':
raise KeyError("nonce required in authorization headers.")
if request.get_header('x-authorization-timestamp') == '':
raise KeyError("X-Authorization-Timestamp is required.")
try:
mac = hmac.HMAC(ba... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_task(self, id, client=None):
"""Deletes a task from the current task queue. If the task isn't found (backend 404), raises a :class:`gcloud.exceptions.... |
client = self._require_client(client)
task = Task(taskqueue=self, id=id)
# We intentionally pass `_target_object=None` since a DELETE
# request has no response value (whether in a standard request or
# in a batch request).
client.connection.api_request(method='DELETE', ... |
<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_task(self, id, client=None):
"""Gets a named task from taskqueue If the task isn't found (backend 404), raises a :class:`gcloud.exceptions.NotFound`. :ty... |
client = self._require_client(client)
task = Task(taskqueue=self, id=id)
try:
response = client.connection.api_request(method='GET', path=task.path, _target_object=task)
task._set_properties(response)
return task
except NotFound:
return 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 lease(self, lease_time, num_tasks, group_by_tag=False, tag=None, client=None):
""" Acquires a lease on the topmost N unowned tasks in the specified queue. :t... |
client = self._require_client(client)
if group_by_tag:
query_params = {"leaseSecs": lease_time, "numTasks": num_tasks, "groupByTag": group_by_tag, "tag": tag}
else:
query_params = {"leaseSecs": lease_time, "numTasks": num_tasks}
response = client.connection.api_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_task(self, id, new_lease_time, client=None):
""" Updates the duration of a task lease If the task isn't found (backend 404), raises a :class:`gcloud.e... |
client = self._require_client(client)
task = Task(taskqueue=self, id=id)
try:
response = client.connection.api_request(method='POST', path=self.path + "/tasks/" + id,
query_params={"newLeaseSeconds": new_lease_time},
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert_task(self, description, tag=None, client=None):
""" Insert task in task queue. If the task isn't found (backend 404), raises a :class:`gcloud.exceptio... |
client = self._require_client(client)
new_task = {
"queueName": self.full_name,
"payloadBase64": base64.b64encode(description).decode('ascii'),
"tag": tag
}
response = client.connection.api_request(method='POST', path=self.path + "/tasks/", data=new... |
<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_to(self, container):
'''
Add the class to @container.
'''
if self.container:
self.remove_from(self.container)
container.add(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def draw(self, surf):
'''
Draw all widgets and sub-containers to @surf.
'''
if self.shown:
for w in self.widgets:
surf.blit(w.image, self.convert_rect(w.rect))
for c in self.containers:
c.draw(surf) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def kill(self):
'''
Remove the class from its container, contained items and sub-widgets.
Runs automatically when the class is garbage collected.
'''
Base.kill(self)
for c in self.containers:
c.remove_internal(self)
for w in self.widgets:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def bspace(self):
'''
Remove the character before the cursor.
'''
try:
self.text.pop(self.cursor_loc - 1)
self.cursor_loc -= 1
except IndexError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def paste(self):
'''
Insert text from the clipboard at the cursor.
'''
try:
t = pygame.scrap.get(SCRAP_TEXT)
if t:
self.insert(t)
return True
except:
# pygame.scrap is experimental, allow for changes
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def animate_cli(animation_, step, event):
"""Print out the animation cycle to stdout. This function is for use with synchronous functions and must be run in a th... |
while True: # run at least once, important for tests!
time.sleep(step)
frame = next(animation_)
sys.stdout.write(frame)
sys.stdout.flush()
if event.is_set():
break
sys.stdout.write(animation_.get_erase_frame())
sys.stdout.flush()
animation_.reset() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def energy_ES(q, v):
"""Compute the kinetic and potential energy of the earth sun system""" |
# Body 0 is the sun, Body 1 is the earth
m0 = mass[0]
m1 = mass[1]
# Positions of sun and earth
q0: np.ndarray = q[:, slices[0]]
q1: np.ndarray = q[:, slices[1]]
# Velocities of sun and earth
v0: np.ndarray = v[:, slices[0]]
v1: np.ndarray = v[:, slices[1]]
# Kinetic energy 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 make_force_ES(q_vars, mass):
"""Fluxion with the potential energy of the earth-sun sytem""" |
# Build the potential energy fluxion; just one pair of bodies
U = U_ij(q_vars, mass, 0, 1)
# Varname arrays for both the coordinate system and U
vn_q = np.array([q.var_name for q in q_vars])
vn_fl = np.array(sorted(U.var_names))
# Permutation array for putting variables in q in the order expec... |
<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, meta, val):
"""Validate an account_id""" |
val = string_or_int_as_string_spec().normalise(meta, val)
if not regexes['amazon_account_id'].match(val):
raise BadOption("Account id must match a particular regex", got=val, should_match=regexes['amazon_account_id'].pattern)
return 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 aws_syncr_spec(self):
"""Spec for aws_syncr options""" |
formatted_string = formatted(string_spec(), MergedOptionStringFormatter, expected_type=string_types)
return create_spec(AwsSyncr
, extra = defaulted(formatted_string, "")
, stage = defaulted(formatted_string, "")
, debug = defaulted(boolean(), False)
, dr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def accounts_spec(self):
"""Spec for accounts options""" |
formatted_account_id = formatted(valid_account_id(), MergedOptionStringFormatter, expected_type=string_types)
return dictof(string_spec(), formatted_account_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 _gen_s3_path(self, model, props):
""" Return the part of the S3 path based on inputs The path will be passed to the s3_upload method & will ultimately be mer... |
now = '%.5f' % time.time()
return '%s/%s/%s/%s.%s' % (model.rtype, model.rid_value,
self._s3_rtype, now, props['file-ext']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_post(self, req, resp, rid):
""" Deserialize the file upload & save it to S3 File uploads are associated with a model of some kind. Ensure the associating ... |
signals.pre_req.send(self.model)
signals.pre_req_upload.send(self.model)
props = req.deserialize(self.mimetypes)
model = find(self.model, rid)
signals.pre_upload.send(self.model, model=model)
try:
conn = s3_connect(self.key, self.secret)
path ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def before(f, chain=False):
"""Runs f before the decorated function.""" |
def decorator(g):
@wraps(g)
def h(*args, **kargs):
if chain:
return g(f(*args, **kargs))
else:
f(*args, **kargs)
return g(*args, **kargs)
return h
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 after(f, chain=False):
"""Runs f with the result of the decorated function.""" |
def decorator(g):
@wraps(g)
def h(*args, **kargs):
if chain:
return f(g(*args, **kargs))
else:
r = g(*args, **kargs)
f(*args, **kargs)
return r
return h
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 during(f):
"""Runs f during the decorated function's execution in a separate thread.""" |
def decorator(g):
@wraps(g)
def h(*args, **kargs):
tf = Thread(target=f, args=args, kwargs=kargs)
tf.start()
r = g(*args, **kargs)
tf.join()
return r
return h
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 current_frame(raw=False):
'''
Gives the current execution frame.
:returns:
The current execution frame that is actually executing this.
'''
# `import sys` is important here, because the `sys` module is special
# and we will end up with the class frame in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def locate(callback, root_frame=None, include_root=False, raw=False):
'''
Locates a frame by criteria.
:param callback:
One argument function to check the frame against. The frame we are
curretly on, is given as that argument.
:param root_frame:
The r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_call(self, func, *args, **kwargs):
""" Sets the function & its arguments to be called when the task is processed. Ex:: task.to_call(my_function, 1, 'c', a... |
self.func = func
self.func_args = args
self.func_kwargs = 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 serialize(self):
""" Serializes the ``Task`` data for storing in the queue. All data must be JSON-serializable in order to be stored properly. :returns: A JS... |
data = {
'task_id': self.task_id,
'retries': self.retries,
'async': self.async,
'module': determine_module(self.func),
'callable': determine_name(self.func),
'args': self.func_args,
'kwargs': self.func_kwargs,
'opti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deserialize(cls, data):
""" Given some data from the queue, deserializes it into a ``Task`` instance. The data must be similar in format to what comes from `... |
data = json.loads(data)
options = data.get('options', {})
task = cls(
task_id=data['task_id'],
retries=data['retries'],
async=data['async']
)
func = import_attr(data['module'], data['callable'])
task.to_call(func, *data.get('args', [... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" Runs the task. This fires the ``on_start`` hook function first (if present), passing the task itself. Then it runs the target function supplie... |
if self.on_start:
self.on_start(self)
try:
result = self.func(*self.func_args, **self.func_kwargs)
except Exception as err:
self.to_failed()
if self.on_error:
self.on_error(self, err)
raise
self.to_success()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _check_typecode_list(ofwhat, tcname):
'''Check a list of typecodes for compliance with Struct
requirements.'''
for o in ofwhat:
if callable(o): #skip if _Mirage
continue
if not isinstance(o, TypeCode):
raise TypeError(
tcname + ' ofwhat outside 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 _get_type_or_substitute(typecode, pyobj, sw, elt):
'''return typecode or substitute type for wildcard or
derived type. For serialization only.
'''
sub = getattr(pyobj, 'typecode', typecode)
if sub is typecode or sub is None:
return typecode
# Element WildCard
if isinstance(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 setDerivedTypeContents(self, extensions=None, restrictions=None):
"""For derived types set appropriate parameter and """ |
if extensions:
ofwhat = list(self.ofwhat)
if type(extensions) in _seqtypes:
ofwhat += list(extensions)
else:
ofwhat.append(extensions)
elif restrictions:
if type(restrictions) in _seqtypes:
ofwhat = restrict... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def contains_non_repeat_actions(self):
'''
Because repeating repeat actions can get ugly real fast
'''
for action in self.actions:
if not isinstance(action, (int, dynamic.RepeatCommand)):
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 _all_correct_list(array):
""" Make sure, that all items in `array` has good type and size. Args: array (list):
Array of python types. Returns: True/False ""... |
if type(array) not in _ITERABLE_TYPES:
return False
for item in array:
if not type(item) in _ITERABLE_TYPES:
return False
if len(item) != 2:
return False
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 _convert_to_dict(data):
""" Convert `data` to dictionary. Tries to get sense in multidimensional arrays. Args: data: List/dict/tuple of variable dimension. R... |
if isinstance(data, dict):
return data
if isinstance(data, list) or isinstance(data, tuple):
if _all_correct_list(data):
return dict(data)
else:
data = zip(data[::2], data[1::2])
return dict(data)
else:
raise MetaParsingException(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_structure(data):
""" Check whether the structure is flat dictionary. If not, try to convert it to dictionary. Args: data: Whatever data you have (dict/... |
if not isinstance(data, dict):
try:
data = _convert_to_dict(data)
except MetaParsingException:
raise
except:
raise MetaParsingException(
"Metadata format has invalid strucure (dict is expected)."
)
for key, val in data.ite... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _remove_accents(self, input_str):
""" Convert unicode string to ASCII. Credit: http://stackoverflow.com/a/517974 """ |
nkfd_form = unicodedata.normalize('NFKD', input_str)
return u"".join([c for c in nkfd_form if not unicodedata.combining(c)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, key, val):
""" Try to look for `key` in all required and optional fields. If found, set the `val`. """ |
for field in self.fields:
if field.check(key, val):
return
for field in self.optional:
if field.check(key, val):
return |
<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_size(cls):
""" Total byte size of fields in this structure => total byte size of the structure on the file """ |
return sum([getattr(cls, name).length
for name in cls.get_fields_names()]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def format_image(path, options):
'''Formats an image.
Args:
path (str): Path to the image file.
options (dict): Options to apply to the image.
Returns:
(list) A list of PIL images. The list will always be of length
1 unless resolutions for resizing are provided in the optio... |
<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_instance(key, expire=None):
"""Return an instance of RedisSet.""" |
global _instances
try:
instance = _instances[key]
except KeyError:
instance = RedisSet(
key,
_redis,
expire=expire
)
_instances[key] = instance
return 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 add(self, value):
"""Add value to set.""" |
added = self.redis.sadd(
self.key,
value
)
if self.redis.scard(self.key) < 2:
self.redis.expire(self.key, self.expire)
return added |
<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(name, keyword, domain, citation, author, description, species, version, contact, licenses, values, functions, output, value_prefix):
"""Build a namespa... |
write_namespace(
name, keyword, domain, author, citation, values,
namespace_description=description,
namespace_species=species,
namespace_version=version,
author_contact=contact,
author_copyright=licenses,
functions=functions,
file=output,
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 history(namespace_module):
"""Hash all versions on Artifactory.""" |
for path in get_namespace_history(namespace_module):
h = get_bel_resource_hash(path.as_posix())
click.echo('{}\t{}'.format(path, h)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_to_annotation(file, output):
"""Convert a namespace file to an annotation file.""" |
resource = parse_bel_resource(file)
write_annotation(
keyword=resource['Namespace']['Keyword'],
values={k: '' for k in resource['Values']},
citation_name=resource['Citation']['NameString'],
description=resource['Namespace']['DescriptionString'],
file=output
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def history(annotation_module):
"""Output the hashes for the annotation resources' versions.""" |
for path in get_annotation_history(annotation_module):
h = get_bel_resource_hash(path.as_posix())
click.echo('{}\t{}'.format(path, h)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_to_namespace(file, output, keyword):
"""Convert an annotation file to a namespace file.""" |
resource = parse_bel_resource(file)
write_namespace(
namespace_keyword=(keyword or resource['AnnotationDefinition']['Keyword']),
namespace_name=resource['AnnotationDefinition']['Keyword'],
namespace_description=resource['AnnotationDefinition']['DescriptionString'],
author_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 get_proxy():
"""Return a random proxy from proxy config.""" |
proxies = _config['proxies']
return proxies[
random.randint(0, len(proxies) - 1)
] if len(proxies) > 0 else 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 get_instance():
"""Return an instance of Client.""" |
global _instances
user_agents = _config['user-agents']
user_agent = user_agents[
random.randint(0, len(user_agents) - 1)
] if len(user_agents) > 0 else DEFAULT_UA
instance_key = user_agent
try:
instance = _instances[instance_key]
except KeyError:
instance = Client... |
<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(self, uri, disable_proxy=False, stream=False):
"""Return Requests response to GET request.""" |
response = requests.get(
uri,
headers=self.headers,
allow_redirects=True,
cookies={},
stream=stream,
proxies=self.proxy if not disable_proxy else False
)
if response.status_code in _PERMITTED_STATUS_CODES:
self... |
<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_content(self, uri, disable_proxy=False):
"""Return content from URI if Response status is good.""" |
return self.get(uri=uri, disable_proxy=disable_proxy) |
<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_iter_content(self, uri, disable_proxy=False):
"""Return iterable content from URI if Response status is good.""" |
return self.get(uri=uri, disable_proxy=disable_proxy, stream=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 dict_diff(first, second):
""" Return a dict of keys that differ with another config object. If a value is not found in one fo the configs, it will be represe... |
diff = {}
# Check all keys in first dict
for key in first:
if key not in second:
diff[key] = (first[key], None)
elif (first[key] != second[key]):
diff[key] = (first[key], second[key])
# Check all keys in second dict to find missing
for key in second:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_file(self, path, dryrun):
""" Concat files and return filename. """ |
# special case - skip output file so we won't include it in result
if path == self._output_path:
return None
# if dryrun skip and return file
if dryrun:
return path
# concat file with output file
with open(path, "rb") as infile:
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 _chain_forks(elements):
"""Detect whether a sequence of elements leads to a fork of streams""" |
# we are only interested in the result, so unwind from the end
for element in reversed(elements):
if element.chain_fork:
return True
elif element.chain_join:
return False
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 parse(filename):
""" parse a scene release string and return a dictionary of parsed values.""" |
screensize = re.compile('720p|1080p', re.I)
source = re.compile(
'\.(AHDTV|MBluRay|MDVDR|CAM|TS|TELESYNC|DVDSCR|DVD9|BDSCR|DDC|R5LINE|R5|DVDRip|HDRip|BRRip|BDRip|WEBRip|WEB-?HD|HDtv|PDTV|WEBDL|BluRay)', re.I)
year = re.compile('(1|2)\d{3}')
series = re.compile('s\d{1,3}e\d{1,3}', re.I)
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 generate_ecdsap256_server_certificate(server_id, server_pub_key, expiry, root_id, root_priv_key):
""" Creates a new server certificate signed by the provided... |
cert = ECDSAP256ServerCertificate()
rc = _lib.xtt_generate_server_certificate_ecdsap256(cert.native,
server_id.native,
server_pub_key.native,
e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project(self, win_width, win_height, fov, viewer_distance):
""" Transforms this 3D point to 2D using a perspective projection. """ |
factor = fov / (viewer_distance + self.z)
x = self.x * factor + win_width // 2
y = -self.y * factor + win_height // 2
return Point3D(x, y, 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 set_default_parser(parser):
""" Set defaulr parser instance Parameters parser : instance or string An instance or registered name of parser class. The specif... |
if isinstance(parser, basestring):
parser = registry.find(parser)()
if not isinstance(parser, BaseParser):
parser = parser()
global _parser
_parser = parser |
<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_default_loader(loader):
""" Set defaulr loader instance Parameters loader : instance or string An instance or registered name of loader class. The specif... |
if isinstance(loader, basestring):
loader = registry.find(loader)()
if not isinstance(loader, BaseLoader):
loader = loader()
global _loader
_loader = loader |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.