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 z(self):
"Day of the year; i.e. '0' to '365'"
doy = self.year_days[self.data.month] + self.data.day
if self.L() and self.data.month > 2:
doy += 1
return doy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_metric(name, count, elapsed):
"""A metric function that prints to standard output :arg str name: name of the metric :arg int count: number of items :ar... |
_do_print(name, count, elapsed, file=sys.stdout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stderr_metric(name, count, elapsed):
"""A metric function that prints to standard error :arg str name: name of the metric :arg int count: number of items :ar... |
_do_print(name, count, elapsed, file=sys.stderr) |
<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_multi_metric(*metrics):
"""Make a new metric function that calls the supplied metrics :arg functions metrics: metric functions :rtype: function """ |
def multi_metric(name, count, elapsed):
"""Calls multiple metrics (closure)"""
for m in metrics:
m(name, count, elapsed)
return multi_metric |
<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_orphan(scc, graph):
""" Return False iff the given scc is reachable from elsewhere. """ |
return all(p in scc for v in scc for p in graph.parents(v)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def key_cycles():
""" Collect cyclic garbage, and return the strongly connected components that were keeping the garbage alive. """ |
graph = garbage()
sccs = graph.strongly_connected_components()
return [scc for scc in sccs if _is_orphan(scc, graph)] |
<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_command(self, command, **kwargs):
"""Wrapper to pass command to plowshare. :param command: The command to pass to plowshare. :type command: str :param *... |
try:
return {'output': subprocess.check_output(command, **kwargs)}
except Exception as e:
return {'error': str(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 _filter_sources(self, sources):
"""Remove sources with errors and return ordered by host success. :param sources: List of potential sources to connect to. :t... |
filtered, hosts = [], []
for source in sources:
if 'error' in source:
continue
filtered.append(source)
hosts.append(source['host_name'])
return sorted(filtered, key=lambda s:
self._hosts_by_success(hosts).index(s['host_n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(self, filename, number_of_hosts):
"""Upload the given file to the specified number of hosts. :param filename: The filename of the file to upload. :typ... |
return self.multiupload(filename, self.random_hosts(number_of_hosts)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, sources, output_directory, filename):
"""Download a file from one of the provided sources The sources will be ordered by least amount of error... |
valid_sources = self._filter_sources(sources)
if not valid_sources:
return {'error': 'no valid sources'}
manager = Manager()
successful_downloads = manager.list([])
def f(source):
if not successful_downloads:
result = self.download_from_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_from_host(self, source, output_directory, filename):
"""Download a file from a given host. This method renames the file to the given string. :param ... |
result = self._run_command(
["plowdown", source["url"], "-o",
output_directory, "--temp-rename"],
stderr=open("/dev/null", "w")
)
result['host_name'] = source['host_name']
if 'error' in result:
return result
temporary_filena... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multiupload(self, filename, hosts):
"""Upload file to multiple hosts simultaneously The upload will be attempted for each host until the optimal file redunda... |
manager = Manager()
successful_uploads = manager.list([])
def f(host):
if len(successful_uploads) / float(len(hosts)) < \
settings.MIN_FILE_REDUNDANCY:
# Optimal redundancy not achieved, keep going
result = self.upload_to_host(fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_to_host(self, filename, hostname):
"""Upload a file to the given host. This method relies on 'plowup' being installed on the system. If it succeeds, t... |
result = self._run_command(
["plowup", hostname, filename],
stderr=open("/dev/null", "w")
)
result['host_name'] = hostname
if 'error' not in result:
result['url'] = self.parse_output(hostname, result.pop('output'))
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 parse_output(self, hostname, output):
"""Parse plowup's output. For now, we just return the last line. :param hostname: Name of host you are working with. :t... |
if isinstance(output, bytes):
output = output.decode('utf-8')
return output.split()[-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 _generate_queues(queues, exchange, platform_queue):
""" Queues known by this worker """ |
return set([
Queue('celery', exchange, routing_key='celery'),
Queue(platform_queue, exchange, routing_key='#'),
] + [
Queue(q_name, exchange, routing_key=q_name)
for q_name in queues
]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _erf(x):
""" Port of cephes ``ndtr.c`` ``erf`` function. See https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtr.c """ |
T = [
9.60497373987051638749E0,
9.00260197203842689217E1,
2.23200534594684319226E3,
7.00332514112805075473E3,
5.55923013010394962768E4,
]
U = [
3.35617141647503099647E1,
5.21357949780152679795E2,
4.59432382970980127987E3,
2.2629000061... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _erfc(a):
""" Port of cephes ``ndtr.c`` ``erfc`` function. See https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtr.c """ |
# approximation for abs(a) < 8 and abs(a) >= 1
P = [
2.46196981473530512524E-10,
5.64189564831068821977E-1,
7.46321056442269912687E0,
4.86371970985681366614E1,
1.96520832956077098242E2,
5.26445194995477358631E2,
9.34528527171957607540E2,
1.0275518... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def erfinv(z):
""" Calculate the inverse error function at point ``z``. This is a direct port of the SciPy ``erfinv`` function, originally written in C. Paramete... |
if abs(z) > 1:
raise ValueError("`z` must be between -1 and 1 inclusive")
# Shortcut special cases
if z == 0:
return 0
if z == 1:
return inf
if z == -1:
return -inf
# otherwise calculate things.
return _ndtri((z + 1) / 2.0) / math.sqrt(2) |
<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_cmap(name, lut=None):
""" Returns the specified colormap. Parameters name: str or :class:`matplotlib.colors.Colormap` If a colormap, it returned unchange... |
if name in rcParams['colors.cmaps']:
colors = rcParams['colors.cmaps'][name]
lut = lut or len(colors)
return FixedColorMap.from_list(name=name, colors=colors, N=lut)
elif name in _cmapnames:
colors = _cmapnames[name]
lut = lut or len(colors)
return FixedColorMap.... |
<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_cmaps(names):
"""Filter the given `names` for colormaps""" |
import matplotlib.pyplot as plt
available_cmaps = list(
chain(plt.cm.cmap_d, _cmapnames, rcParams['colors.cmaps']))
names = list(names)
wrongs = []
for arg in (arg for arg in names if (not isinstance(arg, Colormap) and
arg not in available_cmaps)):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_colormaps(names=[], N=10, show=True, use_qt=None):
"""Function to show standard colormaps from pyplot Parameters ``*args``: str or :class:`matplotlib.co... |
names = safe_list(names)
if use_qt or (use_qt is None and psyplot.with_gui):
from psy_simple.widgets.colors import ColormapDialog
from psyplot_gui.main import mainwindow
return ColormapDialog.show_colormap(names, N, show, parent=mainwindow)
import matplotlib.pyplot as plt
# This... |
<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_stdout_logger(logging_level):
""" create a logger to stdout. This creates logger for a series of module we would like to log information on. """ |
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setFormatter(logging.Formatter(
'[%(asctime)s] %(message)s', "%H:%M:%S"
))
out_hdlr.setLevel(logging_level)
for name in LOGGING_NAMES:
log = logging.getLogger(name)
log.addHandler(out_hdlr)
log.setLevel(logging_le... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Generate a PDF using the async method.""" |
docraptor = DocRaptor()
print("Create PDF")
resp = docraptor.create(
{
"document_content": "<h1>python-docraptor</h1><p>Async Test</p>",
"test": True,
"async": True,
}
)
print("Status ID: {status_id}".format(status_id=resp["status_id"]))
sta... |
<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_alternate_types_resolving_forwardref_union_and_typevar(typ, _memo: List[Any] = None) \ """ Returns a tuple of all alternate types allowed by the `typ` typ... |
# avoid infinite recursion by using a _memo
_memo = _memo or []
if typ in _memo:
return tuple()
# remember that this was already explored
_memo.append(typ)
if is_typevar(typ):
if hasattr(typ, '__bound__') and typ.__bound__ is not None:
# TypeVar is 'bound' to a clas... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def robust_isinstance(inst, typ) -> bool: """ Similar to isinstance, but if 'typ' is a parametrized generic Type, it is first transformed into its base generic cl... |
if typ is Any:
return True
if is_typevar(typ):
if hasattr(typ, '__constraints__') and typ.__constraints__ is not None:
typs = get_args(typ, evaluate=True)
return any(robust_isinstance(inst, t) for t in typs)
elif hasattr(typ, '__bound__') and typ.__bound__ is not... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eval_forward_ref(typ: _ForwardRef):
""" Climbs the current stack until the given Forward reference has been resolved, or raises an InvalidForwardRefError :pa... |
for frame in stack():
m = getmodule(frame[0])
m_name = m.__name__ if m is not None else '<unknown>'
if m_name.startswith('parsyfiles.tests') or not m_name.startswith('parsyfiles'):
try:
# print("File {}:{}".format(frame.filename, frame.lineno))
re... |
<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_valid_pep484_type_hint(typ_hint, allow_forward_refs: bool = False):
""" Returns True if the provided type is a valid PEP484 type hint, False otherwise. No... |
# most common case first, to be faster
try:
if isinstance(typ_hint, type):
return True
except:
pass
# optionally, check forward reference
try:
if allow_forward_refs and is_forward_ref(typ_hint):
return True
except:
pass
# finally che... |
<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_pep484_nonable(typ):
""" Checks if a given type is nonable, meaning that it explicitly or implicitly declares a Union with NoneType. Nested TypeVars and U... |
# TODO rely on typing_inspect if there is an answer to https://github.com/ilevkivskyi/typing_inspect/issues/14
if typ is type(None):
return True
elif is_typevar(typ) or is_union_type(typ):
return any(is_pep484_nonable(tt) for tt in get_alternate_types_resolving_forwardref_union_and_typevar(... |
<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_for_collection_items(item_type, hint):
""" Helper method for collection items :param item_type: :return: """ |
# this leads to infinite loops
# try:
# prt_type = get_pretty_type_str(item_type)
# except:
# prt_type = str(item_type)
return TypeInformationRequiredError("Cannot parse object of type {t} as a collection: this type has no valid "
... |
<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_for_object_attributes(item_type, faulty_attribute_name: str, hint):
""" Helper method for constructor attributes :param item_type: :return: """ |
# this leads to infinite loops
# try:
# prt_type = get_pretty_type_str(item_type)
# except:
# prt_type = str(item_type)
return TypeInformationRequiredError("Cannot create instances of type {t}: constructor attribute '{a}' has an"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exception_class(self, exception):
"""Return a name representing the class of an exception.""" |
cls = type(exception)
if cls.__module__ == 'exceptions': # Built-in exception.
return cls.__name__
return "%s.%s" % (cls.__module__, cls.__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 request_info(self, request):
""" Return a dictionary of information for a given request. This will be run once for every request. """ |
# We have to re-resolve the request path here, because the information
# is not stored on the request.
view, args, kwargs = resolve(request.path)
for i, arg in enumerate(args):
kwargs[i] = arg
parameters = {}
parameters.update(kwargs)
parameters.update(request.POST.items())
environ = request.META... |
<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(self, hdf5, model, positives, negatives):
"""Saves the given intermediate state of the bootstrapping to file.""" |
# write the model and the training set indices to the given HDF5 file
hdf5.set("PositiveIndices", sorted(list(positives)))
hdf5.set("NegativeIndices", sorted(list(negatives)))
hdf5.create_group("Model")
hdf5.cd("Model")
model.save(hdf5)
del hdf5 |
<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(self, hdf5):
"""Loads the intermediate state of the bootstrapping from file.""" |
positives = set(hdf5.get("PositiveIndices"))
negatives = set(hdf5.get("NegativeIndices"))
hdf5.cd("Model")
model = bob.learn.boosting.BoostedMachine(hdf5)
return model, positives, negatives |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def undelay(self):
'''resolves all delayed arguments'''
i = 0
while i < len(self):
op = self[i]
i += 1
if hasattr(op, 'arg1'):
if isinstance(op.arg1,DelayedArg):
op.arg1 = op.arg1.resolve()
if isinst... |
<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_directorship_heads(self, val):
"""Get the head of a directorship Arguments: val -- the cn of the directorship """ |
__ldap_group_ou__ = "cn=groups,cn=accounts,dc=csh,dc=rit,dc=edu"
res = self.__con__.search_s(
__ldap_group_ou__,
ldap.SCOPE_SUBTREE,
"(cn=eboard-%s)" % val,
['member'])
ret = []
for member in res[0][1]['member']:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enqueue_mod(self, dn, mod):
"""Enqueue a LDAP modification. Arguments: dn -- the distinguished name of the object to modify mod -- an ldap modfication entry ... |
# mark for update
if dn not in self.__pending_mod_dn__:
self.__pending_mod_dn__.append(dn)
self.__mod_queue__[dn] = []
self.__mod_queue__[dn].append(mod) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flush_mod(self):
"""Flush all pending LDAP modifications.""" |
for dn in self.__pending_mod_dn__:
try:
if self.__ro__:
for mod in self.__mod_queue__[dn]:
if mod[0] == ldap.MOD_DELETE:
mod_str = "DELETE"
elif mod[0] == ldap.MOD_ADD:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_encoding(value):
"""Returns the character encoding for a JSON string.""" |
# https://tools.ietf.org/html/rfc4627#section-3
if six.PY2:
null_pattern = tuple(bool(ord(char)) for char in value[:4])
else:
null_pattern = tuple(bool(char) for char in value[:4])
encodings = {
# Zero is a null-byte, 1 is anything else.
(0, 0, 0, 1): 'utf-32-be',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _merge_params(url, params):
"""Merge and encode query parameters with an URL.""" |
if isinstance(params, dict):
params = list(params.items())
scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
url_params = urllib.parse.parse_qsl(query, keep_blank_values=True)
url_params.extend(params)
query = _encode_data(url_params)
return urllib.parse.urlunsplit((... |
<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(self, **kwargs):
"""Decodes response as JSON.""" |
encoding = detect_encoding(self.content[:4])
value = self.content.decode(encoding)
return simplejson.loads(value, **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 raise_for_status(self):
"""Raises HTTPError if the request got an error.""" |
if 400 <= self.status_code < 600:
message = 'Error %s for %s' % (self.status_code, self.url)
raise HTTPError(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metric(cls, name, count, elapsed):
"""A metric function that buffers through numpy :arg str name: name of the metric :arg int count: number of items :arg flo... |
if name is None:
warnings.warn("Ignoring unnamed metric", stacklevel=3)
return
with cls.lock:
# register with atexit on first call
if cls.dump_atexit and not cls.instances:
atexit.register(cls.dump)
try:
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 _dump(self):
"""dump data for an individual metric. For internal use only.""" |
try:
self.temp.seek(0) # seek to beginning
arr = np.fromfile(self.temp, self.dtype)
self.count_arr = arr['count']
self.elapsed_arr = arr['elapsed']
if self.calc_stats:
# calculate mean & standard deviation
self.count_... |
<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(self, host_rec=None, service_rec=None, hostfilter=None):
""" Returns a list of vulnerabilities based on t_hosts.id or t_services.id. If neither are set ... |
return self.send.vuln_list(host_rec, service_rec, hostfilter) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ip_info(self, vuln_name=None, vuln_id=None, ip_list_only=True, hostfilter=None):
""" List of all IP Addresses with a vulnerability :param vuln_name: t_vulnda... |
return self.send.vuln_ip_info(vuln_name, vuln_id, ip_list_only, hostfilter) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def service_list(self, vuln_name=None, vuln_id=None, hostfilter=None):
""" Returns a dictionary of vulns with services and IP Addresses :param vuln_name: t_vulnd... |
return self.send.vuln_service_list(vuln_name, vuln_id, hostfilter) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_name(mod_name):
"""Import a module by module name. @param mod_name: module name. """ |
try:
mod_obj_old = sys.modules[mod_name]
except KeyError:
mod_obj_old = None
if mod_obj_old is not None:
return mod_obj_old
__import__(mod_name)
mod_obj = sys.modules[mod_name]
return mod_obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_path(mod_path, mod_name):
"""Import a module by module file path. @param mod_path: module file path. @param mod_name: module name. """ |
mod_code = open(mod_path).read()
mod_obj = import_code(
mod_code=mod_code,
mod_name=mod_name,
)
if not hasattr(mod_obj, '__file__'):
mod_obj.__file__ = mod_path
return mod_obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_obj( uri, mod_name=None, mod_attr_sep='::', attr_chain_sep='.', retn_mod=False, ):
"""Load an object from a module. @param uri: an uri specifying whic... |
if mod_attr_sep is None:
mod_attr_sep = '::'
uri_parts = split_uri(uri=uri, mod_attr_sep=mod_attr_sep)
protocol, mod_uri, attr_chain = uri_parts
if protocol == 'py':
mod_obj = import_name(mod_uri)
else:
if not mod_name:
msg = (
'Argument `mod_... |
<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_sys_modules(mod_name, mod_obj=None):
"""Add a module object to `sys.modules`. @param mod_name: module name, used as key to `sys.modules`. If `mod_name... |
mod_snames = mod_name.split('.')
parent_mod_name = ''
parent_mod_obj = None
for mod_sname in mod_snames:
if parent_mod_name == '':
current_mod_name = mod_sname
else:
current_mod_name = parent_mod_name + '.' + mod_sname
if current_mod_name == mod_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_host(environ):
"""Return the real host for the given WSGI environment. This takes care of the `X-Forwarded-Host` header. :param environ: the WSGI environ... |
scheme = environ.get('wsgi.url_scheme')
if 'HTTP_X_FORWARDED_HOST' in environ:
result = environ['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in environ:
result = environ['HTTP_HOST']
else:
result = environ['SERVER_NAME']
if (scheme, str(environ['SERVER_PORT'])) not \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _raw(cls, vertices, edges, out_edges, in_edges, head, tail):
""" Private constructor for direct construction of an ObjectGraph from its attributes. vertices ... |
self = object.__new__(cls)
self._out_edges = out_edges
self._in_edges = in_edges
self._head = head
self._tail = tail
self._vertices = vertices
self._edges = edges
return 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 annotated(self):
""" Annotate this graph, returning an AnnotatedGraph object with the same structure. """ |
# Build up dictionary of edge annotations.
edge_annotations = {}
for edge in self.edges:
if edge not in edge_annotations:
# We annotate all edges from a given object at once.
referrer = self._tail[edge]
known_refs = annotated_reference... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def owned_objects(self):
""" List of gc-tracked objects owned by this ObjectGraph instance. """ |
return (
[
self,
self.__dict__,
self._head,
self._tail,
self._out_edges,
self._out_edges._keys,
self._out_edges._values,
self._in_edges,
self._in_edges._ke... |
<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_by_typename(self, typename):
""" List of all objects whose type has the given name. """ |
return self.find_by(lambda obj: type(obj).__name__ == typename) |
<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_unset_inputs(self):
""" Return a set of unset inputs """ |
return set([k for k, v in self._inputs.items() if v.is_empty(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 prompt_unset_inputs(self, force=False):
""" Prompt for unset input values """ |
for k, v in self._inputs.items():
if force or v.is_empty(False):
self.get_input(k, force=force) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def values(self, with_defaults=True):
""" Return the values dictionary, defaulting to default values """ |
return dict(((k, str(v)) for k, v in self._inputs.items() if not v.is_empty(with_defaults))) |
<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_values(self):
""" Return the dictionary with which to write values """ |
return dict(((k, v.value) for k, v in self._inputs.items() if not v.is_secret and not v.is_empty(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_param_line(self, line):
""" Parse a single param line. """ |
value = line.strip('\n \t')
if len(value) > 0:
i = Input()
if value.find('#') != -1:
value, extra_attributes = value.split('#')
try:
extra_attributes = eval(extra_attributes)
except SyntaxError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, overwrite=True):
""" Download the zipcodes CSV file. If ``overwrite`` is set to False, the file won't be downloaded if it already exists. """ |
if overwrite or not os.path.exists(self.file_path):
_, f = tempfile.mkstemp()
try:
urlretrieve(self.DOWNLOAD_URL, f)
extract_csv(f, self.file_path)
finally:
os.remove(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_zipcodes_for_canton(self, canton):
""" Return the list of zipcodes for the given canton code. """ |
zipcodes = [
zipcode for zipcode, location in self.get_locations().items()
if location.canton == canton
]
return zipcodes |
<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_cantons(self):
""" Return the list of unique cantons, sorted by name. """ |
return sorted(list(set([
location.canton for location in self.get_locations().values()
]))) |
<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_municipalities(self):
""" Return the list of unique municipalities, sorted by name. """ |
return sorted(list(set([
location.municipality for location in self.get_locations().values()
]))) |
<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_formula_class(self, formula):
""" get a formula class object if it exists, else create one, add it to the dict, and pass return it. """ |
# recursive import otherwise
from sprinter.formula.base import FormulaBase
if formula in LEGACY_MAPPINGS:
formula = LEGACY_MAPPINGS[formula]
formula_class, formula_url = formula, None
if ':' in formula:
formula_class, formula_url = formula.split(":", 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 is_backup_class(cls):
"""Return true if given class supports back up. Currently this means a gludb.data.Storable-derived class that has a mapping as defined ... |
return True if (
isclass(cls) and
issubclass(cls, Storable) and
get_mapping(cls, no_mapping_ok=True)
) else 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 process( hw_num: int, problems_to_do: Optional[Iterable[int]] = None, prefix: Optional[Path] = None, by_hand: Optional[Iterable[int]] = None, ) -> None: """Pr... |
if prefix is None:
prefix = Path(".")
problems: Iterable[Path]
if problems_to_do is None:
# The glob syntax here means a the filename must start with
# homework-, be followed the homework number, followed by a
# dash, then a digit representing the problem number for this
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(argv: Optional[Sequence[str]] = None) -> None: """Parse arguments and process the homework assignment.""" |
parser = ArgumentParser(description="Convert Jupyter Notebook assignments to PDFs")
parser.add_argument(
"--hw",
type=int,
required=True,
help="Homework number to convert",
dest="hw_num",
)
parser.add_argument(
"-p",
"--problems",
type=int... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_vm_by_name(content, name, regex=False):
'''
Get a VM by its name
'''
return get_object_by_name(content, vim.VirtualMachine, name, regex) |
<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_datacenter(content, obj):
'''
Get the datacenter to whom an object belongs
'''
datacenters = content.rootFolder.childEntity
for d in datacenters:
dch = get_all(content, d, type(obj))
if dch is not None and obj in dch:
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_all_vswitches(content):
'''
Get all the virtual switches
'''
vswitches = []
hosts = get_all_hosts(content)
for h in hosts:
for s in h.config.network.vswitch:
vswitches.append(s)
return vswitches |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def print_vm_info(vm):
'''
Print information for a particular virtual machine
'''
summary = vm.summary
print('Name : ', summary.config.name)
print('Path : ', summary.config.vmPathName)
print('Guest : ', summary.config.guestFullName)
annotation = summary.config.annotation
if annotat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def module_import(module_path):
"""Imports the module indicated in name Args: module_path: string representing a module path such as 'app.config' or 'app.extras.... |
try:
# Import whole module path.
module = __import__(module_path)
# Split into components: ['contour',
# 'extras','appengine','ndb_persistence'].
components = module_path.split('.')
# Starting at the second component, set module to a
# a reference to that 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 find_contour_yaml(config_file=__file__, names=None):
""" Traverse directory trees to find a contour.yaml file Begins with the location of this file then chec... |
checked = set()
contour_yaml = _find_countour_yaml(os.path.dirname(config_file), checked,
names=names)
if not contour_yaml:
contour_yaml = _find_countour_yaml(os.getcwd(), checked, names=names)
return contour_yaml |
<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_countour_yaml(start, checked, names=None):
"""Traverse the directory tree identified by start until a directory already in checked is encountered or th... |
extensions = []
if names:
for name in names:
if not os.path.splitext(name)[1]:
extensions.append(name + ".yaml")
extensions.append(name + ".yml")
yaml_names = (names or []) + CONTOUR_YAML_NAMES + extensions
directory = start
while directory not... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _guess_type_from_validator(validator):
""" Utility method to return the declared type of an attribute or None. It handles _OptionalValidator and _AndValidato... |
if isinstance(validator, _OptionalValidator):
# Optional : look inside
return _guess_type_from_validator(validator.validator)
elif isinstance(validator, _AndValidator):
# Sequence : try each of them
for v in validator.validators:
typ = _guess_type_from_validator(v)
... |
<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_optional(attr):
""" Helper method to find if an attribute is mandatory :param attr: :return: """ |
return isinstance(attr.validator, _OptionalValidator) or (attr.default is not None and attr.default is not NOTHING) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preprocess( self, nb: "NotebookNode", resources: dict ) -> Tuple["NotebookNode", dict]: """Remove any raw cells from the Notebook. By default, exclude raw cel... |
if not resources.get("global_content_filter", {}).get("include_raw", False):
keep_cells = []
for cell in nb.cells:
if cell.cell_type != "raw":
keep_cells.append(cell)
nb.cells = keep_cells
return nb, resources |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preprocess( self, nb: "NotebookNode", resources: dict ) -> Tuple["NotebookNode", dict]: """Preprocess the entire notebook.""" |
if "remove_solution" not in resources:
raise KeyError("The resources dictionary must have a remove_solution key.")
if resources["remove_solution"]:
keep_cells_idx = []
for index, cell in enumerate(nb.cells):
if "## solution" in cell.source.lower():
... |
<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_from_dict(json_dict):
""" Given a Unified Uploader message, parse the contents and return a MarketOrderList. :param dict json_dict: A Unified Uploader ... |
order_columns = json_dict['columns']
order_list = MarketOrderList(
upload_keys=json_dict['uploadKeys'],
order_generator=json_dict['generator'],
)
for rowset in json_dict['rowsets']:
generated_at = parse_datetime(rowset['generatedAt'])
region_id = rowset['regionID']
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_to_json(order_list):
""" Encodes this list of MarketOrder instances to a JSON string. :param MarketOrderList order_list: The order list to serialize. ... |
rowsets = []
for items_in_region_list in order_list._orders.values():
region_id = items_in_region_list.region_id
type_id = items_in_region_list.type_id
generated_at = gen_iso_datetime_str(items_in_region_list.generated_at)
rows = []
for order in items_in_region_list.ord... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(f):
"""Extract a `MqttFixedHeader` from ``f``. Parameters f: file Object with read method. Raises ------- DecodeError When bytes decoded have values i... |
decoder = mqtt_io.FileDecoder(f)
(byte_0,) = decoder.unpack(mqtt_io.FIELD_U8)
packet_type_u4 = (byte_0 >> 4)
flags = byte_0 & 0x0f
try:
packet_type = MqttControlPacketType(packet_type_u4)
except ValueError:
raise DecodeError('Unknown packet 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 decode_body(cls, header, f):
"""Generates a `MqttSubscribe` packet given a `MqttFixedHeader`. This method asserts that header.packet_type is `subscribe`. Par... |
assert header.packet_type == MqttControlPacketType.subscribe
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
topics = []
while header.remaining_len > decoder.num_bytes_consumed:
num_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 decode_body(cls, header, f):
"""Generates a `MqttSuback` packet given a `MqttFixedHeader`. This method asserts that header.packet_type is `suback`. Parameter... |
assert header.packet_type == MqttControlPacketType.suback
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
results = []
while header.remaining_len > decoder.num_bytes_consumed:
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 decode_body(cls, header, f):
"""Generates a `MqttPublish` packet given a `MqttFixedHeader`. This method asserts that header.packet_type is `publish`. Paramet... |
assert header.packet_type == MqttControlPacketType.publish
dupe = bool(header.flags & 0x08)
retain = bool(header.flags & 0x01)
qos = ((header.flags & 0x06) >> 1)
if qos == 0 and dupe:
# The DUP flag MUST be set to 0 for all QoS 0 messages
# [MQTT-3.3.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 decode_body(cls, header, f):
"""Generates a `MqttPubrel` packet given a `MqttFixedHeader`. This method asserts that header.packet_type is `pubrel`. Parameter... |
assert header.packet_type == MqttControlPacketType.pubrel
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_U16)
if header.remaining_len != decoder.num_bytes_consumed:
raise DecodeError('Extra bytes at end... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_body(cls, header, f):
"""Generates a `MqttUnsubscribe` packet given a `MqttFixedHeader`. This method asserts that header.packet_type is `unsubscribe`.... |
assert header.packet_type == MqttControlPacketType.unsubscribe
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
topics = []
while header.remaining_len > decoder.num_bytes_consumed:
num_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_body(cls, header, f):
"""Generates a `MqttUnsuback` packet given a `MqttFixedHeader`. This method asserts that header.packet_type is `unsuback`. Param... |
assert header.packet_type == MqttControlPacketType.unsuback
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
if header.remaining_len != decoder.num_bytes_consumed:
raise DecodeError('Extra byte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_body(cls, header, f):
"""Generates a `MqttPingreq` packet given a `MqttFixedHeader`. This method asserts that header.packet_type is `pingreq`. Paramet... |
assert header.packet_type == MqttControlPacketType.pingreq
if header.remaining_len != 0:
raise DecodeError('Extra bytes at end of packet.')
return 0, MqttPingreq() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_body(cls, header, f):
"""Generates a `MqttPingresp` packet given a `MqttFixedHeader`. This method asserts that header.packet_type is `pingresp`. Param... |
assert header.packet_type == MqttControlPacketType.pingresp
if header.remaining_len != 0:
raise DecodeError('Extra bytes at end of packet.')
return 0, MqttPingresp() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
""" Sets up your Phabricator session, it's not necessary to call this directly """ |
if self.token:
self.phab_session = {'token': self.token}
return
req = self.req_session.post('%s/api/conduit.connect' % self.host, data={
'params': json.dumps(self.connect_params),
'output': 'json',
'__conduit__': True,
})
# 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 install(force=False):
"""Install git hooks.""" |
ret, git_dir, _ = run("git rev-parse --show-toplevel")
if ret != 0:
click.echo(
"ERROR: Please run from within a GIT repository.",
file=sys.stderr)
raise click.Abort
git_dir = git_dir[0]
hooks_dir = os.path.join(git_dir, HOOK_PATH)
for hook in HOOKS:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uninstall():
"""Uninstall git hooks.""" |
ret, git_dir, _ = run("git rev-parse --show-toplevel")
if ret != 0:
click.echo(
"ERROR: Please run from within a GIT repository.",
file=sys.stderr)
raise click.Abort
git_dir = git_dir[0]
hooks_dir = os.path.join(git_dir, HOOK_PATH)
for hook in HOOKS:
... |
<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_logger():
""" setup basic logger """ |
logger = logging.getLogger('dockerstache')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
return logger |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def named_any(name):
""" Retrieve a Python object by its fully qualified name from the global Python module namespace. The first part of the name, that describes... |
assert name, 'Empty module name'
names = name.split('.')
topLevelPackage = None
moduleNames = names[:]
while not topLevelPackage:
if moduleNames:
trialname = '.'.join(moduleNames)
try:
topLevelPackage = __import__(trialname)
except Except... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def for_name(modpath, classname):
'''
Returns a class of "classname" from module "modname".
'''
module = __import__(modpath, fromlist=[classname])
classobj = getattr(module, classname)
return classobj() |
<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(self, val):
""" Convert the type if necessary and return if a conversion happened. """ |
if isinstance(val, dict) and not isinstance(val, DotDict):
return DotDict(val), True
elif isinstance(val, list) and not isinstance(val, DotList):
return DotList(val), True
return val, 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 to_json(self):
""" Convert to a JSON string. """ |
obj = {
"vertices": [
{
"id": vertex.id,
"annotation": vertex.annotation,
}
for vertex in self.vertices
],
"edges": [
{
"id": edge.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 from_json(cls, json_graph):
""" Reconstruct the graph from a graph exported to JSON. """ |
obj = json.loads(json_graph)
vertices = [
AnnotatedVertex(
id=vertex["id"],
annotation=vertex["annotation"],
)
for vertex in obj["vertices"]
]
edges = [
AnnotatedEdge(
id=edge["id"],
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.