code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def dock_json_has_plugin_conf(self, plugin_type, plugin_name): """ Check whether a plugin is configured. """ try: self.dock_json_get_plugin_conf(plugin_type, plugin_name) return True except (KeyError, IndexError): return False
Check whether a plugin is configured.
def add_location_timezone_to_device(self, device_obj, location, timezone): """ Returns 'device object' with updated location http://docs.exosite.com/portals/#update-device http://docs.exosite.com/portals/#device-object """ dictify_device_meta(devi...
Returns 'device object' with updated location http://docs.exosite.com/portals/#update-device http://docs.exosite.com/portals/#device-object
def plate_rate_mc(pole1_plon, pole1_plat, pole1_kappa, pole1_N, pole1_age, pole1_age_error, pole2_plon, pole2_plat, pole2_kappa, pole2_N, pole2_age, pole2_age_error, ref_loc_lon, ref_loc_lat, samplesize=10000, random_seed=None, plot=True, savefig=True, save_director...
Determine the latitudinal motion implied by a pair of poles and utilize the Monte Carlo sampling method of Swanson-Hysell (2014) to determine the associated uncertainty. Parameters: ------------ plon : longitude of pole plat : latitude of pole kappa : Fisher precision parameter for VPGs in ...
def get_map_matrix(inputfile, sheet_name): """ Return the matrix representation of the genetic map. :arg inputfile: the path to the input file from which to retrieve the genetic map. :arg sheet_name: the excel sheet containing the data on which to retrieve the genetic map. """ matr...
Return the matrix representation of the genetic map. :arg inputfile: the path to the input file from which to retrieve the genetic map. :arg sheet_name: the excel sheet containing the data on which to retrieve the genetic map.
def domain_score(self, domains): """Calls domain scores endpoint. This method is deprecated since OpenDNS Investigate API endpoint is also deprecated. """ warn( 'OpenDNS Domain Scores endpoint is deprecated. Use ' 'InvestigateApi.categorization() instead'...
Calls domain scores endpoint. This method is deprecated since OpenDNS Investigate API endpoint is also deprecated.
def calc(args): """ %prog calc [prot.fasta] cds.fasta > out.ks Protein file is optional. If only one file is given, it is assumed to be CDS sequences with correct frame (frame 0). Results will be written to stdout. Both protein file and nucleotide file are assumed to be Fasta format, with adjac...
%prog calc [prot.fasta] cds.fasta > out.ks Protein file is optional. If only one file is given, it is assumed to be CDS sequences with correct frame (frame 0). Results will be written to stdout. Both protein file and nucleotide file are assumed to be Fasta format, with adjacent records as the pairs to ...
def bundle_javascript(context: Context): """ Compiles javascript """ args = ['--bail'] if context.verbosity > 0: args.append('--verbose') if not context.use_colour: args.append('--no-colors') return context.node_tool('webpack', *args)
Compiles javascript
def construct_variables(self, kwargs): """ Construct the inputs to the attack graph to be used by generate_np. :param kwargs: Keyword arguments to generate_np. :return: Structural arguments Feedable arguments Output of `arg_type` describing feedable arguments A unique key ""...
Construct the inputs to the attack graph to be used by generate_np. :param kwargs: Keyword arguments to generate_np. :return: Structural arguments Feedable arguments Output of `arg_type` describing feedable arguments A unique key
def check_response(headers: Headers, key: str) -> None: """ Check a handshake response received from the server. ``key`` comes from :func:`build_request`. If the handshake is valid, this function returns ``None``. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception...
Check a handshake response received from the server. ``key`` comes from :func:`build_request`. If the handshake is valid, this function returns ``None``. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception. This function doesn't verify that the response is an HTTP/1.1...
def db_list(**connection_args): ''' Return a list of databases of a MySQL server using the output from the ``SHOW DATABASES`` query. CLI Example: .. code-block:: bash salt '*' mysql.db_list ''' dbc = _connect(**connection_args) if dbc is None: return [] cur = dbc.c...
Return a list of databases of a MySQL server using the output from the ``SHOW DATABASES`` query. CLI Example: .. code-block:: bash salt '*' mysql.db_list
def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]: """ The CONLL 2012 data includes 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are identical, and if it finds any, merges the clusters co...
The CONLL 2012 data includes 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are identical, and if it finds any, merges the clusters containing the identical spans.
def fetch_items(self, category, **kwargs): """Fetch the items (issues or pull_requests) :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] to_date = kwargs['to_date'...
Fetch the items (issues or pull_requests) :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
def _chi_lr(self,r, phi, nl,nr,beta): """ computes the generalized polar basis function in the convention of Massey&Refregier eqn 8 :param nl: left basis :type nl: int :param nr: right basis :type nr: int :param beta: beta --the characteristic scale typically cho...
computes the generalized polar basis function in the convention of Massey&Refregier eqn 8 :param nl: left basis :type nl: int :param nr: right basis :type nr: int :param beta: beta --the characteristic scale typically choosen to be close to the size of the object. :type ...
def _AssertIsLocal(path): ''' Checks if a given path is local, raise an exception if not. This is used in filesystem functions that do not support remote operations yet. :param unicode path: :raises NotImplementedForRemotePathError: If the given path is not local ''' from six.move...
Checks if a given path is local, raise an exception if not. This is used in filesystem functions that do not support remote operations yet. :param unicode path: :raises NotImplementedForRemotePathError: If the given path is not local
def makeCubicxFunc(self,mLvl,pLvl,MedShk,xLvl): ''' Constructs the (unconstrained) expenditure function for this period using bilinear interpolation (over permanent income and the medical shock) among an array of cubic interpolations over market resources. Parameters ---...
Constructs the (unconstrained) expenditure function for this period using bilinear interpolation (over permanent income and the medical shock) among an array of cubic interpolations over market resources. Parameters ---------- mLvl : np.array Corresponding market res...
def add(self, username, courseid, taskid, consumer_key, service_url, result_id): """ Add a job in the queue :param username: :param courseid: :param taskid: :param consumer_key: :param service_url: :param result_id: """ search = {"username": userna...
Add a job in the queue :param username: :param courseid: :param taskid: :param consumer_key: :param service_url: :param result_id:
def __alloc_raw_data(self, initial_values=None): """Pre-allocate re-usagle memory""" #allocate c_ubyte storage if self.__raw_data == None: #first time only, create storage raw_data_type = c_ubyte * self.__raw_report_size self.__raw_data = raw_data_type() eli...
Pre-allocate re-usagle memory
def _next(self, **kwargs): """ Get the next item in any particular category """ spec = self._pagination_default_spec(kwargs) spec.update(kwargs) query = queries.build_query(spec) query = queries.where_after_entry(query, self._record) for record in query.order_by(model.E...
Get the next item in any particular category
def displayHelp(self): """ Output help message of twistedchecker. """ self.outputStream.write(self.linter.help()) sys.exit(32)
Output help message of twistedchecker.
def install_pip(env, requirements): """Install pip and its requirements using setuptools.""" try: installation_source_folder = config.installation_cache_folder() options = setuptools_install_options(installation_source_folder) if installation_source_folder is not None: ...
Install pip and its requirements using setuptools.
def unfollow(self, auth_secret, followee_username): """Unfollow a user. Parameters ---------- auth_secret: str The authentication secret of the logged-in user. followee_username: str The username of the followee. Returns ------- b...
Unfollow a user. Parameters ---------- auth_secret: str The authentication secret of the logged-in user. followee_username: str The username of the followee. Returns ------- bool True if the unfollow is successful, False other...
def simulate(): '''instantiate and execute network simulation''' #separate model execution from parameters for safe import from other files nest.ResetKernel() ''' Configuration of the simulation kernel by the previously defined time resolution used in the simulation. Setting "print_time" to Tru...
instantiate and execute network simulation
def build(config, services): """ Builds images and tags them appropriately. Where "appropriately" means with the output of: git describe --tags HEAD and 'latest' as well (so the "latest" image for each will always be the most recently built) """ filtered_services = {name: service for ...
Builds images and tags them appropriately. Where "appropriately" means with the output of: git describe --tags HEAD and 'latest' as well (so the "latest" image for each will always be the most recently built)
def get_credentials(env=None): """ Gets the TextMagic credentials from current environment :param env: environment :return: username, token """ environ = env or os.environ try: username = environ["TEXTMAGIC_USERNAME"] token = environ["TEXTMAGIC_AUTH_TOKEN"] return us...
Gets the TextMagic credentials from current environment :param env: environment :return: username, token
def _delete_file(fileName, n=10): """Cleanly deletes a file in `n` attempts (if necessary)""" status = False count = 0 while not status and count < n: try: _os.remove(fileName) except OSError: count += 1 _time.sleep(0.2) else: statu...
Cleanly deletes a file in `n` attempts (if necessary)
def post_result_data(self, client, check, output, status): """ Posts check result data. """ data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(da...
Posts check result data.
def _is_bugged_tarfile(self): """ Check for tar file that tarfile library mistakenly reports as invalid. Happens with tar files created on FAT systems. See: http://stackoverflow.com/questions/25552162/tarfile-readerror-file-could-not-be-opened-successfully """ try: ...
Check for tar file that tarfile library mistakenly reports as invalid. Happens with tar files created on FAT systems. See: http://stackoverflow.com/questions/25552162/tarfile-readerror-file-could-not-be-opened-successfully
def rel_path(self, uuid): # type: (UUID) -> Path """Contruct relative path from repository top directory to the file named after this uuid. :param:uuid: :class:`UUID` instance """ _assert_uuid(uuid) filename = str(uuid) return Path(filename[0:2], filename...
Contruct relative path from repository top directory to the file named after this uuid. :param:uuid: :class:`UUID` instance
def pipe_split(context, _INPUT, conf, splits, **kwargs): """An operator that splits a source into identical copies. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : dict splits : number of copies Y...
An operator that splits a source into identical copies. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : dict splits : number of copies Yields ------ _OUTPUT, _OUTPUT2... : copies of all source...
def money_receipts(pronac, dt): """ Checks how many items are in a same receipt when payment type is withdraw/money - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt """ df = verified_repeated_...
Checks how many items are in a same receipt when payment type is withdraw/money - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt
def _needs_download(self, f): ''' Decorator used to make sure that the downloading happens prior to running the task. ''' @wraps(f) def wrapper(self, *args, **kwargs): if not self.isdownloaded(): self.download() return f(self, *args, **kwargs) return wrapper
Decorator used to make sure that the downloading happens prior to running the task.
def retrieve_width(self, signum=None, frame=None): """ Stores the terminal width into ``self.width``, if possible. This function is also the SIGWINCH event handler. """ for method_name, args in self.strategies: method = getattr(self, "from_" + method_name) ...
Stores the terminal width into ``self.width``, if possible. This function is also the SIGWINCH event handler.
def create_download_specifications(ctx_cli_options, config): # type: (dict, dict) -> List[blobxfer.models.download.Specification] """Create a list of Download Specification objects from configuration :param dict ctx_cli_options: cli options :param dict config: config dict :rtype: list :return: l...
Create a list of Download Specification objects from configuration :param dict ctx_cli_options: cli options :param dict config: config dict :rtype: list :return: list of Download Specification objects
def topology_from_numpy(atoms, bonds=None): """Create a mdtraj topology from numpy arrays Parameters ---------- atoms : np.ndarray The atoms in the topology, represented as a data frame. This data frame should have columns "serial" (atom index), "name" (atom name), "element" (at...
Create a mdtraj topology from numpy arrays Parameters ---------- atoms : np.ndarray The atoms in the topology, represented as a data frame. This data frame should have columns "serial" (atom index), "name" (atom name), "element" (atom's element), "resSeq" (index of the residue) ...
def update_dict(self, newdata: dict) -> 'Language': """ Update the attributes of this Language from a dictionary. """ return Language.make( language=newdata.get('language', self.language), extlangs=newdata.get('extlangs', self.extlangs), script=newdata...
Update the attributes of this Language from a dictionary.
def _is_did(did): """Return True if ``did`` is recorded in a local context. ``did``=None is supported and returns False. A DID can be classified with classify_identifier(). """ return d1_gmn.app.models.IdNamespace.objects.filter(did=did).exists()
Return True if ``did`` is recorded in a local context. ``did``=None is supported and returns False. A DID can be classified with classify_identifier().
def _lrepr_fallback( # pylint: disable=too-many-arguments o: Any, human_readable: bool = False, print_dup: bool = PRINT_DUP, print_length: PrintCountSetting = PRINT_LENGTH, print_level: PrintCountSetting = PRINT_LEVEL, print_meta: bool = PRINT_META, print_readably: bool = PRINT_READABLY, ) ...
Fallback function for lrepr for subclasses of standard types. The singledispatch used for standard lrepr dispatches using an exact type match on the first argument, so we will only hit this function for subclasses of common Python types like strings or lists.
def install(name=None, refresh=False, pkgs=None, sources=None, reinstall=False, **kwargs): ''' Install the passed package, add refresh=True to update the opkg database. name The name of the package to be installed. Note that this parameter...
Install the passed package, add refresh=True to update the opkg database. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a ...
async def purge(self, *, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True): """|coro| Purges a list of messages that meet the criteria given by the predicate ``check``. If a ``check`` is not provided then all messages are deleted without discrim...
|coro| Purges a list of messages that meet the criteria given by the predicate ``check``. If a ``check`` is not provided then all messages are deleted without discrimination. You must have the :attr:`~Permissions.manage_messages` permission to delete messages even if they are y...
def configure(self, *, hwm: int=None, rcvtimeo: int=None, sndtimeo: int=None, linger: int=None) -> 'Socket': """ Allows to configure some common socket options and configurations, while allowing method chaining """ if hwm is not None: self.set_hwm(hwm) if rcvtimeo is ...
Allows to configure some common socket options and configurations, while allowing method chaining
def __add_hopscotch_tour_step(self, message, selector=None, name=None, title=None, alignment=None): """ Allows the user to add tour steps for a website. @Params message - The message to display. selector - The CSS Selector of the Element to a...
Allows the user to add tour steps for a website. @Params message - The message to display. selector - The CSS Selector of the Element to attach to. name - If creating multiple tours at the same time, use this to select the tour you wish to add steps to....
def pub_connect(self): ''' Create and connect this thread's zmq socket. If a publisher socket already exists "pub_close" is called before creating and connecting a new socket. ''' if self.pub_sock: self.pub_close() ctx = zmq.Context.instance() ...
Create and connect this thread's zmq socket. If a publisher socket already exists "pub_close" is called before creating and connecting a new socket.
def from_date(cls, date): """ Returns a Month instance from the given datetime.date or datetime.datetime object """ try: date = date.date() except AttributeError: pass return cls(date.year, date.month)
Returns a Month instance from the given datetime.date or datetime.datetime object
def check_lt(self): """ Check is the POSTed LoginTicket is valid, if yes invalide it :return: ``True`` if the LoginTicket is valid, ``False`` otherwise :rtype: bool """ # save LT for later check lt_valid = self.request.session.get('lt', []) lt...
Check is the POSTed LoginTicket is valid, if yes invalide it :return: ``True`` if the LoginTicket is valid, ``False`` otherwise :rtype: bool
def get_Generic_parameters(tp, generic_supertype): """tp must be a subclass of generic_supertype. Retrieves the type values from tp that correspond to parameters defined by generic_supertype. E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent to get_Mapping_key_value(tp) except for the e...
tp must be a subclass of generic_supertype. Retrieves the type values from tp that correspond to parameters defined by generic_supertype. E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent to get_Mapping_key_value(tp) except for the error message. Note that get_Generic_itemtype(tp) is n...
def get_authservers(self, domainid, page=None): """Get Authentication servers""" opts = {} if page: opts['page'] = page return self.api_call( ENDPOINTS['authservers']['list'], dict(domainid=domainid), **opts)
Get Authentication servers
def get(self, sid): """ Constructs a RoomRecordingContext :param sid: The sid :returns: twilio.rest.video.v1.room.recording.RoomRecordingContext :rtype: twilio.rest.video.v1.room.recording.RoomRecordingContext """ return RoomRecordingContext(self._version, room_...
Constructs a RoomRecordingContext :param sid: The sid :returns: twilio.rest.video.v1.room.recording.RoomRecordingContext :rtype: twilio.rest.video.v1.room.recording.RoomRecordingContext
def _get_name_filter(package, context="decorate", reparse=False): """Makes sure that the name filters for the specified package have been loaded. Args: package (str): name of the package that this method belongs to. context (str): one of ['decorate', 'time', 'analyze']; specifies which ...
Makes sure that the name filters for the specified package have been loaded. Args: package (str): name of the package that this method belongs to. context (str): one of ['decorate', 'time', 'analyze']; specifies which section of the configuration settings to check.
def count_account(self, domain): """ Count the number of accounts for a given domain, sorted by cos :returns: a list of pairs <ClassOfService object>,count """ selector = domain.to_selector() cos_list = self.request_list('CountAccount', {'domain': selector}) ret = [] ...
Count the number of accounts for a given domain, sorted by cos :returns: a list of pairs <ClassOfService object>,count
def plot(self, colorbar=True, cb_orientation='vertical', cb_label='geoid, m', show=True, **kwargs): """ Plot the geoid. Usage ----- x.plot([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parame...
Plot the geoid. Usage ----- x.plot([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plottin...
def allLocales(self): """ Returns all the locales that are defined within the babel architecture. :return [<str>, ..] """ if self._allLocales: return self._allLocales expr = re.compile('[a-z]+_[A-Z]+') locales =...
Returns all the locales that are defined within the babel architecture. :return [<str>, ..]
def convert_cg3_to_conll( lines, **kwargs ): ''' Converts the output of VISL_CG3 based syntactic parsing into CONLL format. Expects that the output has been cleaned ( via method cleanup_lines() ). Returns a list of CONLL format lines; Parameters ----------- lines : l...
Converts the output of VISL_CG3 based syntactic parsing into CONLL format. Expects that the output has been cleaned ( via method cleanup_lines() ). Returns a list of CONLL format lines; Parameters ----------- lines : list of str The input text for the pipelin...
def prj_create_atype(self, *args, **kwargs): """Create a new project :returns: None :rtype: None :raises: None """ if not self.cur_prj: return atype = self.create_atype(projects=[self.cur_prj]) if atype: atypedata = djitemdata.Atyp...
Create a new project :returns: None :rtype: None :raises: None
def set_icon(self, icon): '''Sets the listitem's icon image''' self._icon = icon return self._listitem.setIconImage(icon)
Sets the listitem's icon image
def close_comments(self, request, queryset): """ Close the comments for selected entries. """ queryset.update(comment_enabled=False) self.message_user( request, _('Comments are now closed for selected entries.'))
Close the comments for selected entries.
def report_command_error(self, error_dict): """ Report a server error executing a command. We keep track of the command's position in the command list, and we add annotation of what the command was, to the error. :param error_dict: The server's error dict for the error encounter...
Report a server error executing a command. We keep track of the command's position in the command list, and we add annotation of what the command was, to the error. :param error_dict: The server's error dict for the error encountered
def get(self, obj, cls): """ Using the lowercase name of the class as node_type, returns `obj.visit_{node_type}`, or `obj.visit_default` if the type-specific method is not found. """ method = self._cache.get(cls) if not method: name = "visit_" + cls.__name__.lower() method = getattr(...
Using the lowercase name of the class as node_type, returns `obj.visit_{node_type}`, or `obj.visit_default` if the type-specific method is not found.
def has_parser(self, url_info: URLInfo): '''Return whether a parser has been created for the URL.''' key = self.url_info_key(url_info) return key in self._parsers
Return whether a parser has been created for the URL.
def min_base_quality(self): ''' The minimum of the base qualities. In the case of a deletion, in which case there are no bases in this PileupElement, the minimum is taken over the sequenced bases immediately before and after the deletion. ''' try: return min(s...
The minimum of the base qualities. In the case of a deletion, in which case there are no bases in this PileupElement, the minimum is taken over the sequenced bases immediately before and after the deletion.
def checkValidCell(self, index): """Asks the model if the value at *index* is valid See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>` """ col = index.column() row = index.row() return self.model.isFieldValid(row, self._headers[in...
Asks the model if the value at *index* is valid See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>`
def _add_sj_index_commands(fq1, ref_file, gtf_file): """ newer versions of STAR can generate splice junction databases on thephfly this is preferable since we can tailor it to the read lengths """ if _has_sj_index(ref_file): return "" else: rlength = fastq.estimate_maximum_read_l...
newer versions of STAR can generate splice junction databases on thephfly this is preferable since we can tailor it to the read lengths
def _parse_plan(self, match): """Parse a matching plan line.""" expected_tests = int(match.group("expected")) directive = Directive(match.group("directive")) # Only SKIP directives are allowed in the plan. if directive.text and not directive.skip: return Unknown() ...
Parse a matching plan line.
def _read_stdin(): """ Generator for reading from standard input in nonblocking mode. Other ways of reading from ``stdin`` in python waits, until the buffer is big enough, or until EOF character is sent. This functions yields immediately after each line. """ line = sys.stdin.readline() ...
Generator for reading from standard input in nonblocking mode. Other ways of reading from ``stdin`` in python waits, until the buffer is big enough, or until EOF character is sent. This functions yields immediately after each line.
def toggle_aggregation_layer_combo(self): """Toggle the aggregation combo enabled status. Whether the combo is toggled on or off will depend on the current dock status. """ selected_hazard_layer = layer_from_combo(self.hazard_layer_combo) selected_exposure_layer = layer_...
Toggle the aggregation combo enabled status. Whether the combo is toggled on or off will depend on the current dock status.
def _add_method_setting(self, conn, api_id, stage_name, path, key, value, op): """ Update a single method setting on the specified stage. This uses the 'add' operation to PATCH the resource. :param conn: APIGateway API connection :type conn: :py:class...
Update a single method setting on the specified stage. This uses the 'add' operation to PATCH the resource. :param conn: APIGateway API connection :type conn: :py:class:`botocore:APIGateway.Client` :param api_id: ReST API ID :type api_id: str :param stage_name: stage nam...
def siret_validator(): """Validate a SIRET: check its length (14), its final code, and pass it through the Luhn algorithm.""" def _validate_siret(form, field, siret=""): """SIRET validator. A WTForm validator wants a form and a field as parameters. We also want to give directly a s...
Validate a SIRET: check its length (14), its final code, and pass it through the Luhn algorithm.
def save_subresource(self, subresource): """ Save the sub-resource NOTE: Currently assumes subresources are stored within a dictionary, keyed with the subresource's ID """ data = deepcopy(subresource._resource) data.pop('id', None) data.pop(self.resource_...
Save the sub-resource NOTE: Currently assumes subresources are stored within a dictionary, keyed with the subresource's ID
def scan(self, table_name, index_name=None, consistent_read=None, projection_expression=None, filter_expression=None, expression_attribute_names=None, expression_attribute_values=None, segment=None, tota...
The `Scan`_ operation returns one or more items and item attributes by accessing every item in a table or a secondary index. If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and results are returned to the user as a ``LastEvaluatedKey`...
def run(name, cmd, container_type=None, exec_driver=None, output=None, no_start=False, stdin=None, python_shell=True, output_loglevel='debug', ignore_retcode=False, path=None, use_vt=False, keep_env=None): ''' Common...
Common logic for running shell commands in containers path path to the container parent (for LXC only) default: /var/lib/lxc (system default) CLI Example: .. code-block:: bash salt myminion container_resource.run mycontainer 'ps aux' container_type=docker exec_driver=nsenter outp...
def resolve_address(endpoint_type=PUBLIC, override=True): """Return unit address depending on net config. If unit is clustered with vip(s) and has net splits defined, return vip on correct network. If clustered with no nets defined, return primary vip. If not clustered, return unit address ensuring ad...
Return unit address depending on net config. If unit is clustered with vip(s) and has net splits defined, return vip on correct network. If clustered with no nets defined, return primary vip. If not clustered, return unit address ensuring address is on configured net split if one is configured, or a J...
def count(self, conn, filters): ''' Returns the count of the items that match the provided filters. For the meaning of what the ``filters`` argument means, see the ``.search()`` method docs. ''' pipe, intersect, temp_id = self._prepare(conn, filters) pipe.zcard(t...
Returns the count of the items that match the provided filters. For the meaning of what the ``filters`` argument means, see the ``.search()`` method docs.
def rank_subgraph_by_node_filter(graph: BELGraph, node_predicates: Union[NodePredicate, Iterable[NodePredicate]], annotation: str = 'Subgraph', reverse: bool = True, ) -> List[Tuple[str, i...
Rank sub-graphs by which have the most nodes matching an given filter. A use case for this function would be to identify which subgraphs contain the most differentially expressed genes. >>> from pybel import from_pickle >>> from pybel.constants import GENE >>> from pybel_tools.integration import o...
def verify2(self, atv_public_key, data): """Last device verification step.""" self._check_initialized() log_binary(_LOGGER, 'Verify', PublicSecret=atv_public_key, Data=data) # Generate a shared secret key public = curve25519.Public(atv_public_key) shared = self._verify_p...
Last device verification step.
def define_batch_env(constructor, num_agents, env_processes): """Create environments and apply all desired wrappers. Args: constructor: Constructor of an OpenAI gym environment. num_agents: Number of environments to combine in the batch. env_processes: Whether to step environment in external processes....
Create environments and apply all desired wrappers. Args: constructor: Constructor of an OpenAI gym environment. num_agents: Number of environments to combine in the batch. env_processes: Whether to step environment in external processes. Returns: In-graph environments object.
def p_gate_op_3(self, program): """ gate_op : id '(' ')' id_list ';' """ program[0] = node.CustomUnitary([program[1], program[4]]) self.verify_as_gate(program[1], program[4]) self.verify_bit_list(program[4]) self.verify_distinct([program[4]])
gate_op : id '(' ')' id_list ';'
def get_operation_ast( document_ast: DocumentNode, operation_name: Optional[str] = None ) -> Optional[OperationDefinitionNode]: """Get operation AST node. Returns an operation AST given a document AST and optionally an operation name. If a name is not provided, an operation is only returned if only one...
Get operation AST node. Returns an operation AST given a document AST and optionally an operation name. If a name is not provided, an operation is only returned if only one is provided in the document.
def append_to_path (path, directory): """Add a directory to the PATH environment variable, if it is a valid directory.""" if not os.path.isdir(directory) or directory in path: return path if not path.endswith(os.pathsep): path += os.pathsep return path + directory
Add a directory to the PATH environment variable, if it is a valid directory.
def get_iso_time(date_part, time_part): r"""Combign date and time into an iso datetime.""" str_date = datetime.datetime.strptime( date_part, '%m/%d/%Y').strftime('%Y-%m-%d') str_time = datetime.datetime.strptime( time_part, '%I:%M %p').strftime('%H:%M:%S') return str_date + "T" +...
r"""Combign date and time into an iso datetime.
def shutdown(self): """Send shutdown command and wait for the process to exit.""" # Return early if this server has already exited. if not process.proc_alive(self.proc): return logger.info("Attempting to connect to %s", self.hostname) client = self.connection ...
Send shutdown command and wait for the process to exit.
def check_environment_temperature(the_session, the_helper, the_snmp_value, the_unit=1): """ OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.4.1 MIB Excerpt The current temperature reading from the probe displayed in the units shown in the 'iemStatusProbeTempUnits' OID (Celsius or Fahrenheit). Descripti...
OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.4.1 MIB Excerpt The current temperature reading from the probe displayed in the units shown in the 'iemStatusProbeTempUnits' OID (Celsius or Fahrenheit). Description of unit OID OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.5 The temperature scale used to display t...
def ConvertFromWireFormat(self, value, container=None): """The wire format is simply a string.""" result = self.type() ReadIntoObject(value[2], 0, result) return result
The wire format is simply a string.
def get_request_token( cls, consumer_key, redirect_uri='http://example.com/', state=None ): ''' Returns the request token that can be used to fetch the access token ''' headers = { 'X-Accept': 'application/json', } url = 'https://getpocket.com/v3/...
Returns the request token that can be used to fetch the access token
def do_drawing(self, size, frame, cairo_ctx): ''' Update the backing store from a cairo context and schedule a redraw (expose event) :param size: width, height in pixels of bot :param frame: frame # thar was drawn :param cairo_ctx: cairo context the bot was drawn on ...
Update the backing store from a cairo context and schedule a redraw (expose event) :param size: width, height in pixels of bot :param frame: frame # thar was drawn :param cairo_ctx: cairo context the bot was drawn on
def prefix_fragment(self, nid): """ Return prefix and fragment/localid for a node """ sep=':' if nid.startswith('http'): if '#' in nid: sep='#' else: sep='/' parts = nid.split(sep) frag = parts.pop() p...
Return prefix and fragment/localid for a node
def response(request, status, obj): """ Generate a response. :param IRequest request: The request being responsed to. :param int status: The response status code to set. :param obj: Something JSON-dumpable to write into the response body. :return bytes: The response body to write out. eg, ret...
Generate a response. :param IRequest request: The request being responsed to. :param int status: The response status code to set. :param obj: Something JSON-dumpable to write into the response body. :return bytes: The response body to write out. eg, return this from a *render_* method.
def use_in(ContentHandler): """ Modify ContentHandler, a sub-class of pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table classes defined in this module when parsing XML documents. Example: >>> from pycbc_glue.ligolw import ligolw >>> class MyContentHandler(ligolw.LIGOLWContentHandler): ... p...
Modify ContentHandler, a sub-class of pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table classes defined in this module when parsing XML documents. Example: >>> from pycbc_glue.ligolw import ligolw >>> class MyContentHandler(ligolw.LIGOLWContentHandler): ... pass ... >>> use_in(MyContentHand...
def isOriginalLocation(attr): """ Attempt to discover if this appearance of a PythonAttribute representing a class refers to the module where that class was defined. """ sourceModule = inspect.getmodule(attr.load()) if sourceModule is None: return False currentModule = attr ...
Attempt to discover if this appearance of a PythonAttribute representing a class refers to the module where that class was defined.
def next_chunk_boundaries_levels(self, buf, prepend_bytes=0): """Computes the next chunk boundaries within `buf`. Similar to :meth:`.next_chunk_boundaries`, but information about which chunker led to a respective boundary is included in the returned value. Args: buf (bytes)...
Computes the next chunk boundaries within `buf`. Similar to :meth:`.next_chunk_boundaries`, but information about which chunker led to a respective boundary is included in the returned value. Args: buf (bytes): The message that is to be chunked. prepend_bytes (Optional[...
def altitudes_send(self, time_boot_ms, alt_gps, alt_imu, alt_barometric, alt_optical_flow, alt_range_finder, alt_extra, force_mavlink1=False): ''' The altitude measured by sensors and IMU time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) ...
The altitude measured by sensors and IMU time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) alt_gps : GPS altitude in meters, expressed as * 1000 (millimeters), above MSL (int32_t) alt_imu : IMU altitude ...
def xml2object(self, content): r"""Convert xml content to python object. :param content: xml content :rtype: dict .. versionadded:: 1.2 """ content = self.xml_filter(content) element = ET.fromstring(content) tree = self.parse(element) if self.__options['...
r"""Convert xml content to python object. :param content: xml content :rtype: dict .. versionadded:: 1.2
def newer(new_ver, old_ver, strict=False): """Determines if the first version tuple is newer than the second. True if newer, False if older, None if difference is after specified version parts.""" if old_ver == new_ver or old_ver + (0,) == new_ver: return False for n, o in zip(new_ver, old_ver):...
Determines if the first version tuple is newer than the second. True if newer, False if older, None if difference is after specified version parts.
def chords(chord_labels, intervals, fs, **kwargs): """Synthesizes chord labels Parameters ---------- chord_labels : list of str List of chord label strings. intervals : np.ndarray, shape=(len(chord_labels), 2) Start and end times of each chord label fs : int Sampling rat...
Synthesizes chord labels Parameters ---------- chord_labels : list of str List of chord label strings. intervals : np.ndarray, shape=(len(chord_labels), 2) Start and end times of each chord label fs : int Sampling rate to synthesize at kwargs Additional keyword a...
def smartplugs(self): """:return: A list of smartplug objects.""" return [SmartPlug(self, plug.get('name')) for plug in self._state.get('deviceStatusInfo', {}).get('device', []) if plug.get('networkHealthState')]
:return: A list of smartplug objects.
def setHandler(self,handler,cbfn): ''' Register a handler for a particular notification type. These are the types of notifications that are acceptable. | 'async-responses' | 'registrations-expired' | 'de-registrations' | 'reg-updates' | 'registrations' | 'notifications' :param str handler: name...
Register a handler for a particular notification type. These are the types of notifications that are acceptable. | 'async-responses' | 'registrations-expired' | 'de-registrations' | 'reg-updates' | 'registrations' | 'notifications' :param str handler: name of the notification type :param fnptr cb...
def getHelpFileAsString(taskname,taskpath): """ This functions will return useful help as a string read from a file in the task's installed directory called "<module>.help". If no such file can be found, it will simply return an empty string. Notes ----- The location of the actual help fil...
This functions will return useful help as a string read from a file in the task's installed directory called "<module>.help". If no such file can be found, it will simply return an empty string. Notes ----- The location of the actual help file will be found under the task's installed directory...
def OnLineWidth(self, event): """Line width choice event handler""" linewidth_combobox = event.GetEventObject() idx = event.GetInt() width = int(linewidth_combobox.GetString(idx)) borders = self.bordermap[self.borderstate] post_command_event(self, self.BorderWidthMsg, w...
Line width choice event handler
def ogrn(self) -> str: """Generate random valid ``OGRN``. :return: OGRN. :Example: 4715113303725. """ numbers = [] for _ in range(0, 12): numbers.append(self.random.randint(1 if _ == 0 else 0, 9)) ogrn = ''.join([str(x) for x in numbers]...
Generate random valid ``OGRN``. :return: OGRN. :Example: 4715113303725.
def read(self, n=None): """Read at most *n* characters from this stream. If *n* is ``None``, return all available characters. """ response = "" while n is None or n > 0: c = self.stream.read(1) if c == "": break elif c == "<": ...
Read at most *n* characters from this stream. If *n* is ``None``, return all available characters.
def lmfit_parameters(self): """ A [`lmfit.Parameters`][1] object built from `scipy_data_fitting.Fit.fitting_parameters`, see `scipy_data_fitting.Fit.parameters`. Each parameters is assigned a key of the form `p_00000`, `p_00001`, `p_00002`, etc. Thus, `sorted(self.lmfit_paramete...
A [`lmfit.Parameters`][1] object built from `scipy_data_fitting.Fit.fitting_parameters`, see `scipy_data_fitting.Fit.parameters`. Each parameters is assigned a key of the form `p_00000`, `p_00001`, `p_00002`, etc. Thus, `sorted(self.lmfit_parameters)` will give the keys in the same orde...
def make_label_index(self, stream_item): 'make a sortedcollection on body.labels' labels = stream_item.body.labels.get(self.annotator_id) if not labels: labels = [] self.label_index = SortedCollection( [l for l in labels if OffsetType.CHARS in l.offsets], ...
make a sortedcollection on body.labels