code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_distributions(cls, ctx, extra_dist_dirs=[]): '''Returns all the distributions found locally.''' if extra_dist_dirs: raise BuildInterruptingException( 'extra_dist_dirs argument to get_distributions ' 'is not yet implemented') dist_dir = ctx.dist...
Returns all the distributions found locally.
def thaw_parameter(self, name): """ Thaw a parameter by name Args: name: The name of the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) self.unfrozen_mask[i] = True
Thaw a parameter by name Args: name: The name of the parameter
def send_with_media( self, *, text: str, files: List[str], captions: List[str]=[], ) -> List[OutputRecord]: """ Upload media to mastodon, and send status and media, and captions if present. :param text: post text. ...
Upload media to mastodon, and send status and media, and captions if present. :param text: post text. :param files: list of files to upload with post. :param captions: list of captions to include as alt-text with files. :returns: list of output records, each ...
def index_config(request): '''This view returns the index configuration of the current application as JSON. Currently, this consists of a Solr index url and the Fedora content models that this application expects to index. .. Note:: By default, Fedora system content models (such as ``fe...
This view returns the index configuration of the current application as JSON. Currently, this consists of a Solr index url and the Fedora content models that this application expects to index. .. Note:: By default, Fedora system content models (such as ``fedora-system:ContentModel-3.0``) ar...
def _engineServicesRunning(): """ Return true if the engine services are running """ process = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE) stdout = process.communicate()[0] result = process.returncode if result != 0: raise RuntimeError("Unable to check for running client job manager") # ...
Return true if the engine services are running
def parse_parameters_from_response(self, response): """ Returns a response signature and query string generated from the server response. 'h' aka signature argument is stripped from the returned query string. """ lines = response.splitlines() pairs = [line.strip()...
Returns a response signature and query string generated from the server response. 'h' aka signature argument is stripped from the returned query string.
def TermsProcessor(instance, placeholder, rendered_content, original_context): """ Adds links all placeholders plugins except django-terms plugins """ if 'terms' in original_context: return rendered_content return mark_safe(replace_terms(rendered_content))
Adds links all placeholders plugins except django-terms plugins
def spans_columns(self, column_names): """ Checks if this index exactly spans the given column names in the correct order. :type column_names: list :rtype: bool """ columns = self.get_columns() number_of_columns = len(columns) same_columns = True ...
Checks if this index exactly spans the given column names in the correct order. :type column_names: list :rtype: bool
def wait_until_running(self, callback=None): """Waits until the remote worker is running, then calls the callback. Usually, this method is passed to a different thread; the callback is then a function patching results through to the result queue.""" status = self.machine.scheduler.wait_u...
Waits until the remote worker is running, then calls the callback. Usually, this method is passed to a different thread; the callback is then a function patching results through to the result queue.
def set_zone(time_zone): ''' Set the local time zone. Use ``timezone.list_zones`` to list valid time_zone arguments :param str time_zone: The time zone to apply :return: True if successful, False if not :rtype: bool :raises: SaltInvocationError on Invalid Timezone :raises: CommandExec...
Set the local time zone. Use ``timezone.list_zones`` to list valid time_zone arguments :param str time_zone: The time zone to apply :return: True if successful, False if not :rtype: bool :raises: SaltInvocationError on Invalid Timezone :raises: CommandExecutionError on failure CLI Exampl...
def remove(self): """Removes the node from the graph. Note this does not remove the associated data object. See :func:`Node.can_remove` for limitations on what can be deleted. :returns: :class:`BaseNodeData` subclass associated with the deleted Node :raises Attri...
Removes the node from the graph. Note this does not remove the associated data object. See :func:`Node.can_remove` for limitations on what can be deleted. :returns: :class:`BaseNodeData` subclass associated with the deleted Node :raises AttributeError: if call...
def _sim_trajectories(self, time_size, start_pos, rs, total_emission=False, save_pos=False, radial=False, wrap_func=wrap_periodic): """Simulate (in-memory) `time_size` steps of trajectories. Simulate Brownian motion diffusion and emission of all the p...
Simulate (in-memory) `time_size` steps of trajectories. Simulate Brownian motion diffusion and emission of all the particles. Uses the attributes: num_particles, sigma_1d, box, psf. Arguments: time_size (int): number of time steps to be simulated. start_pos (array): sha...
def fetch(dataset_uri, item_identifier): """Return abspath to file with item content. Fetches the file from remote storage if required. """ dataset = dtoolcore.DataSet.from_uri(dataset_uri) click.secho(dataset.item_content_abspath(item_identifier))
Return abspath to file with item content. Fetches the file from remote storage if required.
def parse_record( self, lines ): """ Parse a TRANSFAC record out of `lines` and return a motif. """ # Break lines up temp_lines = [] for line in lines: fields = line.rstrip( "\r\n" ).split( None, 1 ) if len( fields ) == 1: fields.ap...
Parse a TRANSFAC record out of `lines` and return a motif.
def _weighting(weights, exponent): """Return a weighting whose type is inferred from the arguments.""" if np.isscalar(weights): weighting = NumpyTensorSpaceConstWeighting(weights, exponent) elif weights is None: weighting = NumpyTensorSpaceConstWeighting(1.0, exponent) else: # last poss...
Return a weighting whose type is inferred from the arguments.
def rec_new(self, zone, record_type, name, content, ttl=1, priority=None, service=None, service_name=None, protocol=None, weight=None, port=None, target=None): """ Create a DNS record for the given zone :param zone: domain name :type zone: str :param record_type: ...
Create a DNS record for the given zone :param zone: domain name :type zone: str :param record_type: Type of DNS record. Valid values are [A/CNAME/MX/TXT/SPF/AAAA/NS/SRV/LOC] :type record_type: str :param name: name of the DNS record :type name: str :param content:...
def set_unit_desired_state(self, unit, desired_state): """Update the desired state of a unit running in the cluster Args: unit (str, Unit): The Unit, or name of the unit to update desired_state: State the user wishes the Unit to be in ("inactive", "loa...
Update the desired state of a unit running in the cluster Args: unit (str, Unit): The Unit, or name of the unit to update desired_state: State the user wishes the Unit to be in ("inactive", "loaded", or "launched") Returns: Unit: The unit t...
def parse_ts(ts): """ parse timestamp. :param ts: timestamp in ISO8601 format :return: tbd!!! """ # ISO8601 = '%Y-%m-%dT%H:%M:%SZ' # ISO8601_MS = '%Y-%m-%dT%H:%M:%S.%fZ' # RFC1123 = '%a, %d %b %Y %H:%M:%S %Z' dt = maya.parse(ts.strip()) return dt.datetime(naive=True)
parse timestamp. :param ts: timestamp in ISO8601 format :return: tbd!!!
def _conditional_toward_zero(method, sign): """ Whether to round toward zero. :param method: rounding method :type method: element of RoundingMethods.METHODS() :param int sign: -1, 0, or 1 as appropriate Complexity: O(1) """ return method is RoundingMeth...
Whether to round toward zero. :param method: rounding method :type method: element of RoundingMethods.METHODS() :param int sign: -1, 0, or 1 as appropriate Complexity: O(1)
def _social_auth_login(self, request, **kwargs): ''' View function that redirects to social auth login, in case the user is not logged in. ''' if request.user.is_authenticated(): if not request.user.is_active or not request.user.is_staff: raise PermissionDenied() else...
View function that redirects to social auth login, in case the user is not logged in.
def files_mkdir(self, path, parents=False, **kwargs): """Creates a directory within the MFS. .. code-block:: python >>> c.files_mkdir("/test") b'' Parameters ---------- path : str Filepath within the MFS parents : bool Cr...
Creates a directory within the MFS. .. code-block:: python >>> c.files_mkdir("/test") b'' Parameters ---------- path : str Filepath within the MFS parents : bool Create parent directories as needed and do not raise an exception ...
def _onCompletionListItemSelected(self, index): """Item selected. Insert completion to editor """ model = self._widget.model() selectedWord = model.words[index] textToInsert = selectedWord[len(model.typedText()):] self._qpart.textCursor().insertText(textToInsert) ...
Item selected. Insert completion to editor
def process_view(self, request, view_func, view_args, view_kwargs): """ Forwards unauthenticated requests to the admin page to the CAS login URL, as well as calls to django.contrib.auth.views.login and logout. """ if view_func == login: return cas_login(reque...
Forwards unauthenticated requests to the admin page to the CAS login URL, as well as calls to django.contrib.auth.views.login and logout.
def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an SNS topic exists. CLI example:: salt myminion boto_sns.exists mytopic region=us-east-1 ''' topics = get_all_topics(region=region, key=key, keyid=keyid, profile=profile) ...
Check to see if an SNS topic exists. CLI example:: salt myminion boto_sns.exists mytopic region=us-east-1
def create_parser(subparsers): ''' :param subparsers: :return: ''' parser = subparsers.add_parser( 'restart', help='Restart a topology', usage="%(prog)s [options] cluster/[role]/[env] <topology-name> [container-id]", add_help=True) args.add_titles(parser) args.add_cluster_role_env...
:param subparsers: :return:
def get_filter_solvers(self, filter_): """Returns the filter solvers that can solve the given filter. Arguments --------- filter : dataql.resources.BaseFilter An instance of the a subclass of ``BaseFilter`` for which we want to get the solver classes that can sol...
Returns the filter solvers that can solve the given filter. Arguments --------- filter : dataql.resources.BaseFilter An instance of the a subclass of ``BaseFilter`` for which we want to get the solver classes that can solve it. Returns ------- li...
def receiver(url, **kwargs): """ Return receiver instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080' """ res = url_to_resources(url) fnc = res["receiver"] return fnc(res.get("url"), **kwargs)
Return receiver instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080'
def set_learning_objectives(self, objective_ids): """Sets the learning objectives. arg: objective_ids (osid.id.Id[]): the learning objective ``Ids`` raise: InvalidArgument - ``objective_ids`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` ...
Sets the learning objectives. arg: objective_ids (osid.id.Id[]): the learning objective ``Ids`` raise: InvalidArgument - ``objective_ids`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
def add_assay(self, name, assay): """ Add an assay to the material. :param name: The name of the new assay. :param assay: A numpy array containing the size class mass fractions for the assay. The sequence of the assay's elements must correspond to the sequence of the...
Add an assay to the material. :param name: The name of the new assay. :param assay: A numpy array containing the size class mass fractions for the assay. The sequence of the assay's elements must correspond to the sequence of the material's size classes.
def get_count(self, *args, **selectors): """ Return the count of UI object with *selectors* Example: | ${count} | Get Count | text=Accessibility | # Get the count of UI object text=Accessibility | | ${accessibility_text} | Get Object | text=Ac...
Return the count of UI object with *selectors* Example: | ${count} | Get Count | text=Accessibility | # Get the count of UI object text=Accessibility | | ${accessibility_text} | Get Object | text=Accessibility | # These two keywords combination ...
def _submit_gauges_from_histogram(self, metric_name, metric, scraper_config, hostname=None): """ Extracts metrics from a prometheus histogram and sends them as gauges """ for sample in metric.samples: val = sample[self.SAMPLE_VALUE] if not self._is_value_valid(val...
Extracts metrics from a prometheus histogram and sends them as gauges
def replace_handler(logger, match_handler, reconfigure): """ Prepare to replace a handler. :param logger: Refer to :func:`find_handler()`. :param match_handler: Refer to :func:`find_handler()`. :param reconfigure: :data:`True` if an existing handler should be replaced, :data...
Prepare to replace a handler. :param logger: Refer to :func:`find_handler()`. :param match_handler: Refer to :func:`find_handler()`. :param reconfigure: :data:`True` if an existing handler should be replaced, :data:`False` otherwise. :returns: A tuple of two values: ...
def setup_columns(self): """Creates the treeview stuff""" tv = self.view['tv_categories'] # sets the model tv.set_model(self.model) # creates the columns cell = gtk.CellRendererText() tvcol = gtk.TreeViewColumn('Name', cell) def cell_data_func(c...
Creates the treeview stuff
def dump_http(method, url, request_headers, response, output_stream): """ Dump all headers and response headers into output_stream. :param request_headers: Dictionary of HTTP request headers. :param response_headers: Dictionary of HTTP response headers. :param output_stream: Stream where the reques...
Dump all headers and response headers into output_stream. :param request_headers: Dictionary of HTTP request headers. :param response_headers: Dictionary of HTTP response headers. :param output_stream: Stream where the request is being dumped at.
def _gatherDataFromLookups(gpos, scriptOrder): """ Gather kerning and classes from the applicable lookups and return them in script order. """ lookupIndexes = _gatherLookupIndexes(gpos) seenLookups = set() kerningDictionaries = [] leftClassDictionaries = [] rightClassDictionaries = [...
Gather kerning and classes from the applicable lookups and return them in script order.
def parse_args(): """ parse main() args """ description = ( "Get Wikipedia article info and Wikidata via MediaWiki APIs.\n\n" "Gets a random English Wikipedia article by default, or in the\n" "language -lang, or from the wikisite -wiki, or by specific\n" "title -title. Th...
parse main() args
def first_true(iterable, default=False, pred=None): """Returns the first true value in the iterable. If no true value is found, returns *default* If *pred* is not None, returns the first item for which pred(item) is true. """ # first_true([a,b,c], x) --> a or b or c or x # first_true([a,b...
Returns the first true value in the iterable. If no true value is found, returns *default* If *pred* is not None, returns the first item for which pred(item) is true.
def _back_transform(self,inplace=True): """ Private method to remove log10 transformation from ensemble Parameters ---------- inplace: bool back transform self in place Returns ------ ParameterEnsemble : ParameterEnsemble if inplace if Fa...
Private method to remove log10 transformation from ensemble Parameters ---------- inplace: bool back transform self in place Returns ------ ParameterEnsemble : ParameterEnsemble if inplace if False Note ---- Don't call th...
def reconfigure_messaging(self, msg_host, msg_port): '''force messaging reconnector to the connect to the (host, port)''' self._messaging.create_external_route( 'rabbitmq', host=msg_host, port=msg_port)
force messaging reconnector to the connect to the (host, port)
def create_task_from_cu(cu, prof=None): """ Purpose: Create a Task based on the Compute Unit. Details: Currently, only the uid, parent_stage and parent_pipeline are retrieved. The exact initial Task (that was converted to a CUD) cannot be recovered as the RP API does not provide the same attributes for...
Purpose: Create a Task based on the Compute Unit. Details: Currently, only the uid, parent_stage and parent_pipeline are retrieved. The exact initial Task (that was converted to a CUD) cannot be recovered as the RP API does not provide the same attributes for a CU as for a CUD. Also, this is not required f...
def add_loaded_callback(self, callback): """Add a callback to be run when the ALDB load is complete.""" if callback not in self._cb_aldb_loaded: self._cb_aldb_loaded.append(callback)
Add a callback to be run when the ALDB load is complete.
def unchunk(self): """ Convert a chunked array back into a full array with (key,value) pairs where key is a tuple of indices, and value is an ndarray. """ plan, padding, vshape, split = self.plan, self.padding, self.vshape, self.split nchunks = self.getnumber(plan, vshape...
Convert a chunked array back into a full array with (key,value) pairs where key is a tuple of indices, and value is an ndarray.
def _calculate_comparison_stats(truth_vcf): """Identify calls to validate from the input truth VCF. """ # Avoid very small events for average calculations min_stat_size = 50 min_median_size = 250 sizes = [] svtypes = set([]) with utils.open_gzipsafe(truth_vcf) as in_handle: for c...
Identify calls to validate from the input truth VCF.
def open(uri, mode, kerberos=False, user=None, password=None): """Implement streamed reader from a web site. Supports Kerberos and Basic HTTP authentication. Parameters ---------- url: str The URL to open. mode: str The mode to open using. kerberos: boolean, optional ...
Implement streamed reader from a web site. Supports Kerberos and Basic HTTP authentication. Parameters ---------- url: str The URL to open. mode: str The mode to open using. kerberos: boolean, optional If True, will attempt to use the local Kerberos credentials user...
def find_all_matches(finder, ireq, pre=False): # type: (PackageFinder, InstallRequirement, bool) -> List[InstallationCandidate] """Find all matching dependencies using the supplied finder and the given ireq. :param finder: A package finder for discovering matching candidates. :type finder: :class:`...
Find all matching dependencies using the supplied finder and the given ireq. :param finder: A package finder for discovering matching candidates. :type finder: :class:`~pip._internal.index.PackageFinder` :param ireq: An install requirement. :type ireq: :class:`~pip._internal.req.req_install.Install...
def set_tile(self, row, col, value): """ Set the tile at position row, col to have the given value. """ #print('set_tile: y=', row, 'x=', col) if col < 0: print("ERROR - x less than zero", col) col = 0 #return if col > s...
Set the tile at position row, col to have the given value.
def tarbell_configure(command, args): """ Tarbell configuration routine. """ puts("Configuring Tarbell. Press ctrl-c to bail out!") # Check if there's settings configured settings = Settings() path = settings.path prompt = True if len(args): prompt = False config = _ge...
Tarbell configuration routine.
def createJobSubscriptionAsync(self, ackCallback, callback, jobExecutionType=jobExecutionTopicType.JOB_WILDCARD_TOPIC, jobReplyType=jobExecutionTopicReplyType.JOB_REQUEST_TYPE, jobId=None): """ **Description** Asynchronously creates an MQTT subscription to a jobs related topic based on the prov...
**Description** Asynchronously creates an MQTT subscription to a jobs related topic based on the provided arguments **Syntax** .. code:: python #Subscribe to notify-next topic to monitor change in job referred to by $next myAWSIoTMQTTJobsClient.createJobSubscriptionAsync(...
def Register(self, name, constructor): """Registers a new constructor in the factory. Args: name: A name associated with given constructor. constructor: A constructor function that creates instances. Raises: ValueError: If there already is a constructor associated with given name. ""...
Registers a new constructor in the factory. Args: name: A name associated with given constructor. constructor: A constructor function that creates instances. Raises: ValueError: If there already is a constructor associated with given name.
def insertValue(self, pos, configValue, displayValue=None): """ Will insert the configValue in the configValues and the displayValue in the displayValues list. If displayValue is None, the configValue is set in the displayValues as well """ self._configValues.insert(pos, ...
Will insert the configValue in the configValues and the displayValue in the displayValues list. If displayValue is None, the configValue is set in the displayValues as well
def _execute(self, sql, params): """Execute statement with reconnecting by connection closed error codes. 2006 (CR_SERVER_GONE_ERROR): MySQL server has gone away 2013 (CR_SERVER_LOST): Lost connection to MySQL server during query 2055 (CR_SERVER_LOST_EXTENDED): Lost connection to MySQL ...
Execute statement with reconnecting by connection closed error codes. 2006 (CR_SERVER_GONE_ERROR): MySQL server has gone away 2013 (CR_SERVER_LOST): Lost connection to MySQL server during query 2055 (CR_SERVER_LOST_EXTENDED): Lost connection to MySQL server at '%s', system error: %d
def find_field_by_name(browser, field_type, name): """ Locate the control input with the given ``name``. :param browser: ``world.browser`` :param string field_type: a field type (i.e. `button`) :param string name: ``name`` attribute Returns: an :class:`ElementSelector` """ return Eleme...
Locate the control input with the given ``name``. :param browser: ``world.browser`` :param string field_type: a field type (i.e. `button`) :param string name: ``name`` attribute Returns: an :class:`ElementSelector`
def table(self, name, database=None, schema=None): """Create a table expression that references a particular a table called `name` in a MySQL database called `database`. Parameters ---------- name : str The name of the table to retrieve. database : str, optio...
Create a table expression that references a particular a table called `name` in a MySQL database called `database`. Parameters ---------- name : str The name of the table to retrieve. database : str, optional The database in which the table referred to by...
def build(self): """Builds this controlled gate. :return: The controlled gate, defined by this object. :rtype: Program """ self.defined_gates = set(STANDARD_GATE_NAMES) prog = self._recursive_builder(self.operation, self.gate_name, ...
Builds this controlled gate. :return: The controlled gate, defined by this object. :rtype: Program
def item_count(self, request, variant_id=None): """ Get quantity of a single item in the basket """ bid = utils.basket_id(request) item = ProductVariant.objects.get(id=variant_id) try: count = BasketItem.objects.get(basket_id=bid, variant=item).quantity...
Get quantity of a single item in the basket
async def download(self, resource_url): ''' Download given Resource URL by finding path through graph and applying each step ''' resolver_path = self.find_path_from_url(resource_url) await self.apply_resolver_path(resource_url, resolver_path)
Download given Resource URL by finding path through graph and applying each step
def build_bam_tags(): '''builds the list of BAM tags to be added to output BAMs''' #pylint: disable=unused-argument def _combine_filters(fam, paired_align, align): filters = [x.filter_value for x in [fam, align] if x and x.filter_value] if filters: return ";".join(filters).replac...
builds the list of BAM tags to be added to output BAMs
def validate(self): """ Error check the attributes of the ActivateRequestPayload object. """ if self.unique_identifier is not None: if not isinstance(self.unique_identifier, attributes.UniqueIdentifier): msg = "invalid unique iden...
Error check the attributes of the ActivateRequestPayload object.
def unicode_to_hex(unicode_string): """ Return a string containing the Unicode hexadecimal codepoint of each Unicode character in the given Unicode string. Return ``None`` if ``unicode_string`` is ``None``. Example:: a => U+0061 ab => U+0061 U+0062 :param str unicode_string: ...
Return a string containing the Unicode hexadecimal codepoint of each Unicode character in the given Unicode string. Return ``None`` if ``unicode_string`` is ``None``. Example:: a => U+0061 ab => U+0061 U+0062 :param str unicode_string: the Unicode string to convert :rtype: (Unico...
def _encode_observations(self, observations): """Encodes observations as PNG.""" return [ Observation( self._session.obj.run( self._encoded_image_t.obj, feed_dict={self._decoded_image_p.obj: observation} ), self._decode_png ) ...
Encodes observations as PNG.
def retweet(self, id): """ Retweet a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise """ try: self._client.retweet(id=id) return True except TweepError as e: if e.api_code == TWITTER_PAGE...
Retweet a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise
def bytes_to_number(b, endian='big'): """ Convert a string to an integer. :param b: String or bytearray to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case version of str...
Convert a string to an integer. :param b: String or bytearray to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case version of string_to_number with a full base-256 ASCII alpha...
def http_post(self, path, query_data={}, post_data={}, files=None, **kwargs): """Make a POST request to the Gitlab server. Args: path (str): Path or full URL to query ('/projects' or 'http://whatever/v4/api/projecs') query_data (dict): D...
Make a POST request to the Gitlab server. Args: path (str): Path or full URL to query ('/projects' or 'http://whatever/v4/api/projecs') query_data (dict): Data to send as query parameters post_data (dict): Data to send in the body (will be converted t...
def main(): """Used for development and testing.""" expr_list = [ "max(-_.千幸福的笑脸{घोड़ा=馬, " "dn2=dv2,千幸福的笑脸घ=千幸福的笑脸घ}) gte 100 " "times 3 && " "(min(ເຮືອນ{dn3=dv3,家=дом}) < 10 or sum(biz{dn5=dv5}) >99 and " "count(fizzle) lt 0or count(baz) > 1)".decode('utf8'), ...
Used for development and testing.
def applicationpolicy(arg=None): """ Decorator for application policy method. Allows policy to be built up from methods registered for different event classes. """ def _mutator(func): wrapped = singledispatch(func) @wraps(wrapped) def wrapper(*args, **kwargs): ...
Decorator for application policy method. Allows policy to be built up from methods registered for different event classes.
def _find_by_android(self, browser, criteria, tag, constraints): """Find element matches by UI Automator.""" return self._filter_elements( browser.find_elements_by_android_uiautomator(criteria), tag, constraints)
Find element matches by UI Automator.
def selectlastrow(self, window_name, object_name): """ Select last row @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LD...
Select last row @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: strin...
async def get_creds(self, proof_req_json: str, filt: dict = None, filt_dflt_incl: bool = False) -> (Set[str], str): """ Get credentials from HolderProver wallet corresponding to proof request and filter criteria; return credential identifiers from wallet and credentials json. Return empt...
Get credentials from HolderProver wallet corresponding to proof request and filter criteria; return credential identifiers from wallet and credentials json. Return empty set and empty production for no such credentials. :param proof_req_json: proof request json as Verifier creates; has entries ...
def get_reference_templates(self, ref_types): """Return the reference templates for the types as an ordered dictionary.""" return OrderedDict([(x, self.get_reference_template(x)) for x in ref_types])
Return the reference templates for the types as an ordered dictionary.
def putscript(self, name, content): """Upload a script to the server See MANAGESIEVE specifications, section 2.6 :param name: script's name :param content: script's content :rtype: boolean """ content = tools.to_bytes(content) content = tools.to_bytes("{...
Upload a script to the server See MANAGESIEVE specifications, section 2.6 :param name: script's name :param content: script's content :rtype: boolean
def svm_version_path(version): """ Path to specified spark version. Accepts semantic version numbering. :param version: Spark version as String :return: String. """ return os.path.join(Spark.HOME_DIR, Spark.SVM_DIR, 'v{}'.format(version))
Path to specified spark version. Accepts semantic version numbering. :param version: Spark version as String :return: String.
def insert(self, cache_key, paths, overwrite=False): """Cache the output of a build. By default, checks cache.has(key) first, only proceeding to create and insert an artifact if it is not already in the cache (though `overwrite` can be used to skip the check and unconditionally insert). :param Cac...
Cache the output of a build. By default, checks cache.has(key) first, only proceeding to create and insert an artifact if it is not already in the cache (though `overwrite` can be used to skip the check and unconditionally insert). :param CacheKey cache_key: A CacheKey object. :param list<str> pat...
def create_build_configuration_set_raw(**kwargs): """ Create a new BuildConfigurationSet. """ config_set = _create_build_config_set_object(**kwargs) response = utils.checked_api_call(pnc_api.build_group_configs, 'create_new', body=config_set) if response: return response.content
Create a new BuildConfigurationSet.
def set_scanner (type, scanner): """ Sets a scanner class that will be used for this 'type'. """ if __debug__: from .scanner import Scanner assert isinstance(type, basestring) assert issubclass(scanner, Scanner) validate (type) __types [type]['scanner'] = scanner
Sets a scanner class that will be used for this 'type'.
def missing_intervals(startdate, enddate, start, end, dateconverter=None, parseinterval=None, intervals=None): '''Given a ``startdate`` and an ``enddate`` dates, evaluate the date intervals from which data is not available. It return a list of ...
Given a ``startdate`` and an ``enddate`` dates, evaluate the date intervals from which data is not available. It return a list of two-dimensional tuples containing start and end date for the interval. The list could countain 0,1 or 2 tuples.
def showMetadata(dat): """ Display the metadata specified LiPD in pretty print | Example | showMetadata(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict dat: Metadata :return none: """ _tmp = rm_values_fields(copy.deepcopy(dat)) print(json.dumps(_tmp, indent=2)) return
Display the metadata specified LiPD in pretty print | Example | showMetadata(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict dat: Metadata :return none:
def _latex_format(obj: Any) -> str: """Format an object as a latex string.""" if isinstance(obj, float): try: return sympy.latex(symbolize(obj)) except ValueError: return "{0:.4g}".format(obj) return str(obj)
Format an object as a latex string.
def _get_required_fn(fn, root_path): """ Definition of the MD5 file requires, that all paths will be absolute for the package directory, not for the filesystem. This function converts filesystem-absolute paths to package-absolute paths. Args: fn (str): Local/absolute path to the file. ...
Definition of the MD5 file requires, that all paths will be absolute for the package directory, not for the filesystem. This function converts filesystem-absolute paths to package-absolute paths. Args: fn (str): Local/absolute path to the file. root_path (str): Local/absolute path to the p...
def write(self, data, auto_flush=True): """ <Purpose> Writes a data string to the file. <Arguments> data: A string containing some data. auto_flush: Boolean argument, if set to 'True', all data will be flushed from internal buffer. <Exceptions> None. ...
<Purpose> Writes a data string to the file. <Arguments> data: A string containing some data. auto_flush: Boolean argument, if set to 'True', all data will be flushed from internal buffer. <Exceptions> None. <Return> None.
def upload(self, *args, **kwargs): """Runs command on every job in the run.""" for job in self.jobs: job.upload(*args, **kwargs)
Runs command on every job in the run.
def load_plugins(self): """ Tells core to take plugin options and instantiate plugin classes """ logger.info("Loading plugins...") for (plugin_name, plugin_path, plugin_cfg) in self.config.plugins: logger.debug("Loading plugin %s from %s", plugin_name, plugin_path) ...
Tells core to take plugin options and instantiate plugin classes
def tag(self, text): """Retrieves list of regex_matches in text. Parameters ---------- text: Text The estnltk text object to search for events. Returns ------- list of matches """ matches = self._match(text.text) matches = sel...
Retrieves list of regex_matches in text. Parameters ---------- text: Text The estnltk text object to search for events. Returns ------- list of matches
def parse_arguments(filters, arguments, modern=False): """ Return a dict of parameters. Take a list of filters and for each try to get the corresponding value in arguments or a default value. Then check that value's type. The @modern parameter indicates how the arguments should be interpreted. T...
Return a dict of parameters. Take a list of filters and for each try to get the corresponding value in arguments or a default value. Then check that value's type. The @modern parameter indicates how the arguments should be interpreted. The old way is that you always specify a list and in the list yo...
def _show_doc(cls, fmt_func, keys=None, indent=0, grouped=False, func=None, include_links=False, *args, **kwargs): """ Classmethod to print the formatoptions and their documentation This function is the basis for the :meth:`show_summaries` and :meth:`show_docs` methods...
Classmethod to print the formatoptions and their documentation This function is the basis for the :meth:`show_summaries` and :meth:`show_docs` methods Parameters ---------- fmt_func: function A function that takes the key, the key as it is printed, and the ...
def flatten(struct): """ Creates a flat list of all all items in structured output (dicts, lists, items): .. code-block:: python >>> sorted(flatten({'a': 'foo', 'b': 'bar'})) ['bar', 'foo'] >>> sorted(flatten(['foo', ['bar', 'troll']])) ['bar', 'foo', 'troll'] >>> f...
Creates a flat list of all all items in structured output (dicts, lists, items): .. code-block:: python >>> sorted(flatten({'a': 'foo', 'b': 'bar'})) ['bar', 'foo'] >>> sorted(flatten(['foo', ['bar', 'troll']])) ['bar', 'foo', 'troll'] >>> flatten('foo') ['foo'] ...
def from_opcode(cls, opcode, arg=_no_arg): """ Create an instruction from an opcode and raw argument. Parameters ---------- opcode : int Opcode for the instruction to create. arg : int, optional The argument for the instruction. Returns ...
Create an instruction from an opcode and raw argument. Parameters ---------- opcode : int Opcode for the instruction to create. arg : int, optional The argument for the instruction. Returns ------- intsr : Instruction An insta...
def toVerticalPotential(Pot,R,phi=None): """ NAME: toVerticalPotential PURPOSE: convert a Potential to a vertical potential at a given R INPUT: Pot - Potential instance or list of such instances R - Galactocentric radius at which to evaluate the vertical potential (can ...
NAME: toVerticalPotential PURPOSE: convert a Potential to a vertical potential at a given R INPUT: Pot - Potential instance or list of such instances R - Galactocentric radius at which to evaluate the vertical potential (can be Quantity) phi= (None) Galactocentric azimu...
def last_commit(): """Returns the SHA1 of the last commit.""" try: root = subprocess.check_output( ['hg', 'parent', '--template={node}'], stderr=subprocess.STDOUT).strip() # Convert to unicode first return root.decode('utf-8') except subprocess.CalledProcessEr...
Returns the SHA1 of the last commit.
def hil_controls_send(self, time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode, force_mavlink1=False): ''' Sent from autopilot to simulation. Hardware in the loop control outputs time_usec ...
Sent from autopilot to simulation. Hardware in the loop control outputs time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) roll_ailerons : Control output -1 .. 1 (float) pitch_ele...
def _future_completed(future): """ Helper for run_in_executor() """ exc = future.exception() if exc: log.debug("Failed to run task on executor", exc_info=exc)
Helper for run_in_executor()
def write_mates(self): '''Scan the current chromosome for matches to any of the reads stored in the read1s buffer''' if self.chrom is not None: U.debug("Dumping %i mates for contig %s" % ( len(self.read1s), self.chrom)) for read in self.infile.fetch(reference...
Scan the current chromosome for matches to any of the reads stored in the read1s buffer
def _add_redundancy_router_interfaces(self, context, router, itfc_info, new_port, redundancy_router_ids=None, ha_settings_db=None, create_ha_group=True): """To be called in add_router_in...
To be called in add_router_interface() AFTER interface has been added to router in DB.
def session_dump(self, cell, hash, fname_session): """ Dump ipython session to file :param hash: cell hash :param fname_session: output filename :return: """ logging.debug('Cell {}: Dumping session to {}'.format(hash, fname_session)) inject_code = ['impo...
Dump ipython session to file :param hash: cell hash :param fname_session: output filename :return:
def meanAndStdDev(self, limit=None): """return the mean and the standard deviation optionally limited to the last limit values""" if limit is None or len(self.values) < limit: limit = len(self.values) if limit > 0: mean = sum(self.values[-limit:]) / float(limit) ...
return the mean and the standard deviation optionally limited to the last limit values
def add_cell_markdown(self, cell_str): """ Add a markdown cell :param cell_str: markdown text :return: """ logging.debug("add_cell_markdown: {}".format(cell_str)) # drop spaces and taps at beginning and end of all lines #cell = '\n'.join(map(lambda x: x.s...
Add a markdown cell :param cell_str: markdown text :return:
def clear_database(engine: Connectable, schemas: Iterable[str] = ()) -> None: """ Clear any tables from an existing database. :param engine: the engine or connection to use :param schemas: full list of schema names to expect (ignored for SQLite) """ assert check_argument_types() metadatas ...
Clear any tables from an existing database. :param engine: the engine or connection to use :param schemas: full list of schema names to expect (ignored for SQLite)
def auto_assign_decodings(self, decodings): """ :type decodings: list of Encoding """ nrz_decodings = [decoding for decoding in decodings if decoding.is_nrz or decoding.is_nrzi] fallback = nrz_decodings[0] if nrz_decodings else None candidate_decodings = [decoding for dec...
:type decodings: list of Encoding
def _split_path(path): """split a path return by the api return - the sentinel: - the rest of the path as a list. - the original path stripped of / for normalisation. """ path = path.strip('/') list_path = path.split('/') sentinel = list_path.pop(0) return sentinel, ...
split a path return by the api return - the sentinel: - the rest of the path as a list. - the original path stripped of / for normalisation.
def on_menu_make_MagIC_results_tables(self, event): """ Creates or Updates Specimens or Pmag Specimens MagIC table, overwrites .redo file for safety, and starts User dialog to generate other MagIC tables for later contribution to the MagIC database. The following describes th...
Creates or Updates Specimens or Pmag Specimens MagIC table, overwrites .redo file for safety, and starts User dialog to generate other MagIC tables for later contribution to the MagIC database. The following describes the steps used in the 2.5 data format to do this: 1. rea...
def train_nn_segmentation_classifier(X, y): """ Train a neural network classifier. Parameters ---------- X : numpy array A list of feature vectors y : numpy array A list of labels Returns ------- Theano expression : The trained neural network """ de...
Train a neural network classifier. Parameters ---------- X : numpy array A list of feature vectors y : numpy array A list of labels Returns ------- Theano expression : The trained neural network