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 unique_list(input_, key=lambda x:x):
"""Return the unique elements from the input, in order.""" |
seen = set()
output = []
for x in input_:
keyx = key(x)
if keyx not in seen:
seen.add(keyx)
output.append(x)
return 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 get_environ_list(name, default=None):
"""Return the split colon-delimited list from an environment variable. Returns an empty list if the variable didn't exi... |
packed = os.environ.get(name)
if packed is not None:
return packed.split(':')
elif default is not None:
return default
else:
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 is_indel(reference_bases, alternate_bases):
""" Return whether or not the variant is an INDEL """ |
if len(reference_bases) > 1:
return True
for alt in alternate_bases:
if alt is None:
return True
elif len(alt) != len(reference_bases):
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 is_snp(reference_bases, alternate_bases):
""" Return whether or not the variant is a SNP """ |
if len(reference_bases) > 1:
return False
for alt in alternate_bases:
if alt is None:
return False
if alt not in ['A', 'C', 'G', 'T', 'N', '*']:
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 is_deletion(reference_bases, alternate_bases):
""" Return whether or not the INDEL is a deletion """ |
# if multiple alts, it is unclear if we have a transition
if len(alternate_bases) > 1:
return False
if is_indel(reference_bases, alternate_bases):
# just one alt allele
alt_allele = alternate_bases[0]
if alt_allele is None:
return True
if len(reference_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 overlapping(self, other):
"""Do these variants overlap in the reference""" |
return (
other.start in self.ref_range) or (
self.start in other.ref_range) |
<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_pgurl(self, url):
""" Given a Postgres url, return a dict with keys for user, password, host, port, and database. """ |
parsed = urlsplit(url)
return {
'user': parsed.username,
'password': parsed.password,
'database': parsed.path.lstrip('/'),
'host': parsed.hostname,
'port': parsed.port or 5432,
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value_change(self, model, name, info):
"""The model is changed and the view must be updated""" |
msg = self.model.get_message(info.new)
self.view.set_msg(msg)
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 reset_current_row(self, *args, **kwargs):
"""Reset the selected rows value to its default value :returns: None :rtype: None :raises: None """ |
i = self.configobj_treev.currentIndex()
m = self.configobj_treev.model()
m.restore_default(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 get_configs(self):
"""Load all config files and return the configobjs :returns: a list of configobjs :raises: None It always loads the coreconfig. Then it lo... |
# all loaded configs are stored in confs
confs = []
# always load core config. it is not part of the plugin configs
try:
confs.append(iniconf.get_core_config())
except ConfigError, e:
log.error("Could not load Core config! Reason was: %s" % 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 set_inifile(self, current, previous):
"""Set the configobj to the current index of the files_lv This is a slot for the currentChanged signal :param current: ... |
c = self.inimodel.data(current, self.inimodel.confobjRole)
self.confobjmodel = ConfigObjModel(c)
self.configobj_treev.setModel(self.confobjmodel)
self.configobj_treev.expandAll()
self.confobjmodel.dataChanged.connect(self.iniedited) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iniedited(self, *args, **kwargs):
"""Set the current index of inimodel to modified :returns: None :rtype: None :raises: None """ |
self.inimodel.set_index_edited(self.files_lv.currentIndex(), 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 closeEvent(self, event):
"""Handles closing of the window. If configs were edited, ask user to continue. :param event: the close event :type event: QCloseEve... |
if self.inimodel.get_edited():
r = self.doc_modified_prompt()
if r == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
else:
event.accept() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def doc_modified_prompt(self, ):
"""Create a message box, that asks the user to continue although files have been modified :returns: value of the standard button... |
msgbox = QtGui.QMessageBox()
msgbox.setWindowTitle("Discard changes?")
msgbox.setText("Documents have been modified.")
msgbox.setInformativeText("Do you really want to exit? Changes will be lost!")
msgbox.setStandardButtons(msgbox.Yes | msgbox.Cancel)
msgbox.setDefaultBu... |
<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_current_config(self, ):
"""Saves the currently displayed config :returns: None :rtype: None :raises: None This resets the edited status of the file to F... |
# check if all configs validate correctly
btn = None
for row in range(self.inimodel.rowCount()):
i = self.inimodel.index(row, 0)
r = self.inimodel.validate(i)
if r is not True:
btn = self.invalid_prompt()
break
if btn ... |
<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_virtualenv_path(self, requirements_option: RequirementsOptions, requirements_hash: Optional[str]) -> Path: """ Returns the path to the virtualenv the curr... |
if requirements_option == RequirementsOptions.no_requirements:
venv_name = "no_requirements"
else:
venv_name = requirements_hash
return Path(self._arca.base_dir) / "venvs" / venv_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_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str: """ Handles the requirements in the target repository, return... |
return str(self.get_or_create_venv(repo_path).resolve() / "bin" / "python") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def annotate_mapper(**decargs):
"""Add input and output watermarks to processed events.""" |
def decorator(func):
"""Annotate events with entry and/or exit timestamps."""
def wrapper(event, *args, **kwargs):
"""Add enter and exit annotations to the processed event."""
funcname = ":".join([func.__module__, func.__name__])
enter_ts = time.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 annotate_filter(**decargs):
"""Add input and output watermarks to filtered events.""" |
def decorator(func):
"""Annotate events with entry and/or exit timestamps."""
def wrapper(event, *args, **kwargs):
"""Add enter and exit annotations to the processed event."""
funcname = ":".join([func.__module__, func.__name__])
enter_key = funcname + "|enter"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _error_repr(error):
"""A compact unique representation of an error.""" |
error_repr = repr(error)
if len(error_repr) > 200:
error_repr = hash(type(error))
return error_repr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def annotation_has_expired(event, key, timeout):
"""Check if an event error has expired.""" |
anns = get_annotations(event, key)
if anns:
return (time.time() - anns[0]["ts"]) > timeout
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 replace_event_annotations(event, newanns):
"""Replace event annotations with the provided ones.""" |
_humilis = event.get("_humilis", {})
if not _humilis:
event["_humilis"] = {"annotation": newanns}
else:
event["_humilis"]["annotation"] = newanns |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def annotate_event(ev, key, ts=None, namespace=None, **kwargs):
"""Add an annotation to an event.""" |
ann = {}
if ts is None:
ts = time.time()
ann["ts"] = ts
ann["key"] = key
if namespace is None and "HUMILIS_ENVIRONMENT" in os.environ:
namespace = "{}:{}:{}".format(
os.environ.get("HUMILIS_ENVIRONMENT"),
os.environ.get("HUMILIS_LAYER"),
os.enviro... |
<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_annotations(event, key, namespace=None, matchfunc=None):
"""Produce the list of annotations for a given key.""" |
if matchfunc is None:
matchfunc = _is_equal
if isinstance(key, Exception):
key = _error_repr(key)
return [ann for ann in event.get("_humilis", {}).get("annotation", [])
if (matchfunc(key, ann["key"]) and
(namespace is None or ann.get("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 delete_annotations(event, key, namespace=None, matchfunc=None):
"""Delete all event annotations with a matching key.""" |
if matchfunc is None:
matchfunc = _is_equal
if isinstance(key, Exception):
key = _error_repr(key)
newanns = [ann for ann in event.get("_humilis", {}).get("annotation", [])
if not (matchfunc(key, ann["key"]) and
(namespace is None or ann.get("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 get_function_annotations(event, funcname, type=None, namespace=None):
"""Produce a list of function annotations in in this event.""" |
if type:
postfix = "|" + type
else:
postfix = "|.+"
def matchfunc(key, annkey):
"""Check if the provider regex matches an annotation key."""
return re.match(key, annkey) is not None
return get_annotations(event, funcname + postfix, 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 add_task(self, keywords, context, rule):
"""Map a function to a list of keywords Parameters keywords : iterable of str sequence of strings which should trigg... |
for keyword in keywords:
self._tasks[keyword] = {'context': context, 'rule': rule} |
<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_modifier(self, modifier, keywords, relative_pos, action, parameter=None):
"""Modify existing tasks based on presence of a keyword. Parameters modifier : ... |
if relative_pos == 0:
raise ValueError("relative_pos cannot be 0")
modifier_dict = self._modifiers.get(modifier, {})
value = (action, parameter, relative_pos)
for keyword in keywords:
action_list = list(modifier_dict.get(keyword, []))
action_list.appe... |
<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(self, text):
"""Parse the string `text` and return a tuple of left over Data fields. Parameters text : str A string to be parsed Returns ------- result... |
self._parsed_list = []
self._most_recent_report = []
self._token_list = text.lower().split()
modifier_index_list = []
for item in self._token_list:
if(self._is_token_data_callback(item)):
self._parsed_list.append(self._clean_data_callback... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connectionLost(self, reason):
""" Called when the response body has been completely delivered. @param reason: Either a twisted.web.client.ResponseDone except... |
self.remaining.reset()
try:
result = json.load(self.remaining)
except Exception, e:
self.finished.errback(e)
return
returnValue = result
if self.heartbeater:
self.heartbeater.nextToken = result['token']
returnValue = ... |
<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, method, path, options=None, payload=None, heartbeater=None, retry_count=0):
""" Make a request to the Service Registry API. @param method: HTTP... |
def _request(authHeaders, options, payload, heartbeater, retry_count):
tenantId = authHeaders['X-Tenant-Id']
requestUrl = self.baseUrl + tenantId + path
if options:
requestUrl += '?' + urlencode(options)
payload = StringProducer(json.dumps(payload... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _initialized(self, partitioner):
"""Store the partitioner and reset the internal state. Now that we successfully got an actual :class:`kazoo.recipe.partition... |
self._partitioner = partitioner
self._thimble = Thimble(self.reactor, self.pool,
partitioner, _blocking_partitioner_methods)
self._state = 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 inject_arca(self, arca):
""" Apart from the usual validation stuff it also creates log file for this instance. """ |
super().inject_arca(arca)
import vagrant
self.log_path = Path(self._arca.base_dir) / "logs" / (str(uuid4()) + ".log")
self.log_path.parent.mkdir(exist_ok=True, parents=True)
logger.info("Storing vagrant log in %s", self.log_path)
self.log_cm = vagrant.make_file_cm(sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_vagrant(self, vagrant_file):
""" Creates a Vagrantfile in the target dir, with only the base image pulled. Copies the runner script to the directory so ... |
if self.inherit_image:
image_name, image_tag = str(self.inherit_image).split(":")
else:
image_name = self.get_arca_base_name()
image_tag = self.get_python_base_tag(self.get_python_version())
logger.info("Creating Vagrantfile located in %s, base image %s:%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 fabric_task(self):
""" Returns a fabric task which executes the script in the Vagrant VM """ |
from fabric import api
@api.task
def run_script(container_name, definition_filename, image_name, image_tag, repository, timeout):
""" Sequence to run inside the VM.
Starts up the container if the container is not running
(and copies over the data and... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_vm_running(self, vm_location):
""" Gets or creates a Vagrantfile in ``vm_location`` and calls ``vagrant up`` if the VM is not running. """ |
import vagrant
if self.vagrant is None:
vagrant_file = vm_location / "Vagrantfile"
if not vagrant_file.exists():
self.init_vagrant(vagrant_file)
self.vagrant = vagrant.Vagrant(vm_location,
quiet_stdout=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 run(self, repo: str, branch: str, task: Task, git_repo: Repo, repo_path: Path):
""" Starts up a VM, builds an docker image and gets it to the VM, runs the sc... |
from fabric import api
from fabric.exceptions import CommandTimeout
# start up or get running VM
vm_location = self.get_vm_location()
self.ensure_vm_running(vm_location)
logger.info("Running with VM located at %s", vm_location)
# pushes the image to the registr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop_vm(self):
""" Stops or destroys the VM used to launch tasks. """ |
if self.vagrant is not None:
if self.destroy:
self.vagrant.destroy()
shutil.rmtree(self.vagrant.root, ignore_errors=True)
self.vagrant = None
else:
self.vagrant.halt() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url_content(url, cache_duration=None, from_cache_on_error=False):
""" Get content for the given URL :param str url: The URL to get content from :param int ca... |
cache_file = _url_content_cache_file(url)
if cache_duration:
if os.path.exists(cache_file):
stat = os.stat(cache_file)
cached_time = stat.st_mtime
if time.time() - cached_time < cache_duration:
with open(cache_file) as fp:
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 route(**kwargs):
""" Route a request to different views based on http verb. Kwargs should be 'GET', 'POST', 'PUT', 'DELETE' or 'ELSE', where the first four m... |
def routed(request, *args2, **kwargs2):
method = request.method
if method in kwargs:
req_method = kwargs[method]
return req_method(request, *args2, **kwargs2)
elif 'ELSE' in kwargs:
return kwargs['ELSE'](request, *args2, **kwargs2)
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 log(message=None, out=sys.stdout):
"""Log a message before passing through to the wrapped function. This is useful if you want to determine whether wrappers ... |
def decorator(view_fn):
@wraps(view_fn)
def f(*args, **kwargs):
print(message, file=out)
return view_fn(*args, **kwargs)
return f
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 render_template(template):
""" takes a template to render to and returns a function that takes an object to render the data for this template. If callable_or... |
def outer_wrapper(callable_or_dict=None, statuscode=None, **kwargs):
def wrapper(request, *args, **wrapper_kwargs):
if callable(callable_or_dict):
params = callable_or_dict(request, *args, **wrapper_kwargs)
else:
params = callable_or_dict
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json_api_call(req_function):
""" Wrap a view-like function that returns an object that is convertable from json """ |
@wraps(req_function)
def newreq(request, *args, **kwargs):
outp = req_function(request, *args, **kwargs)
if issubclass(outp.__class__, HttpResponse):
return outp
else:
return '%s' % json.dumps(outp, cls=LazyEncoder)
return string_to_response("application/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 string_to_response(content_type):
""" Wrap a view-like function that returns a string and marshalls it into an HttpResponse with the given Content-Type If th... |
def outer_wrapper(req_function):
@wraps(req_function)
def newreq(request, *args, **kwargs):
try:
outp = req_function(request, *args, **kwargs)
if issubclass(outp.__class__, HttpResponse):
response = outp
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 username_matches_request_user(view_fn):
"""Checks if the username matches the request user, and if so replaces username with the actual user object. Returns ... |
@wraps(view_fn)
def wrapper(request, username, *args, **kwargs):
User = get_user_model()
user = get_object_or_404(User, username=username)
if user != request.user:
return HttpResponseForbidden()
else:
return view_fn(request, user, *args, **kwargs)
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 get_boolean(self, input_string):
""" Return boolean type user input """ |
if input_string in ('--write_roc', '--plot', '--compare'):
# was the flag set?
try:
index = self.args.index(input_string) + 1
except ValueError:
# it wasn't, args are optional, so return the appropriate default
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 load_fixture(filename, kind, post_processor=None):
""" Loads a file into entities of a given class, run the post_processor on each instance before it's saved... |
def _load(od, kind, post_processor, parent=None, presets={}):
"""
Loads a single dictionary (od) into an object, overlays the values in
presets, persists it and
calls itself on the objects in __children__* keys
"""
if hasattr(kind, 'keys'): # kind is a map
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_resource(mod, view, **kwargs):
"""Register the resource on the resource name or a custom url""" |
resource_name = view.__name__.lower()[:-8]
endpoint = kwargs.get('endpoint', "{}_api".format(resource_name))
plural_resource_name = inflect.engine().plural(resource_name)
path = kwargs.get('url', plural_resource_name).strip('/')
url = '/{}'.format(path)
setattr(view, '_url', url) # need this 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 get_participants_for_gradebook(gradebook_id, person=None):
""" Returns a list of gradebook participants for the passed gradebook_id and person. """ |
if not valid_gradebook_id(gradebook_id):
raise InvalidGradebookID(gradebook_id)
url = "/rest/gradebook/v1/book/{}/participants".format(gradebook_id)
headers = {}
if person is not None:
headers["X-UW-Act-as"] = person.uwnetid
data = get_resource(url, headers)
participants = [... |
<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_participants_for_section(section, person=None):
""" Returns a list of gradebook participants for the passed section and person. """ |
section_label = encode_section_label(section.section_label())
url = "/rest/gradebook/v1/section/{}/participants".format(section_label)
headers = {}
if person is not None:
headers["X-UW-Act-as"] = person.uwnetid
data = get_resource(url, headers)
participants = []
for pt in data["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 to_python(self, value, context=None):
"""Convert the value to a real python object""" |
value = value.copy()
res = {}
errors = []
for field, schema in self._fields.items():
name = schema.get_attr('name', field)
if name in value:
try:
res[field] = schema.to_python(
value.pop(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 to_raw(self, value, context=None):
"""Convert the value to a JSON compatible value""" |
if value is None:
return None
res = {}
value = value.copy()
errors = []
for field in list(set(value) & set(self._fields)):
schema = self._fields.get(field)
name = schema.get_attr('name', field)
try:
res[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_jsonschema(self, context=None):
"""Ensure the generic schema, remove `types` :return: Gives back the schema :rtype: dict """ |
schema = super(Enum, self).get_jsonschema(context=None)
schema.pop('type')
if self.get_attr('enum'):
schema['enum'] = self.get_attr('enum')
return schema |
<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_references(references, components):
""" Sets references to multiple components. To set references components must implement [[IReferenceable]] interface.... |
if components == None:
return
for component in components:
Referencer.set_references_for_one(references, component) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reduce_opacity(self):
""" Reduce opacity for watermark image. """ |
if self.image.mode != 'RGBA':
image = self.image.convert('RGBA')
else:
image = self.image.copy()
alpha = image.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(self.opacity)
image.putalpha(alpha)
self.image = image |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instructions(self):
""" Retrieve the instructions for the rule. """ |
if self._instructions is None:
# Compile the rule into an Instructions instance; we do
# this lazily to amortize the cost of the compilation,
# then cache that result for efficiency...
self._instructions = parser.parse_rule(self.name, self.text)
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_pages():
'''returns list of urllib file objects'''
pages =[]
counter = 1
print "Checking for themes..."
while(True):
page = urllib.urlopen('http://dotshare.it/category/terms/colors/p/%d/' % counter)
print "Page%d: %s" % (counter, "OK" if (page.code < 400) else "Fail!")
... |
<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_urls(htmlDoc, limit=200):
'''takes in html document as string, returns links to dots'''
soup = BeautifulSoup( htmlDoc )
anchors = soup.findAll( 'a' )
urls = {}
counter = 0
for i,v in enumerate( anchors ):
href = anchors[i].get( 'href' )
if ('dots' in href and counter <... |
<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_themes(urls):
'''takes in dict of names and urls, downloads and saves files'''
length = len(urls)
counter = 1
widgets = ['Fetching themes:', Percentage(), ' ',
Bar(marker='-'), ' ', ETA()]
pbar = ProgressBar( widgets=widgets, maxval=length ).start()
for i in urls.keys()... |
<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_section_path(section):
"""Return a list with keys to access the section from root :param section: A Section :type section: Section :returns: list of stri... |
keys = []
p = section
for i in range(section.depth):
keys.insert(0, p.name)
p = p.parent
return keys |
<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_default_values(section, key, validator=None):
"""Raise an MissingDefaultError if a value in section does not have a default values :param section: the ... |
if validator is None:
validator = Validator()
try:
validator.get_default_value(section[key])
except KeyError:
#dv = set(section.default_values.keys()) # set of all defined default values
#scalars = set(section.scalars) # set of all keys
#if dv != scalars:
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 fix_errors(config, validation):
"""Replace errors with their default values :param config: a validated ConfigObj to fix :type config: ConfigObj :param valida... |
for e in flatten_errors(config, validation):
sections, key, err = e
sec = config
for section in sections:
sec = sec[section]
if key is not None:
sec[key] = sec.default_values.get(key, sec[key])
else:
sec.walk(set_to_default)
return con... |
<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_to_default(section, key):
"""Set the value of the given seciton and key to default :param section: the section of a configspec :type section: section :pa... |
section[key] = section.default_values.get(key, section[key]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_config(config):
"""Check if all values have defaults and replace errors with their default value :param config: the configobj to clean :type config: Co... |
if config.configspec is None:
return
vld = Validator()
validation = config.validate(vld, copy=True)
config.configspec.walk(check_default_values, validator=vld)
fix_errors(config, validation)
validation = config.validate(vld, copy=True)
if not (validation == True): # NOQA seems unpy... |
<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_config(f, spec):
"""Return the ConfigObj for the specified file :param f: the config file path :type f: str :param spec: the path to the configspec :typ... |
dirname = os.path.dirname(f)
if not os.path.exists(dirname):
os.makedirs(dirname)
c = ConfigObj(infile=f, configspec=spec,
interpolation=False, create_empty=True)
try:
clean_config(c)
except ConfigError, e:
msg = "Config %s could not be loaded. Reason: %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 load_config():
""" Validate the config """ |
configuration = MyParser()
configuration.read(_config)
d = configuration.as_dict()
if 'jira' not in d:
raise custom_exceptions.NotConfigured
# Special handling of the boolean for error reporting
d['jira']['error_reporting'] = configuration.getboolean('jira', 'error_reporting')
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 _save_config(jira_url, username, password, error_reporting):
""" Saves the username and password to the config """ |
# Delete what is there before we re-write. New user means new everything
os.path.exists(_config) and os.remove(_config)
config = ConfigParser.SafeConfigParser()
config.read(_config)
if not config.has_section('jira'):
config.add_section('jira')
if 'http' not in jira_url:
jira_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 _get_cookies_as_dict():
""" Get cookies as a dict """ |
config = ConfigParser.SafeConfigParser()
config.read(_config)
if config.has_section('cookies'):
cookie_dict = {}
for option in config.options('cookies'):
option_key = option.upper() if option == 'jsessionid' else option
cookie_dict[option_key] = config.get('cookies'... |
<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_cli(subparsers):
"""Given a parser, load the CLI subcommands""" |
for command_name in available_commands():
module = '{}.{}'.format(__package__, command_name)
loader, description = _import_loader(module)
parser = subparsers.add_parser(command_name,
description=description)
command = loader(parser)
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_command_chain(self, command):
""" Builds execution chain including all intercepters and the specified command. :param command: the command to build a ... |
next = command
for intercepter in reversed(self._intercepters):
next = InterceptedCommand(intercepter, next)
self._commands_by_name[next.get_name()] = next |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notify(self, correlation_id, event, value):
""" Fires event specified by its name and notifies all registered IEventListener listeners :param correlation_id:... |
e = self.find_event(event)
if e != None:
e.notify(correlation_id, value) |
<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_nullable_boolean(value):
""" Converts value into boolean or returns None when conversion is not possible. :param value: the value to convert. :return: boo... |
# Shortcuts
if value == None:
return None
if type(value) == type(True):
return value
str_value = str(value).lower()
# All true values
if str_value in ['1', 'true', 't', 'yes', 'y']:
return True
# All false values
if st... |
<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_boolean_with_default(value, default_value):
""" Converts value into boolean or returns default value when conversion is not possible :param value: the val... |
result = BooleanConverter.to_nullable_boolean(value)
return result if result != None else default_value |
<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_lists(self, username, member_type="USER"):
""" Look up all the lists that the user is a member of. Args: username (str):
The MIT username of the user m... |
return self.client.service.getUserLists(username, member_type, self.proxy_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 user_list_membership(self, username, member_type="USER", recursive=True, max_return_count=999):
""" Get info for lists a user is a member of. This is similar... |
return self.client.service.getUserListMembership(
username,
member_type,
recursive,
max_return_count,
self.proxy_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 list_members(self, name, type="USER", recurse=True, max_results=1000):
""" Look up all the members of a list. Args: name (str):
The name of the list type (s... |
results = self.client.service.getListMembership(
name, type, recurse, max_results, self.proxy_id,
)
return [item["member"] for item in results] |
<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_attributes(self, name):
""" Look up the attributes of a list. Args: name (str):
The name of the list Returns: dict: attributes of the list """ |
result = self.client.service.getListAttributes(name, self.proxy_id)
if isinstance(result, list) and len(result) == 1:
return result[0]
return result |
<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_member_to_list(self, username, listname, member_type="USER"):
""" Add a member to an existing list. Args: username (str):
The username of the user to ad... |
return self.client.service.addMemberToList(
listname, username, member_type, self.proxy_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 create_list( self, name, description="Created by mit_moira client", is_active=True, is_public=True, is_hidden=True, is_group=False, is_nfs_group=False, is_mai... |
attrs = {
"aceName": "mit_moira",
"aceType": "LIST",
"activeList": is_active,
"description": description,
"gid": "",
"group": is_group,
"hiddenList": is_hidden,
"listName": name,
"mailList": is_mail_list... |
<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, model):
"""raises an exception if the model cannot be added""" |
def foo(m, p, i):
if m[i][0].name == model.name:
raise ValueError("Model already exists")
return
# checks if already existing
self.foreach(foo)
self.append((model,))
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 vectorize_dialogues(self, dialogues):
""" Take in a list of dialogues and vectorize them all """ |
return np.array([self.vectorize_dialogue(d) for d in dialogues]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def devectorize_utterance(self, utterance):
""" Take in a sequence of indices and transform it back into a tokenized utterance """ |
utterance = self.swap_pad_and_zero(utterance)
return self.ie.inverse_transform(utterance).tolist() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vectorize_batch_ohe(self, batch):
""" One-hot vectorize a whole batch of dialogues """ |
return np.array([self.vectorize_dialogue_ohe(dia) for dia in batch]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vectorize_utterance_ohe(self, utterance):
""" Take in a tokenized utterance and transform it into a sequence of one-hot vectors """ |
for i, word in enumerate(utterance):
if not word in self.vocab_list:
utterance[i] = '<unk>'
ie_utterance = self.swap_pad_and_zero(self.ie.transform(utterance))
ohe_utterance = np.array(self.ohe.transform(ie_utterance.reshape(len(ie_utterance), 1)))
return o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def devectorize_utterance_ohe(self, ohe_utterance):
""" Take in a sequence of one-hot vectors and transform it into a tokenized utterance """ |
ie_utterance = [argmax(w) for w in ohe_utterance]
utterance = self.ie.inverse_transform(self.swap_pad_and_zero(ie_utterance))
return utterance |
<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_jukebox_logger():
"""Setup the jukebox top-level logger with handlers The logger has the name ``jukebox`` and is the top-level logger for all other log... |
log = logging.getLogger("jb")
log.propagate = False
handler = logging.StreamHandler(sys.stdout)
fmt = "%(levelname)-8s:%(name)s: %(message)s"
formatter = logging.Formatter(fmt)
handler.setFormatter(formatter)
log.addHandler(handler)
level = DEFAULT_LOGGING_LEVEL
log.setLevel(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_logger(name, level=None):
""" Return a setup logger for the given name :param name: The name for the logger. It is advised to use __name__. The logger na... |
log = logging.getLogger("jb.%s" % name)
if level is not None:
log.setLevel(level)
return log |
<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_cartouche_text(lines):
'''Parse text in cartouche format and return a reStructuredText equivalent
Args:
lines: A sequence of strings representing the lines of a single
docstring as read from the source by Sphinx. This string should be
in a format that can be parsed by ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unindent(lines):
'''Convert an iterable of indented lines into a sequence of tuples.
The first element of each tuple is the indent in number of characters, and
the second element is the unindented string.
Args:
lines: A sequence of strings representing the lines of text in a docstring.
... |
<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_exception(line):
'''Parse the first line of a Cartouche exception description.
Args:
line (str): A single line Cartouche exception description.
Returns:
A 2-tuple containing the exception type and the first line of the description.
'''
m = RAISES_REGEX.match(line)
if ... |
<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_paragraphs(indent_paragraphs):
'''
Group paragraphs so that more indented paragraphs become children of less
indented paragraphs.
'''
# The tree consists of tuples of the form (indent, [children]) where the
# children may be strings or other tuples
root = Node(0, [], None)
cur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def first_paragraph_indent(indent_texts):
'''Fix the indentation on the first paragraph.
This occurs because the first line of a multi-line docstring following the
opening quote usually has no indent.
Args:
indent_texts: The lines of the docstring as an iterable over 2-tuples
each ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def determine_opening_indent(indent_texts):
'''Determine the opening indent level for a docstring.
The opening indent level is the indent level is the first non-zero indent
level of a non-empty line in the docstring.
Args:
indent_texts: The lines of the docstring as an iterable over 2-tuples
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def rewrite_autodoc(app, what, name, obj, options, lines):
'''Convert lines from Cartouche to Sphinx format.
The function to be called by the Sphinx autodoc extension when autodoc
has read and processed a docstring. This function modified its
``lines`` argument *in place* replacing Cartouche syntax inp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_exe(arch='x86'):
"""Get the path to an exe launcher provided by this package. The options for arch are currently 'x86' and 'x64'. """ |
if arch == 'x86':
return os.path.join(_pkg_dir, 'cli-32.exe')
elif arch == 'x64':
return os.path.join(_pkg_dir, 'cli-64.exe')
raise ValueError('Unrecognised arch: %r' % arch) |
<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():
""" | Load the configuration file. | Add dynamically configuration to the module. :rtype: None """ |
config = ConfigParser.RawConfigParser(DEFAULTS)
config.readfp(open(CONF_PATH))
for section in config.sections():
globals()[section] = {}
for key, val in config.items(section):
globals()[section][key] = 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 declfuncs(self):
"""generator on all declaration of functions""" |
for f in self.body:
if (hasattr(f, '_ctype')
and isinstance(f._ctype, FuncType)
and not hasattr(f, 'body')):
yield 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 implfuncs(self):
"""generator on all implemented functions""" |
for f in self.body:
if (hasattr(f, '_ctype')
and isinstance(f._ctype, FuncType)
and hasattr(f, 'body')):
yield 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 defvars(self):
"""generator on all definition of variable""" |
for f in self.body:
if (hasattr(f, '_ctype')
and f._name != ''
and not isinstance(f._ctype, FuncType)
and f._ctype._storage != Storages.TYPEDEF):
yield 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 deftypes(self):
"""generator on all definition of type""" |
for f in self.body:
if (hasattr(f, '_ctype')
and (f._ctype._storage == Storages.TYPEDEF
or (f._name == '' and isinstance(f._ctype, ComposedType)))):
yield f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.