code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
try:
df = self.df.copy()
df[ratio_col] = df[[col]].apply(
lambda x: 100 * x / float(x.sum()))
self.df = df
except Exception as e:
self.err(e, self.ratio, "Can not calculate ratio") | def ratio(self, col: str, ratio_col: str="Ratio") | Add a column whith the percentages ratio from a column
:param col: column to calculate ratio from
:type col: str
:param ratio_col: new ratio column name, defaults to "Ratio"
:param ratio_col: str, optional
:example: ``ds2 = ds.ratio("Col 1")`` | 4.249691 | 4.420978 | 0.961256 |
for key in self.keys():
setattr(self, key, value.get(key, None)) | def from_dict(self, value) | Set the values of the model based upon the content of the passed in
dictionary.
:param dict value: The dictionary of values to assign to this model | 3.404548 | 4.628145 | 0.735618 |
sha1 = hashlib.sha1(''.join(['%s:%s' % (k,v) for k,v in self.items()]))
return str(sha1.hexdigest()) | def sha1(self) | Return a sha1 hash of the model items.
:rtype: str | 2.87637 | 3.678303 | 0.781983 |
result = gen.Task(self._redis_client.delete, self._key)
raise gen.Return(bool(result)) | def delete(self) | Delete the item from storage
:rtype: bool | 11.017508 | 10.119779 | 1.08871 |
raw = yield gen.Task(self._redis_client.get, self._key)
if raw:
self.loads(base64.b64decode(raw))
raise gen.Return(True)
raise gen.Return(False) | def fetch(self) | Fetch the data for the model from Redis and assign the values.
:rtype: bool | 3.85149 | 3.566242 | 1.079986 |
pipeline = self._redis_client.pipeline()
pipeline.set(self._key, base64.b64encode(self.dumps()))
if self._ttl:
pipeline.expire(self._key, self._ttl)
result = yield gen.Task(pipeline.execute)
self._dirty, self._saved = not all(result), all(result)
rais... | def save(self) | Store the model in Redis.
:rtype: bool | 4.271961 | 3.807629 | 1.121948 |
codes = sorted(get_language_code_list())
return {'LANGUAGE_CODES': codes,
'LANGUAGE_CODES_AND_NAMES': [(c, LANG_DICT.get(c, c)) for c in codes],
'DEFAULT_LANGUAGE_CODE': get_default_language_code(),
'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX} | def multilingual(request) | Returns context variables containing information about available languages. | 3.495299 | 3.376772 | 1.0351 |
print("Parsing", url, file=sys.stderr)
try:
data = getPageContent(url, session)
except IOError as msg:
print("ERROR:", msg, file=sys.stderr)
return
for match in url_matcher.finditer(data):
url = match.group(1) + '/'
name = unescape(match.group(2))
nam... | def handle_url(url, session, res) | Parse one search result page. | 4.173833 | 4.108626 | 1.015871 |
names = [
("Creators/%s" % name).lower(),
("GoComics/%s" % name).lower(),
]
for scraperclass in get_scraperclasses():
lname = scraperclass.getName().lower()
if lname in names:
return True
return False | def has_comic(name) | Check if comic name already exists. | 5.647926 | 5.56355 | 1.015166 |
if SPLUNK_DEBUG:
print('{} -------------------------------'.format(
rnow()))
print('{} splunkpub: atexit.register - start'.format(
rnow()))
worked = True
for instance in instances:
try:
if SPLUNK_DEBUG:
print('{} - shutting dow... | def perform_exit() | perform_exit
Handling at-the-exit events
---------------------------
This will cleanup each worker process which
could be in the middle of a request/sleep/block
action. This has been tested on python 3 with
Celery and single processes. | 3.371035 | 3.29915 | 1.021789 |
if SPLUNK_DEBUG:
print('{} -------------------------------'.format(
rnow()))
print('{} splunkpub: force_flush - start'.format(
rnow()))
worked = True
for instance in instances:
try:
instance.force_flush()
except Exception as e:
... | def force_flush() | force_flush | 4.055311 | 3.994121 | 1.01532 |
self.debug_log('emit')
try:
record = self.format_record(
record)
except Exception as e:
self.write_log(
'Exception in Splunk logging handler={}'.format(e))
self.write_log(
traceback.format_exc())
... | def emit(
self,
record) | emit
Emit handler for queue-ing message for
the helper thread to send to Splunk on the ``sleep_interval``
:param record: LogRecord to send to Splunk
https://docs.python.org/3/library/logging.html | 5.312327 | 4.87744 | 1.089163 |
# Start a worker thread responsible for sending logs
if self.sleep_interval > 0:
self.debug_log(
'starting worker thread')
self.timer = Timer(
sleep_interval,
self.perform_work)
self.timer.daemon = True # Auto-... | def start_worker_thread(
self,
sleep_interval=1.0) | start_worker_thread
Start the helper worker thread to publish queued messages
to Splunk
:param sleep_interval: sleep in seconds before reading from
the queue again | 5.043589 | 5.455486 | 0.924499 |
self.debug_log((
'perform_work - start'))
self.tid = threading.current_thread().ident
if self.sleep_interval > 0:
# Stop the timer. Happens automatically if this is called
# via the timer, does not if invoked by force_flush()
if self.ti... | def perform_work(
self) | perform_work
Process handler function for processing messages
found in the ``multiprocessing.Manager.queue``
Build the ``self.log_payload`` from the queued log messages
and POST it to the Splunk endpoint | 3.520895 | 3.427604 | 1.027217 |
self.debug_log('publish_to_splunk - start')
use_payload = payload
if not use_payload:
use_payload = self.log_payload
self.num_sent = 0
if use_payload:
url = 'https://{}:{}/services/collector'.format(
self.host,
s... | def publish_to_splunk(
self,
payload=None) | publish_to_splunk
Build the ``self.log_payload`` from the queued log messages
and POST it to the Splunk endpoint
:param payload: string message to send to Splunk | 2.953066 | 2.872286 | 1.028124 |
return bool(
shutdown_event.is_set()
or self.shutdown_now
or self.run_once) | def is_shutting_down(
self,
shutdown_event) | is_shutting_down
Determine if the parent is shutting down or this was
triggered to shutdown
:param shutdown_event: shutdown event | 6.772745 | 8.771172 | 0.77216 |
self.debug_log('close - start')
self.shutdown()
logging.Handler.close(self)
self.debug_log('close - done') | def close(
self) | close | 6.004899 | 5.533846 | 1.085122 |
self.debug_log('shutdown - start')
# Only initiate shutdown once
if not self.shutdown_now:
self.debug_log('shutdown - still shutting down')
# Cancels the scheduled Timer, allows exit immediately
if self.timer:
self.timer.cancel()
... | def shutdown(
self) | shutdown | 5.757405 | 5.709286 | 1.008428 |
return (self.application.settings.get('statsd',
{}).get('host',
self.STATSD_HOST),
self.application.settings.get('statsd',
{}).get('port',
... | def _statsd_address(self) | Return a tuple of host and port for the statsd server to send
stats to.
:return: tuple(host, port) | 3.225788 | 3.478217 | 0.927426 |
super(StatsdMixin, self).on_finish()
key = '%s.%s.%s.%s' % (self.__module__,
self.__class__.__name__,
self.request.method, self._status_code)
LOGGER.info('Processing %s', key)
self.statsd_incr(key)
self.statsd... | def on_finish(self) | Invoked once the request has been finished. Increment a counter
created in the format:
package[.module].Class.METHOD.STATUS
tornado.web.RequestHandler.GET.200 | 3.834048 | 3.223996 | 1.189222 |
if 'tornadoredis' not in globals():
import tornadoredis
kwargs = self._redis_connection_settings()
LOGGER.info('Connecting to %(host)s:%(port)s DB %(selected_db)s',
kwargs)
return tornadoredis.Client(**kwargs) | def _new_redis_client(self) | Create a new redis client and assign it the class _redis_client
attribute for reuse across requests.
:rtype: tornadoredis.Client() | 4.897174 | 4.4148 | 1.109263 |
return {config.HOST: self.settings.get(config.HOST, self._REDIS_HOST),
config.PORT: self.settings.get(config.PORT, self._REDIS_PORT),
'selected_db': self.settings.get(config.DB, self._REDIS_DB)} | def _redis_connection_settings(self) | Return a dictionary of redis connection settings. | 3.159443 | 2.835012 | 1.114437 |
# Create the model and fetch its data
self.model = self.get_model(kwargs.get('id'))
result = yield self.model.fetch()
# If model is not found, return 404
if not result:
self.not_found()
return
# Stub to check for delete permissions
... | def delete(self, *args, **kwargs) | Handle delete of an item
:param args:
:param kwargs: | 4.526403 | 4.380584 | 1.033288 |
# Create the model and fetch its data
self.model = self.get_model(kwargs.get('id'))
result = yield self.model.fetch()
# If model is not found, return 404
if not result:
self.not_found()
return
# Stub to check for read permissions
... | def head(self, *args, **kwargs) | Handle HEAD requests for the item
:param args:
:param kwargs: | 4.950959 | 4.681443 | 1.057571 |
# Create the model and fetch its data
self.model = self.get_model(kwargs.get('id'))
result = yield self.model.fetch()
# If model is not found, return 404
if not result:
LOGGER.debug('Not found')
self.not_found()
return
# Stub... | def get(self, *args, **kwargs) | Handle reading of the model
:param args:
:param kwargs: | 4.603075 | 4.462407 | 1.031523 |
self.initialize_post()
# Don't allow the post if the poster does not have permission
if not self.has_create_permission():
LOGGER.debug('Does not have write_permission')
self.set_status(403, self.status_message('Creation Forbidden'))
self.finish()
... | def post(self, *args, **kwargs) | Handle creation of an item.
:param args:
:param kwargs: | 3.905329 | 4.126634 | 0.946372 |
self.initialize_put(kwargs.get('id'))
if not self.has_update_permission():
self.set_status(403, self.status_message('Creation Forbidden'))
self.finish()
return
for key, value in self.model.items():
if self.json_arguments.get(key) != valu... | def put(self, *args, **kwargs) | Handle updates of an item.
:param args:
:param kwargs: | 2.915315 | 2.882324 | 1.011446 |
self.model = self.get_model()
for key in self.model.keys():
self.model.set(key, self.json_arguments.get(key)) | def initialize_post(self) | Invoked by the ModelAPIRequestHandler.post method prior to taking
any action. | 5.754032 | 4.331829 | 1.328315 |
return {name: (self.categorical_mappings_[name][val] if name in self.categorical_mappings_ else val)
for (name, val) in param_dict.items()} | def _convert_nonstring_categoricals(self, param_dict) | Apply the self.categorical_mappings_ mappings where necessary. | 4.344851 | 2.470727 | 1.758531 |
return self._fit(X, y=y, groups=groups, **fit_params) | def fit(self, X, y=None, groups=None, **fit_params) | Run fit on the estimator with parameters chosen sequentially by SigOpt.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vector, where n_samples in the number of samples and
n_features is the number of features.
y : array-like, shape ... | 3.038485 | 4.969696 | 0.611403 |
Host.name = name
Host.registry_host = registry_host
Host.registry_port = registry_port
Host.pubsub_host = pubsub_host
Host.pubsub_port = pubsub_port | def configure(cls, name, registry_host: str="0.0.0.0", registry_port: int=4500,
pubsub_host: str="0.0.0.0", pubsub_port: int=6379) | A convenience method for providing registry and pubsub(redis) endpoints
:param name: Used for process name
:param registry_host: IP Address for vyked-registry; default = 0.0.0.0
:param registry_port: Port for vyked-registry; default = 4500
:param pubsub_host: IP Address for pubsub compo... | 2.024599 | 2.248588 | 0.900387 |
invalid_service = True
_service_classes = {'_tcp_service': TCPService, '_http_service': HTTPService}
for key, value in _service_classes.items():
if isinstance(service, value):
cls._services[key] = service
invalid_service = False
... | def attach_service(cls, service) | Allows you to attach one TCP and one HTTP service
deprecated:: 2.1.73 use http and tcp specific methods
:param service: A vyked TCP or HTTP service that needs to be hosted | 4.279775 | 4.380229 | 0.977066 |
if cls._services['_http_service'] is None:
cls._services['_http_service'] = http_service
cls._set_bus(http_service)
else:
warnings.warn('HTTP service is already attached') | def attach_http_service(cls, http_service: HTTPService) | Attaches a service for hosting
:param http_service: A HTTPService instance | 4.568046 | 4.473425 | 1.021152 |
if cls._services['_tcp_service'] is None:
cls._services['_tcp_service'] = tcp_service
cls._set_bus(tcp_service)
else:
warnings.warn('TCP service is already attached') | def attach_tcp_service(cls, tcp_service: TCPService) | Attaches a service for hosting
:param tcp_service: A TCPService instance | 4.76309 | 4.643034 | 1.025857 |
if not all(v is None for v in cls._services.values()):
cls._set_host_id()
cls._setup_logging()
cls._set_process_name()
cls._set_signal_handlers()
cls._start_server()
else:
cls._logger.error('No services to host') | def run(cls) | Fires up the event loop and starts serving attached services | 5.205441 | 4.542376 | 1.145973 |
self.clear()
if os.path.isfile(self._filename):
os.unlink(self._filename)
else:
LOGGER.debug('Session file did not exist: %s', self._filename) | def delete(self) | Extend to the delete the session from storage | 4.449701 | 3.545573 | 1.255002 |
try:
with open(self._filename, 'wb') as session_file:
session_file.write(self.dumps())
except IOError as error:
LOGGER.error('Session file error: %s', error)
raise error | def save(self) | Save the session for later retrieval
:raises: IOError | 3.981539 | 3.530726 | 1.127683 |
for filename in os.listdir(self._storage_dir):
file_path = path.join(self._storage_dir, filename)
file_stat = os.stat(file_path)
evaluate = max(file_stat.st_ctime, file_stat.st_mtime)
if evaluate + self._duration < time.time():
LOGGER.debu... | def _cleanup(self) | Remove any stale files from the session storage directory | 2.982741 | 2.497041 | 1.19451 |
dir_path = self._settings.get(config.DIRECTORY)
if dir_path is None:
dir_path = self._default_path
if not os.path.exists(dir_path):
self._make_path(dir_path)
else:
dir_path = path.abspath(dir_path)
if not os.path.exists(dir... | def _setup_storage_dir(self) | Setup the storage directory path value and ensure the path exists.
:rtype: str
:raises: tinman.exceptions.ConfigurationException | 2.870487 | 2.656579 | 1.08052 |
if 'tornadoredis' not in globals():
import tornadoredis
kwargs = {'host': settings.get('host', cls.REDIS_HOST),
'port': settings.get('port', cls.REDIS_PORT),
'selected_db': settings.get('db', cls.REDIS_DB)}
LOGGER.info('Connecting to %(hos... | def _redis_connect(cls, settings) | Connect to redis and assign the client to the RedisSession class
so that it is globally available in this process.
:param dict settings: The redis session configuration | 2.701214 | 2.93778 | 0.919474 |
result = yield gen.Task(RedisSession._redis_client.delete, self._key)
LOGGER.debug('Deleted session %s (%r)', self.id, result)
self.clear()
raise gen.Return(result) | def delete(self) | Delete the item from storage
:param method callback: The callback method to invoke when done | 5.906691 | 7.770077 | 0.760184 |
LOGGER.debug('Fetching session data: %s', self.id)
result = yield gen.Task(RedisSession._redis_client.get, self._key)
if result:
self.loads(result)
raise gen.Return(True)
else:
raise gen.Return(False) | def fetch(self) | Fetch the data for the model from Redis and assign the values.
:param method callback: The callback method to invoke when done | 5.028373 | 4.929671 | 1.020022 |
result = yield gen.Task(RedisSession._redis_client.set,
self._key, self.dumps())
LOGGER.debug('Saved session %s (%r)', self.id, result)
raise gen.Return(result) | def save(self) | Store the session data in redis
:param method callback: The callback method to invoke when done | 6.405643 | 6.305906 | 1.015817 |
if name not in self.templates:
self.templates[name] = self._create_template(name)
return self.templates[name] | def load(self, name, parent_path=None) | Loads a template.
:param str name: The template name
:param str parent_path: The optional path for a parent document
:rtype: tornado.template.Template | 3.278289 | 3.556918 | 0.921666 |
url = '%s/%s' % (self._base_url, escape.url_escape(name))
LOGGER.debug('Making HTTP GET request to %s', url)
response = self._http_client.fetch(url)
data = json.loads(response.body, ensure_ascii=False)
return template.Template(data['template'], name=name, loader=self) | def _create_template(self, name) | Create an instance of a tornado.template.Template object for the
given template name.
:param str name: The name/path to the template
:rtype: tornado.template.Template | 3.858593 | 3.728487 | 1.034895 |
code = crianza.compile(crianza.parse(source_code), optimize=optimize)
return crianza.native.compile(code, args=args) | def xcompile(source_code, args=0, optimize=True) | Parses Crianza source code and returns a native Python function.
Args:
args: The resulting function's number of input parameters.
Returns:
A callable Python function. | 7.597885 | 8.444677 | 0.899725 |
native = xcompile(source, optimize=optimize)
return native() | def xeval(source, optimize=True) | Compiles to native Python bytecode and runs program, returning the
topmost value on the stack.
Args:
optimize: Whether to optimize the code after parsing it.
Returns:
None: If the stack is empty
obj: If the stack contains a single value
[obj, obj, ...]: If the stack contain... | 11.107051 | 27.050478 | 0.410605 |
# Uses several _cte_node_* parameters, so ensure they exist.
self._ensure_parameters()
for vf in [
self.model._cte_node_depth,
self.model._cte_node_path,
self.model._cte_node_ordering,
]:
if not hasattr(node, vf):
r... | def _ensure_virtual_fields(self, node) | Attempts to read the virtual fields from the given `node` in order
to ensure they exist, resulting in an early :class:`AttributeError`
exception in case of missing virtual fields. This method requires
several parameters, and thus invoked :meth:`_ensure_parameters`
first, ... | 7.760143 | 6.632896 | 1.169948 |
# The CTEQuerySet uses _cte_node_* attributes from the Model, so ensure
# they exist.
self._ensure_parameters()
return CTEQuerySet(self.model, using=self._db) | def get_queryset(self) | Returns a custom :class:`QuerySet` which provides the CTE
functionality for all queries concerning :class:`CTENode` objects.
This method overrides the default :meth:`get_queryset` method of
the :class:`Manager` class.
:returns: a custom :class:`QuerySet` which provides t... | 14.285922 | 10.342632 | 1.381266 |
# We need to read the _cte_node_children attribute, so ensure it exists.
self._ensure_parameters()
return self.exclude(
**{"%s__id__in" % self.model._cte_node_children: self.all()}
) | def leaves(self) | Returns a :class:`QuerySet` of all leaf nodes (nodes with no
children).
:return: A :class:`QuerySet` of all leaf nodes (nodes with no
children). | 12.955231 | 12.357156 | 1.048399 |
# We need to read the _cte_node_children attribute, so ensure it exists.
self._ensure_parameters()
return self.filter(
**{"%s__id__in" % self.model._cte_node_children: self.all()}
).distinct() | def branches(self) | Returns a :class:`QuerySet` of all branch nodes (nodes with at least
one child).
:return: A :class:`QuerySet` of all leaf nodes (nodes with at least
one child). | 12.160703 | 11.024008 | 1.103111 |
# We need to use the path virtual field, so ensure it exists.
self._ensure_virtual_fields(node)
return self.get(pk=getattr(node, self.model._cte_node_path)[0]) | def root(self, node) | Returns the :class:`CTENode` which is the root of the tree in which
the given `node` participates (or `node` if it is a root node). This
method functions through the :meth:`get` method.
:param node: A :class:`CTENode` whose root is required.
:return: A :class:`CTENode` ... | 13.313876 | 13.866583 | 0.960141 |
# We need to read the _cte_node_parent* attributes, so ensure they
# exist.
self._ensure_parameters()
# We need to construct: filter(parent = node.parent_id)
return self.filter(
**{
self.model._cte_node_parent: getattr(
nod... | def siblings(self, node) | Returns a :class:`QuerySet` of all siblings of a given
:class:`CTENode` `node`.
:param node: a :class:`CTENode` whose siblings are required.
:returns: A :class:`QuerySet` of all siblings of the given `node`. | 8.798208 | 7.864334 | 1.118748 |
# We need to use the path virtual field, so ensure it exists.
self._ensure_virtual_fields(node)
return self.filter(pk__in=getattr(node, self.model._cte_node_path)[:-1]) | def ancestors(self, node) | Returns a :class:`QuerySet` of all ancestors of a given
:class:`CTENode` `node`.
:param node: A :class:`CTENode` whose ancestors are required.
:returns: A :class:`QuerySet` of all ancestors of the given `node`. | 11.721157 | 10.57329 | 1.108563 |
# We need to read the _cte_node_* attributes, so ensure they exist.
self._ensure_parameters()
# This is implemented in the CTE WHERE logic, so we pass a reference to
# the offset CTENode to the custom QuerySet, which will process it.
# Because the compiler will include t... | def descendants(self, node) | Returns a :class:`QuerySet` with all descendants for a given
:class:`CTENode` `node`.
:param node: the :class:`CTENode` whose descendants are required.
:returns: A :class:`QuerySet` with all descendants of the given
`node`. | 13.764414 | 12.608281 | 1.091696 |
# Ensure nodes are not siblings of themselves.
return not node.id == subject.id and node.parent_id == subject.parent_id | def is_sibling_of(self, node, subject) | Returns ``True`` if the given `node` is a sibling of the given
`subject` node, ``False`` otherwise. This method uses the
:attr:`parent` field, and so does not perform any query.
:param node: the :class:`CTENode' for which to determine whether it
is a sibling of the `... | 6.111013 | 8.433838 | 0.724583 |
# We will need to use the path virtual field, so ensure it exists.
self._ensure_virtual_fields(node)
# Convenience check so is_ancestor_of can be combined with methods
# returning nodes without the caller having to worry about a None
# subject.
if subject is Non... | def is_ancestor_of(self, node, subject) | Returns ``True`` if the given `node` is an ancestor of the given
`subject` node, ``False`` otherwise. This method uses the
:attr:`path` virtual field, and so does not perform any query.
:param node: the :class:`CTENode' for which to determine whether it
is an ancesto... | 7.941826 | 7.488134 | 1.060588 |
return [visitor(c, attribute) or missing for c in node.ancestors()] + [
visitor(node, attribute) or missing
] | def attribute_path(
self,
node,
attribute,
missing=None,
visitor=lambda node, attribute: getattr(node, attribute, None),
) | Generates a list of values of the `attribute` of all ancestors of
the given `node` (as well as the node itself). If a value is
``None``, then the optional value of `missing` is used (by default
``None``).
By default, the ``getattr(node, attribute, None) or missing``
... | 6.32219 | 4.558347 | 1.386948 |
return [
root.as_tree(visitor=visitor, children=children) for root in self.roots()
] | def as_tree(self, visitor=None, children=None) | Recursively traverses each tree (starting from each root) in order
to generate a dictionary-based tree structure of the entire forest.
Each level of the forest/tree is a list of nodes, and each node
consists of a dictionary representation, where the entry
``children`` (by... | 5.338684 | 6.281133 | 0.849956 |
tree = visitor(self, node)
tree.update(children(self, node, visitor, children))
return tree | def node_as_tree(
self,
node,
visitor=lambda self, node: self._default_node_visitor(node),
children=lambda self, node, visitor, children: self._default_node_children(
node, visitor, children
),
) | Visits a :class:`CTENode` `node` and delegates to the (optional)
`visitor` callback, as well as the (optional) `children` callback,
in order to generate a dictionary representation of the node along
with its children nodes.
:param node: the :class:`CTENode` for which to ... | 4.123089 | 4.481135 | 0.920099 |
return {
"depth": getattr(node, node._cte_node_depth),
"path": [str(c) for c in getattr(node, node._cte_node_path)],
"ordering": getattr(node, node._cte_node_ordering),
"leaf": node.is_leaf(),
"branch": node.is_branch(),
"node": no... | def _default_node_visitor(self, node) | Generates a dictionary representation of the given :class:`CTENode`
`node`, which consists of the node itself under the key ``node``, as
well as structural information under the keys ``depth``, ``path``,
``ordering``, ``leaf``, and ``branch``.
:param node: the :class:`CTENode` for which... | 3.96576 | 2.675847 | 1.482058 |
return {
self.model._cte_node_children: [
self.node_as_tree(child, visitor=visitor, children=children)
for child in node.children.all()
]
} | def _default_node_children(self, node, visitor, children) | Generates a key and list of children of the given :class:`CTENode`
`node`, intended to be used as an update to the dictionary
representation generated by the :meth:`node_as_tree` method. The key is
``children`` and the list consists of the children of the given node as
determined by the ... | 6.329813 | 5.175842 | 1.222953 |
# empty path result in first root, if present
if len(path) == 0:
try:
return self.roots()[0]
except IndexError:
raise self.model.DoesNotExist
# bootstrap with the first component, then iterate through the remaining
# comp... | def drilldown(self, attributes, path) | Recursively descends the tree/forest (starting from each root node)
in order to find a :class:`CTENode` which corresponds to the given
`path`. The path is expected to be an iterable of tuples, called
path components, consisting of attribute values with which to filter
thr... | 5.099552 | 4.09075 | 1.246605 |
# If no delete method preference is specified, use attribute.
if method is None:
method = node._cte_node_delete_method
# If no preference specified, use default.
if method == self.DELETE_METHOD_NONE:
method = self.DEFAULT_DELETE_METHOD
# Delegate ... | def prepare_delete(self, node, method, position=None, save=True) | Prepares a given :class:`CTENode` `node` for deletion, by executing
the required deletion semantics (Pharaoh, Grandmother, or Monarchy).
The `method` argument can be one of the valid
:const:`DELETE_METHODS` choices. If it is
:const:`DELETE_METHOD_NONE` or ``None``, then ... | 4.833503 | 3.531389 | 1.368726 |
# Move all children to the node's parent.
for child in node.children.all():
child.move(node.parent, position, save) | def prepare_delete_grandmother(self, node, position=None, save=True) | Prepares a given :class:`CTENode` `node` for deletion, by executing
the :const:`DELETE_METHOD_GRANDMOTHER` semantics. Descendant nodes,
if present, will be moved; in this case the optional `position` can
be a ``callable`` which is invoked prior to each move operation (see
... | 4.670867 | 6.723911 | 0.694665 |
# We are going to iterate all children, even though the first child is
# treated in a special way, because the query iterator may be custom, so
# we will avoid using slicing children[0] and children[1:].
first = None
for child in node.children.all():
if first... | def prepare_delete_monarchy(self, node, position=None, save=True) | Prepares a given :class:`CTENode` `node` for deletion, by executing
the :const:`DELETE_METHOD_MONARCHY` semantics. Descendant nodes,
if present, will be moved; in this case the optional `position` can
be a ``callable`` which is invoked prior to each move operation (see
:m... | 7.740205 | 8.004509 | 0.966981 |
# Allow custom positioning semantics to specify the position before
# setting the parent.
if position is not None:
position(node, destination)
node.parent = destination
if save:
node.save()
return node | def move(self, node, destination, position=None, save=False) | Moves the given :class:`CTENode` `node` and places it as a child
node of the `destination` :class:`CTENode` (or makes it a root node
if `destination` is ``None``).
Optionally, `position` can be a callable which is invoked prior to
placement of the `node` with the `node` ... | 7.079061 | 6.303063 | 1.123114 |
super(CTENode, self).clean()
if self.parent and self.pk in getattr(self.parent, self._cte_node_path):
raise ValidationError(_("A node cannot be made a descendant of itself.")) | def clean(self) | Prevents cycles in the tree. | 8.9029 | 8.819777 | 1.009425 |
_parameters = {"node": self, "attribute": attribute}
if missing is not None:
_parameters["missing"] = missing
if visitor is not None:
_parameters["visitor"] = visitor
return self.__class__.objects.attribute_path(**_parameters) | def attribute_path(self, attribute, missing=None, visitor=None) | Generates a list of values of the `attribute` of all ancestors of
this node (as well as the node itself). If a value is ``None``, then
the optional value of `missing` is used (by default ``None``).
By default, the ``getattr(node, attribute, None) or missing``
mechanism i... | 2.782848 | 3.486202 | 0.798246 |
_parameters = {"node": self}
if visitor is not None:
_parameters["visitor"] = visitor
if children is not None:
_parameters["children"] = children
return self.__class__.objects.node_as_tree(**_parameters) | def as_tree(self, visitor=None, children=None) | Recursively traverses each tree (starting from each root) in order
to generate a dictionary-based tree structure of the entire forest.
Each level of the forest/tree is a list of nodes, and each node
consists of a dictionary representation, where the entry
``children`` (by... | 3.469332 | 3.860877 | 0.898587 |
return self.__class__.objects.move(self, destination, position, save) | def move(self, destination=None, position=None, save=False) | Moves this node and places it as a child node of the `destination`
:class:`CTENode` (or makes it a root node if `destination` is
``None``).
Optionally, `position` can be a callable which is invoked prior to
placement of the node with this node and the destination node as... | 4.912434 | 9.154823 | 0.536595 |
self.__class__.objects.prepare_delete(
self, method=method, position=position, save=save
)
return super(CTENode, self).delete() | def delete(self, method=None, position=None, save=True) | Prepares the tree for deletion according to the deletion semantics
specified for the :class:`CTENode` Model, and then delegates to the
:class:`CTENode` superclass ``delete`` method.
Default deletion `method` and `position` callable can be overridden
by being supplied as ... | 5.962684 | 5.103174 | 1.168427 |
if article_lookup is None:
return request.current_article
if isinstance(article_lookup, Article):
if hasattr(request, 'current_article') and request.current_article.pk == article_lookup.pk:
return request.current_article
return article_lookup
if isinstance(article_lo... | def _get_article_by_untyped_arg(article_lookup, request, site_id) | The `article_lookup` argument can be of any of the following types:
- Integer: interpreted as `pk` of the desired article
- `dict`: a dictionary containing keyword arguments to find the desired article
(for instance: `{'pk': 1}`)
- `Article`: you can also pass an Article object directly, in which case t... | 2.769862 | 2.678649 | 1.034052 |
'Build the parser and parse the arguments'
parser = argparse.ArgumentParser(
description='www.duckduckgo.com zero-click api for your command-line'
)
parser.add_argument('query', nargs='*', help='the search query')
parser.add_argument('-b', '--bang', action='store_true',
... | def main() | Controls the flow of the ddg application | 3.636898 | 3.62338 | 1.003731 |
redirect_mode = args.bang or args.search or args.lucky
if redirect_mode:
results_priority = ['redirect', 'result', 'abstract']
else:
results_priority = ['answer', 'abstract', 'result']
insert_pos = 0 if args.define else len(results_priority)
results_priority.insert(insert_pos,... | def get_results_priority(args) | Return a result priority list based on user input | 6.679597 | 6.48855 | 1.029444 |
redirect_mode = args.bang or args.search or args.lucky
if redirect_mode and not args.url:
return webbrowser.open_new_tab
else:
return print_result | def get_action(args) | Return a function to launch the web browser or print a result | 10.040827 | 5.970902 | 1.681626 |
redirect_mode = args.bang or args.search or args.lucky
if redirect_mode or args.url:
return 'url'
else:
return 'text' | def get_text_or_url(args) | Determine if we need text or url output | 9.216279 | 7.918013 | 1.163964 |
try:
print result
except UnicodeEncodeError:
if sys.stdout.encoding:
print result.encode(sys.stdout.encoding, 'replace')
else:
print result.encode('utf8')
except:
print "Unexpected error attempting to print result" | def print_result(result) | Print the result, ascii encode if necessary | 3.521317 | 3.066861 | 1.148183 |
token = spylunking.get_token.get_token(
url='https://{}'.format(
SPLUNK_API_ADDRESS))
log.info(token) | def run_main() | run_main | 16.825676 | 17.767664 | 0.946983 |
if self._check_db() == False:
return
try:
pmodels = self._tables()
if pmodels is None:
return
num = len(pmodels)
s = "s"
if num == 1:
s = ""
msg = "Found " + colors.bold(str(num))... | def tables(self) | Print the existing tables in a database
:example: ``ds.tables()`` | 3.986027 | 4.028337 | 0.989497 |
if self._check_db() == False:
return
try:
return self._tables()
except Exception as e:
self.err(e, "Can not print tables") | def tables_(self) -> list | Return a list of the existing tables in a database
:return: list of the table names
:rtype: list
:example: ``tables = ds.tables_()`` | 8.17369 | 9.132578 | 0.895004 |
if self._check_db() == False:
return
try:
res = self.getall(name)
except Exception as e:
self.err(e, self.table, "Can not get records from database")
return
if res is None:
self.warning("Table", name, "does not contain ... | def table(self, name: str) | Display info about a table: number of rows
and columns
:param name: name of the table
:type name: str
:example: ``tables = ds.table("mytable")`` | 5.562865 | 5.767137 | 0.96458 |
requested_expands = []
for key, val in request.params.items():
if key == query_key:
requested_expands += val.split(',')
return requested_expands | def parse_requested_expands(query_key, request) | Extracts the value of the expand query string parameter from a request.
Supports comma separated lists.
:param query_key: The name query string parameter.
:param request: Request instance.
:return: List of strings representing the values of the expand query string value. | 2.851707 | 2.867983 | 0.994325 |
query = super(ExpandableViewMixin, self).get_query()
expandable_fields = getattr(self, 'expandable_fields', [])
if expandable_fields:
requested_expands = parse_requested_expands(self.schema_class.QUERY_KEY, self.request)
if requested_expands:
a... | def get_query(self) | If you override this method do not forget to call ``super()``. | 3.168979 | 2.985284 | 1.061533 |
self.debug_log('emit - start')
try:
record = self.format_record(
record)
except Exception as e:
self.write_log(
'exception in Splunk logging handler: %s' % str(e))
self.write_log(
traceback.format_exc()... | def emit(
self,
record) | emit
Emit handler for queue-ing message for
the helper thread to send to Splunk on the ``self.sleep_interval``
:param record: LogRecord to send to Splunk
https://docs.python.org/3/library/logging.html | 4.754406 | 4.420328 | 1.075578 |
# Start a worker thread responsible for sending logs
if not self.is_shutting_down(shutdown_event=self.shutdown_event) \
and self.sleep_interval > 0.1:
self.processes = []
self.debug_log(
'start_worker - start multiprocessing.Process')
... | def start_worker(
self) | start_worker
Start the helper worker process to package queued messages
and send them to Splunk | 3.425926 | 3.581561 | 0.956546 |
self.debug_log((
'perform_work - start'))
# Handle CTRL + C
signal.signal(
signal.SIGINT,
signal.SIG_IGN)
self.debug_log((
'perform_work - ready'))
try:
not_done = not self.is_shutting_down(
... | def perform_work(
self,
use_queue,
shutdown_event,
shutdown_ack_event,
already_done_event) | perform_work
Process handler function for processing messages
found in the ``multiprocessing.Manager.queue``
Build the ``self.log_payload`` from the queued log messages
and POST it to the Splunk endpoint
:param use_queue: multiprocessing.Queue - queue holding the messages
... | 2.753668 | 2.662965 | 1.034061 |
not_done = True
while not_done:
if self.is_shutting_down(
shutdown_event=shutdown_event):
self.debug_log(
'build_payload shutting down')
return True
self.debug_log('reading from queue={}'.format(
... | def build_payload_from_queued_messages(
self,
use_queue,
shutdown_event) | build_payload_from_queued_messages
Empty the queued messages by building a large ``self.log_payload``
:param use_queue: queue holding the messages
:param shutdown_event: shutdown event | 3.365031 | 3.333927 | 1.009329 |
self.debug_log('force flush requested')
self.perform_work(
self.queue,
self.shutdown_event,
self.shutdown_ack,
self.already_done) | def force_flush(
self) | force_flush
Flush the queue and publish everything to Splunk | 10.305204 | 9.942741 | 1.036455 |
self.debug_log(
'close - start shutdown')
self.shutdown()
logging.Handler.close(self)
self.debug_log(
'close - handler join on processes={}'.format(
len(self.processes)))
self.debug_log(
'close - done') | def close(self) | close | 8.001776 | 7.626961 | 1.049143 |
# Only initiate shutdown once
if self.is_shutting_down(
shutdown_event=self.shutdown_event):
self.debug_log('shutdown - still shutting down')
return
else:
self.debug_log('shutdown - start - setting instance shutdown')
self... | def shutdown(
self) | shutdown | 5.765104 | 5.731925 | 1.005788 |
'''
Delete a device.
\b
DOES:
Delete a device.
sn: device_sn
wio delete <device_sn>
\b
EXAMPLE:
wio delete 2885b2cab8abc5fb8e229e4a77bf5e4d
'''
user_token = wio.config.get("token", None)
api_prefix = wio.config.get("mserver", None)
if not api_pre... | def cli(wio, sn) | Delete a device.
\b
DOES:
Delete a device.
sn: device_sn
wio delete <device_sn>
\b
EXAMPLE:
wio delete 2885b2cab8abc5fb8e229e4a77bf5e4d | 3.828947 | 2.495663 | 1.53424 |
methodnamehyphen = methodname.replace('_', '-')
ret = format_string
ret = ret.replace('{methodname}', methodname)
ret = ret.replace('{methodnamehyphen}', methodnamehyphen)
return ret | def replace_methodname(format_string, methodname) | Partially format a format_string, swapping out any '{methodname}' or '{methodnamehyphen}' components. | 2.932807 | 2.026434 | 1.447275 |
lookup = self.get_lookup(viewset)
routes = self.get_routes(viewset)
for route in routes:
# Only actions which actually exist on the viewset will be bound
mapping = self.get_method_map(viewset, route.mapping)
if not mapping:
continue... | def register(self, prefix, viewset, basename, factory=None, permission=None) | Factory and permission are likely only going to exist until I have enough time
to write a permissions module for PRF.
:param prefix: the uri route prefix.
:param viewset: The ViewSet class to route.
:param basename: Used to name the route in pyramid.
:param factory: Optional, ro... | 2.854232 | 2.943056 | 0.969819 |
known_actions = list(flatten([route.mapping.values() for route in self.routes if isinstance(route, Route)]))
# Determine any `@detail_route` or `@list_route` decorated methods on the viewset
detail_routes = []
list_routes = []
for methodname in dir(viewset):
... | def get_routes(self, viewset) | Augment `self.routes` with any dynamically generated routes.
Returns a list of the Route namedtuple. | 2.730171 | 2.682355 | 1.017826 |
bound_methods = {}
for method, action in method_map.items():
if hasattr(viewset, action):
bound_methods[method] = action
return bound_methods | def get_method_map(self, viewset, method_map) | Given a viewset, and a mapping of http methods to actions, return a new mapping which only
includes any mappings that are actually implemented by the viewset. | 3.602511 | 2.703509 | 1.332532 |
self.set_header('Allow', ', '.join(self.ALLOW))
self.set_status(204)
self.finish() | def options(self, *args, **kwargs) | Implement the HTTP OPTIONS method
:param list args: Positional arguments
:param dict kwargs: Keyword arguments | 4.161756 | 3.238294 | 1.285169 |
super(RequestHandler, self).prepare()
if self.request.headers.get('content-type', '').startswith(self.JSON):
self.request.body = escape.json_decode(self.request.body) | def prepare(self) | Prepare the incoming request, checking to see the request is sending
JSON content in the request body. If so, the content is decoded and
assigned to the json_arguments attribute. | 4.289848 | 3.210617 | 1.336145 |
if self._finished:
raise RuntimeError("Cannot write() after finish(). May be caused "
"by using async operations without the "
"@asynchronous decorator.")
if isinstance(chunk, dict):
options = {'ensure_ascii'... | def write(self, chunk) | Writes the given chunk to the output buffer. Checks for curl in the
user-agent and if set, provides indented output if returning JSON.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and set
the Content-Type of t... | 4.534606 | 4.112095 | 1.102748 |
super(SessionRequestHandler, self).on_finish()
LOGGER.debug('Entering SessionRequestHandler.on_finish: %s',
self.session.id)
self.session.last_request_at = self.current_epoch()
self.session.last_request_uri = self.request.uri
if self.session.dirty:
... | def on_finish(self) | Called by Tornado when the request is done. Update the session data
and remove the session object. | 3.715189 | 3.260638 | 1.139406 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.