code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def visit(self, node): """launch the visit starting from the given node""" if node in self._visited: return None self._visited[node] = 1 # FIXME: use set ? methods = self.get_callbacks(node) if methods[0] is not None: methods[0](node) if hasattr(n...
launch the visit starting from the given node
def mark_variables(variables, gradients, grad_reqs='write'): """Mark NDArrays as variables to compute gradient for autograd. Parameters ---------- variables: NDArray or list of NDArray gradients: NDArray or list of NDArray grad_reqs: str or list of str """ if isinstance(variables, NDArr...
Mark NDArrays as variables to compute gradient for autograd. Parameters ---------- variables: NDArray or list of NDArray gradients: NDArray or list of NDArray grad_reqs: str or list of str
def convert_aws_args(aws_args): """Convert old style options into arguments to boto3.session.Session.""" if not isinstance(aws_args, dict): raise errors.InvalidConfiguration( 'Elastic DocManager config option "aws" must be a dict' ) old_session_kwargs = dict( region="regi...
Convert old style options into arguments to boto3.session.Session.
def get_row_failures(df, value_cols, type_cols, verbose=False, outfile=None): """ Input: already validated DataFrame, value & type column names, and output options. Get details on each detected issue, row by row. Output: DataFrame with type & value validation columns, plus an "issues" column wit...
Input: already validated DataFrame, value & type column names, and output options. Get details on each detected issue, row by row. Output: DataFrame with type & value validation columns, plus an "issues" column with a dictionary of every problem for that row.
def enable_rights(self): """ Enables rights management provided by :class:`fatbotslim.handlers.RightsHandler`. """ if self.rights is None: handler_instance = RightsHandler(self) self.handlers.insert(len(self.default_handlers), handler_instance)
Enables rights management provided by :class:`fatbotslim.handlers.RightsHandler`.
def build(self, words): """Construct dictionary DAWG from tokenized words.""" words = [self._normalize(tokens) for tokens in words] self._dawg = dawg.CompletionDAWG(words) self._loaded_model = True
Construct dictionary DAWG from tokenized words.
def add_task( self, title, tags=None): """*Add a task to this taskpaper object* **Key Arguments:** - ``title`` -- the title for the task. - ``tags`` -- tag string (*'@one @two(data)'*) or list of tags (*['one', 'two(data)']*) **Return...
*Add a task to this taskpaper object* **Key Arguments:** - ``title`` -- the title for the task. - ``tags`` -- tag string (*'@one @two(data)'*) or list of tags (*['one', 'two(data)']*) **Return:** - ``task`` -- the new taskpaper task object **Usage:** ...
def validate_parsed_json(obj_json, options=None): """ Validate objects from parsed JSON. This supports a single object, or a list of objects. If a single object is given, a single result is returned. Otherwise, a list of results is returned. If an error occurs, a ValidationErrorResults instance ...
Validate objects from parsed JSON. This supports a single object, or a list of objects. If a single object is given, a single result is returned. Otherwise, a list of results is returned. If an error occurs, a ValidationErrorResults instance or list which includes one of these instances, is returned...
def deliver_hook(self, instance, payload_override=None): """ Deliver the payload to the target URL. By default it serializes to JSON and POSTs. """ payload = payload_override or self.serialize_hook(instance) if getattr(settings, 'HOOK_DELIVERER', None): deliv...
Deliver the payload to the target URL. By default it serializes to JSON and POSTs.
def get_matching_process_ids(cmd_pattern, user_pattern): """ CommandLine: export PID=30196 export PID=$(python -c "import utool as ut; print(ut.get_matching_process_ids('jonc', 'python2.7'))") export PID=$(python -c "import utool as ut; print(ut.get_matching_process_ids('jonc', 'matlab')...
CommandLine: export PID=30196 export PID=$(python -c "import utool as ut; print(ut.get_matching_process_ids('jonc', 'python2.7'))") export PID=$(python -c "import utool as ut; print(ut.get_matching_process_ids('jonc', 'matlab'))") sudo -H echo $PID ps -o pid,comm,nice -p $PID ...
def fetch(self, order_id, data={}, **kwargs): """" Fetch Order for given Id Args: order_id : Id for which order object has to be retrieved Returns: Order dict for given order Id """ return super(Order, self).fetch(order_id, data, **kwargs)
Fetch Order for given Id Args: order_id : Id for which order object has to be retrieved Returns: Order dict for given order Id
def disconnect(self): """We are no more interested in this remote process""" try: os.kill(-self.pid, signal.SIGKILL) except OSError: # The process was already dead, no problem pass self.read_buffer = b'' self.write_buffer = b'' self.set...
We are no more interested in this remote process
def blockgen(bytes, block_size=16): ''' a block generator for pprp ''' for i in range(0, len(bytes), block_size): block = bytes[i:i + block_size] block_len = len(block) if block_len > 0: yield block if block_len < block_size: break
a block generator for pprp
def report(hp, rhr): """ Rule reports a response if there is more than 1 host entry defined in the /etc/hosts file. Arguments: hp (HostParser): Parser object for the custom parser in this module. rhr (RedhatRelease): Parser object for the /etc/redhat-release file...
Rule reports a response if there is more than 1 host entry defined in the /etc/hosts file. Arguments: hp (HostParser): Parser object for the custom parser in this module. rhr (RedhatRelease): Parser object for the /etc/redhat-release file.
def authorize_redirect(self, redirect_uri=None, client_id=None, client_secret=None, extra_params=None ): """Redirects the user to obtain OAuth authorization for this service. Some providers require that you register a Callback URL with your application. You should cal...
Redirects the user to obtain OAuth authorization for this service. Some providers require that you register a Callback URL with your application. You should call this method to log the user in, and then call get_authenticated_user() in the handler you registered as your Callback URL to ...
def StoreResults(self, responses): """Stores the responses.""" client_id = responses.request.client_id if responses.success: logging.info("Client %s has a file %s.", client_id, self.args.filename) else: logging.info("Client %s has no file %s.", client_id, self.args.filename) self.MarkC...
Stores the responses.
def evaluate(self, dataset, metric='auto', output_type='dict', iou_threshold=None, confidence_threshold=None, verbose=True): """ Evaluate the model by making predictions and comparing these to ground truth bounding box annotations. Parameters ---------- ...
Evaluate the model by making predictions and comparing these to ground truth bounding box annotations. Parameters ---------- dataset : SFrame Dataset of new observations. Must include columns with the same names as the annotations and feature used for model train...
def htmlNodeDumpFormatOutput(self, doc, cur, encoding, format): """Dump an HTML node, recursive behaviour,children are printed too. """ if doc is None: doc__o = None else: doc__o = doc._o if cur is None: cur__o = None else: cur__o = cur._o libxml2mod.htmlNodeDu...
Dump an HTML node, recursive behaviour,children are printed too.
def _postprocess(self, x, out=None): """Return the post-processed version of ``x``. C2C: use ``tmp_r`` or ``tmp_f`` (C2C operation) R2C: use ``tmp_f`` (C2C operation) HALFC: use ``tmp_r`` (R2R operation) The result is stored in ``out`` if given, otherwise in a temporary...
Return the post-processed version of ``x``. C2C: use ``tmp_r`` or ``tmp_f`` (C2C operation) R2C: use ``tmp_f`` (C2C operation) HALFC: use ``tmp_r`` (R2R operation) The result is stored in ``out`` if given, otherwise in a temporary or a new array.
def list_dataset_uris(cls, base_uri, config_path): """Return list containing URIs with base URI.""" storage_account_name = generous_parse_uri(base_uri).netloc blobservice = get_blob_service(storage_account_name, config_path) containers = blobservice.list_containers(include_metadata=True...
Return list containing URIs with base URI.
def write(self, output_file): """ Writes this MessageHeader to an output stream. Messages are written as a sequence of *<message_text-message_level>***=** *<message_text-text>* pairs separated by '\r\n'. The sequence is terminated by a pair of '\r\n' sequences. """ for ...
Writes this MessageHeader to an output stream. Messages are written as a sequence of *<message_text-message_level>***=** *<message_text-text>* pairs separated by '\r\n'. The sequence is terminated by a pair of '\r\n' sequences.
def make_item_ref(app, env, fromdocname, item_info): """ Creates a reference node for an item, embedded in a paragraph. Reference text adds also a caption if it exists. """ id = item_info['target']['refid'] if item_info['caption'] != '': caption = ', ' + item_info['caption'] else: ...
Creates a reference node for an item, embedded in a paragraph. Reference text adds also a caption if it exists.
def _set_lsp_frr_bandwidth(self, v, load=False): """ Setter method for lsp_frr_bandwidth, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/lsp_frr/lsp_frr_bandwidth (container) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_frr_bandwidth is co...
Setter method for lsp_frr_bandwidth, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/lsp_frr/lsp_frr_bandwidth (container) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_frr_bandwidth is considered as a private method. Backends looking to populat...
def _organizerPluginName(plugin): """ Get a name for C{plugin}, taking into account the fact that it might not have defined L{IOrganizerPlugin.name}. @type plugin: L{IOrganizerPlugin} provider. @rtype: C{unicode} """ name = getattr(plugin, 'name', None) if name is not None: ret...
Get a name for C{plugin}, taking into account the fact that it might not have defined L{IOrganizerPlugin.name}. @type plugin: L{IOrganizerPlugin} provider. @rtype: C{unicode}
def get_available_facets(self): """ Returns Available facets for the document """ result = [] for k, v in list(self.properties.items()): if isinstance(v, DateField): if not v.tokenize: result.append((k, "date")) elif isi...
Returns Available facets for the document
def add_event(self, key, event): """Add an event and its corresponding key to the store.""" assert isinstance(key, str) assert isinstance(event, bytes) self.conn.execute('INSERT INTO events(uuid,event) VALUES (?,?)', (key, event.decode('utf-8')))
Add an event and its corresponding key to the store.
def increment_download_count(self, id, attachmentID, doc_type='book'): ''' Increment the download counter of a specific file ''' body = self.es.get(index=self.index_name, id=id, doc_type='book', _source_include='_attachments')['_source'] for attachment in body['_attachments']: ...
Increment the download counter of a specific file
def ip_address_2_json(self): """ transform ariane_clip3 OS Instance object to Ariane server JSON obj :return: Ariane JSON obj """ LOGGER.debug("IPAddress.ip_address_2_json") json_obj = { 'ipAddressID': self.id, 'ipAddressIPA': self.ip_address, ...
transform ariane_clip3 OS Instance object to Ariane server JSON obj :return: Ariane JSON obj
def is_bytes(string): """Check if a string is a bytes instance :param Union[str, bytes] string: A string that may be string or bytes like :return: Whether the provided string is a bytes type or not :rtype: bool """ if six.PY3 and isinstance(string, (bytes, memoryview, bytearray)): # noqa ...
Check if a string is a bytes instance :param Union[str, bytes] string: A string that may be string or bytes like :return: Whether the provided string is a bytes type or not :rtype: bool
def min(self, expr, extra_constraints=(), solver=None, model_callback=None): """ Return the minimum value of `expr`. :param expr: expression (an AST) to evaluate :param solver: a solver object, native to the backend, to assist in the evaluation (for example, a z3....
Return the minimum value of `expr`. :param expr: expression (an AST) to evaluate :param solver: a solver object, native to the backend, to assist in the evaluation (for example, a z3.Solver) :param extra_constraints: extra constraints (as ASTs) to add to the solver for th...
def typeset(table, field): """ Return a set containing all Python types found for values in the given field. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar', 'baz'], ... ['A', 1, '2'], ... ['B', u'2', '3.4'], ... [u'B', u'3', '7.8'...
Return a set containing all Python types found for values in the given field. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar', 'baz'], ... ['A', 1, '2'], ... ['B', u'2', '3.4'], ... [u'B', u'3', '7.8', True], ... ['D', u'x...
def create_task(function, *args, **kwargs): """ Create a task object name: The name of the task. function: The actual task function. It should take no arguments, and return a False-y value if it fails. dependencies: (optional, ()) Any dependencies that this task relies on. """ ...
Create a task object name: The name of the task. function: The actual task function. It should take no arguments, and return a False-y value if it fails. dependencies: (optional, ()) Any dependencies that this task relies on.
def find_eq_stress(strains, stresses, tol=1e-10): """ Finds stress corresponding to zero strain state in stress-strain list Args: strains (Nx3x3 array-like): array corresponding to strains stresses (Nx3x3 array-like): array corresponding to stresses tol (float): tolerance to find ze...
Finds stress corresponding to zero strain state in stress-strain list Args: strains (Nx3x3 array-like): array corresponding to strains stresses (Nx3x3 array-like): array corresponding to stresses tol (float): tolerance to find zero strain state
def kl(samples1, samples2, pdf1=False, pdf2=False, bins=30, hist_min=None, hist_max=None): """ Computes the Kullback-Leibler divergence for a single parameter from two distributions. Parameters ---------- samples1 : numpy.array Samples or probability density function (must also set `...
Computes the Kullback-Leibler divergence for a single parameter from two distributions. Parameters ---------- samples1 : numpy.array Samples or probability density function (must also set `pdf1=True`). samples2 : numpy.array Samples or probability density function (must also set `pd...
def pop(self, key=__marker, default=__marker): """ If ``key`` is in the pqdict, remove it and return its priority value, else return ``default``. If ``default`` is not provided and ``key`` is not in the pqdict, raise a ``KeyError``. If ``key`` is not provided, remove the top ite...
If ``key`` is in the pqdict, remove it and return its priority value, else return ``default``. If ``default`` is not provided and ``key`` is not in the pqdict, raise a ``KeyError``. If ``key`` is not provided, remove the top item and return its key, or raise ``KeyError`` if the pqdict i...
def call_gui_callback(callback, *args, **kwargs): """Wrapper method for GLib.idle_add This method is intended as replacement for idle_add. It wraps the method with a callback option. The advantage is that this way, the call is blocking. The method return, when the callback method has been called and execut...
Wrapper method for GLib.idle_add This method is intended as replacement for idle_add. It wraps the method with a callback option. The advantage is that this way, the call is blocking. The method return, when the callback method has been called and executed. :param callback: The callback method, e.g. on_op...
def _collect_arrays(self): """Collect internal arrays from executors.""" # convenient data structures self.data_arrays = [[(self.slices[i], e.arg_dict[name]) for i, e in enumerate(self.execs)] for name, _ in self.data_shapes] self.state_arrays = [[e.arg_dict[...
Collect internal arrays from executors.
def bind(self, database): """Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ super(TransactionPingingPool, self)...
Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed.
def extract_text(input_file, pageno=1): """Use the txtwrite device to get text layout information out For details on options of -dTextFormat see https://www.ghostscript.com/doc/current/VectorDevices.htm#TXT Format is like <page> <line> <span bbox="left top right bottom" font="..." size=".....
Use the txtwrite device to get text layout information out For details on options of -dTextFormat see https://www.ghostscript.com/doc/current/VectorDevices.htm#TXT Format is like <page> <line> <span bbox="left top right bottom" font="..." size="..."> <char bbox="...." c="X"/> :param p...
def validlocations(configuration=None): # type: () -> List[Dict] """ Read valid locations from HDX Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. Returns: List[Dict]: A list of valid locations ...
Read valid locations from HDX Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. Returns: List[Dict]: A list of valid locations
def compute(self): """Generator which yield the actual state of the system every dt. Yields ------ tuple : t, fields Actual time and updated fields container. """ fields = self.fields t = self.t pars = self.parameters self._started_tim...
Generator which yield the actual state of the system every dt. Yields ------ tuple : t, fields Actual time and updated fields container.
def get_stats(package): """ Fetch raw statistics of a package, no corrections are made to this data. You should use get_corrected_stats(). """ grand_total = 0 if '==' in package: package, version = package.split('==') try: package = normalize(package) version = None...
Fetch raw statistics of a package, no corrections are made to this data. You should use get_corrected_stats().
def absorb(self, trits, offset=0, length=None): # type: (MutableSequence[int], int, Optional[int]) -> None """ Absorb trits into the sponge from a buffer. :param trits: Buffer that contains the trits to absorb. :param offset: Starting offset in ``trits``...
Absorb trits into the sponge from a buffer. :param trits: Buffer that contains the trits to absorb. :param offset: Starting offset in ``trits``. :param length: Number of trits to absorb. Defaults to ``len(trits)``.
def load(self, modelfile, layer=None): """ Load or update a model or layers in a model. :param modelfile: The name of the json file to load. :type modelfile: str :param layer: Optionally load only specified layer. :type layer: str """ # read modelfile, co...
Load or update a model or layers in a model. :param modelfile: The name of the json file to load. :type modelfile: str :param layer: Optionally load only specified layer. :type layer: str
def __handle_rate_limit_exception(self, rate_limit_exception): """ Sleep for the time specified in the exception. If not specified, wait for 60 seconds. """ retry_after = int( rate_limit_exception.response.headers.get('Retry-After', 60)) self.log.info( ...
Sleep for the time specified in the exception. If not specified, wait for 60 seconds.
def vary_name(name: Text): """ Validates the name and creates variations """ snake = re.match(r'^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$', name) if not snake: fail('The project name is not a valid snake-case Python variable name') camel = [x[0].upper() + x[1:] for x in name.split('_')] re...
Validates the name and creates variations
def nearest_int(x): """ Return nearest long integer to x """ if x == 0: return np.int64(0) elif x > 0: return np.int64(x + 0.5) else: return np.int64(x - 0.5)
Return nearest long integer to x
def _set_logical_chassis(self, v, load=False): """ Setter method for logical_chassis, mapped from YANG variable /rbridge_id/logical_chassis (container) If this variable is read-only (config: false) in the source YANG file, then _set_logical_chassis is considered as a private method. Backends looking...
Setter method for logical_chassis, mapped from YANG variable /rbridge_id/logical_chassis (container) If this variable is read-only (config: false) in the source YANG file, then _set_logical_chassis is considered as a private method. Backends looking to populate this variable should do so via calling thi...
def get_arca_base(self, pull=True): """ Returns the name and tag of image that has the basic build dependencies installed with just pyenv installed, with no python installed. (Builds or pulls the image if it doesn't exist locally.) """ name = self.get_arca_base_name() tag...
Returns the name and tag of image that has the basic build dependencies installed with just pyenv installed, with no python installed. (Builds or pulls the image if it doesn't exist locally.)
def write(connection, skip, directory, force): """Write all as BEL.""" os.makedirs(directory, exist_ok=True) from .manager.bel_manager import BELManagerMixin import pybel for idx, name, manager in _iterate_managers(connection, skip): if not isinstance(manager, BELManagerMixin): c...
Write all as BEL.
def create(self, data, update=False, **kwargs): """ Creates a new object pretreated input data. .. code-block:: python DBSession.sacrud(Users).create({'name': 'Vasya', 'sex': 1}) Support JSON: .. code-block:: python DBSession.sacrud(Users).create('{"n...
Creates a new object pretreated input data. .. code-block:: python DBSession.sacrud(Users).create({'name': 'Vasya', 'sex': 1}) Support JSON: .. code-block:: python DBSession.sacrud(Users).create('{"name": "Vasya", "sex": 1}') For adding multiple data for m2m...
def remote(): """Update package info from PyPI.""" logger.info("Fetching latest data from PyPI.") results = defaultdict(list) packages = PackageVersion.objects.exclude(is_editable=True) for pv in packages: pv.update_from_pypi() results[pv.diff_status].append(pv) logger.debug(...
Update package info from PyPI.
def p_prj_name_art_1(self, p): """prj_name_art : ART_PRJ_NAME LINE""" try: if six.PY2: value = p[2].decode(encoding='utf-8') else: value = p[2] self.builder.set_file_atrificat_of_project(self.document, 'name', value) except Orde...
prj_name_art : ART_PRJ_NAME LINE
def find_in_coord_list(coord_list, coord, atol=1e-8): """ Find the indices of matches of a particular coord in a coord_list. Args: coord_list: List of coords to test coord: Specific coordinates atol: Absolute tolerance. Defaults to 1e-8. Accepts both scalar and array. ...
Find the indices of matches of a particular coord in a coord_list. Args: coord_list: List of coords to test coord: Specific coordinates atol: Absolute tolerance. Defaults to 1e-8. Accepts both scalar and array. Returns: Indices of matches, e.g., [0, 1, 2, 3]. Empty ...
def next(self): """Returns the next query result. :return: The next query result. :rtype: dict :raises StopIteration: If no more result is left. """ try: return next(self._execution_context) except HTTPFailure as e: ...
Returns the next query result. :return: The next query result. :rtype: dict :raises StopIteration: If no more result is left.
def downsample(f1, f2, data, N, quick=False): """ get N random headers from a fastq file without reading the whole thing into memory modified from: http://www.biostars.org/p/6544/ quick=True will just grab the first N reads rather than do a true downsampling """ if quick: rand_record...
get N random headers from a fastq file without reading the whole thing into memory modified from: http://www.biostars.org/p/6544/ quick=True will just grab the first N reads rather than do a true downsampling
def get_clan(self, *tags: crtag, **params: keys): """Get a clan information Parameters ---------- \*tags: str Valid clan tags. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys should be inclu...
Get a clan information Parameters ---------- \*tags: str Valid clan tags. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional...
def get_http_headers(user_agent=None, referer=None, accept_language=None): """ Update the default requests HTTP headers with OSMnx info. Parameters ---------- user_agent : str the user agent string, if None will set with OSMnx default referer : str the referer string, if None wi...
Update the default requests HTTP headers with OSMnx info. Parameters ---------- user_agent : str the user agent string, if None will set with OSMnx default referer : str the referer string, if None will set with OSMnx default accept_language : str make accept-language explic...
def evaluate_conditionals_in_context (properties, context): """ Removes all conditional properties which conditions are not met For those with met conditions, removes the condition. Properies in conditions are looked up in 'context' """ if __debug__: from .property_set import Propert...
Removes all conditional properties which conditions are not met For those with met conditions, removes the condition. Properies in conditions are looked up in 'context'
def get_verse(self, v=1): """Get a specific verse.""" verse_count = len(self.verses) if v - 1 < verse_count: return self.verses[v - 1]
Get a specific verse.
def validate(self, method, *args, **kwargs): """Validate authentication and values passed to the specified method. Raises a PyCronofyValidationError on error. :param string method: Method name to check. :param *args: Arguments for "Method". :param **kwargs: Keyword arguments for...
Validate authentication and values passed to the specified method. Raises a PyCronofyValidationError on error. :param string method: Method name to check. :param *args: Arguments for "Method". :param **kwargs: Keyword arguments for "Method".
def get_keystone_session(self, keystone_ip, username, password, api_version=False, admin_port=False, user_domain_name=None, domain_name=None, project_domain_name=None, project_name=None): """Return a keystone session object""...
Return a keystone session object
async def send_file(self, file_type, method, file, payload) -> Union[Dict, base.Boolean]: """ Send file https://core.telegram.org/bots/api#inputfile :param file_type: field name :param method: API method :param file: String or io.IOBase :param payload: request p...
Send file https://core.telegram.org/bots/api#inputfile :param file_type: field name :param method: API method :param file: String or io.IOBase :param payload: request payload :return: response
def _choose_scheme(self): """Choose color scheme""" if self.style_cols[self.color] in ('string', 'boolean', ): self.scheme = antique(10) elif self.style_cols[self.color] in ('number', ): self.scheme = mint(5) elif self.style_cols[self.color] in ('date', 'geometry'...
Choose color scheme
def filter_slow_requests(slowness): """Filter :class:`.Line` objects by their response time. :param slowness: minimum time, in milliseconds, a server needs to answer a request. If the server takes more time than that the log line is accepted. :type slowness: string :returns: a function that...
Filter :class:`.Line` objects by their response time. :param slowness: minimum time, in milliseconds, a server needs to answer a request. If the server takes more time than that the log line is accepted. :type slowness: string :returns: a function that filters by the server response time. :...
def get_mol_filename(chebi_id): '''Returns mol file''' mol = get_mol(chebi_id) if mol is None: return None file_descriptor, mol_filename = tempfile.mkstemp(str(chebi_id) + '_', '.mol') mol_file = open(mol_filename, 'w') mol_file.writ...
Returns mol file
def closed(self, block_identifier: BlockSpecification) -> bool: """ Returns if the channel is closed. """ return self.token_network.channel_is_closed( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channe...
Returns if the channel is closed.
def delete_element_when_value_none(data_structure): """ This method remove all entries in a Python dict when its value is None. :param data_structure: Python dict (lists are supported). e.i: [{"element1": "e1", "element2": {"element2.1": "e2", "element2.2": ...
This method remove all entries in a Python dict when its value is None. :param data_structure: Python dict (lists are supported). e.i: [{"element1": "e1", "element2": {"element2.1": "e2", "element2.2": None}, "element3": "e3"}, {"elementA":...
def add_cmd(self, name, help=None, func=None): """ If func is None, this is regarded as a sub-parser which can contains sub-command. Else, this is a leaf node in cmd tree which can not add sub-command. :rtype: AParser """ if self.subparsers is None: se...
If func is None, this is regarded as a sub-parser which can contains sub-command. Else, this is a leaf node in cmd tree which can not add sub-command. :rtype: AParser
def get(self, *args, **kwargs): ''' /label/s/view ''' url_arr = self.parse_url(args[0]) if len(url_arr) == 2: if url_arr[0] == 'remove': self.remove_redis_keyword(url_arr[1]) else: self.list(url_arr[0], url_arr[1]) ...
/label/s/view
def p_conditional_expr(self, p): """ conditional_expr \ : logical_or_expr | logical_or_expr CONDOP assignment_expr COLON assignment_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = self.asttypes.Conditional( predica...
conditional_expr \ : logical_or_expr | logical_or_expr CONDOP assignment_expr COLON assignment_expr
def create_user(self, user_name, initial_password): """Create a new user with an initial password via provisioning API. It is not an error, if the user already existed before. If you get back an error 999, then the provisioning API is not enabled. :param user_name: name of user to be c...
Create a new user with an initial password via provisioning API. It is not an error, if the user already existed before. If you get back an error 999, then the provisioning API is not enabled. :param user_name: name of user to be created :param initial_password: password for user bein...
def command(state, args): """Fix cache issues caused by schema pre-v4.""" if len(args) > 1: print(f'Usage: {args[0]}') return db = state.db _refresh_incomplete_anime(db) _fix_cached_completed(db)
Fix cache issues caused by schema pre-v4.
def edge_iterator(edges=[], edges_fn=None): """Yield documents from edge for loading into ArangoDB""" for edge in itertools.chain(edges, files.read_edges(edges_fn)): subj = copy.deepcopy(edge["edge"]["subject"]) subj_id = str(utils._create_hash_from_doc(subj)) subj["_key"] = subj_id ...
Yield documents from edge for loading into ArangoDB
def fetch_profile_data_from_file(): """ takes profile data from file and saves in the profile_data DB """ with open(SEARCH_PROFILE_DATA_FILE, 'r') as fin: profiles = json.load(fin) counter = 0 log.debug("-" * 5) log.debug("Fetching profile data from file") for entry in profiles: ...
takes profile data from file and saves in the profile_data DB
def _set_ta_limit(self, limit_name, value): """ Set the value for the limit as reported by Trusted Advisor, for the specified limit. This method should only be called by :py:class:`~.TrustedAdvisor`. :param limit_name: the name of the limit to override the value for :ty...
Set the value for the limit as reported by Trusted Advisor, for the specified limit. This method should only be called by :py:class:`~.TrustedAdvisor`. :param limit_name: the name of the limit to override the value for :type limit_name: str :param value: the Trusted Advisor lim...
def get_signature_data(fileobj, filesize): """Read data from MAR file that is required for MAR signatures. Args: fileboj (file-like object): file-like object to read the MAR data from filesize (int): the total size of the file Yields: blocks of bytes representing the data required ...
Read data from MAR file that is required for MAR signatures. Args: fileboj (file-like object): file-like object to read the MAR data from filesize (int): the total size of the file Yields: blocks of bytes representing the data required to generate or validate signatures.
def submit_curation(hash_val, tag, curator, text=None, source='indra_rest_client', ev_hash=None, is_test=False): """Submit a curation for the given statement at the relevant level. Parameters ---------- hash_val : int The hash corresponding to the statement. tag : str ...
Submit a curation for the given statement at the relevant level. Parameters ---------- hash_val : int The hash corresponding to the statement. tag : str A very short phrase categorizing the error or type of curation, e.g. "grounding" for a grounding error, or "correct" if you ar...
def GetArtifactKnowledgeBase(client_obj, allow_uninitialized=False): """This generates an artifact knowledge base from a GRR client. Args: client_obj: A GRRClient object which is opened for reading. allow_uninitialized: If True we accept an uninitialized knowledge_base. Returns: A KnowledgeBase sema...
This generates an artifact knowledge base from a GRR client. Args: client_obj: A GRRClient object which is opened for reading. allow_uninitialized: If True we accept an uninitialized knowledge_base. Returns: A KnowledgeBase semantic value. Raises: ArtifactProcessingError: If called when the kno...
def matches_ip(self, ip): """Return True if the given IP is blacklisted, False otherwise.""" # Check the cache if caching is enabled if self.cache is not None: matches_ip = self.cache.get(ip) if matches_ip is not None: return matches_ip # Query M...
Return True if the given IP is blacklisted, False otherwise.
def update_ngram(self, ngram, count): """ Updates a given ngram in the database. The ngram has to be in the database, otherwise this method will stop with an error. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. count :...
Updates a given ngram in the database. The ngram has to be in the database, otherwise this method will stop with an error. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. count : int The count for the given n-gram.
def safe_get(data, key_list): ''' Safely access dictionary keys when plugin may have failed ''' for key in key_list: data = data.get(key, {}) return data if data else 'plugin_failed'
Safely access dictionary keys when plugin may have failed
def coord_to_tilepath(self, lat, lon, zoom): '''return the tile ID that covers a latitude/longitude at a specified zoom level ''' tile = self.coord_to_tile(lat, lon, zoom) return self.tile_to_path(tile)
return the tile ID that covers a latitude/longitude at a specified zoom level
def set_state(profile, state, store='local'): ''' Configure the firewall state. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private state (str): The firewall state. Valid option...
Configure the firewall state. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private state (str): The firewall state. Valid options are: - on - off - n...
def read_criteria_file(self, criteria_file_name=None): """ reads 2.5 or 3.0 formatted PmagPy criteria file and returns a set of nested dictionary 2.5 formated criteria data that can be passed into pmag.grade to filter data. Parameters ---------- criteria_file : n...
reads 2.5 or 3.0 formatted PmagPy criteria file and returns a set of nested dictionary 2.5 formated criteria data that can be passed into pmag.grade to filter data. Parameters ---------- criteria_file : name of criteria file to read in Returns ------- ne...
def clone_wire(old_wire, name=None): """ Makes a copy of any existing wire :param old_wire: The wire to clone :param name: a name fo rhte new wire Note that this function is mainly intended to be used when the two wires are from different blocks. Making two wires with the same name in the ...
Makes a copy of any existing wire :param old_wire: The wire to clone :param name: a name fo rhte new wire Note that this function is mainly intended to be used when the two wires are from different blocks. Making two wires with the same name in the same block is not allowed
def verify(self, byts, sign): ''' Verify the signature for the given bytes using the ECC public key. Args: byts (bytes): The data bytes. sign (bytes): The signature bytes. Returns: bool: True if the data was verified, False otherwise. ...
Verify the signature for the given bytes using the ECC public key. Args: byts (bytes): The data bytes. sign (bytes): The signature bytes. Returns: bool: True if the data was verified, False otherwise.
def _process_response(response): """ Decodes the JSON response, returning a dict. Raises an exception if an invalid response code is received. """ if response.status_code == 404: raise Trovebox404Error("HTTP Error %d: %s" % (response...
Decodes the JSON response, returning a dict. Raises an exception if an invalid response code is received.
def _convert_trigger(self, trigger_def, parent): """Convert a TriggerDefinition into a stream, trigger pair.""" if trigger_def.explicit_stream is None: stream = parent.resolve_identifier(trigger_def.named_event, DataStream) trigger = TrueTrigger() else: strea...
Convert a TriggerDefinition into a stream, trigger pair.
def _get_image_infos(config,image): ''' Verify that the image exists We will try to resolve either by: - name - image_id - tag image Image Name / Image Id / Image Tag Returns dict ''' client = _get_client(config) infos = None try: infos = _se...
Verify that the image exists We will try to resolve either by: - name - image_id - tag image Image Name / Image Id / Image Tag Returns dict
def push(self, metric_type, metric_id, value, timestamp=None): """ Pushes a single metric_id, datapoint combination to the server. This method is an assistant method for the put method by removing the need to create data structures first. :param metric_type: MetricType to be ma...
Pushes a single metric_id, datapoint combination to the server. This method is an assistant method for the put method by removing the need to create data structures first. :param metric_type: MetricType to be matched (required) :param metric_id: Exact string matching metric id ...
def type_assert_dict( d, kcls=None, vcls=None, allow_none=False, cast_from=None, cast_to=None, dynamic=None, objcls=None, ctor=None, ): """ Checks that every key/value in @d is an instance of @kcls: @vcls Will also unmarshal JSON objects to Python objects if the ...
Checks that every key/value in @d is an instance of @kcls: @vcls Will also unmarshal JSON objects to Python objects if the value is an instance of dict and @vcls is a class type Args: d: The dict to type assert kcls: The class to type assert for keys. ...
def reload(self, hooks=None): """This method will reload the configuration using input argument from the command line interface. 1. pasing arguments 2. applying hooks 3. addding help argument 4. reloading configuration using cli argument like a configuration file ...
This method will reload the configuration using input argument from the command line interface. 1. pasing arguments 2. applying hooks 3. addding help argument 4. reloading configuration using cli argument like a configuration file name.
def add(self, operator, *args): """Adds a proximal operator to the list of operators""" if isinstance(operator, str): op = getattr(proxops, operator)(*args) elif isinstance(operator, proxops.ProximalOperatorBaseClass): op = operator else: raise ValueE...
Adds a proximal operator to the list of operators
def doppler_width(transition, Temperature): r"""Return the Doppler width of a transition at a given temperature (in angular frequency). The usual Doppler FWHM of the rubidium D2 line (in MHz). >>> g = State("Rb", 87, 5, 0, 1/Integer(2), 2) >>> e = State("Rb", 87, 5, 1, 3/Integer(2)) >>> t = Tr...
r"""Return the Doppler width of a transition at a given temperature (in angular frequency). The usual Doppler FWHM of the rubidium D2 line (in MHz). >>> g = State("Rb", 87, 5, 0, 1/Integer(2), 2) >>> e = State("Rb", 87, 5, 1, 3/Integer(2)) >>> t = Transition(e, g) >>> omega = doppler_width(t, ...
def get_route_to(self, destination="", protocol=""): """ Only IPv4 supported, vrf aware, longer_prefixes parameter ready """ longer_pref = "" # longer_prefixes support, for future use vrf = "" ip_version = None try: ip_version = IPNetwork(destination...
Only IPv4 supported, vrf aware, longer_prefixes parameter ready
def nsx_controller_name(self, **kwargs): """ Get/Set nsx controller name Args: name: (str) : Name of the nsx controller get (bool) : Get nsx controller config(True,False) callback (function): A function executed upon completion of the metho...
Get/Set nsx controller name Args: name: (str) : Name of the nsx controller get (bool) : Get nsx controller config(True,False) callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. ...
def compress_and_upload(data, compressed_file, s3_path, multipart_chunk_size_mb=500, method='gz', delete=False, access_key=None, secret_key=None): ''' Compresses data and uploads to S3. S3 upload uses ``s3cmd``, so you must either: 1) Manually configure ``s3cmd`` prior to use (typically using ...
Compresses data and uploads to S3. S3 upload uses ``s3cmd``, so you must either: 1) Manually configure ``s3cmd`` prior to use (typically using ``s3cmd --configure``). 2) Configure ``s3cmd`` using ``s3.configure()``. 3) Pass your access key and secret key to ``compress_and_upload``, which...
def resolve_colors(n_colors=None, colormap=None, colors=None): """ Generates a list of colors based on common color arguments, for example the name of a colormap or palette or another iterable of colors. The list is then truncated (or multiplied) to the specific number of requested colors. Para...
Generates a list of colors based on common color arguments, for example the name of a colormap or palette or another iterable of colors. The list is then truncated (or multiplied) to the specific number of requested colors. Parameters ---------- n_colors : int, default: None Specify the...
def make_item_class_for_custom_generator_class(cls): """ cls: The custom generator class for which to create an item-class """ clsname = cls.__tohu_items_name__ attr_names = cls.field_gens.keys() return make_item_class(clsname, attr_names)
cls: The custom generator class for which to create an item-class