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 list_deployments(self):
"""List all running deployments. :returns: list of deployments :rtype: list[:class:`marathon.models.deployment.MarathonDeployment`] "... |
response = self._do_request('GET', '/v2/deployments')
return self._parse_response(response, MarathonDeployment, is_list=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 list_queue(self, embed_last_unused_offers=False):
"""List all the tasks queued up or waiting to be scheduled. :returns: list of queue items :rtype: list[:cla... |
if embed_last_unused_offers:
params = {'embed': 'lastUnusedOffers'}
else:
params = {}
response = self._do_request('GET', '/v2/queue', params=params)
return self._parse_response(response, MarathonQueueItem, is_list=True, resource_name='queue') |
<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_deployment(self, deployment_id, force=False):
"""Cancel a deployment. :param str deployment_id: deployment id :param bool force: if true, don't create... |
if force:
params = {'force': True}
self._do_request('DELETE', '/v2/deployments/{deployment}'.format(
deployment=deployment_id), params=params)
# Successful DELETE with ?force=true returns empty text (and status
# code 202). Client code should poll... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assert_valid_path(path):
"""Checks if a path is a correct format that Marathon expects. Raises ValueError if not valid. :param str path: The app id. :rtype: ... |
if path is None:
return
# As seen in:
# https://github.com/mesosphere/marathon/blob/0c11661ca2f259f8a903d114ef79023649a6f04b/src/main/scala/mesosphere/marathon/state/PathId.scala#L71
for id in filter(None, path.strip('/').split('/')):
if not ID_PATTERN.match(id):
raise 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 assert_valid_id(id):
"""Checks if an id is the correct format that Marathon expects. Raises ValueError if not valid. :param str id: App or group id. :rtype: ... |
if id is None:
return
if not ID_PATTERN.match(id.strip('/')):
raise ValueError(
'invalid id (allowed: lowercase letters, digits, hyphen, ".", ".."): %r' % id)
return 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, attributes):
"""Construct an object from a parsed response. :param dict attributes: object attributes from parsed response """ |
return cls(**{to_snake_case(k): v for k, v in attributes.items()}) |
<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, minimal=True):
"""Encode an object as a JSON string. :param bool minimal: Construct a minimal representation of the object (ignore nulls and em... |
if minimal:
return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True)
else:
return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=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 from_json(cls, obj):
"""Construct a MarathonConstraint from a parsed response. :param dict attributes: object attributes from parsed response :rtype: :class:... |
if len(obj) == 2:
(field, operator) = obj
return cls(field, operator)
if len(obj) > 2:
(field, operator, value) = obj
return cls(field, operator, 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 from_tasks(cls, tasks):
"""Construct a list of MarathonEndpoints from a list of tasks. :param list[:class:`marathon.models.MarathonTask`] tasks: list of task... |
endpoints = [
[
MarathonEndpoint(task.app_id, task.service_ports[
port_index], task.host, task.id, port)
for port_index, port in enumerate(task.ports)
]
for task in tasks
]
# Flatten 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 _format_newlines(prefix, formatted_node, options):
""" Convert newlines into U+23EC characters, followed by an actual newline and then a tree prefix so as to... |
replacement = u''.join([
options.NEWLINE,
u'\n',
prefix])
return formatted_node.replace(u'\n', replacement) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def get_player(self, tag):
"""Gets a player. Gets a player with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a braw... |
tag = tag.strip("#")
tag = tag.upper()
try:
async with self.session.get(self._base_url + 'players/' + tag, timeout=self.timeout,
headers=self.headers) as resp:
if resp.status == 200:
data = await resp.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 lazy_module(modname, error_strings=None, lazy_mod_class=LazyModule, level='leaf'):
"""Function allowing lazy importing of a module into the namespace. A lazy... |
if error_strings is None:
error_strings = {}
_set_default_errornames(modname, error_strings)
mod = _lazy_module(modname, error_strings, lazy_mod_class)
if level == 'base':
return sys.modules[module_basename(modname)]
elif level == 'leaf':
return mod
else:
raise ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lazy_callable(modname, *names, **kwargs):
"""Performs lazy importing of one or more callables. :func:`lazy_callable` creates functions that are thin wrappers... |
if not names:
modname, _, name = modname.rpartition(".")
lazy_mod_class = _setdef(kwargs, 'lazy_mod_class', LazyModule)
lazy_call_class = _setdef(kwargs, 'lazy_call_class', LazyCallable)
error_strings = _setdef(kwargs, 'error_strings', {})
_set_default_errornames(modname, error_strings, cal... |
<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_module(module):
"""Ensures that a module, and its parents, are properly loaded """ |
modclass = type(module)
# We only take care of our own LazyModule instances
if not issubclass(modclass, LazyModule):
raise TypeError("Passed module is not a LazyModule instance.")
with _ImportLockContext():
parent, _, modname = module.__name__.rpartition('.')
logger.debug("loadi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setdef(argdict, name, defaultvalue):
"""Like dict.setdefault but sets the default value also if None is present. """ |
if not name in argdict or argdict[name] is None:
argdict[name] = defaultvalue
return argdict[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 _clean_lazymodule(module):
"""Removes all lazy behavior from a module's class, for loading. Also removes all module attributes listed under the module's clas... |
modclass = type(module)
_clean_lazy_submod_refs(module)
modclass.__getattribute__ = ModuleType.__getattribute__
modclass.__setattr__ = ModuleType.__setattr__
cls_attrs = {}
for cls_attr in _CLS_ATTRS:
try:
cls_attrs[cls_attr] = getattr(modclass, cls_attr)
delatt... |
<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_lazymodule(module, cls_attrs):
"""Resets a module's lazy state from cached data. """ |
modclass = type(module)
del modclass.__getattribute__
del modclass.__setattr__
try:
del modclass._LOADING
except AttributeError:
pass
for cls_attr in _CLS_ATTRS:
try:
setattr(modclass, cls_attr, cls_attrs[cls_attr])
except KeyError:
pass
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timestamp_from_datetime(dt):
""" Compute timestamp from a datetime object that could be timezone aware or unaware. """ |
try:
utc_dt = dt.astimezone(pytz.utc)
except ValueError:
utc_dt = dt.replace(tzinfo=pytz.utc)
return timegm(utc_dt.timetuple()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
""" Similar to smart_bytes, except that lazy instances are resolved to strings, rather... |
if isinstance(s, memoryview):
s = bytes(s)
if isinstance(s, bytes):
if encoding == 'utf-8':
return s
else:
return s.decode('utf-8', errors).encode(encoding, errors)
if strings_only and (s is None or isinstance(s, int)):
return s
if not isinstance(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def memoize(func, cache, num_args):
""" Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be ... |
@wraps(func)
def wrapper(*args):
mem_args = args[:num_args]
if mem_args in cache:
return cache[mem_args]
result = func(*args)
cache[mem_args] = result
return result
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hide_auth(msg):
"""Remove sensitive information from msg.""" |
for pattern, repl in RE_HIDE_AUTH:
msg = pattern.sub(repl, msg)
return msg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Prepare the HTTP handler, URL, and HTTP headers for all subsequent requests""" |
self.debug('Initializing %r', self)
proto = self.server.split('://')[0]
if proto == 'https':
if hasattr(ssl, 'create_default_context'):
context = ssl.create_default_context()
if self.ssl_verify:
context.check_hostname = 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 get_age(dt):
"""Calculate delta between current time and datetime and return a human readable form of the delta object""" |
delta = datetime.now() - dt
days = delta.days
hours, rem = divmod(delta.seconds, 3600)
minutes, seconds = divmod(rem, 60)
if days:
return '%dd %dh %dm' % (days, hours, minutes)
else:
return '%dh %dm %ds' % (hours, minutes, seconds) |
<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_obj(self, method, params=None, auth=True):
"""Return JSON object expected by the Zabbix API""" |
if params is None:
params = {}
obj = {
'jsonrpc': '2.0',
'method': method,
'params': params,
'auth': self.__auth if auth else None,
'id': self.id,
}
return json.dumps(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 do_request(self, json_obj):
"""Perform one HTTP request to Zabbix API""" |
self.debug('Request: url="%s" headers=%s', self._api_url, self._http_headers)
self.debug('Request: body=%s', json_obj)
self.r_query.append(json_obj)
request = urllib2.Request(url=self._api_url, data=json_obj.encode('utf-8'), headers=self._http_headers)
opener = urllib2.build_op... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self, user=None, password=None, save=True):
"""Perform a user.login API request""" |
if user and password:
if save:
self.__username = user
self.__password = password
elif self.__username and self.__password:
user = self.__username
password = self.__password
else:
raise ZabbixAPIException('No authent... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relogin(self):
"""Perform a re-login""" |
try:
self.__auth = None # reset auth before relogin
self.login()
except ZabbixAPIException as e:
self.log(ERROR, 'Zabbix API relogin error (%s)', e)
self.__auth = None # logged_in() will always return False
raise |
<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_auth(self):
"""Perform a re-login if not signed in or raise an exception""" |
if not self.logged_in:
if self.relogin_interval and self.last_login and (time() - self.last_login) > self.relogin_interval:
self.log(WARNING, 'Zabbix API not logged in. Performing Zabbix API relogin after %d seconds',
self.relogin_interval)
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 call(self, method, params=None):
"""Check authentication and perform actual API request and relogin if needed""" |
start_time = time()
self.check_auth()
self.log(INFO, '[%s-%05d] Calling Zabbix API method "%s"', start_time, self.id, method)
self.log(DEBUG, '\twith parameters: %s', params)
try:
return self.do_request(self.json_obj(method, params=params))
except ZabbixAPIE... |
<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_parallel(url, directory, idx, min_file_size = 0, max_file_size = -1, no_redirects = False, pos = 0, mode = 's'):
""" download function to down... |
global main_it
global exit_flag
global total_chunks
global file_name
global i_max
file_name[idx]= url.split('/')[-1]
file_address = directory + '/' + file_name[idx]
is_redirects = not no_redirects
resp = s.get(url, stream = True, allow_redirects = is_redirects)
if not resp.status_code == 200:
# ignore t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_parallel_gui(root, urls, directory, min_file_size, max_file_size, no_redirects):
""" called when paralled downloading is true """ |
global parallel
# create directory to save files
if not os.path.exists(directory):
os.makedirs(directory)
parallel = True
app = progress_class(root, urls, directory, min_file_size, max_file_size, no_redirects) |
<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_series_gui(frame, urls, directory, min_file_size, max_file_size, no_redirects):
""" called when user wants serial downloading """ |
# create directory to save files
if not os.path.exists(directory):
os.makedirs(directory)
app = progress_class(frame, urls, directory, min_file_size, max_file_size, no_redirects) |
<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):
""" function called when thread is started """ |
global parallel
if parallel:
download_parallel(self.url, self.directory, self.idx,
self.min_file_size, self.max_file_size, self.no_redirects)
else:
download(self.url, self.directory, self.idx,
self.min_file_size, self.max_file_size, self.no_redirects) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
""" function to initialize thread for downloading """ |
global parallel
for self.i in range(0, self.length):
if parallel:
self.thread.append(myThread(self.url[ self.i ], self.directory, self.i,
self.min_file_size, self.max_file_size, self.no_redirects))
else:
# if not parallel whole url list is passed
self.thread.append(myThread(self.url, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_bytes(self):
""" reading bytes; update progress bar after 1 ms """ |
global exit_flag
for self.i in range(0, self.length) :
self.bytes[self.i] = i_max[self.i]
self.maxbytes[self.i] = total_chunks[self.i]
self.progress[self.i]["maximum"] = total_chunks[self.i]
self.progress[self.i]["value"] = self.bytes[self.i]
self.str[self.i].set(file_name[self.i]+ " " + str(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def declare_type(self, declared_type):
# type: (TypeDef) -> TypeDef """Add this type to our collection, if needed.""" |
if declared_type not in self.collected_types:
self.collected_types[declared_type.name] = declared_type
return declared_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 add_namespaces(metadata, namespaces):
# type: (Mapping[Text, Any], MutableMapping[Text, Text]) -> None """Collect the provided namespaces, checking for confl... |
for key, value in metadata.items():
if key not in namespaces:
namespaces[key] = value
elif namespaces[key] != value:
raise validate.ValidationException(
"Namespace prefix '{}' has conflicting definitions '{}'"
" and '{}'.".format(key, namespac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect_namespaces(metadata):
# type: (Mapping[Text, Any]) -> Dict[Text, Text] """Walk through the metadata object, collecting namespace declarations.""" |
namespaces = {} # type: Dict[Text, Text]
if "$import_metadata" in metadata:
for value in metadata["$import_metadata"].values():
add_namespaces(collect_namespaces(value), namespaces)
if "$namespaces" in metadata:
add_namespaces(metadata["$namespaces"], namespaces)
return nam... |
<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_schema(schema_ref, # type: Union[CommentedMap, CommentedSeq, Text] cache=None # type: Dict ):
""" Load a schema that can be used to validate documents u... |
metaschema_names, _metaschema_doc, metaschema_loader = get_metaschema()
if cache is not None:
metaschema_loader.cache.update(cache)
schema_doc, schema_metadata = metaschema_loader.resolve_ref(schema_ref, "")
if not isinstance(schema_doc, MutableSequence):
raise ValueError("Schema refe... |
<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_and_validate(document_loader, # type: Loader avsc_names, # type: Names document, # type: Union[CommentedMap, Text] strict, # type: bool strict_foreign_pr... |
try:
if isinstance(document, CommentedMap):
data, metadata = document_loader.resolve_all(
document, document["id"], checklinks=True,
strict_foreign_properties=strict_foreign_properties)
else:
data, metadata = document_loader.resolve_ref(
... |
<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_anon_name(rec):
# type: (MutableMapping[Text, Any]) -> Text """Calculate a reproducible name for anonymous types.""" |
if "name" in rec:
return rec["name"]
anon_name = ""
if rec['type'] in ('enum', 'https://w3id.org/cwl/salad#enum'):
for sym in rec["symbols"]:
anon_name += sym
return "enum_"+hashlib.sha1(anon_name.encode("UTF-8")).hexdigest()
if rec['type'] in ('record', 'https://w3i... |
<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_type(items, spec, loader, found, find_embeds=True, deepen=True):
# type: (Any, Dict[Text, Any], Loader, Set[Text], bool, bool) -> Any """ Go through ... |
if isinstance(items, MutableMapping):
# recursively check these fields for types to replace
if items.get("type") in ("record", "enum") and items.get("name"):
if items["name"] in found:
return items["name"]
found.add(items["name"])
if not deepen:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def avro_name(url):
# type: (AnyStr) -> AnyStr """ Turn a URL into an Avro-safe name. If the URL has no fragment, return this plain URL. Extract either the last ... |
frg = urllib.parse.urldefrag(url)[1]
if frg != '':
if '/' in frg:
return frg[frg.rindex('/') + 1:]
return frg
return url |
<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_valid_avro(items, # type: Avro alltypes, # type: Dict[Text, Dict[Text, Any]] found, # type: Set[Text] union=False # type: bool ):
"""Convert our schema ... |
# Possibly could be integrated into our fork of avro/schema.py?
if isinstance(items, MutableMapping):
items = copy.copy(items)
if items.get("name") and items.get("inVocab", True):
items["name"] = avro_name(items["name"])
if "type" in items and items["type"] in (
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deepcopy_strip(item):
# type: (Any) -> Any """ Make a deep copy of list and dict objects. Intentionally do not copy attributes. This is to discard CommentedM... |
if isinstance(item, MutableMapping):
return {k: deepcopy_strip(v) for k, v in iteritems(item)}
if isinstance(item, MutableSequence):
return [deepcopy_strip(k) for k in item]
return item |
<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_avro_schema(i, # type: List[Any] loader # type: Loader """ All in one convenience function. Call make_avro() and make_avro_schema_from_avro() separately ... |
names = Names()
avro = make_avro(i, loader)
make_avsc_object(convert_to_dict(avro), names)
return names |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shortname(inputid):
# type: (Text) -> Text """Returns the last segment of the provided fragment or path.""" |
parsed_id = urllib.parse.urlparse(inputid)
if parsed_id.fragment:
return parsed_id.fragment.split(u"/")[-1]
return parsed_id.path.split(u"/")[-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 print_inheritance(doc, stream):
# type: (List[Dict[Text, Any]], IO) -> None """Write a Grapviz inheritance graph for the supplied document.""" |
stream.write("digraph {\n")
for entry in doc:
if entry["type"] == "record":
label = name = shortname(entry["name"])
fields = entry.get("fields", [])
if fields:
label += "\\n* %s\\l" % (
"\\l* ".join(shortname(field["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 print_fieldrefs(doc, loader, stream):
# type: (List[Dict[Text, Any]], Loader, IO) -> None """Write a GraphViz graph of the relationships between the fields."... |
obj = extend_and_specialize(doc, loader)
primitives = set(("http://www.w3.org/2001/XMLSchema#string",
"http://www.w3.org/2001/XMLSchema#boolean",
"http://www.w3.org/2001/XMLSchema#int",
"http://www.w3.org/2001/XMLSchema#long",
... |
<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_other_props(all_props, reserved_props):
# type: (Dict, Tuple) -> Optional[Dict] """ Retrieve the non-reserved properties from a dictionary of properties ... |
if hasattr(all_props, 'items') and callable(all_props.items):
return dict([(k,v) for (k,v) in list(all_props.items()) if k not in
reserved_props])
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_avsc_object(json_data, names=None):
# type: (Union[Dict[Text, Text], List[Any], Text], Optional[Names]) -> Schema """ Build Avro Schema from data parsed... |
if names is None:
names = Names()
assert isinstance(names, Names)
# JSON object (non-union)
if hasattr(json_data, 'get') and callable(json_data.get): # type: ignore
assert isinstance(json_data, Dict)
atype = cast(Text, json_data.get('type'))
other_props = get_other_pro... |
<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_space(self):
# type: () -> Optional[Text] """Back out a namespace from full name.""" |
if self._full is None:
return None
if self._full.find('.') > 0:
return self._full.rsplit(".", 1)[0]
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 add_name(self, name_attr, space_attr, new_schema):
# type: (Text, Optional[Text], NamedSchema) -> Name """ Add a new schema object to the name set. @arg name... |
to_add = Name(name_attr, space_attr, self.default_namespace)
if to_add.fullname in VALID_TYPES:
fail_msg = '%s is a reserved type name.' % to_add.fullname
raise SchemaParseException(fail_msg)
elif to_add.fullname in self.names:
fail_msg = 'The name "%s" is a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_field_objects(field_data, names):
# type: (List[Dict[Text, Text]], Names) -> List[Field] """We're going to need to make message parameters too.""" |
field_objects = []
field_names = [] # type: List[Text]
for field in field_data:
if hasattr(field, 'get') and callable(field.get):
atype = cast(Text, field.get('type'))
name = cast(Text, field.get('name'))
# null values can have a def... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_function(root1, q, s, f, l, o='g'):
""" function to get links """ |
global links
links = search(q, o, s, f, l)
root1.destroy()
root1.quit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def task(ft):
""" to create loading progress bar """ |
ft.pack(expand = True, fill = BOTH, side = TOP)
pb_hD = ttk.Progressbar(ft, orient = 'horizontal', mode = 'indeterminate')
pb_hD.pack(expand = True, fill = BOTH, side = TOP)
pb_hD.start(50)
ft.mainloop() |
<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_content_gui(**args):
""" function to fetch links and download them """ |
global row
if not args ['directory']:
args ['directory'] = args ['query'].replace(' ', '-')
root1 = Frame(root)
t1 = threading.Thread(target = search_function, args = (root1,
args['query'], args['website'], args['file_type'], args['limit'],args['option']))
t1.start()
task(root1)
t1.join()
#new fr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def click_download(self, event):
""" event for download button """ |
args ['parallel'] = self.p.get()
args ['file_type'] = self.optionmenu.get()
args ['no_redirects'] = self.t.get()
args ['query'] = self.entry_query.get()
args ['min_file_size'] = int( self.entry_min.get())
args ['max_file_size'] = int( self.entry_max.get())
args ['limit'] = int( self.entry_limit.get())
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_entry_click(self, event):
""" function that gets called whenever entry is clicked """ |
if event.widget.config('fg') [4] == 'grey':
event.widget.delete(0, "end" ) # delete all the text in the entry
event.widget.insert(0, '') #Insert blank for user input
event.widget.config(fg = 'black') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_focusout(self, event, a):
""" function that gets called whenever anywhere except entry is clicked """ |
if event.widget.get() == '':
event.widget.insert(0, default_text[a])
event.widget.config(fg = 'grey') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ask_dir(self):
""" dialogue box for choosing directory """ |
args ['directory'] = askdirectory(**self.dir_opt)
self.dir_text.set(args ['directory']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scrape_links(html, engine):
""" function to scrape file links from html response """ |
soup = BeautifulSoup(html, 'lxml')
links = []
if engine == 'd':
results = soup.findAll('a', {'class': 'result__a'})
for result in results:
link = result.get('href')[15:]
link = link.replace('/blob/', '/raw/')
links.append(link)
elif engine == 'g':
results = soup.findAll('h3', {'class': '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_url_nofollow(url):
""" function to get return code of a url Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-ret... |
try:
response = urlopen(url)
code = response.getcode()
return code
except HTTPError as e:
return e.code
except:
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(query, engine='g', site="", file_type = 'pdf', limit = 10):
""" main function to search for links and return valid ones """ |
if site == "":
search_query = "filetype:{0} {1}".format(file_type, query)
else:
search_query = "site:{0} filetype:{1} {2}".format(site,file_type, query)
headers = {
'User Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) \
Gecko/20100101 Firefox/53.0'
}
if engine == "g":
params = {
'q': sear... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_args(**args):
""" function to check if input query is not None and set missing arguments to default value """ |
if not args['query']:
print("\nMissing required query argument.")
sys.exit()
for key in DEFAULTS:
if key not in args:
args[key] = DEFAULTS[key]
return args |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_content(**args):
""" main function to fetch links and download them """ |
args = validate_args(**args)
if not args['directory']:
args['directory'] = args['query'].replace(' ', '-')
print("Downloading {0} {1} files on topic {2} from {3} and saving to directory: {4}"
.format(args['limit'], args['file_type'], args['query'], args['website'], args['directory']))
links = search(args... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_filetypes(extensions):
""" function to show valid file extensions """ |
for item in extensions.items():
val = item[1]
if type(item[1]) == list:
val = ", ".join(str(x) for x in item[1])
print("{0:4}: {1}".format(val, item[0])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(self, name):
""" Return a list of subset of VM that match the pattern name @param name (str):
the vm name of the virtual machine @param name (Obj):
th... |
if name.__class__ is 'base.Server.Pro' or name.__class__ is 'base.Server.Smart':
# print('DEBUG: matched VM object %s' % name.__class__)
pattern = name.vm_name
else:
# print('DEBUG: matched Str Object %s' % name.__class__)
pattern = name
# 14/06/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_hypervisors(self):
""" Initialize the internal list containing each template available for each hypervisor. :return: [bool] True in case of success, othe... |
json_scheme = self.gen_def_json_scheme('GetHypervisors')
json_obj = self.call_method_post(method='GetHypervisors', json_scheme=json_scheme)
self.json_templates = json_obj
d = dict(json_obj)
for elem in d['Value']:
hv = self.hypervisors[elem['HypervisorType']]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def purchase_ip(self, debug=False):
""" Return an ip object representing a new bought IP @param debug [Boolean] if true, request and response will be printed @re... |
json_scheme = self.gen_def_json_scheme('SetPurchaseIpAddress')
json_obj = self.call_method_post(method='SetPurchaseIpAddress', json_scheme=json_scheme, debug=debug)
try:
ip = Ip()
ip.ip_addr = json_obj['Value']['Value']
ip.resid = json_obj['Value']['ResourceI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_ip(self, ip_id):
""" Delete an Ip from the boughs ip list @param (str) ip_id: a string representing the resource id of the IP @return: True if json me... |
ip_id = ' "IpAddressResourceId": %s' % ip_id
json_scheme = self.gen_def_json_scheme('SetRemoveIpAddress', ip_id)
json_obj = self.call_method_post(method='SetRemoveIpAddress', json_scheme=json_scheme)
pprint(json_obj)
return True if json_obj['Success'] is 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 get_package_id(self, name):
""" Retrieve the smart package id given is English name @param (str) name: the Aruba Smart package size name, ie: "small", "mediu... |
json_scheme = self.gen_def_json_scheme('GetPreConfiguredPackages', dict(HypervisorType=4))
json_obj = self.call_method_post(method='GetPreConfiguredPackages ', json_scheme=json_scheme)
for package in json_obj['Value']:
packageId = package['PackageID']
for description in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get(self, *args, **kwargs):
"""Wrapper around Requests for GET requests Returns: Response: A Requests Response object """ |
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.get(*args, **kwargs)
return req |
<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_xml(self, *args, **kwargs):
"""Wrapper around Requests for GET XML requests Returns: Response: A Requests Response object """ |
req = self.session_xml.get(*args, **kwargs)
return req |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _put(self, *args, **kwargs):
"""Wrapper around Requests for PUT requests Returns: Response: A Requests Response object """ |
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.put(*args, **kwargs)
return req |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _delete(self, *args, **kwargs):
"""Wrapper around Requests for DELETE requests Returns: Response: A Requests Response object """ |
if 'timeout' not in kwargs:
kwargs['timeout'] = self.timeout
req = self.session.delete(*args, **kwargs)
return req |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auth_ping(self):
"""Test that application can authenticate to Crowd. Attempts to authenticate the application user against the Crowd server. In order for use... |
url = self.rest_url + "/non-existent/location"
response = self._get(url)
if response.status_code == 401:
return False
elif response.status_code == 404:
return True
else:
# An error encountered - problem with the Crowd server?
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auth_user(self, username, password):
"""Authenticate a user account against the Crowd server. Attempts to authenticate the user against the Crowd server. Arg... |
response = self._post(self.rest_url + "/authentication",
data=json.dumps({"value": password}),
params={"username": username})
# If authentication failed for any reason return None
if not response.ok:
return None
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_session(self, username, password, remote="127.0.0.1", proxy=None):
"""Create a session for a user. Attempts to create a user session on the Crowd server.... |
params = {
"username": username,
"password": password,
"validation-factors": {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
}
if proxy:
params["validati... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_session(self, token, remote="127.0.0.1", proxy=None):
"""Validate a session token. Validate a previously acquired session token against the Crowd se... |
params = {
"validationFactors": [
{"name": "remote_address", "value": remote, },
]
}
if proxy:
params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, })
url = self.rest_url + "/session/%... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def terminate_session(self, token):
"""Terminates the session token, effectively logging out the user from all crowd-enabled services. Args: token: The session t... |
url = self.rest_url + "/session/%s" % token
response = self._delete(url)
# For consistency between methods use None rather than False
# If token validation failed for any reason return None
if not response.ok:
return None
# Otherwise return True
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 add_user(self, username, raise_on_error=False, **kwargs):
"""Add a user to the directory Args: username: The account username raise_on_error: optional (defau... |
# Check that mandatory elements have been provided
if 'password' not in kwargs:
raise ValueError("missing password")
if 'email' not in kwargs:
raise ValueError("missing email")
# Populate data with default and mandatory values.
# A KeyError means a manda... |
<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_user(self, username):
"""Retrieve information about a user Returns: dict: User information None: If no user or failure occurred """ |
response = self._get(self.rest_url + "/user",
params={"username": username,
"expand": "attributes"})
if not response.ok:
return None
return response.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 set_active(self, username, active_state):
"""Set the active state of a user Args: username: The account username active_state: True or False Returns: True: I... |
if active_state not in (True, False):
raise ValueError("active_state must be True or False")
user = self.get_user(username)
if user is None:
return None
if user['active'] is active_state:
# Already in desired state
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 change_password(self, username, newpassword, raise_on_error=False):
"""Change new password for a user Args: username: The account username. newpassword: The ... |
response = self._put(self.rest_url + "/user/password",
data=json.dumps({"value": newpassword}),
params={"username": username})
if response.ok:
return True
if raise_on_error:
raise RuntimeError(response.json()['... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_nested_group_users(self, groupname):
"""Retrieves a list of all users that directly or indirectly belong to the given groupname. Args: groupname: The gro... |
response = self._get(self.rest_url + "/group/user/nested",
params={"groupname": groupname,
"start-index": 0,
"max-results": 99999})
if not response.ok:
return None
return [u['na... |
<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_exists(self, username):
"""Determines if the user exists. Args: username: The user name. Returns: bool: True if the user exists in the Crowd application... |
response = self._get(self.rest_url + "/user",
params={"username": username})
if not response.ok:
return None
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_memberships(self):
"""Fetches all group memberships. Returns: dict: key: group name value: (array of users, array of groups) """ |
response = self._get_xml(self.rest_url + "/group/membership")
if not response.ok:
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
# coerce values to unicode in a python 2 and 3 compatib... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API. https://deve... |
params = {
"entity-type": entity_type,
"expand": entity_type,
"property-search-restriction": {
"property": {"name": property_name, "type": "STRING"},
"match-mode": "CONTAINS",
"value": search_string,
}
}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def versions(self) -> List(BlenderVersion):
""" The versions associated with Blender """ |
return [BlenderVersion(tag) for tag in self.git_repo.tags] + [BlenderVersion(BLENDER_VERSION_MASTER)] |
<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):
""" Copy libraries from the bin directory and place them as appropriate """ |
self.announce("Moving library files", level=3)
# We have already built the libraries in the previous build_ext step
self.skip_build = True
bin_dir = self.distribution.bin_dir
libs = [os.path.join(bin_dir, _lib) for _lib in
os.listdir(bin_dir) 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 run(self):
""" Perform build_cmake before doing the 'normal' stuff """ |
for extension in self.extensions:
if extension.name == "bpy":
self.build_cmake(extension)
super().run() |
<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_oauth(username, password, basemaps_token_uri, authcfg_id=AUTHCFG_ID, authcfg_name=AUTHCFG_NAME):
"""Setup oauth configuration to access the BCS API, re... |
cfgjson = {
"accessMethod" : 0,
"apiKey" : "",
"clientId" : "",
"clientSecret" : "",
"configType" : 1,
"grantFlow" : 2,
"password" : password,
"persistToken" : False,
"redirectPort" : '7070',
"redirectUrl" : "",
"refreshTokenUrl" : "",
"requestTimeout" : ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_search_queryset(self, instance_id, index="_all"):
""" Return True if an object is part of the search index queryset. Sometimes it's useful to know if an o... |
return self.get_search_queryset(index=index).filter(pk=instance_id).exists() |
<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_sql(self, values):
"""Prepare SQL statement consisting of a sequence of WHEN .. THEN statements.""" |
if isinstance(self.model._meta.pk, CharField):
when_clauses = " ".join(
[self._when("'{}'".format(x), y) for (x, y) in values]
)
else:
when_clauses = " ".join([self._when(x, y) for (x, y) in values])
table_name = self.model._meta.db_table
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_document_cache_key(self):
"""Key used for storing search docs in local cache.""" |
return "elasticsearch_django:{}.{}.{}".format(
self._meta.app_label, self._meta.model_name, self.pk
) |
<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_field_serializable(self, field_name):
"""Return True if the field can be serialized into a JSON doc.""" |
return (
self._meta.get_field(field_name).get_internal_type()
in self.SIMPLE_UPDATE_FIELD_TYPES
) |
<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_update_fields(self, index, update_fields):
""" Clean the list of update_fields based on the index being updated.\ If any field in the update_fields lis... |
search_fields = get_model_index_properties(self, index)
clean_fields = [f for f in update_fields if f in search_fields]
ignore = [f for f in update_fields if f not in search_fields]
if ignore:
logger.debug(
"Ignoring fields from partial update: %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 as_search_document_update(self, *, index, update_fields):
""" Return a partial update document based on which fields have been updated. If an object is saved... |
if UPDATE_STRATEGY == UPDATE_STRATEGY_FULL:
return self.as_search_document(index=index)
if UPDATE_STRATEGY == UPDATE_STRATEGY_PARTIAL:
# in partial mode we update the intersection of update_fields and
# properties found in the mapping file.
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 as_search_action(self, *, index, action):
""" Return an object as represented in a bulk api operation. Bulk API operations have a very specific format. This ... |
if action not in ("index", "update", "delete"):
raise ValueError("Action must be 'index', 'update' or 'delete'.")
document = {
"_index": index,
"_type": self.search_doc_type,
"_op_type": action,
"_id": self.pk,
}
if action ==... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.