INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Create and start an app. | def create_app(self, app_id, app, minimal=True):
"""Create and start an app.
:param str app_id: application ID
:param :class:`marathon.models.app.MarathonApp` app: the application to create
:param bool minimal: ignore nulls and empty collections
:returns: the created app (on su... |
List all apps. | def list_apps(self, cmd=None, embed_tasks=False, embed_counts=False,
embed_deployments=False, embed_readiness=False,
embed_last_task_failure=False, embed_failures=False,
embed_task_stats=False, app_id=None, label=None, **kwargs):
"""List all apps.
:... |
Get a single app. | def get_app(self, app_id, embed_tasks=False, embed_counts=False,
embed_deployments=False, embed_readiness=False,
embed_last_task_failure=False, embed_failures=False,
embed_task_stats=False):
"""Get a single app.
:param str app_id: application ID
:... |
Update an app. | def update_app(self, app_id, app, force=False, minimal=True):
"""Update an app.
Applies writable settings in `app` to `app_id`
Note: this method can not be used to rename apps.
:param str app_id: target application ID
:param app: application settings
:type app: :class:`... |
Update multiple apps. | def update_apps(self, apps, force=False, minimal=True):
"""Update multiple apps.
Applies writable settings in elements of apps either by upgrading existing ones or creating new ones
:param apps: sequence of application settings
:param bool force: apply even if a deployment is in progre... |
Roll an app back to a previous version. | def rollback_app(self, app_id, version, force=False):
"""Roll an app back to a previous version.
:param str app_id: application ID
:param str version: application version
:param bool force: apply even if a deployment is in progress
:returns: a dict containing the deployment id ... |
Stop and destroy an app. | def delete_app(self, app_id, force=False):
"""Stop and destroy an app.
:param str app_id: application ID
:param bool force: apply even if a deployment is in progress
:returns: a dict containing the deployment id and version
:rtype: dict
"""
params = {'force': fo... |
Scale an app. | def scale_app(self, app_id, instances=None, delta=None, force=False):
"""Scale an app.
Scale an app to a target number of instances (with `instances`), or scale the number of
instances up or down by some delta (`delta`). If the resulting number of instances would be negative,
desired in... |
Create and start a group. | def create_group(self, group):
"""Create and start a group.
:param :class:`marathon.models.group.MarathonGroup` group: the group to create
:returns: success
:rtype: dict containing the version ID
"""
data = group.to_json()
response = self._do_request('POST', '/v... |
List all groups. | def list_groups(self, **kwargs):
"""List all groups.
:param kwargs: arbitrary search filters
:returns: list of groups
:rtype: list[:class:`marathon.models.group.MarathonGroup`]
"""
response = self._do_request('GET', '/v2/groups')
groups = self._parse_response(
... |
Get a single group. | def get_group(self, group_id):
"""Get a single group.
:param str group_id: group ID
:returns: group
:rtype: :class:`marathon.models.group.MarathonGroup`
"""
response = self._do_request(
'GET', '/v2/groups/{group_id}'.format(group_id=group_id))
return... |
Update a group. | def update_group(self, group_id, group, force=False, minimal=True):
"""Update a group.
Applies writable settings in `group` to `group_id`
Note: this method can not be used to rename groups.
:param str group_id: target group ID
:param group: group settings
:type group: :... |
Roll a group back to a previous version. | def rollback_group(self, group_id, version, force=False):
"""Roll a group back to a previous version.
:param str group_id: group ID
:param str version: group version
:param bool force: apply even if a deployment is in progress
:returns: a dict containing the deployment id and v... |
Stop and destroy a group. | def delete_group(self, group_id, force=False):
"""Stop and destroy a group.
:param str group_id: group ID
:param bool force: apply even if a deployment is in progress
:returns: a dict containing the deleted version
:rtype: dict
"""
params = {'force': force}
... |
Scale a group by a factor. | def scale_group(self, group_id, scale_by):
"""Scale a group by a factor.
:param str group_id: group ID
:param int scale_by: factor to scale by
:returns: a dict containing the deployment id and version
:rtype: dict
"""
data = {'scaleBy': scale_by}
respons... |
List running tasks optionally filtered by app_id. | def list_tasks(self, app_id=None, **kwargs):
"""List running tasks, optionally filtered by app_id.
:param str app_id: if passed, only show tasks for this application
:param kwargs: arbitrary search filters
:returns: list of tasks
:rtype: list[:class:`marathon.models.task.Marath... |
Kill a list of given tasks. | def kill_given_tasks(self, task_ids, scale=False, force=None):
"""Kill a list of given tasks.
:param list[str] task_ids: tasks to kill
:param bool scale: if true, scale down the app by the number of tasks killed
:param bool force: if true, ignore any current running deployments
... |
Kill all tasks belonging to app. | def kill_tasks(self, app_id, scale=False, wipe=False,
host=None, batch_size=0, batch_delay=0):
"""Kill all tasks belonging to app.
:param str app_id: application ID
:param bool scale: if true, scale down the app by the number of tasks killed
:param str host: if provid... |
Kill a task. | def kill_task(self, app_id, task_id, scale=False, wipe=False):
"""Kill a task.
:param str app_id: application ID
:param str task_id: the task to kill
:param bool scale: if true, scale down the app by one if the task exists
:returns: the killed task
:rtype: :class:`marat... |
List the versions of an app. | def list_versions(self, app_id):
"""List the versions of an app.
:param str app_id: application ID
:returns: list of versions
:rtype: list[str]
"""
response = self._do_request(
'GET', '/v2/apps/{app_id}/versions'.format(app_id=app_id))
return [versio... |
Get the configuration of an app at a specific version. | def get_version(self, app_id, version):
"""Get the configuration of an app at a specific version.
:param str app_id: application ID
:param str version: application version
:return: application configuration
:rtype: :class:`marathon.models.app.MarathonApp`
"""
re... |
Register a callback URL as an event subscriber. | def create_event_subscription(self, url):
"""Register a callback URL as an event subscriber.
:param str url: callback URL
:returns: the created event subscription
:rtype: dict
"""
params = {'callbackUrl': url}
response = self._do_request('POST', '/v2/eventSubscr... |
Deregister a callback URL as an event subscriber. | def delete_event_subscription(self, url):
"""Deregister a callback URL as an event subscriber.
:param str url: callback URL
:returns: the deleted event subscription
:rtype: dict
"""
params = {'callbackUrl': url}
response = self._do_request('DELETE', '/v2/eventSu... |
List all running deployments. | 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, MarathonDeploym... |
List all the tasks queued up or waiting to be scheduled. | 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[:class:`marathon.models.queue.MarathonQueueItem`]
"""
if embed_last_unused_offers:
params = {'embed': 'lastUnu... |
Cancel a deployment. | 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 a rollback deployment to restore the previous configuration
:returns: a dict containing the deployment id and version (empty... |
Polls event bus using/ v2/ events | def event_stream(self, raw=False, event_types=None):
"""Polls event bus using /v2/events
:param bool raw: if true, yield raw event text, else yield MarathonEvent object
:param event_types: a list of event types to consume
:type event_types: list[type] or list[str]
:returns: iter... |
Checks if a path is a correct format that Marathon expects. Raises ValueError if not valid. | 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: str
"""
if path is None:
return
# As seen in:
# https://github.com/mesosphere/marathon/blob/0c11661ca2f259f8a903d114ef790... |
Checks if an id is the correct format that Marathon expects. Raises ValueError if not valid. | 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: str
"""
if id is None:
return
if not ID_PATTERN.match(id.strip('/')):
raise ValueError(
'invalid id (allo... |
Construct a JSON - friendly representation of the object. | def json_repr(self, minimal=False):
"""Construct a JSON-friendly representation of the object.
:param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections)
:rtype: dict
"""
if minimal:
return {to_camel_case(k): v for k, ... |
Construct an object from a parsed response. | 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()}) |
Encode an object as a JSON string. | 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 empty collections)
:rtype: str
"""
if minimal:
return json.dumps(self.json_repr(minimal=True), cls=Marathon... |
Construct a JSON - friendly representation of the object. | def json_repr(self, minimal=False):
"""Construct a JSON-friendly representation of the object.
:param bool minimal: [ignored]
:rtype: list
"""
if self.value:
return [self.field, self.operator, self.value]
else:
return [self.field, self.operator] |
Construct a MarathonConstraint from a parsed response. | def from_json(cls, obj):
"""Construct a MarathonConstraint from a parsed response.
:param dict attributes: object attributes from parsed response
:rtype: :class:`MarathonConstraint`
"""
if len(obj) == 2:
(field, operator) = obj
return cls(field, operator... |
: param str constraint: The string representation of a constraint | def from_string(cls, constraint):
"""
:param str constraint: The string representation of a constraint
:rtype: :class:`MarathonConstraint`
"""
obj = constraint.split(':')
marathon_constraint = cls.from_json(obj)
if marathon_constraint:
return maratho... |
Construct a list of MarathonEndpoints from a list of tasks. | def from_tasks(cls, tasks):
"""Construct a list of MarathonEndpoints from a list of tasks.
:param list[:class:`marathon.models.MarathonTask`] tasks: list of tasks to parse
:rtype: list[:class:`MarathonEndpoint`]
"""
endpoints = [
[
MarathonEndpoint(... |
Convert newlines into U + 23EC characters followed by an actual newline and then a tree prefix so as to position the remaining text under the previous line. | 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 position the remaining text under the previous
line.
"""
replacement = u''.join([
options.NEWLINE,
u'\n',
pref... |
Gets a band. | def get_band(self, tag):
"""Gets a band.
Gets a band with specified tag. If no tag is specified, the request will fail.
If the tag is invalid, a brawlstars.InvalidTag will be raised.
If the data is missing, a ValueError will be raised.
If the connection times out, a brawlstars.T... |
Gets a player. | 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 brawlstars.InvalidTag will be raised.
If the data is missing, a ValueError will be raised.
If the connection times out, a ... |
Gets a band. | async def get_band(self, tag):
"""Gets a band.
Gets a band with specified tag. If no tag is specified, the request will fail.
If the tag is invalid, a brawlstars.InvalidTag will be raised.
If the data is missing, a ValueError will be raised.
If the connection times out, a brawls... |
Function allowing lazy importing of a module into the namespace. | 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 module object is created, registered in `sys.modules`, and
returned. This is a hollow module; actual loading, and `ImportErrors... |
Performs lazy importing of one or more callables. | def lazy_callable(modname, *names, **kwargs):
"""Performs lazy importing of one or more callables.
:func:`lazy_callable` creates functions that are thin wrappers that pass
any and all arguments straight to the target module's callables. These can
be functions or classes. The full loading of that module... |
Ensures that a module and its parents are properly loaded | 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 _ImportLo... |
Like dict. setdefault but sets the default value also if None is present. | 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] |
Removes all lazy behavior from a module s class for loading. | 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 class deletion
dictionaries. Deletion dictionaries are class attributes with names
specified in `_DELETION_DICT`.
Parameters
----------
... |
Resets a module s lazy state from cached data. | 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:
... |
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. | def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if six.PY... |
Compute timestamp from a datetime object that could be timezone aware or unaware. | 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()) |
Similar to smart_bytes except that lazy instances are resolved to strings rather than kept as lazy objects. | 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 than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, memoryview):
... |
Wrap a function so that results for any argument tuple are stored in cache. Note that the args to the function must be usable as dictionary keys. Only the first num_args are considered when creating the key. | 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 usable as dictionary
keys.
Only the first num_args are considered when creating the key.
"""
@wraps(func)
def wrapper(*args):
... |
Obtained from https:// github. com/ dcramer/ reraise/ blob/ master/ src/ reraise. py >>> try: >>> do_something_crazy () >>> except Exception: >>> reraise_as ( UnhandledException ) | def reraise_as(new_exception_or_type):
"""
Obtained from https://github.com/dcramer/reraise/blob/master/src/reraise.py
>>> try:
>>> do_something_crazy()
>>> except Exception:
>>> reraise_as(UnhandledException)
"""
__traceback_hide__ = True # NOQA
e_type, e_value, e_tracebac... |
Remove sensitive information from msg. | def hide_auth(msg):
"""Remove sensitive information from msg."""
for pattern, repl in RE_HIDE_AUTH:
msg = pattern.sub(repl, msg)
return msg |
Prepare the HTTP handler URL and HTTP headers for all subsequent requests | 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_defa... |
Convert unix timestamp to human readable date/ time string | def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT):
"""Convert unix timestamp to human readable date/time string"""
return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format) |
Calculate delta between current time and datetime and return a human readable form of the delta object | 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:
re... |
Return JSON object expected by the Zabbix API | 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,... |
Perform one HTTP request to Zabbix API | 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=jso... |
Perform a user. login API request | 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
... |
Perform a re - login | 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 F... |
Perform a re - login if not signed in or raise an exception | 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... |
Check authentication and perform actual API request and relogin if needed | 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: %... |
download function to download parallely | def download_parallel(url, directory, idx, min_file_size = 0, max_file_size = -1,
no_redirects = False, pos = 0, mode = 's'):
"""
download function to download parallely
"""
global main_it
global exit_flag
global total_chunks
global file_name
global i_max
file_name[idx]= url.split('/')[-1]
file_addres... |
called when paralled downloading is true | 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, ... |
called when user wants serial downloading | 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_... |
function called when thread is started | 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... |
function to initialize thread for downloading | 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 ... |
reading bytes ; update progress bar after 1 ms | 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"]... |
Add this type to our collection if needed. | 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 |
Instantiate the metaschema. | def get_metaschema(): # type: () -> Tuple[Names, List[Dict[Text, Any]], Loader]
"""Instantiate the metaschema."""
loader = ref_resolver.Loader({
"Any": "https://w3id.org/cwl/salad#Any",
"ArraySchema": "https://w3id.org/cwl/salad#ArraySchema",
"Array_symbol": "https://w3id.org/cwl/salad#... |
Collect the provided namespaces checking for conflicts. | def add_namespaces(metadata, namespaces):
# type: (Mapping[Text, Any], MutableMapping[Text, Text]) -> None
"""Collect the provided namespaces, checking for conflicts."""
for key, value in metadata.items():
if key not in namespaces:
namespaces[key] = value
elif namespaces[key] != ... |
Walk through the metadata object collecting namespace declarations. | 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():
... |
Load a schema that can be used to validate documents using load_and_validate. | def load_schema(schema_ref, # type: Union[CommentedMap, CommentedSeq, Text]
cache=None # type: Dict
):
# type: (...) -> Tuple[Loader, Union[Names, SchemaParseException], Dict[Text, Any], Loader]
"""
Load a schema that can be used to validate documents using load_and_valida... |
Load a document and validate it with the provided schema. | def load_and_validate(document_loader, # type: Loader
avsc_names, # type: Names
document, # type: Union[CommentedMap, Text]
strict, # type: bool
st... |
Validate a document using the provided schema. | def validate_doc(schema_names, # type: Names
doc, # type: Union[Dict[Text, Any], List[Dict[Text, Any]], Text, None]
loader, # type: Loader
strict, # type: bool
strict_foreign_properties=False # type: bool
):
... |
Calculate a reproducible name for anonymous types. | 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_... |
Go through and replace types in the spec mapping | 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 and replace types in the 'spec' mapping"""
if isinstance(items, MutableMapping):
# recursively check these fields for types to replace
... |
Turn a URL into an Avro - safe name. | 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 part of the URL fragment past the slash, otherwise
the whole fragment.
"""
frg = urllib.parse.urldefrag(url)[1]
if frg != ''... |
Convert our schema to be more avro like. | def make_valid_avro(items, # type: Avro
alltypes, # type: Dict[Text, Dict[Text, Any]]
found, # type: Set[Text]
union=False # type: bool
):
# type: (...) -> Union[Avro, Dict, Text]
"""Convert our schema to... |
Make a deep copy of list and dict objects. | 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 CommentedMap and
CommentedSeq metadata which is very expensive with regular copy.deepcopy.
"""
if isinstance(item, MutableMapping):
r... |
Apply extend and specialize to fully materialize derived record types. | def extend_and_specialize(items, loader):
# type: (List[Dict[Text, Any]], Loader) -> List[Dict[Text, Any]]
"""
Apply 'extend' and 'specialize' to fully materialize derived record types.
"""
items = deepcopy_strip(items)
types = {i["name"]: i for i in items} # type: Dict[Text, Any]
results ... |
All in one convenience function. | def make_avro_schema(i, # type: List[Any]
loader # type: Loader
): # type: (...) -> Names
"""
All in one convenience function.
Call make_avro() and make_avro_schema_from_avro() separately if you need
the intermediate result for diagnostic output.
... |
Returns the last segment of the provided fragment or path. | 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] |
Write a Grapviz inheritance graph for the supplied document. | 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 = ... |
Write a GraphViz graph of the relationships between the fields. | 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.... |
Retrieve the non - reserved properties from a dictionary of properties | def get_other_props(all_props, reserved_props):
# type: (Dict, Tuple) -> Optional[Dict]
"""
Retrieve the non-reserved properties from a dictionary of properties
@args reserved_props: The set of reserved properties to exclude
"""
if hasattr(all_props, 'items') and callable(all_props.items):
... |
Build Avro Schema from data parsed out of JSON string. | 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 out of JSON string.
@arg names: A Name object (tracks seen names and default space)
"""
if names is None:
names = Names()
... |
Back out a namespace from full name. | 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 "" |
Add a new schema object to the name set. | 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_attr: name value read in schema
@arg space_attr: namespace value read in schema.
@return: the Name tha... |
We re going to need to make message parameters too. | 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 ca... |
function to get links | 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() |
to create loading progress bar | 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() |
function to fetch links and download them | 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['fil... |
main function | def main():
"""
main function
"""
s = ttk.Style()
s.theme_use('clam')
ents = makeform(root)
root.mainloop() |
event for download button | 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( ... |
function that gets called whenever entry is clicked | 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') |
function that gets called whenever anywhere except entry is clicked | 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') |
function to check input filetype against threat extensions list | def check_threat(self):
"""
function to check input filetype against threat extensions list
"""
is_high_threat = False
for val in THREAT_EXTENSIONS.values():
if type(val) == list:
for el in val:
if self.optionmenu.get() == el:
is_high_threat = True
break
else:
if self.optionmen... |
dialogue box for choosing directory | def ask_dir(self):
"""
dialogue box for choosing directory
"""
args ['directory'] = askdirectory(**self.dir_opt)
self.dir_text.set(args ['directory']) |
function to fetch links equal to limit | def get_google_links(limit, params, headers):
"""
function to fetch links equal to limit
every Google search result page has a start index.
every page contains 10 search results.
"""
links = []
for start_index in range(0, limit, 10):
params['start'] = start_index
resp = s.get("https://www.google.com/search"... |
function to fetch links equal to limit | def get_duckduckgo_links(limit, params, headers):
"""
function to fetch links equal to limit
duckduckgo pagination is not static, so there is a limit on
maximum number of links that can be scraped
"""
resp = s.get('https://duckduckgo.com/html', params = params, headers = headers)
links = scrape_links(resp.conte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.