code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
value = value.lower()
if value in _true_strings:
return True
elif value in _false_strings:
return False
else:
return None | def _parse_boolean(value) | Coerce value into an bool.
:param str value: Value to parse.
:returns: bool or None if the value is not a boolean string. | 2.463654 | 3.1934 | 0.771483 |
value = value.lstrip()
if not value or value[0] not in _brace_strings:
return None
return json.loads(value) | def _parse_object(value) | Coerce value into a dict.
:param str value: Value to parse.
:returns: dict or None if the value is not a JSON object
:raises: TypeError or ValueError if value appears to be an object but can't
be parsed as JSON. | 6.153571 | 7.019373 | 0.876655 |
if not isinstance(value, str):
raise ValueError('value for %r must be a string' % name)
if isinstance(allowed_types, str):
allowed_types = [allowed_types]
# Note that the order of these type considerations is important. Because we
# have an untyped value that may be one of any give... | def parse_value(value, allowed_types, name='value') | Parse a value into one of a number of types.
This function is used to coerce untyped HTTP parameter strings into an
appropriate type. It tries to coerce the value into each of the allowed
types, and uses the first that evaluates properly.
Because this is coercing a string into multiple, potentially am... | 4.302944 | 4.167763 | 1.032435 |
try:
loaded = json.loads(value)
except Exception as e:
message = 'Error parsing JSON: %r error: %s' % (value, e)
logging.debug(message, exc_info=e)
raise ParseError(message)
if sig_params is not None:
return map_param_names(loaded, sig_params)
return loaded | def parse_json(value: str, sig_params: List[inspect.Parameter] = None) -> dict | Parse a value as JSON.
This is just a wrapper around json.loads which re-raises any errors as a
ParseError instead.
:param str value: JSON string.
:param dict sig_params: The logic function's signature parameters.
:returns: the parsed JSON value | 3.44752 | 3.569243 | 0.965897 |
new_request_params = {}
for k, param in sig_params.items():
param_name = getattr(param.annotation, 'param_name', None)
key = k if param_name is None else param_name
if key in req_params:
new_request_params[k] = req_params[key]
return new_request_params | def map_param_names(
req_params: dict, sig_params: List[inspect.Parameter]) -> dict | Maps request param names to match logic function param names.
If a doctor type defined a `param_name` attribute for the name of the
parameter in the request, we should use that as the key when looking up
the value for the request parameter.
When we declare a type we can specify what the parameter name... | 2.818531 | 2.356699 | 1.195965 |
# Importing here to prevent circular dependencies.
from doctor.types import SuperType, UnionType
errors = {}
parsed_params = {}
for param, value in req_params.items():
# Skip request variables not in the function signature.
if param not in sig_params:
continue
... | def parse_form_and_query_params(req_params: dict, sig_params: dict) -> dict | Uses the parameter annotations to coerce string params.
This is used for HTTP requests, in which the form parameters are all
strings, but need to be converted to the appropriate types before
validating them.
:param dict req_params: The parameters specified in the request.
:param dict sig_params: T... | 3.05362 | 2.891834 | 1.055946 |
headers = self.request.headers
message = None
try:
status_code, output = process_async_task(
headers, self.request.body)
except AbortAndRestart as restart:
# Async retry status code
status_code = 549
message = 'Ret... | def _handle_task(self) | Pass request info to the async framework. | 6.256602 | 5.501166 | 1.137323 |
mapping = {}
for resource in autoload_details.resources:
resource.model = "{shell_name}.{model}".format(shell_name=shell_name, model=resource.model)
mapping[resource.relative_address] = resource.model
for attribute in autoload_details.attributes:
if not attribute.relative_add... | def migrate_autoload_details(autoload_details, shell_name, shell_type) | Migrate autoload details. Add namespace for attributes
:param autoload_details:
:param shell_name:
:param shell_type:
:return: | 2.628229 | 2.653601 | 0.990438 |
result = GenericFirewallResource(shell_name=shell_name, name=context.resource.name, supported_os=supported_os)
result.address = context.resource.address
result.family = context.resource.family
result.fullname = context.resource.fullname
result.attributes = dict(context.resource.attributes)
... | def create_firewall_resource_from_context(shell_name, supported_os, context) | Creates an instance of Firewall Resource by given context
:param shell_name: Shell Name
:type shell_name: str
:param supported_os: list of supported OS
:type supported_os: list
:param context: cloudshell.shell.core.driver_context.ResourceCommandContext
:type context: cloudshell.shell.core.driver... | 3.592572 | 3.50567 | 1.024789 |
for type_, method in self._map.items():
if type(self.value) is bool and type_ is not bool:
continue
if isinstance(self.value, type_):
return method
if is_sql_instance(self.value):
return self._raw
return self._undefined | def _get_convert_method(self) | Get right method to convert of the value. | 5.863045 | 5.114779 | 1.146295 |
n = rho.shape[0]
idx = np.triu_indices(n, k=1)
tab = pd.DataFrame(
columns=['i', 'j', 'cor', 'pval'],
data=np.c_[idx[0], idx[1], rho[idx], pval[idx]])
tab[['i', "j"]] = tab[['i', "j"]].astype(int)
if sortby == "cor":
tab['abscor'] = np.abs(tab['cor'])
tab.sort... | def flatten(rho, pval, sortby="cor") | Flatten correlation and p-value matrix
Parameters:
-----------
rho : ndarray
Correlation Matrix
pval : ndarray
Matrix with p-values
sortby : str
sort the output table by
- "cor" the highest absolute correlation coefficient
- "pval" the lowest p-value
... | 2.12946 | 2.11967 | 1.004619 |
if self.signed:
v = (1 << (self.bits - 1)) - 1
else:
v = (1 << self.bits) - 1
if self.lsb0:
v = v - (v % 2)
return v | def max(self) -> int | Get the maximum value this immediate can have
:return: Maximum value of this immediate | 3.585401 | 3.620345 | 0.990348 |
if not isinstance(value, int):
raise self.exception("{} is not an integer".format(value))
if self.lsb0 and self.value % 2 == 1:
raise self.exception("{} not power of two".format(value))
if not self.signed and value < 0:
raise self.exception("{} cannot... | def set(self, value: int) | Set the immediate to a value. This function checks if the value is valid and will raise an
:class:`InvalidImmediateException` if it doesn't.
:param value: Value to set the immediate to
:type value: int
:raises InvalidImmediateException: value does not match immediate | 2.88649 | 3.136908 | 0.920171 |
if self.signed:
value = -(value & self.tcmask) + (value & ~self.tcmask)
self.set(value) | def set_from_bits(self, value: int) | Set the immediate value from machine code bits. Those are not sign extended, so it will take care of the
proper handling.
:param value: Value to set the immediate to
:type value: int | 8.706999 | 8.848577 | 0.984 |
self.value = randint(self.min(), self.max())
if self.lsb0:
self.value = self.value - (self.value % 2) | def randomize(self) | Randomize this immediate to a legal value | 5.722857 | 5.235586 | 1.093069 |
# If there is a context and it is initialized to this request,
# return, otherwise reinitialize the _local_context.
if (hasattr(_local_context, '_initialized') and
_local_context._initialized == os.environ.get('REQUEST_ID_HASH')):
return
# Used to track the context object stack... | def _init() | Initialize the furious context and registry.
NOTE: Do not directly run this method. | 5.982511 | 5.831449 | 1.025905 |
async = get_current_async()
async_options = async.get_options()
job = async_options.get('job')
if not job:
raise Exception('This async contains no job to execute!')
__, args, kwargs = job
if args is None:
args = ()
if kwargs is None:
kwargs = {}
function... | def run_job() | Takes an async object and executes its job. | 4.930847 | 4.640378 | 1.062596 |
results_processor = options.get('_process_results')
if not results_processor:
results_processor = _process_results
processor_result = results_processor()
if isinstance(processor_result, (Async, Context)):
processor_result.start() | def _handle_results(options) | Process the results of executing the Async's target. | 5.778298 | 4.810402 | 1.201209 |
import sys
return AsyncException(unicode(exception),
exception.args,
sys.exc_info(),
exception) | def encode_exception(exception) | Encode exception to a form that can be passed around and serialized.
This will grab the stack, then strip off the last two calls which are
encode_exception and the function that called it. | 12.652115 | 15.371492 | 0.82309 |
async = get_current_async()
callbacks = async.get_callbacks()
if not isinstance(async.result.payload, AsyncException):
callback = callbacks.get('success')
else:
callback = callbacks.get('error')
if not callback:
raise async.result.payload.exception, None, \
... | def _process_results() | Process the results from an Async job. | 5.778343 | 5.048697 | 1.144522 |
from furious.async import Async
if not callback:
return async.result.payload
if isinstance(callback, Async):
return callback.start()
return callback() | def _execute_callback(async, callback) | Execute the given callback or insert the Async callback, or if no
callback is given return the async.result. | 9.874873 | 6.393387 | 1.544545 |
from random import choice
states = ['ALPHA', 'BRAVO', 'BRAVO', 'DONE']
if last_state:
states.remove(last_state) # Slightly lower chances of previous state.
state = choice(states)
logging.info('Generating a state... %s', state)
return state | def complex_state_generator_bravo(last_state='') | Pick a state. | 6.642621 | 5.945059 | 1.117335 |
from furious.async import Async
from furious.context import get_current_async
result = get_current_async().result
if result == 'ALPHA':
logging.info('Inserting continuation for state %s.', result)
return Async(target=complex_state_generator_alpha, args=[result])
elif result =... | def state_machine_success() | A positive result! Iterate! | 5.552678 | 5.381887 | 1.031734 |
parts = ['curl {}'.format(pipes.quote(url))]
parts.append('-X {}'.format(method))
for header in headers:
parts.append("-H '{}: {}'".format(header, headers[header]))
if method not in ('DELETE', 'GET'):
# Don't append a json body if there are no params.
if params:
... | def get_example_curl_lines(method: str, url: str, params: dict,
headers: dict) -> List[str] | Render a cURL command for the given request.
:param str method: HTTP request method (e.g. "GET").
:param str url: HTTP request URL.
:param dict params: JSON body, for POST and PUT requests.
:param dict headers: A dict of HTTP headers.
:returns: list | 2.743793 | 2.820395 | 0.97284 |
lines = ['', 'Example Request:', '', '.. code-block:: bash', '']
lines.extend(prefix_lines(
get_example_curl_lines(method, url, params, headers), ' '))
lines.extend(['', 'Example Response:', ''])
try:
# Try to parse and prettify the response as JSON. If it fails
# (for wha... | def get_example_lines(headers: Dict[str, str], method: str, url: str,
params: Dict[str, Any], response: str) -> List[str] | Render a reStructuredText example for the given request and response.
:param dict headers: A dict of HTTP headers.
:param str method: HTTP request method (e.g. "GET").
:param str url: HTTP request URL.
:param dict params: Form parameters, for POST and PUT requests.
:param str response: Text respons... | 3.102771 | 3.407481 | 0.910576 |
resource_name = obj.title
if resource_name is None:
class_name = obj.__name__
resource_name = class_name_to_resource_name(class_name)
ALL_RESOURCES[resource_name] = obj
return ' See :ref:`resource-{}`.'.format(
'-'.join(resource_name.split(' ')).lower().strip()) | def get_object_reference(obj: Object) -> str | Gets an object reference string from the obj instance.
This adds the object type to ALL_RESOURCES so that it gets documented and
returns a str which contains a sphinx reference to the documented object.
:param obj: The Object instance.
:returns: A sphinx docs reference str. | 5.569459 | 4.704066 | 1.183967 |
desc = ''
if isinstance(item.items, list):
# This means the type has a list of types where each position is
# mapped to a different type. Document what each type should be.
desc = ''
item_pos_template = (
' *Item {pos} must be*: {description}{enum}{ref}')
... | def get_array_items_description(item: Array) -> str | Returns a description for an array's items.
:param item: The Array type whose items should be documented.
:returns: A string documenting what type the array's items should be. | 2.971883 | 2.8214 | 1.053336 |
types = []
if issubclass(annotated_type, UnionType):
types = [str(t.native_type.__name__) for t in annotated_type.types]
elif issubclass(annotated_type, Array):
# Include the type of items in the list if items is defined.
if annotated_type.items is not None:
if not i... | def get_json_types(annotated_type: SuperType) -> List[str] | Returns the json types for the provided annotated type.
This handles special cases for when we encounter UnionType and an Array.
UnionType's will have all valid types returned. An Array will document
what the items type is by placing that value in brackets, e.g. `list[str]`.
:param annotated_type: A ... | 2.6746 | 2.603541 | 1.027293 |
sig_params = annotation.logic._doctor_signature.parameters
required_lines = []
lines = []
default_field = field
for prop in sorted(properties.keys()):
annotated_type = properties[prop]
# If the property is a url parameter override the field to use
# param so that it's no... | def get_json_object_lines(annotation: ResourceAnnotation,
properties: Dict[str, Any], field: str,
url_params: Dict, request: bool = False,
object_property: bool = False) -> List[str] | Generate documentation for the given object annotation.
:param doctor.resource.ResourceAnnotation annotation:
Annotation object for the associated handler method.
:param str field: Sphinx field type to use (e.g. '<json').
:param list url_params: A list of url parameter strings.
:param bool requ... | 3.752351 | 3.683149 | 1.018789 |
url_params = URL_PARAMS_RE.findall(route)
if not request:
return_type = annotation.logic._doctor_signature.return_annotation
# Check if our return annotation is a Response that supplied a
# type we can use to document. If so, use that type for api docs.
# e.g. def logic() -... | def get_json_lines(annotation: ResourceAnnotation, field: str, route: str,
request: bool = False) -> List | Generate documentation lines for the given annotation.
This only documents schemas of type "object", or type "list" where each
"item" is an object. Other types are ignored (but a warning is logged).
:param doctor.resource.ResourceAnnotation annotation:
Annotation object for the associated handler ... | 4.712682 | 4.528541 | 1.040662 |
# First loop through all resources and make sure to add any properties that
# are objects and not already in `ALL_RESOURCES`. We iterate over a copy
# since we will be modifying the dict during the loop.
for resource_name, a_type in ALL_RESOURCES.copy().items():
for prop_a_type in a_type.... | def get_resource_object_doc_lines() -> List[str] | Generate documentation lines for all collected resource objects.
As API documentation is generated we keep a running list of objects used
in request parameters and responses. This section will generate
documentation for each object and provide an inline reference in the API
documentation.
:return... | 2.509468 | 2.456633 | 1.021507 |
if value.__module__ == '__builtin__':
return value.__name__
else:
return '.'.join((value.__module__, value.__name__)) | def get_name(value) -> str | Return a best guess at the qualified name for a class or function.
:param value: A class or function object.
:type value: class or function
:returns str: | 3.827245 | 3.070626 | 1.246405 |
normalized_route = str(route).lstrip('^').rstrip('$').rstrip('?')
normalized_route = normalized_route.replace('<', '(').replace('>', ')')
return normalized_route | def normalize_route(route: str) -> str | Strip some of the ugly regexp characters from the given pattern.
>>> normalize_route('^/user/<user_id:int>/?$')
u'/user/(user_id:int)/' | 4.695394 | 5.538741 | 0.847737 |
if isinstance(lines, bytes):
lines = lines.decode('utf-8')
if isinstance(lines, str):
lines = lines.splitlines()
return [prefix + line for line in lines] | def prefix_lines(lines, prefix) | Add the prefix to each of the lines.
>>> prefix_lines(['foo', 'bar'], ' ')
[' foo', ' bar']
>>> prefix_lines('foo\\nbar', ' ')
[' foo', ' bar']
:param list or str lines: A string or a list of strings. If a string is
passed, the string is split using splitlines().
:param str prefi... | 2.18495 | 2.589713 | 0.843704 |
s = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', class_name)
return re.sub('([a-z0-9])([A-Z])', r'\1 \2', s) | def class_name_to_resource_name(class_name: str) -> str | Converts a camel case class name to a resource name with spaces.
>>> class_name_to_resource_name('FooBarObject')
'Foo Bar Object'
:param class_name: The name to convert.
:returns: The resource name. | 2.078894 | 2.241091 | 0.927626 |
# Track places where we use this directive, so we can check for
# outdated documents in the future.
state = DirectiveState()
setattr(env, self.directive_name, state)
else:
state = getattr(env, self.directive_name)
return env, state | def _prepare_env(self): # pragma: no cover
env = self.state.document.settings.env
if not hasattr(env, self.directive_name) | Setup the document's environment, if necessary. | 6.50182 | 6.138009 | 1.059272 |
# Set the route and handler as attributes so we can retrieve them
# when we loop through them all below.
for annotation in annotations:
annotation.route = route
annotation.handler = handler
heading_to_annotations_map[heading].append(ann... | def _render_rst(self): # pragma: no cover
# Create a mapping of headers to annotations. We want to group
# all annotations by a header, but they could be in multiple handlers
# so we create a map of them here with the heading as the key and
# the list of associated annotations... | Render lines of reStructuredText for items yielded by
:meth:`~doctor.docs.base.BaseHarness.iter_annotations`. | 4.223567 | 4.205728 | 1.004242 |
raise NotImplementedError('directive_name must be implemented by '
'subclasses of BaseDirective')
env, state = self._prepare_env()
state.doc_names.add(env.docname)
directive_name = '<{}>'.format(self.directive_name)
node = nodes.section()... | def run(self): # pragma: no cover
if self.directive_name is None | Called by Sphinx to generate documentation for this directive. | 4.289687 | 3.982859 | 1.077037 |
# This is stupid for now, and always says everything that uses
# this autodoc generation needs to be updated. We should make this
# smarter at some point and actually figure out what modules are
# touched, and whether they have been changed.
return sorted(stat... | def get_outdated_docs(
cls, app, env, added, changed, removed): # pragma: no cover
state = getattr(env, cls.directive_name, None)
if state and state.doc_names | Handler for Sphinx's env-get-outdated event.
This handler gives a Sphinx extension a chance to indicate that some
set of documents are out of date and need to be re-rendered. The
implementation here is stupid, for now, and always says that anything
that uses the directive needs to be re... | 15.839437 | 10.576545 | 1.4976 |
state.doc_names.remove(docname) | def purge_docs(cls, app, env, docname): # pragma: no cover
state = getattr(env, cls.directive_name, None)
if state and docname in state.doc_names | Handler for Sphinx's env-purge-doc event.
This event is emitted when all traces of a source file should be cleaned
from the environment (that is, if the source file is removed, or before
it is freshly read). This is for extensions that keep their own caches
in attributes of the environm... | 12.134736 | 11.04581 | 1.098583 |
raise NotImplementedError('directive_name must be set by '
'subclasses of BaseDirective')
if not app.registry.has_domain('http'):
setup_httpdomain(app)
app.add_config_value('{}_harness'.format(cls.directive_name),
... | def setup(cls, app): # pragma: no cover
if cls.directive_name is None | Called by Sphinx to setup an extension. | 3.199208 | 2.903644 | 1.10179 |
self.defined_header_values[(http_method.lower(), route)] = {
'update': update,
'values': values
} | def define_header_values(self, http_method, route, values, update=False) | Define header values for a given request.
By default, header values are determined from the class attribute
`headers`. But if you want to change the headers used in the
documentation for a specific route, this method lets you do that.
:param str http_method: An HTTP method, like "get".... | 3.946803 | 5.935217 | 0.66498 |
self.defined_example_values[(http_method.lower(), route)] = {
'update': update,
'values': values
} | def define_example_values(self, http_method, route, values, update=False) | Define example values for a given request.
By default, example values are determined from the example properties
in the schema. But if you want to change the example used in the
documentation for a specific route, and this method lets you do that.
:param str http_method: An HTTP method... | 3.969928 | 5.638187 | 0.704114 |
if hasattr(handler, '_doctor_heading'):
return handler._doctor_heading
heading = ''
handler_path = str(handler)
try:
handler_file_name = handler_path.split('.')[-2]
except IndexError:
# In the event there is no path and we just have t... | def _get_annotation_heading(self, handler, route, heading=None) | Returns the heading text for an annotation.
Attempts to get the name of the heading from the handler attribute
`schematic_title` first.
If `schematic_title` it is not present, it attempts to generate
the title from the class path.
This path: advertiser_api.handlers.foo_bar.FooL... | 4.074321 | 3.726673 | 1.093286 |
headers = self.headers.copy()
defined_header_values = self.defined_header_values.get(
(annotation.http_method.lower(), str(route)))
if defined_header_values is not None:
if defined_header_values['update']:
headers.update(defined_header_values['val... | def _get_headers(self, route: str, annotation: ResourceAnnotation) -> Dict | Gets headers for the provided route.
:param route: The route to get example values for.
:type route: werkzeug.routing.Rule for a flask api.
:param annotation: Schema annotation for the method to be requested.
:type annotation: doctor.resource.ResourceAnnotation
:retruns: A dict ... | 3.149228 | 3.248255 | 0.969514 |
defined_values = self.defined_example_values.get(
(annotation.http_method.lower(), str(route)))
if defined_values and not defined_values['update']:
return defined_values['values']
# If we defined a req_obj_type for the logic, use that type's
# example va... | def _get_example_values(self, route: str,
annotation: ResourceAnnotation) -> Dict[str, Any] | Gets example values for all properties in the annotation's schema.
:param route: The route to get example values for.
:type route: werkzeug.routing.Rule for a flask api.
:param annotation: Schema annotation for the method to be requested.
:type annotation: doctor.resource.ResourceAnnota... | 4.10848 | 3.988136 | 1.030176 |
try:
with open(file_name, "rb") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=delimiter)
for row in csv_reader:
if len(row) >= 2 and row[0] == sys_obj_id:
return row[1]
except IOError:
pass # file does not exists
... | def get_device_name(file_name, sys_obj_id, delimiter=":") | Get device name by its SNMP sysObjectID property from the file map
:param str file_name:
:param str sys_obj_id:
:param str delimiter:
:rtype: str | 1.972774 | 2.16768 | 0.910086 |
if super().has(querypart_name, value):
return True
if not value:
return super().has('select_options', querypart_name)
return False | def has(self, querypart_name, value=None) | Returns ``True`` if ``querypart_name`` with ``value`` is set. For example
you can check if you already used condition by ``sql.has('where')``.
If you want to check for more information, for example if that condition
also contain ID, you can do this by ``sql.has('where', 'id')``. | 4.711666 | 5.484674 | 0.85906 |
self._group_by.group_by(*args, **kwds)
return self | def group_by(self, *args, **kwds) | Default ordering is ``ASC``.
``group_by`` accept ``dict`` as you would expect, but note that ``dict``
does not have same order. Same for named arguments.
.. code-block:: python
>>> sqlpuzzle.select('c').from_('t').group_by('a', ('b', 'desc'))
<Select: SELECT "c" FROM "... | 4.793689 | 14.64256 | 0.327381 |
self._order_by.order_by(*args, **kwds)
return self | def order_by(self, *args, **kwds) | Default ordering is ``ASC``.
``order_by`` accept ``dict`` as you would expect, but note that ``dict``
does not have same order.
.. code-block:: python
>>> sqlpuzzle.select('c').from_('t').order_by('a', ('b', 'desc'))
<Select: SELECT "c" FROM "t" ORDER BY "a", "b" DESC> | 4.562574 | 11.5577 | 0.394765 |
logging.info('Context %s is.......... DONE.', context_id)
from furious.context import get_current_async_with_context
_, context = get_current_async_with_context()
if not context:
logging.error("Could not load context")
return
for task_id, result in context.result.items():
... | def context_complete(context_id) | Log out that the context is complete. | 5.75953 | 5.847867 | 0.984894 |
from furious.batcher import bump_batch
from furious.batcher import MESSAGE_DEFAULT_QUEUE
from furious.batcher import MessageIterator
from furious.batcher import MessageProcessor
from google.appengine.api import memcache
# since we don't have a flag for checking complete we'll re-insert a
... | def process_messages(tag, retries=0) | Processes the messages pulled fromm a queue based off the tag passed in.
Will insert another processor if any work was processed or the retry count
is under the max retry count. Will update a aggregated stats object with
the data in the payload of the messages processed.
:param tag: :class: `str` Tag t... | 6.164345 | 6.040758 | 1.020459 |
stats["total_count"] += 1
stats["value"] += value
stats["average"] = stats["value"] / stats["total_count"]
# this is just a basic example and not the best way to track aggregation.
# for max and min old there are cases where this will not work correctly.
if value > stats["max"]:
st... | def set_stats(stats, value) | Updates the stats with the value passed in.
:param stats: :class: `dict`
:param value: :class: `int` | 4.84163 | 5.330418 | 0.908302 |
default_stats = {
"total_count": 0,
"max": 0,
"min": 0,
"value": 0,
"average": 0,
"last_update": None,
}
return {
"totals": default_stats,
"colors": {
"red": default_stats.copy(),
"blue": default_stats.copy(),
... | def get_default_stats() | Returns a :class: `dict` of the default stats structure. | 2.601753 | 2.472209 | 1.0524 |
json = jsonpickle.encode(result, unpicklable=unpicklable)
result_for_output = str(json)
return result_for_output | def serialize_to_json(result, unpicklable=False) | Serializes output as JSON and writes it to console output wrapped with special prefix and suffix
:param result: Result to return
:param unpicklable: If True adds JSON can be deserialized as real object.
When False will be deserialized as dictionary | 4.210572 | 5.339782 | 0.788529 |
if hasattr(self.resource_config, "vrf_management_name"):
vrf_management_name = vrf_management_name or self.resource_config.vrf_management_name
self._validate_configuration_type(configuration_type)
folder_path = self.get_path(folder_path)
system_name = re.sub('\s+',... | def save(self, folder_path='', configuration_type='running', vrf_management_name=None, return_artifact=False) | Backup 'startup-config' or 'running-config' from device to provided file_system [ftp|tftp]
Also possible to backup config to localhost
:param folder_path: tftp/ftp server where file be saved
:param configuration_type: type of configuration that will be saved (StartUp or Running)
:param ... | 2.842414 | 2.692384 | 1.055724 |
if hasattr(self.resource_config, "vrf_management_name"):
vrf_management_name = vrf_management_name or self.resource_config.vrf_management_name
self._validate_configuration_type(configuration_type)
path = self.get_path(path)
self.restore_flow.execute_flow(path=path,... | def restore(self, path, configuration_type="running", restore_method="override", vrf_management_name=None) | Restore configuration on device from provided configuration file
Restore configuration from local file system or ftp/tftp server into 'running-config' or 'startup-config'.
:param path: relative path to the file on the remote host tftp://server/sourcefile
:param configuration_type: the configurat... | 2.607371 | 2.823997 | 0.923291 |
save_params = {'folder_path': '', 'configuration_type': 'running', 'return_artifact': True}
params = dict()
if custom_params:
params = jsonpickle.decode(custom_params)
save_params.update(params.get('custom_params', {}))
save_params['folder_path'] = self.get... | def orchestration_save(self, mode="shallow", custom_params=None) | Orchestration Save command
:param mode:
:param custom_params: json with all required action to configure or remove vlans from certain port
:return Serialized OrchestrationSavedArtifact to json
:rtype json | 3.930322 | 3.942415 | 0.996933 |
if saved_artifact_info is None or saved_artifact_info == '':
raise Exception('ConfigurationOperations', 'saved_artifact_info is None or empty')
saved_artifact_info = JsonRequestDeserializer(jsonpickle.decode(saved_artifact_info))
if not hasattr(saved_artifact_info, 'saved_... | def orchestration_restore(self, saved_artifact_info, custom_params=None) | Orchestration restore
:param saved_artifact_info: json with all required data to restore configuration on the device
:param custom_params: custom parameters | 2.891752 | 2.899183 | 0.997437 |
if not path:
host = self.resource_config.backup_location
if ':' not in host:
scheme = self.resource_config.backup_type
if not scheme or scheme.lower() == self.DEFAULT_FILE_SYSTEM.lower():
scheme = self.file_system
... | def get_path(self, path='') | Validate incoming path, if path is empty, build it from resource attributes,
If path is invalid - raise exception
:param path: path to remote file storage
:return: valid path or :raise Exception: | 4.045675 | 3.872345 | 1.044761 |
if configuration_type.lower() != 'running' and configuration_type.lower() != 'startup':
raise Exception(self.__class__.__name__, 'Configuration Type is invalid. Should be startup or running') | def _validate_configuration_type(self, configuration_type) | Validate configuration type
:param configuration_type: configuration_type, should be Startup or Running
:raise Exception: | 5.394068 | 3.821884 | 1.411364 |
is_fail = False
fail_attribute = ''
for class_attribute in self.REQUIRED_SAVE_ATTRIBUTES_LIST:
if type(class_attribute) is tuple:
if not hasattr(saved_config, class_attribute[0]):
is_fail = True
fail_attribute = class_a... | def _validate_artifact_info(self, saved_config) | Validate OrchestrationSavedArtifactInfo object for key components
:param OrchestrationSavedArtifactInfo saved_config: object to validate | 2.913898 | 2.815137 | 1.035082 |
'''Adds resolver to global container'''
get_current_scope().container.register(key, initializer, param) | def register(key, initializer: callable, param=None) | Adds resolver to global container | 19.08317 | 8.469396 | 2.253191 |
'''Generates resolver to return singleton value and adds it to global container'''
get_current_scope().container.register(key, lambda: value, param) | def register_single(key, value, param=None) | Generates resolver to return singleton value and adds it to global container | 22.954363 | 6.602087 | 3.476835 |
'''Wraps function with scope. If scope_name is None current scope is used'''
if scope_name is None:
scope_name = get_current_scope().name
return lambda *args, scope=scope_name, **kwargs: \
_call_with_scope(func, scope, args, kwargs) | def wrap_with_scope(func, scope_name=None) | Wraps function with scope. If scope_name is None current scope is used | 3.385696 | 2.745437 | 1.233209 |
'''Resolves dependencies using global container and passed it with optional parameters'''
def _decorate(func):
def _decorated(*args, **kwargs):
args = list(args)
keys_to_inject = [name for name in injections if name not in kwargs]
for key in keys_to_inject:
... | def inject(*injections) | Resolves dependencies using global container and passed it with optional parameters | 4.19182 | 2.731339 | 1.534713 |
'''Add resolver to container'''
if not callable(initializer):
raise DependencyError('Initializer {0} is not callable'.format(initializer))
if key not in self._initializers:
self._initializers[key] = {}
self._initializers[key][param] = initializer | def register(self, key, initializer: callable, param=None) | Add resolver to container | 4.022306 | 2.976963 | 1.351144 |
'''Resolve dependecy'''
try:
return self._initializers[key][param]()
except KeyError:
if key in self._factories:
return self._factories[key](param)
raise DependencyError('Dependency "{0}" is not found'.format(key)) | def get(self, key, param=None) | Resolve dependecy | 5.609091 | 4.432044 | 1.265577 |
return doctor_create_routes(
routes, handle_http, default_base_handler_class=Resource) | def create_routes(routes: Tuple[Route]) -> List[Tuple[str, Resource]] | A thin wrapper around create_routes that passes in flask specific values.
:param routes: A tuple containing the route and another tuple with
all http methods allowed for the route.
:returns: A list of tuples containing the route and generated handler. | 41.429119 | 43.43977 | 0.953714 |
if len(args) is 1:
tn, fp, fn, tp = args[0].ravel().astype(float)
elif len(args) is 4:
tn, fp, fn, tp = [float(a) for a in args]
else:
raise Exception((
"Input argument is not an 2x2 matrix, "
"nor 4 elements tn, fp, fn, tp."))
return (tp * tn - fp *... | def confusion_to_mcc(*args) | Convert the confusion matrix to the Matthews correlation coefficient
Parameters:
-----------
cm : ndarray
2x2 confusion matrix with np.array([[tn, fp], [fn, tp]])
tn, fp, fn, tp : float
four scalar variables
- tn : number of true negatives
- fp : number of false positiv... | 3.139018 | 2.92898 | 1.07171 |
# transpose if axis<>0
if axis is not 0:
x = x.T
# read dimensions and
n, c = x.shape
# check if enough variables provided
if c < 2:
raise Exception(
"Only " + str(c) + " variables provided. Min. 2 required.")
# allocate variables
r = np.ones((c, c))
... | def mcc(x, axis=0, autocorrect=False) | Matthews correlation
Parameters
----------
x : ndarray
dataset of binary [0,1] values
axis : int, optional
Variables as columns is the default (axis=0). If variables
are in the rows use axis=1
autocorrect : bool, optional
If all predictions are True or all are Fals... | 3.274619 | 3.012816 | 1.086897 |
'''Creates node from xml node using namespace as module and tag name as class name'''
inst_type = get_inst_type(xml_node)
init_args['xml_node'] = xml_node
inst = create_inst(inst_type, **init_args)
if not isinstance(inst, Node):
inst = convert_to_node(inst, **init_args)
return inst | def create_node(xml_node: XmlNode, **init_args) | Creates node from xml node using namespace as module and tag name as class name | 4.261253 | 2.838092 | 1.50145 |
'''Returns type by xml node'''
(module_path, class_name) = (xml_node.namespace, xml_node.name)
try:
return import_module(module_path).__dict__[class_name]
except (KeyError, ImportError, ModuleNotFoundError):
message = 'Import "{0}.{1}" is failed.'.format(module_path, class_name)
... | def get_inst_type(xml_node: XmlNode) | Returns type by xml node | 4.549419 | 3.752613 | 1.212334 |
'''Creates class instance with args'''
args, kwargs = get_init_args(inst_type, init_args)
return inst_type(*args, **kwargs) | def create_inst(inst_type, **init_args) | Creates class instance with args | 4.646821 | 4.177139 | 1.112441 |
'''Returns tuple with args and kwargs to pass it to inst_type constructor'''
try:
parameters = signature(inst_type).parameters.values()
args_keys = [p.name for p in parameters \
if p.kind in [Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD] \
and p.defa... | def get_init_args(inst_type, init_args: dict, add_kwargs=False) -> Tuple[List, Dict] | Returns tuple with args and kwargs to pass it to inst_type constructor | 3.478089 | 3.081347 | 1.128756 |
'''Wraps passed instance with InstanceNode'''
return InstanceNode(instance, xml_node, node_globals) | def convert_to_node(instance, xml_node: XmlNode, node_globals: InheritedDict = None)\
-> InstanceNode | Wraps passed instance with InstanceNode | 8.271127 | 5.415827 | 1.527214 |
logger = LoggingSessionContext.get_logger_for_context(context)
child = logger.getChild(threading.currentThread().name)
for handler in logger.handlers:
child.addHandler(handler)
child.level = logger.level
for log_filter in logger.filters:
child.addFilter(log_filter)
return ch... | def get_logger_with_thread_id(context) | Create QS Logger for command context AutoLoadCommandContext, ResourceCommandContext
or ResourceRemoteCommandContext with thread name
:param context:
:return: | 3.458586 | 3.545665 | 0.975441 |
if '3' in resource_config.snmp_version:
return SNMPV3Parameters(ip=resource_config.address,
snmp_user=resource_config.snmp_v3_user or '',
snmp_password=api.DecryptPassword(resource_config.snmp_v3_password).Value or '',
... | def get_snmp_parameters_from_command_context(resource_config, api, force_decrypt=False) | :param ResourceCommandContext resource_config: command context
:return: | 2.191197 | 2.187442 | 1.001717 |
# In superclass, add new task to our list of tasks
target = super(
AutoContext, self).add(target, args, kwargs, **options)
self._auto_insert_check()
return target | def add(self, target, args=None, kwargs=None, **options) | Add an Async job to this context.
Like Context.add(): creates an Async and adds it to our list of tasks.
but also calls _auto_insert_check() to add tasks to queues
automatically. | 11.302272 | 6.304777 | 1.792652 |
if not self.batch_size:
return
if len(self._tasks) >= self.batch_size:
self._handle_tasks() | def _auto_insert_check(self) | Automatically insert tasks asynchronously.
Depending on batch_size, insert or wait until next call. | 6.785541 | 3.778457 | 1.79585 |
def wrapper(wrapped):
class WrappedClass(wrapped):
_mnemonic = mnemonic
_opcode = opcode
_funct3 = funct3
_funct7 = funct7
_variant = variant
_extension = extension
@staticmethod
def _... | def isa(mnemonic: str, opcode: int, funct3: int=None, funct7: int=None, *, variant=RV32I, extension=None) | Decorator for the instructions. The decorator contains the static information for the instructions, in particular
the encoding parameters and the assembler mnemonic.
:param mnemonic: Assembler mnemonic
:param opcode: Opcode of this instruction
:param funct3: 3 bit function code on bits 14 to 12 (R-, I-... | 2.264281 | 2.113552 | 1.071316 |
insns = []
if cls is None:
cls = Instruction
if "_mnemonic" in cls.__dict__.keys():
insns = [cls]
for subcls in cls.__subclasses__():
insns += get_insns(subcls)
return insns | def get_insns(cls = None) | Get all Instructions. This is based on all known subclasses of `cls`. If non is given, all Instructions are returned.
Only such instructions are returned that can be generated, i.e., that have a mnemonic, opcode, etc. So other
classes in the hierarchy are not matched.
:param cls: Base class to get list
... | 3.267982 | 3.684321 | 0.886997 |
for i in get_insns():
if "_mnemonic" in i.__dict__ and i._mnemonic == mnemonic:
return i
return None | def reverse_lookup(mnemonic: str) | Find instruction that matches the mnemonic.
:param mnemonic: Mnemonic to match
:return: :class:`Instruction` that matches or None | 6.415825 | 5.587827 | 1.148179 |
resolved_definition = definition.copy()
if '$ref' in resolved_definition:
try:
# NOTE: The resolve method recursively resolves references, so
# we don't need to worry about that in this function.
resolved_definition = schema.resolve(definition['$ref'])
ex... | def get_value_from_schema(schema, definition: dict, key: str,
definition_key: str) | Gets a value from a schema and definition.
If the value has references it will recursively attempt to resolve them.
:param ResourceSchema schema: The resource schema.
:param dict definition: The definition dict from the schema.
:param str key: The key to use to get the value from the schema.
:para... | 3.375749 | 3.198105 | 1.055547 |
# If the type is a list, use the first non 'null' value as the type.
if isinstance(json_type, list):
for j_type in json_type:
if j_type != 'null':
json_type = j_type
break
return (json_type, JSON_TYPES_TO_NATIVE[json_type]) | def get_types(json_type: StrOrList) -> typing.Tuple[str, str] | Returns the json and native python type based on the json_type input.
If json_type is a list of types it will return the first non 'null' value.
:param json_type: A json type or a list of json types.
:returns: A tuple containing the json type and native python type. | 3.323392 | 2.920356 | 1.138009 |
# Importing here to avoid circular dependencies
from doctor.resource import ResourceSchema
schema = ResourceSchema.from_file(schema_file)
kwargs['schema'] = schema
# Look up the description, example and type in the schema.
definition_key = kwargs.get('definition_key')
if definition_key... | def json_schema_type(schema_file: str, **kwargs) -> typing.Type | Create a :class:`~doctor.types.JsonSchema` type.
This function will automatically load the schema and set it as an attribute
of the class along with the description and example.
:param schema_file: The full path to the json schema file to load.
:param kwargs: Can include any attribute defined in
... | 2.271261 | 2.184981 | 1.039487 |
kwargs['description'] = description
return type('String', (String,), kwargs) | def string(description: str, **kwargs) -> typing.Type | Create a :class:`~doctor.types.String` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.String` | 7.311396 | 8.4693 | 0.863282 |
kwargs['description'] = description
return type('Integer', (Integer,), kwargs) | def integer(description, **kwargs) -> typing.Type | Create a :class:`~doctor.types.Integer` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Integer` | 8.299911 | 9.0138 | 0.9208 |
kwargs['description'] = description
return type('Number', (Number,), kwargs) | def number(description, **kwargs) -> typing.Type | Create a :class:`~doctor.types.Number` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Number` | 7.072618 | 9.216202 | 0.767411 |
kwargs['description'] = description
return type('Boolean', (Boolean,), kwargs) | def boolean(description, **kwargs) -> typing.Type | Create a :class:`~doctor.types.Boolean` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Boolean` | 7.061038 | 8.057286 | 0.876354 |
kwargs['description'] = description
return type('Enum', (Enum,), kwargs) | def enum(description, **kwargs) -> typing.Type | Create a :class:`~doctor.types.Enum` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Enum` | 6.930422 | 9.803596 | 0.706927 |
kwargs['description'] = description
return type('Array', (Array,), kwargs) | def array(description, **kwargs) -> typing.Type | Create a :class:`~doctor.types.Array` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Array` | 6.961432 | 8.823895 | 0.78893 |
props = dict(cls.__dict__)
props.update(kwargs)
return type(cls.__name__, (cls,), props) | def new_type(cls, **kwargs) -> typing.Type | Create a user defined type.
The new type will contain all attributes of the `cls` type passed in.
Any attribute's value can be overwritten using kwargs.
:param kwargs: Can include any attribute defined in
the provided user defined type. | 3.682356 | 4.627358 | 0.795779 |
if cls.example is not None:
return cls.example
return {k: v.get_example() for k, v in cls.properties.items()} | def get_example(cls) -> dict | Returns an example value for the Dict type.
If an example isn't a defined attribute on the class we return
a dict of example values based on each property's annotation. | 3.892127 | 3.185074 | 1.221989 |
if cls.example is not None:
return cls.example
if cls.items is not None:
if isinstance(cls.items, list):
return [item.get_example() for item in cls.items]
else:
return [cls.items.get_example()]
return [1] | def get_example(cls) -> list | Returns an example value for the Array type.
If an example isn't a defined attribute on the class we return
a list of 1 item containing the example value of the `items` attribute.
If `items` is None we simply return a `[1]`. | 2.592236 | 2.027872 | 1.278304 |
try:
node = create_node(xml_node, **args)
pipeline = get_pipeline(node)
run_steps(node, pipeline, **args)
return node
except CoreError as error:
error.add_view_info(xml_node.view_info)
raise
except:
info = exc_info()
msg = 'Unknown error o... | def render_node(xml_node: XmlNode, **args) -> Node | Renders node from xml node | 3.852024 | 3.875871 | 0.993847 |
pipeline = _get_registered_pipeline(node)
if pipeline is None:
msg = _get_pipeline_registration_error_message(node)
raise RenderingError(msg)
return pipeline | def get_pipeline(node: Node) -> RenderingPipeline | Gets rendering pipeline for passed node | 3.973064 | 3.581817 | 1.109231 |
for step in pipeline.steps:
result = step(node, pipeline=pipeline, **args)
if isinstance(result, dict):
args = {**args, **result} | def run_steps(node: Node, pipeline: RenderingPipeline, **args) | Runs instance node rendering steps | 3.546093 | 2.96321 | 1.196707 |
for attr in node.xml_node.attrs:
apply_attribute(node, attr) | def apply_attributes(node: Node, **_) | Applies xml attributes to instance node and setups bindings | 8.055267 | 5.956864 | 1.352266 |
setter = get_setter(attr)
stripped_value = attr.value.strip() if attr.value else ''
if is_expression(stripped_value):
(binding_type, expr_body) = parse_expression(stripped_value)
binder().apply(binding_type, node=node, attr=attr, modifier=setter, expr_body=expr_body)
else:
s... | def apply_attribute(node: Node, attr: XmlAttr) | Maps xml attribute to instance node property and setups bindings | 4.83924 | 4.304339 | 1.12427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.