code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def to_xml(self): """Convert this datapoint into a form suitable for pushing to device cloud An XML string will be returned that will contain all pieces of information set on this datapoint. Values not set (e.g. quality) will be ommitted. """ type_converter = _get_encoder_meth...
Convert this datapoint into a form suitable for pushing to device cloud An XML string will be returned that will contain all pieces of information set on this datapoint. Values not set (e.g. quality) will be ommitted.
def predict_ipcw(self, y): """Return inverse probability of censoring weights at given time points. :math:`\\omega_i = \\delta_i / \\hat{G}(y_i)` Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicato...
Return inverse probability of censoring weights at given time points. :math:`\\omega_i = \\delta_i / \\hat{G}(y_i)` Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time...
def _get_sizes_checksums(checksums_path): """Returns {URL: (size, checksum)}s stored within file.""" checksums = {} for line in _read_file(checksums_path).split('\n'): if not line: continue # URL might have spaces inside, but size and checksum will not. url, size, checksum = line.rsplit(' ', 2) ...
Returns {URL: (size, checksum)}s stored within file.
def _compute_vline_scores(self): """Does the hard work to prepare ``vline_score``. """ M, N, L = self.M, self.N, self.L vline_score = {} for x in range(M): laststart = [0 if (x, 0, 1, k) in self else None for k in range(L)] for y in range(N): ...
Does the hard work to prepare ``vline_score``.
def filelist(folderpath, ext=None): ''' Returns a list of all the files contained in the folder specified by `folderpath`. To filter the files by extension simply add a list containing all the extension with `.` as the second argument. If `flat` is False, then the Path objects are returned. ''' ...
Returns a list of all the files contained in the folder specified by `folderpath`. To filter the files by extension simply add a list containing all the extension with `.` as the second argument. If `flat` is False, then the Path objects are returned.
def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection ...
:param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name.
def reduce(self, func): """Return a new DStream where each RDD was reduced with ``func``. :rtype: DStream """ # avoid RDD.reduce() which does not return an RDD return self.transform( lambda rdd: ( rdd .map(lambda i: (None, i)) ...
Return a new DStream where each RDD was reduced with ``func``. :rtype: DStream
def get_or_create(self, event): """Gets or creates a new event hook for the specified event (key). This method treats qcore.EnumBase-typed event keys specially: enum_member.name is used as key instead of enum instance in case such a key is passed. Note that on/off/trigger/safe_...
Gets or creates a new event hook for the specified event (key). This method treats qcore.EnumBase-typed event keys specially: enum_member.name is used as key instead of enum instance in case such a key is passed. Note that on/off/trigger/safe_trigger methods rely on this method, ...
def visit_unaryop(self, node): """check use of the non-existent ++ and -- operator operator""" if ( (node.op in "+-") and isinstance(node.operand, astroid.UnaryOp) and (node.operand.op == node.op) ): self.add_message("nonexistent-operator", node=no...
check use of the non-existent ++ and -- operator operator
def run_svc_action(self, name, replace=None, svc=None): """ backwards compatible to reflex service object. This looks for hooks on current object as well as in the actions sub-object. """ actions = svc.get('actions') if actions and actions.get(name): return se...
backwards compatible to reflex service object. This looks for hooks on current object as well as in the actions sub-object.
def unapply(self): """Reset the current configuration to the previous state.""" for key, value in self._old_config.items(): _config[key] = value
Reset the current configuration to the previous state.
def python_app(function=None, data_flow_kernel=None, walltime=60, cache=False, executors='all'): """Decorator function for making python apps. Parameters ---------- function : function Do not pass this keyword argument directly. This is needed in order to allow for omitted parenthesis, ...
Decorator function for making python apps. Parameters ---------- function : function Do not pass this keyword argument directly. This is needed in order to allow for omitted parenthesis, for example, `@python_app` if using all defaults or `@python_app(walltime=120)`. If the decorato...
def xiphias_get_users_by_alias(self, alias_jids: Union[str, List[str]]): """ Like xiphias_get_users, but for aliases instead of jids. :param alias_jids: one jid, or a list of jids """ return self._send_xmpp_element(xiphias.UsersByAliasRequest(alias_jids))
Like xiphias_get_users, but for aliases instead of jids. :param alias_jids: one jid, or a list of jids
def transform(self, X, y=None, sample_weight=None): ''' Transforms the time series data with linear direct value interpolation If y is a time series and passed, it will be transformed as well The time dimension is removed from the data Parameters ---------- X : a...
Transforms the time series data with linear direct value interpolation If y is a time series and passed, it will be transformed as well The time dimension is removed from the data Parameters ---------- X : array-like, shape [n_series, ...] Time series data and (option...
def printConcordance(concordance, prefix): """Print the concordance. :param concordance: the concordance of each sample. :param prefix: the prefix of all the files. :type concordance: dict :type prefix: str :returns: the concordance percentage (dict) The concordance is the number of geno...
Print the concordance. :param concordance: the concordance of each sample. :param prefix: the prefix of all the files. :type concordance: dict :type prefix: str :returns: the concordance percentage (dict) The concordance is the number of genotypes that are equal when comparing a duplicat...
def list_datastores_full(service_instance): ''' Returns a list of datastores associated with a given service instance. The list contains basic information about the datastore: name, type, url, capacity, free, used, usage, hosts service_instance The Service Instance Object from which to ...
Returns a list of datastores associated with a given service instance. The list contains basic information about the datastore: name, type, url, capacity, free, used, usage, hosts service_instance The Service Instance Object from which to obtain datastores.
async def createcsrf(self, csrfarg = '_csrf'): """ Create a anti-CSRF token in the session """ await self.sessionstart() if not csrfarg in self.session.vars: self.session.vars[csrfarg] = uuid.uuid4().hex
Create a anti-CSRF token in the session
def resolve_alias(self, path_str): """Returns the actual command name. Uses the alias mapping.""" if path_str in self.aliases: return self.aliases[path_str] return path_str
Returns the actual command name. Uses the alias mapping.
def get(self, id): """Retrieves custom domain. See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/get_custom_domains_by_id """ url = self._url('%s' % (id)) return self.client.get(url)
Retrieves custom domain. See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/get_custom_domains_by_id
def as_flat_array(iterables): '''Given a sequence of sequences, return a flat numpy array. Parameters ---------- iterables : sequence of sequence of number A sequence of tuples or lists containing numbers. Typically these come from something that represents each joint in a skeleton, lik...
Given a sequence of sequences, return a flat numpy array. Parameters ---------- iterables : sequence of sequence of number A sequence of tuples or lists containing numbers. Typically these come from something that represents each joint in a skeleton, like angle. Returns ------- ...
def reset(self): """" Reset the state as new """ self.last_usage = None self.last_collect = None self.last_metrics = None self.snapshot_countdown = 0 self.run()
Reset the state as new
def annotate(self, **annotations): """Custom version of the standard annotate function that allows using field names as annotated fields. Normally, the annotate function doesn't allow you to use the name of an existing field on the model as the alias name. This version of the fu...
Custom version of the standard annotate function that allows using field names as annotated fields. Normally, the annotate function doesn't allow you to use the name of an existing field on the model as the alias name. This version of the function does allow that.
def get_reference(self, rtype: str, label: str): """ Return reference filed under rtype/label The references are organized by field/label, e.g. category/cat1. This lets us use a shorthand notation to go the resource, e.g. ref:category:cat1 instead of folder1/folder2/cat1. ""...
Return reference filed under rtype/label The references are organized by field/label, e.g. category/cat1. This lets us use a shorthand notation to go the resource, e.g. ref:category:cat1 instead of folder1/folder2/cat1.
def register_add_user_command(self, add_user_func): """ Add the add-user command to the parser and call add_user_func(project_name, user_full_name, auth_role) when chosen. :param add_user_func: func Called when this option is chosen: upload_func(project_name, user_full_name, auth_role). ...
Add the add-user command to the parser and call add_user_func(project_name, user_full_name, auth_role) when chosen. :param add_user_func: func Called when this option is chosen: upload_func(project_name, user_full_name, auth_role).
def get_lattice_type(number): """Return the lattice crystal system. Hexagonal cells are differentiated into rhombohedral and hexagonal lattices. Args: number (int): The international space group number. Returns: str: The lattice crystal system. ...
Return the lattice crystal system. Hexagonal cells are differentiated into rhombohedral and hexagonal lattices. Args: number (int): The international space group number. Returns: str: The lattice crystal system.
def get_authorization_url(self, acr_values=None, prompt=None, scope=None, custom_params=None): """Function to get the authorization url that can be opened in the browser for the user to provide authorization and authentication Parameters: * **acr_values...
Function to get the authorization url that can be opened in the browser for the user to provide authorization and authentication Parameters: * **acr_values (list, optional):** acr values in the order of priority * **prompt (string, optional):** prompt=login is required if you wa...
def resolve(self, requirements, max_rounds=20): """Take a collection of constraints, spit out the resolution result. The return value is a representation to the final resolution result. It is a tuple subclass with two public members: * `mapping`: A dict of resolved candidates. Each key...
Take a collection of constraints, spit out the resolution result. The return value is a representation to the final resolution result. It is a tuple subclass with two public members: * `mapping`: A dict of resolved candidates. Each key is an identifier of a requirement (as returned...
def minimum_multivariate_ess(nmr_params, alpha=0.05, epsilon=0.05): r"""Calculate the minimum multivariate Effective Sample Size you will need to obtain the desired precision. This implements the inequality from Vats et al. (2016): .. math:: \widehat{ESS} \geq \frac{2^{2/p}\pi}{(p\Gamma(p/2))^{2/...
r"""Calculate the minimum multivariate Effective Sample Size you will need to obtain the desired precision. This implements the inequality from Vats et al. (2016): .. math:: \widehat{ESS} \geq \frac{2^{2/p}\pi}{(p\Gamma(p/2))^{2/p}} \frac{\chi^{2}_{1-\alpha,p}}{\epsilon^{2}} Where :math:`p` is t...
def p_speed_information_duration(self, p): 'speed : information IN duration' logger.debug('speed = information %s in duration %s', p[1], p[3]) p[0] = p[1].in_duration(p[3])
speed : information IN duration
def _reference_dates(self, start_date, end_date): """ Get reference dates for the holiday. Return reference dates for the holiday also returning the year prior to the start_date and year following the end_date. This ensures that any offsets to be applied will yield the holidays...
Get reference dates for the holiday. Return reference dates for the holiday also returning the year prior to the start_date and year following the end_date. This ensures that any offsets to be applied will yield the holidays within the passed in dates.
def remove_attribute_listener(self, attr_name, *args, **kwargs): """ Remove a paremeter listener that was previously added using :py:func:`add_attribute_listener`. For example to remove the ``thr_min_callback()`` callback function: .. code:: python vehicle.parameters.remov...
Remove a paremeter listener that was previously added using :py:func:`add_attribute_listener`. For example to remove the ``thr_min_callback()`` callback function: .. code:: python vehicle.parameters.remove_attribute_listener('thr_min', thr_min_callback) See :ref:`vehicle_state_ob...
def require_authentication(self, realm, environ): """Return True if this realm requires authentication (grant anonymous access otherwise).""" realm_entry = self._get_realm_entry(realm) if realm_entry is None: _logger.error( 'Missing configuration simple_dc.user_mappin...
Return True if this realm requires authentication (grant anonymous access otherwise).
def doctree_read(app, doctree): """ Inject AutoAPI into the TOC Tree dynamically. """ if app.env.docname == "index": all_docs = set() insert = True nodes = doctree.traverse(toctree) toc_entry = "%s/index" % app.config.autoapi_root add_entry = ( nodes ...
Inject AutoAPI into the TOC Tree dynamically.
def run(self): """ Initializes the stream. """ if not hasattr(self, 'queue'): raise RuntimeError("Audio queue is not intialized.") self.stream.start_stream() self.keep_listening = True while self.keep_listening: try: frame = self.queue.get(False, timeout=queue_timeout) self.stream.write(fra...
Initializes the stream.
def do_py(self, args: argparse.Namespace) -> bool: """Invoke Python command or shell""" from .pyscript_bridge import PyscriptBridge if self._in_py: err = "Recursively entering interactive Python consoles is not allowed." self.perror(err, traceback_war=False) r...
Invoke Python command or shell
def cycle_find_app(_parser, cmd, args): # pragma: no cover """ Find the first position of a value in a de Bruijn sequence. """ parser = argparse.ArgumentParser( prog=_parser.prog, description=_parser.description, ) parser.add_argument('-w', '--width', type=int, default=4, help=...
Find the first position of a value in a de Bruijn sequence.
def remove_tag(self, name, user, message=None, date=None): """ Removes tag with the given ``name``. :param name: name of the tag to be removed :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" :param message: message of the tag's removal commit :param dat...
Removes tag with the given ``name``. :param name: name of the tag to be removed :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" :param message: message of the tag's removal commit :param date: date of tag's removal commit :raises TagDoesNotExistError: if tag w...
def as_dict(self, replace_value_names=True): """Return the whole section as a dict""" old_children = self.children self.children = self.terms d = super(SectionTerm, self).as_dict(replace_value_names) self.children = old_children return d
Return the whole section as a dict
def add(self, tensor, tf_sess=None, key=None, **kwargs): """ Adds a new root *tensor* for a *key* which, if *None*, defaults to a consecutive number. When *tensor* is not an instance of :py:class:`Tensor` but an instance of ``tensorflow.Tensor``, it is converted first. In that case, *tf_...
Adds a new root *tensor* for a *key* which, if *None*, defaults to a consecutive number. When *tensor* is not an instance of :py:class:`Tensor` but an instance of ``tensorflow.Tensor``, it is converted first. In that case, *tf_sess* should be a valid tensorflow session and *kwargs* are forwarded...
def should_cache(self, request, response): """ Given the request and response should it be cached """ if not getattr(request, '_cache_update_cache', False): return False if not response.status_code in getattr(settings, 'BETTERCACHE_CACHEABLE_STATUS', CACHEABLE_STATUS): r...
Given the request and response should it be cached
def jr(self,pot=None,**kwargs): """ NAME: jr PURPOSE: calculate the radial action INPUT: pot - potential type= ('staeckel') type of actionAngle module to use 1) 'adiabatic' 2) 'staeckel' 3) 'is...
NAME: jr PURPOSE: calculate the radial action INPUT: pot - potential type= ('staeckel') type of actionAngle module to use 1) 'adiabatic' 2) 'staeckel' 3) 'isochroneApprox' 4) 'spherical' ...
def main(): """Main function.""" # Get the command line arg args = docopt(__doc__, version="Mackup {}".format(VERSION)) mckp = Mackup() app_db = ApplicationsDatabase() def printAppHeader(app_name): if verbose: print(("\n{0} {1} {0}").format(header("---"), bold(app_name))) ...
Main function.
def add_to_parent(self): """Adds this node to the parent's ``children`` collection if it exists.""" parent = self.parent if parent is not None: try: children = parent.children except AttributeError: pass else: include(children, ...
Adds this node to the parent's ``children`` collection if it exists.
def _hn2db(self, hn): ''' This will add a hostname for a hostname for an included domain or return an existing entry ''' db = self.hn_db hn_found = False for k,v in db.items(): if v == hn: #the hostname is in the database ret_hn = k ...
This will add a hostname for a hostname for an included domain or return an existing entry
def AmericanDateToEpoch(self, date_str): """Take a US format date and return epoch.""" try: epoch = time.strptime(date_str, "%m/%d/%Y") return int(calendar.timegm(epoch)) * 1000000 except ValueError: return 0
Take a US format date and return epoch.
def register_dte_task(self, *args, **kwargs): """Register a Dte task.""" kwargs["task_class"] = DteTask return self.register_task(*args, **kwargs)
Register a Dte task.
async def unpinChatMessage(self, chat_id): """ See: https://core.telegram.org/bots/api#unpinchatmessage """ p = _strip(locals()) return await self._api_request('unpinChatMessage', _rectify(p))
See: https://core.telegram.org/bots/api#unpinchatmessage
def _marginal_hidden_probs(self): """Compute marginal pdf for each individual observable.""" initial_log_probs = tf.broadcast_to(self._log_init, tf.concat([self.batch_shape_tensor(), [self._num_states]], ...
Compute marginal pdf for each individual observable.
def create(self, **kwargs): """ Create the tag. """ for attr in kwargs.keys(): setattr(self, attr, kwargs[attr]) params = {"name": self.name} output = self.get_data("tags", type="POST", params=params) if output: self.name = output['ta...
Create the tag.
def upload(self, url, filename, data=None, formname=None, otherfields=()): """Upload a file to the url :param url: :param filename: The name of the file :param data: A file object or data to use rather than reading from the file. :return: ...
Upload a file to the url :param url: :param filename: The name of the file :param data: A file object or data to use rather than reading from the file. :return:
def run_queue(self, pool): """Given a pool, submit jobs from the queue to the pool. """ def callback(result): """Note: mark_done, at a minimum, must happen here or dbt will deadlock during ephemeral result error handling! """ self._handle_result(re...
Given a pool, submit jobs from the queue to the pool.
def _tostr(self,obj): """ converts a object to list, if object is a list, it creates a comma seperated string. """ if not obj: return '' if isinstance(obj, list): return ', '.join(map(self._tostr, obj)) return str(obj)
converts a object to list, if object is a list, it creates a comma seperated string.
def delete_columns(self, columns): """ Delete columns from the DataFrame :param columns: list of columns to delete :return: nothing """ columns = [columns] if not isinstance(columns, (list, blist)) else columns if not all([x in self._columns for x in columns]): ...
Delete columns from the DataFrame :param columns: list of columns to delete :return: nothing
def functional(self, *pattern, **kwargs): """ Add functional pattern :param pattern: :type pattern: :return: self :rtype: Rebulk """ self.pattern(self.build_functional(*pattern, **kwargs)) return self
Add functional pattern :param pattern: :type pattern: :return: self :rtype: Rebulk
def _wrap_el(self, value): """Convert WebElement Object to {'Element': 1234} Args: value(str|list|dict): The local value. Returns: The wrapped value. """ if isinstance(value, dict): return {k: self._wrap_el(v) for k, v in value.items()} ...
Convert WebElement Object to {'Element': 1234} Args: value(str|list|dict): The local value. Returns: The wrapped value.
def printMetrics(self, m, d): """ Prints out table rows based on the size of the data in columns """ for metric in self.metrics: mstr = metric['displayName'] dstr = metric['description'] mlen = m - len(mstr) dlen = d - len(dstr) ...
Prints out table rows based on the size of the data in columns
def p_jointype(self,t): """jointype : kw_join | kw_inner kw_join | outerjoin kw_outer kw_join | outerjoin kw_join """ if len(t) <= 2 or t[1] == 'inner': t[0] = JoinTypeX(None, False, None) else: t[0] = JoinTypeX(t[1], True, None)
jointype : kw_join | kw_inner kw_join | outerjoin kw_outer kw_join | outerjoin kw_join
def create(self, resource): """Create a new package. :param resource: :class:`packages.Package <packages.Package>` object :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package """ schema = PackageSchema(exclude=('id', 'created', 'updated',...
Create a new package. :param resource: :class:`packages.Package <packages.Package>` object :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package
def footnotemap(self, cache=True): """return the footnotes from the docx, keyed to string id.""" if self.__footnotemap is not None and cache==True: return self.__footnotemap else: x = self.xml(src='word/footnotes.xml') d = Dict() if x is None: retu...
return the footnotes from the docx, keyed to string id.
def get_retention_policy(database, name, **client_args): ''' Get an existing retention policy. database Name of the database for which the retention policy was defined. name Name of the retention policy. CLI Example: .. code-block:: bash salt '*' influxdb.get...
Get an existing retention policy. database Name of the database for which the retention policy was defined. name Name of the retention policy. CLI Example: .. code-block:: bash salt '*' influxdb.get_retention_policy metrics default
def oc_attr_isdefault(o): """Return wether an OC attribute has been defined or not.""" if not o._changed() and not o.default(): return True if o == o.default(): return True return False
Return wether an OC attribute has been defined or not.
def kill(path): """ Kills the process, if it still exists. :type path: str :param path: The name of the pidfile. """ # try to read the pid from the pidfile pid = read(path) if pid is None: return # Try to kill the process. logging.info("Killing PID %s", pid) try: ...
Kills the process, if it still exists. :type path: str :param path: The name of the pidfile.
def list_device_subscriptions(self, device_id, **kwargs): """Lists all subscribed resources from a single device :param device_id: ID of the device (Required) :returns: a list of subscribed resources :rtype: list of str """ api = self._get_api(mds.SubscriptionsApi) ...
Lists all subscribed resources from a single device :param device_id: ID of the device (Required) :returns: a list of subscribed resources :rtype: list of str
def get_fields(self): """ Return static and instance fields :rtype: a list of :class:`EncodedField` objects """ return [x for x in self.static_fields] + [x for x in self.instance_fields]
Return static and instance fields :rtype: a list of :class:`EncodedField` objects
def request(self, method, *parts, **options): """Requests a URL and returns a *Bunched* response. This method basically wraps the request method of the requests module and adds a `path` and `debug` option. :param method: The request method, e.g. 'get', 'post', etc. :param parts...
Requests a URL and returns a *Bunched* response. This method basically wraps the request method of the requests module and adds a `path` and `debug` option. :param method: The request method, e.g. 'get', 'post', etc. :param parts: (optional) Additional path parts to append to the URL ...
def clone(self): """todo: Docstring for clone :return: :rtype: """ logger.debug("") if not self.url: estr = "Cannot install this repos without a URL. %s" % self.info() logger.warning(estr) raise ValueError(estr) # check if...
todo: Docstring for clone :return: :rtype:
def check_hex(value): """ Check if the given hex value is a valid RGB color It should match the format: [0-9a-fA-F] and be of length 3 or 6. """ length = len(value) if length not in (3, 6): raise ValueError('Hex string #{} is too long'.format(value)) regex = r'[0-9a-f]{{{length...
Check if the given hex value is a valid RGB color It should match the format: [0-9a-fA-F] and be of length 3 or 6.
def remove_excluded(self): """Remove all sources marked as excluded. """ # import yaml # print yaml.dump({k:v.__json__() for k,v in self.sources.items()}, default_flow_style=False) sources = list(self.sources.values()) for src in sources: if src.excluded: ...
Remove all sources marked as excluded.
def list_pkgs(versions_as_list=False, include_components=True, include_updates=True, **kwargs): ''' List the packages currently installed. .. note:: To view installed software as displayed in the Add/Remove Programs, set ``include_components`` and `...
List the packages currently installed. .. note:: To view installed software as displayed in the Add/Remove Programs, set ``include_components`` and ``include_updates`` to False. Args: versions_as_list (bool): Returns the versions as a list include_components (bool...
def environment_session_entity_type_path(cls, project, environment, user, session, entity_type): """Return a fully-qualified environment_session_entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/environm...
Return a fully-qualified environment_session_entity_type string.
def add_plugin(self, f): """Adding and verifying plugin. Args: f: the filepath for the plugin. """ if f.endswith('.py'): # Just the basename without extension plugin_name = os.path.splitext(os.path.basename(f))[0] # It's possible the plu...
Adding and verifying plugin. Args: f: the filepath for the plugin.
def abort(self): """Return an HTML Response representation of the exception.""" resp = make_response(render_template('error.html', error=self.code, message=self.message), self.code) return resp
Return an HTML Response representation of the exception.
def cmd_reload_global(self, plname): """reload_global `plname` Reload the *global* plugin named `plname`. You should close all instances of the plugin before attempting to reload. """ gpmon = self.fv.gpmon p_info = gpmon.get_plugin_info(plname) gpmon.stop_plugin...
reload_global `plname` Reload the *global* plugin named `plname`. You should close all instances of the plugin before attempting to reload.
async def main(): """Get the data from a *hole instance.""" async with aiohttp.ClientSession() as session: data = Hole('192.168.0.215', loop, session) await data.get_data() # Get the raw data print(json.dumps(data.data, indent=4, sort_keys=True)) print("Status:", data.s...
Get the data from a *hole instance.
def get_none_packages(self): """ Get packages with None (not founded), recursively """ not_found = set() for package_name, package in self.packages.items(): if package is None: not_found.add(package_name) else: if package.pa...
Get packages with None (not founded), recursively
def validate_analysis_period(self): """Get a collection where the header analysis_period aligns with datetimes. This means that checks for four criteria will be performed: 1) All days in the data collection are chronological starting from the analysis_period start day to the end day...
Get a collection where the header analysis_period aligns with datetimes. This means that checks for four criteria will be performed: 1) All days in the data collection are chronological starting from the analysis_period start day to the end day. 2) No duplicate days exist in the dat...
def _build_train_op(self): """Build training specific ops for the graph.""" num_gpus = self.hps.num_gpus if self.hps.num_gpus != 0 else 1 # The learning rate schedule is dependent on the number of gpus. boundaries = [int(20000 * i / np.sqrt(num_gpus)) for i in range(2, 5)] values...
Build training specific ops for the graph.
def announce_done(self): """Announce that future is done running and run associated callbacks This will run any failure cleanups if the transfer failed if not they have not been run, allows the result() to be unblocked, and will run any done callbacks associated to the TransferFuture if...
Announce that future is done running and run associated callbacks This will run any failure cleanups if the transfer failed if not they have not been run, allows the result() to be unblocked, and will run any done callbacks associated to the TransferFuture if they have not already been ...
def event_callback(self, event_data): ''' Invoked for every Ansible event to collect stdout with the event data and store it for later use ''' self.last_stdout_update = time.time() job_events_path = os.path.join(self.config.artifact_dir, 'job_events') if not os.pa...
Invoked for every Ansible event to collect stdout with the event data and store it for later use
def _symlink_or_copy_grabix(in_file, out_file, data): """We cannot symlink in CWL, but may be able to use inputs or copy """ if cwlutils.is_cwl_run(data): # Has grabix indexes, we're okay to go if utils.file_exists(in_file + ".gbi"): out_file = in_file else: u...
We cannot symlink in CWL, but may be able to use inputs or copy
def vote_IRV(candidates, votes, n_winners): """Perform IRV voting based on votes. Ties are resolved randomly. :param candidates: All candidates in the vote :param votes: Votes from the agents :param int n_winners: The number of vote winners """ # TODO: Check what is wrong in here. vote...
Perform IRV voting based on votes. Ties are resolved randomly. :param candidates: All candidates in the vote :param votes: Votes from the agents :param int n_winners: The number of vote winners
def has_constraint_violation(A, right_eigenvectors, epsilon=1E-8): """Check for constraint violations in transformation matrix. Parameters ---------- A : ndarray The transformation matrix. right_eigenvectors : ndarray The right eigenvectors. epsilon : float, optional Tol...
Check for constraint violations in transformation matrix. Parameters ---------- A : ndarray The transformation matrix. right_eigenvectors : ndarray The right eigenvectors. epsilon : float, optional Tolerance of constraint violation. Returns ------- truth : bool ...
def dists(node): """ :returns: hpdist, npdist and magScaleRel from the given pointSource node """ hd = tuple((node['probability'], node['depth']) for node in node.hypoDepthDist) npd = tuple( ((node['probability'], node['rake'], node['strike'], node['dip'])) for node in...
:returns: hpdist, npdist and magScaleRel from the given pointSource node
async def post(self): """Creates new account Accepts: - message (signed dict): - "device_id" - str - "email" - str - "phone" - str - "public_key" - str - "signature" - str Returns: dictionary with following fields: - "device_id" - str - "phone" - str - "public_key" - str ...
Creates new account Accepts: - message (signed dict): - "device_id" - str - "email" - str - "phone" - str - "public_key" - str - "signature" - str Returns: dictionary with following fields: - "device_id" - str - "phone" - str - "public_key" - str - "count" - int ( wallets ...
def _update_header(orig_vcf, base_file, new_lines, chrom_process_fn=None): """Fix header with additional lines and remapping of generic sample names. """ new_header = "%s-sample_header.txt" % utils.splitext_plus(base_file)[0] with open(new_header, "w") as out_handle: chrom_line = None wi...
Fix header with additional lines and remapping of generic sample names.
def _get_object_by_name(self, object_endpoint, object_name, timeout=None): """ generic function to get object (metadata, tag, ) by name from SignalFx. Args: object_endpoint (string): API endpoint suffix (e.g. 'v2/tag') object_name (string): name of the object (e.g. 'jvm....
generic function to get object (metadata, tag, ) by name from SignalFx. Args: object_endpoint (string): API endpoint suffix (e.g. 'v2/tag') object_name (string): name of the object (e.g. 'jvm.cpu.load') Returns: dictionary of response
def get_dependent_data_items(self, data_item: DataItem) -> typing.List[DataItem]: """Return the dependent data items the data item argument. :return: The list of :py:class:`nion.swift.Facade.DataItem` objects. .. versionadded:: 1.0 Scriptable: Yes """ return [DataItem(...
Return the dependent data items the data item argument. :return: The list of :py:class:`nion.swift.Facade.DataItem` objects. .. versionadded:: 1.0 Scriptable: Yes
def set(self, value): """ Sets the value of the DNS name :param value: A unicode string """ if not isinstance(value, str_cls): raise TypeError(unwrap( ''' %s value must be a unicode string, not %s ''', ...
Sets the value of the DNS name :param value: A unicode string
def set_attribute(self, selector, attribute, value, by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT): """ This method uses JavaScript to set/update an attribute. """ if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(ti...
This method uses JavaScript to set/update an attribute.
def _copy_convert(X, const=None, remove_mean=False, copy=True): r""" Makes a copy or converts the data type if needed Copies the data and converts the data type if unsuitable for covariance calculation. The standard data type for covariance computations is float64, because the double precision (but not...
r""" Makes a copy or converts the data type if needed Copies the data and converts the data type if unsuitable for covariance calculation. The standard data type for covariance computations is float64, because the double precision (but not single precision) is usually sufficient to compute the long sum...
def generateFeatureGroups(fgiContainer, linkageGroups, matchArr, timeKey, massKey, logMassKey, massScalingFactor): """ #TODO: docstring :param fgiContainer: :param linkageGroups: :returns: a list of ids of the newly generated :class:`Fgi` """ #Generate feature groups ...
#TODO: docstring :param fgiContainer: :param linkageGroups: :returns: a list of ids of the newly generated :class:`Fgi`
def _write_training_metrics(self): """ Write all CSV metrics :return: """ for brain_name in self.trainers.keys(): if brain_name in self.trainer_metrics: self.trainers[brain_name].write_training_metrics()
Write all CSV metrics :return:
def set_from_json(self, name, json, models=None, setter=None): ''' Set a property value on this object from JSON. Args: name: (str) : name of the attribute to set json: (JSON-value) : value to set to the attribute to models (dict or None, optional) : ...
Set a property value on this object from JSON. Args: name: (str) : name of the attribute to set json: (JSON-value) : value to set to the attribute to models (dict or None, optional) : Mapping of model ids to models (default: None) This is n...
def _ruby_installed(ret, ruby, user=None): ''' Check to see if given ruby is installed. ''' default = __salt__['rbenv.default'](runas=user) for version in __salt__['rbenv.versions'](user): if version == ruby: ret['result'] = True ret['comment'] = 'Requested ruby exist...
Check to see if given ruby is installed.
def to_XML(self, xml_declaration=True, xmlns=True): """ Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefix...
Dumps object fields to an XML-formatted string. The 'xml_declaration' switch enables printing of a leading standard XML line containing XML version and encoding. The 'xmlns' switch enables printing of qualified XMLNS prefixes. :param XML_declaration: if ``True`` (default) prints a lead...
def fix_scheme(url): '''Prepends the http:// scheme if necessary to a url. Fails if a scheme other than http is used''' splitted = url.split('://') if len(splitted) == 2: if splitted[0] in ('http', 'https'): return url else: raise exc.WileECoyoteException( ...
Prepends the http:// scheme if necessary to a url. Fails if a scheme other than http is used
def options_by_section(self): """return an iterator on options grouped by section (section, [list of (optname, optdict, optvalue)]) """ sections = {} for optname, optdict in self.options: sections.setdefault(optdict.get("group"), []).append( (optname,...
return an iterator on options grouped by section (section, [list of (optname, optdict, optvalue)])
def scope_compose(scope, name, sep=private.SCOPE_SEPARATOR): """ compose a new scope :param str scope: current scope :param str name: name of next level in scope :return the composed scope """ if name == None: new_scope = scope else: new_scope = scope if scope else name ...
compose a new scope :param str scope: current scope :param str name: name of next level in scope :return the composed scope
def parse_setup() -> Tuple[PackagesType, PackagesType, Set[str], Set[str]]: """Parse all dependencies out of the setup.py script.""" essential_packages: PackagesType = {} test_packages: PackagesType = {} essential_duplicates: Set[str] = set() test_duplicates: Set[str] = set() with open('setup.p...
Parse all dependencies out of the setup.py script.
def _int64_feature_list(values): """Wrapper for inserting an int64 FeatureList into a SequenceExample proto, e.g, sentence in list of ints """ return tf.train.FeatureList(feature=[_int64_feature(v) for v in values])
Wrapper for inserting an int64 FeatureList into a SequenceExample proto, e.g, sentence in list of ints