code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def configureLogger(self): """ Configures the python logging system to log to a debug file and to stdout for warn and above. :return: the base logger. """ baseLogLevel = logging.DEBUG if self.isDebugLogging() else logging.INFO # create recorder app root logger log...
Configures the python logging system to log to a debug file and to stdout for warn and above. :return: the base logger.
def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False): """Return a list of dictionaries fit for ReferenceResultsField consumption. Only services which have float()able entries in result,min and max field will be included. If any of min, m...
Return a list of dictionaries fit for ReferenceResultsField consumption. Only services which have float()able entries in result,min and max field will be included. If any of min, max, or result fields are blank, the row value is ignored here.
def serve_forever(self, poll_interval=0.5): """ Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread. """ self.__is_shut_down.clear() ...
Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread.
def redirect(self): """ This is the HTTP-redirect endpoint """ logger.info("--- In SSO Redirect ---") saml_msg = self.unpack_redirect() try: _key = saml_msg["key"] saml_msg = IDP.ticket[_key] self.req_info = saml_msg["req_info"] del IDP.t...
This is the HTTP-redirect endpoint
def touch(fname, times=None): """Creates an empty file at fname, creating path if necessary Answer taken from Stack Overflow http://stackoverflow.com/a/1160227 User: ephemient http://stackoverflow.com/users/20713 License: CC-BY-SA 3.0 https://creativecommons.org/licenses/by-sa/3.0/ """ fpath, f ...
Creates an empty file at fname, creating path if necessary Answer taken from Stack Overflow http://stackoverflow.com/a/1160227 User: ephemient http://stackoverflow.com/users/20713 License: CC-BY-SA 3.0 https://creativecommons.org/licenses/by-sa/3.0/
def getTypeByPosition(self, idx): """Return ASN.1 type object by its position in fields set. Parameters ---------- idx: :py:class:`int` Field index Returns ------- : ASN.1 type Raises ------ : :class:`~pyasn1.erro...
Return ASN.1 type object by its position in fields set. Parameters ---------- idx: :py:class:`int` Field index Returns ------- : ASN.1 type Raises ------ : :class:`~pyasn1.error.PyAsn1Error` If given position ...
def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands, restartinitcommands): ''' Formats the output of the restartcheck module. Returns: String - formatted output. Args: kernel_restart: indicates that newer kernel i...
Formats the output of the restartcheck module. Returns: String - formatted output. Args: kernel_restart: indicates that newer kernel is instaled packages: list of packages that should be restarted verbose: enables extensive output restartable: list of restartable packag...
def parse_unknown_args(args): """ Parse arguments not consumed by arg parser into a dicitonary """ retval = {} preceded_by_key = False for arg in args: if arg.startswith('--'): if '=' in arg: key = arg.split('=')[0][2:] value = arg.split('=')[1...
Parse arguments not consumed by arg parser into a dicitonary
def chmod(self, path, mode): """ Change the mode (permissions) of a file. The permissions are unix-style and identical to those used by python's C{os.chmod} function. @param path: path of the file to change the permissions of @type path: str @param mode: new per...
Change the mode (permissions) of a file. The permissions are unix-style and identical to those used by python's C{os.chmod} function. @param path: path of the file to change the permissions of @type path: str @param mode: new permissions @type mode: int
def _validate_place_types(self, types): """Validate place types and return a mapping for use in requests.""" for pt in types: if pt not in self.place_types: raise InvalidPlaceTypeError(pt) return {'types': ",".join(types)}
Validate place types and return a mapping for use in requests.
def manhattan_distant(vector1, vector2): """曼哈顿距离""" vector1 = np.mat(vector1) vector2 = np.mat(vector2) return np.sum(np.abs(vector1 - vector2))
曼哈顿距离
def key_value_to_tree(data): ''' Convert key/value to tree ''' tree = {} for flatkey, value in six.iteritems(data): t = tree keys = flatkey.split(__opts__['pepa_delimiter']) for i, key in enumerate(keys, 1): if i == len(keys): t[key] = value ...
Convert key/value to tree
def args_range(min_value, max_value, *args): """ 检查参数范围 """ not_null(*args) if not all(map(lambda v: min_value <= v <= max_value, args)): raise ValueError("Argument must be between {0} and {1}!".format(min_value, max_value))
检查参数范围
def _hammer_function_precompute(self,x0, L, Min, model): """ Pre-computes the parameters of a penalizer centered at x0. """ if x0 is None: return None, None if len(x0.shape)==1: x0 = x0[None,:] m = model.predict(x0)[0] pred = model.predict(x0)[1].copy() pr...
Pre-computes the parameters of a penalizer centered at x0.
def apply_bbox(sf,ax): """ Use bbox as xlim and ylim in ax """ limits = sf.bbox xlim = limits[0],limits[2] ylim = limits[1],limits[3] ax.set_xlim(xlim) ax.set_ylim(ylim)
Use bbox as xlim and ylim in ax
def run_gblocks(align_fasta_file, **kwargs): """ remove poorly aligned positions and divergent regions with Gblocks """ cl = GblocksCommandline(aln_file=align_fasta_file, **kwargs) r, e = cl.run() print("Gblocks:", cl, file=sys.stderr) if e: print("***Gblocks could not run", file=s...
remove poorly aligned positions and divergent regions with Gblocks
def get_file_courses(self, id, course_id, include=None): """ Get file. Returns the standard attachment json object """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id ...
Get file. Returns the standard attachment json object
def tables_get(self, table_name): """Issues a request to retrieve information about a table. Args: table_name: a tuple representing the full name of the table. Returns: A parsed result object. Raises: Exception if there is an error performing the operation. """ url = Api._ENDP...
Issues a request to retrieve information about a table. Args: table_name: a tuple representing the full name of the table. Returns: A parsed result object. Raises: Exception if there is an error performing the operation.
def set_opt(self, name, value): """ Set option. """ self.cache['opts'][name] = value if name == 'compress': self.cache['delims'] = self.def_delims if not value else ( '', '', '')
Set option.
def watch(self, path, recursive=False): """Watch for files in a directory and apply normalizations. Watch for new or changed files in a directory and apply normalizations over them. Args: path: Path to the directory. recursive: Whether to find files recursively ...
Watch for files in a directory and apply normalizations. Watch for new or changed files in a directory and apply normalizations over them. Args: path: Path to the directory. recursive: Whether to find files recursively or not.
def wait_script(name, source=None, template=None, onlyif=None, unless=None, cwd=None, runas=None, shell=None, env=None, stateful=False, umask=None, ...
Download a script from a remote source and execute it only if a watch statement calls it. source The source script being downloaded to the minion, this source script is hosted on the salt master server. If the file is located on the master in the directory named spam, and is called egg...
def list_view_on_selected(self, widget, selected_item_key): """ The selection event of the listView, returns a key of the clicked event. You can retrieve the item rapidly """ self.lbl.set_text('List selection: ' + self.listView.children[selected_item_key].get_text())
The selection event of the listView, returns a key of the clicked event. You can retrieve the item rapidly
def _lab_to_rgb(labs): """Convert Nx3 or Nx4 lab to rgb""" # adapted from BSD-licensed work in MATLAB by Mark Ruzon # Based on ITU-R Recommendation BT.709 using the D65 labs, n_dim = _check_color_dim(labs) # Convert Lab->XYZ (silly indexing used to preserve dimensionality) y = (labs[:, 0] + 16....
Convert Nx3 or Nx4 lab to rgb
def gen_df_state( list_table: list, set_initcond: set, set_runcontrol: set, set_input_runcontrol: set)->pd.DataFrame: '''generate dataframe of all state variables used by supy Parameters ---------- list_table : list csv files for site info: `SUEWS_xx.csv` on gith...
generate dataframe of all state variables used by supy Parameters ---------- list_table : list csv files for site info: `SUEWS_xx.csv` on github SUEWS-docs repo set_initcond : set initial condition related variables set_runcontrol : set runcontrol related variables set_i...
def parse_reports(self): """ Find RSeQC junction_saturation frequency reports and parse their data """ # Set up vars self.junction_saturation_all = dict() self.junction_saturation_known = dict() self.junction_saturation_novel = dict() # Go through files and parse data for f in self.find_lo...
Find RSeQC junction_saturation frequency reports and parse their data
def most_even(number, group): """Divide a number into a list of numbers as even as possible.""" count, rest = divmod(number, group) counts = zip_longest([count] * group, [1] * rest, fillvalue=0) chunks = [sum(one) for one in counts] logging.debug('chunks: %s', chunks) return chunks
Divide a number into a list of numbers as even as possible.
def unique(seen, *iterables): """ Get the unique items in iterables while preserving order. Note that this mutates the seen set provided only when the returned generator is used. Args: seen (set): either an empty set, or the set of things already seen *iterables: one or more iterable l...
Get the unique items in iterables while preserving order. Note that this mutates the seen set provided only when the returned generator is used. Args: seen (set): either an empty set, or the set of things already seen *iterables: one or more iterable lists to chain together Returns: ...
def dump(doc, output_stream=None): """ Dump a :class:`.Doc` object into a JSON-encoded text string. The output will be sent to :data:`sys.stdout` unless an alternative text stream is given. To dump to :data:`sys.stdout` just do: >>> import panflute as pf >>> doc = pf.Doc(Para(Str(...
Dump a :class:`.Doc` object into a JSON-encoded text string. The output will be sent to :data:`sys.stdout` unless an alternative text stream is given. To dump to :data:`sys.stdout` just do: >>> import panflute as pf >>> doc = pf.Doc(Para(Str('a'))) # Create sample document >>> pf...
def v1_highlights_get(response, kvlclient, file_id_str, max_elapsed = 300): '''Obtain highlights for a document POSTed previously to this end point. See documentation for v1_highlights_post for further details. If the `state` is still `pending` for more than `max_elapsed` after the start of the `WorkU...
Obtain highlights for a document POSTed previously to this end point. See documentation for v1_highlights_post for further details. If the `state` is still `pending` for more than `max_elapsed` after the start of the `WorkUnit`, then this reports an error, although the `WorkUnit` may continue in the b...
def page(self, course): """ Get all data and display the page """ if not self.webdav_host: raise web.notfound() url = self.webdav_host + "/" + course.get_id() username = self.user_manager.session_username() apikey = self.user_manager.session_api_key() return ...
Get all data and display the page
def public_key_to_connection_id(self, public_key): """ Get stored connection id for a public key. """ with self._connections_lock: for connection_id, connection_info in self._connections.items(): if connection_info.public_key == public_key: ...
Get stored connection id for a public key.
def get_effective_domain_id(request): """Gets the id of the default domain. If the requests default domain is the same as DEFAULT_DOMAIN, return None. """ default_domain = get_default_domain(request) domain_id = default_domain.get('id') domain_name = default_domain.get('name') return No...
Gets the id of the default domain. If the requests default domain is the same as DEFAULT_DOMAIN, return None.
def get_url_endpoint(self): """ Returns the Hypermap endpoint for a layer. This endpoint will be the WMTS MapProxy endpoint, only for WM we use the original endpoint. """ endpoint = self.url if self.type not in ('Hypermap:WorldMap',): endpoint = 'registry/%s/l...
Returns the Hypermap endpoint for a layer. This endpoint will be the WMTS MapProxy endpoint, only for WM we use the original endpoint.
def kick_job(self, job: JobOrID) -> None: """Moves a delayed or buried job into the ready queue. :param job: The job or job ID to kick. """ self._send_cmd(b'kick-job %d' % _to_id(job), b'KICKED')
Moves a delayed or buried job into the ready queue. :param job: The job or job ID to kick.
def experiments_predictions_list(self, listing_url, offset=0, limit=-1, properties=None): """Get list of experiment resources from a SCO-API. Parameters ---------- listing_url : string url for experiments run listing. offset : int, optional Starting offse...
Get list of experiment resources from a SCO-API. Parameters ---------- listing_url : string url for experiments run listing. offset : int, optional Starting offset for returned list items limit : int, optional Limit the number of items in the ...
def res_to_str(res): """ :param res: :class:`requests.Response` object Parse the given request and generate an informative string from it """ if 'Authorization' in res.request.headers: res.request.headers['Authorization'] = "*****" return """ #################################### url = %...
:param res: :class:`requests.Response` object Parse the given request and generate an informative string from it
def plot(feature, mp=None, style_function=None, **map_kwargs): """Plots a GeoVector in an ipyleaflet map. Parameters ---------- feature : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection Data to plot. mp : ipyleaflet.Map, optional Map in ...
Plots a GeoVector in an ipyleaflet map. Parameters ---------- feature : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection Data to plot. mp : ipyleaflet.Map, optional Map in which to plot, default to None (creates a new one). style_function...
def authenticate(name, remote_addr, password, cert, key, verify_cert=True): ''' Authenticate with a remote peer. .. notes: This function makes every time you run this a connection to remote_addr, you better call this only once. remote_addr : An URL to a remote Server, you also...
Authenticate with a remote peer. .. notes: This function makes every time you run this a connection to remote_addr, you better call this only once. remote_addr : An URL to a remote Server, you also have to give cert and key if you provide remote_addr! Examples: ...
def relevant(symbol, token='', version=''): '''Same as peers https://iexcloud.io/docs/api/#relevant Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: dict: result ''' _raiseIfNotStr(symbol) return _g...
Same as peers https://iexcloud.io/docs/api/#relevant Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: dict: result
def could_be(self, other): """Return True if the other PersonName is not explicitly inconsistent.""" # TODO: Some suffix and title differences should be allowed if type(other) is not type(self): return NotImplemented if self == other: return True for attr ...
Return True if the other PersonName is not explicitly inconsistent.
def _coulomb(n1, n2, k, r): """Calculates Coulomb forces and updates node data.""" # Get relevant positional data delta = [x2 - x1 for x1, x2 in zip(n1['velocity'], n2['velocity'])] distance = sqrt(sum(d ** 2 for d in delta)) # If the deltas are too small, use random values to keep things moving ...
Calculates Coulomb forces and updates node data.
def to_e164(name, origin=public_enum_domain, want_plus_prefix=True): """Convert an ENUM domain name into an E.164 number. @param name: the ENUM domain name. @type name: dns.name.Name object. @param origin: A domain containing the ENUM domain name. The name is relativized to this domain before being...
Convert an ENUM domain name into an E.164 number. @param name: the ENUM domain name. @type name: dns.name.Name object. @param origin: A domain containing the ENUM domain name. The name is relativized to this domain before being converted to text. @type: dns.name.Name object or None @param want_...
def until_condition(self, condition, condition_description): """ Waits until conditions is True or returns a non-None value. If any of the trait is still not present after timeout, raises a TimeoutException. """ end_time = time.time() + self._timeout count = 1 whi...
Waits until conditions is True or returns a non-None value. If any of the trait is still not present after timeout, raises a TimeoutException.
def userParamFromDict(attributes): """Python representation of a mzML userParam = tuple(name, value, unitAccession, type) :param attributes: #TODO: docstring :returns: #TODO: docstring """ keys = ['name', 'value', 'unitAccession', 'type'] return tuple(attributes[key] if key in attributes e...
Python representation of a mzML userParam = tuple(name, value, unitAccession, type) :param attributes: #TODO: docstring :returns: #TODO: docstring
def get_gc_property(value, is_bytes=False): """Get `GC` property.""" obj = unidata.ascii_properties if is_bytes else unidata.unicode_properties if value.startswith('^'): negate = True value = value[1:] else: negate = False value = unidata.unicode_alias['generalcategory'].g...
Get `GC` property.
def name(self): """ Algo name. """ if self._name is None: self._name = self.__class__.__name__ return self._name
Algo name.
def on_state_execution_status_changed_after(self, model, prop_name, info): """ Show current execution status in the widget This function specifies what happens if the state machine execution status of a state changes :param model: the model of the state that has changed (most likely it...
Show current execution status in the widget This function specifies what happens if the state machine execution status of a state changes :param model: the model of the state that has changed (most likely its execution status) :param prop_name: property name that has been changed ...
def __initialize_node(self, attributes_flags=int(Qt.ItemIsSelectable | Qt.ItemIsEnabled)): """ Initializes the node. :param attributes_flags: Attributes flags. :type attributes_flags: int """ self["traced"] = umbra.ui.nodes.GraphModelAttribute(name="traced", ...
Initializes the node. :param attributes_flags: Attributes flags. :type attributes_flags: int
def redo(self, channel, image): """This method is called when an image is set in a channel.""" imname = image.get('name', 'none') chname = channel.name # is image in contents tree yet? in_contents = self.is_in_contents(chname, imname) # get old highlighted entries for t...
This method is called when an image is set in a channel.
def GetMessage(self, log_source, lcid, message_identifier): """Retrieves a specific message for a specific Event Log source. Args: log_source (str): Event Log source. lcid (int): language code identifier (LCID). message_identifier (int): message identifier. Returns: str: message st...
Retrieves a specific message for a specific Event Log source. Args: log_source (str): Event Log source. lcid (int): language code identifier (LCID). message_identifier (int): message identifier. Returns: str: message string or None if not available.
def quit(self): """ Quit the player, blocking until the process has died """ if self._process is None: logger.debug('Quit was called after self._process had already been released') return try: logger.debug('Quitting OMXPlayer') proc...
Quit the player, blocking until the process has died
def sum_dicts(dicts, normalize=False): """Sums the given dicts into a single dict mapping each numberic-valued key to the sum of its mappings in all given dicts. Keys mapping to non-numeric values retain the last value (by the given order). Parameters ---------- dicts : list A list of d...
Sums the given dicts into a single dict mapping each numberic-valued key to the sum of its mappings in all given dicts. Keys mapping to non-numeric values retain the last value (by the given order). Parameters ---------- dicts : list A list of dict objects mapping each key to an numeric val...
def set_fraction(self, value): """Set the meter indicator. Value should be between 0 and 1.""" if value < 0: value *= -1 value = min(value, 1) if self.horizontal: width = int(self.width * value) height = self.height else: width = se...
Set the meter indicator. Value should be between 0 and 1.
def ticket_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/tickets#delete-ticket" api_path = "/api/v2/tickets/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
https://developer.zendesk.com/rest_api/docs/core/tickets#delete-ticket
def conversion_rate(self): """ The percentage of participants that have converted for this variant. Returns a > 0 float representing a percentage rate. """ participants = self.participant_count if participants == 0: return 0.0 return self.experiment.c...
The percentage of participants that have converted for this variant. Returns a > 0 float representing a percentage rate.
def get_savename_from_varname( varname, varname_prefix=None, savename_prefix=None): """ Args: varname(str): a variable name in the graph varname_prefix(str): an optional prefix that may need to be removed in varname savename_prefix(str): an optional prefix to append to al...
Args: varname(str): a variable name in the graph varname_prefix(str): an optional prefix that may need to be removed in varname savename_prefix(str): an optional prefix to append to all savename Returns: str: the name used to save the variable
def _update_rs_with_primary_from_member( sds, replica_set_name, server_description): """RS with known primary. Process a response from a non-primary. Pass in a dict of ServerDescriptions, current replica set name, and the ServerDescription we are processing. Returns new topolog...
RS with known primary. Process a response from a non-primary. Pass in a dict of ServerDescriptions, current replica set name, and the ServerDescription we are processing. Returns new topology type.
def fromProfileName(cls, name): """Return a `SessionAPI` from a given configuration profile name. :see: `ProfileStore`. """ with profiles.ProfileStore.open() as config: return cls.fromProfile(config.load(name))
Return a `SessionAPI` from a given configuration profile name. :see: `ProfileStore`.
def as_ordered_dict(self, preference_orders: List[List[str]] = None) -> OrderedDict: """ Returns Ordered Dict of Params from list of partial order preferences. Parameters ---------- preference_orders: List[List[str]], optional ``preference_orders`` is list of partial...
Returns Ordered Dict of Params from list of partial order preferences. Parameters ---------- preference_orders: List[List[str]], optional ``preference_orders`` is list of partial preference orders. ["A", "B", "C"] means "A" > "B" > "C". For multiple preference_orders fir...
def manipulate(self, stored_instance, component_instance): """ Stores the given StoredInstance bean. :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance """ # Store the stored instance... self._ipopo_instan...
Stores the given StoredInstance bean. :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance
def hgetall(self, key): """ Returns all fields and values of the has stored at `key`. The underlying redis `HGETALL`_ command returns an array of pairs. This method converts that to a Python :class:`dict`. It will return an empty :class:`dict` when the key is not found....
Returns all fields and values of the has stored at `key`. The underlying redis `HGETALL`_ command returns an array of pairs. This method converts that to a Python :class:`dict`. It will return an empty :class:`dict` when the key is not found. .. note:: **Time compl...
def is_from_parent(cls, attribute_name, value=None): # type: (type, str, bool) -> bool """ Tests if the current attribute value is shared by a parent of the given class. Returns None if the attribute value is None. :param cls: Child class with the requested attribute :param attribute_name:...
Tests if the current attribute value is shared by a parent of the given class. Returns None if the attribute value is None. :param cls: Child class with the requested attribute :param attribute_name: Name of the attribute to be tested :param value: The exact value in the child class (optional) ...
def _append_record(test_data, results, test_path): """Adds data of single testcase results to results database.""" statuses = test_data.get("statuses") jenkins_data = test_data.get("jenkins") or {} data = [ ("title", test_data.get("test_name") or _get_testname(test_path)), ("verdict", s...
Adds data of single testcase results to results database.
def delete_ipv6(self, ipv6_id): """ Delete ipv6 """ uri = 'api/ipv6/%s/' % (ipv6_id) return super(ApiNetworkIPv6, self).delete(uri)
Delete ipv6
def sg_argmin(tensor, opt): r"""Returns the indices of the minimum values along the specified axis. See `tf.argin()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis: Target axis. Default is the last one. name: If provided, replace current tenso...
r"""Returns the indices of the minimum values along the specified axis. See `tf.argin()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis: Target axis. Default is the last one. name: If provided, replace current tensor's name. Returns: A ...
def translate_rgb_to_ansi_code(red, green, blue, offset, colormode): """ Translate the given RGB color into the appropriate ANSI escape code for the given color mode. The offset is used for the base color which is used. The ``colormode`` has to be one of: * 0: no colors / disabled *...
Translate the given RGB color into the appropriate ANSI escape code for the given color mode. The offset is used for the base color which is used. The ``colormode`` has to be one of: * 0: no colors / disabled * 8: use ANSI 8 colors * 16: use ANSI 16 colors (same as 8 but with bright...
def wait_until_alert_is_present(self, timeout=None): """ Waits for an alert to be present @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @rtype: webdriverwrapper.WebElementWrapper ...
Waits for an alert to be present @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found
def execute_all_rules(self, matches, context): """ Execute all rules from this rules list. All when condition with same priority will be performed before calling then actions. :param matches: :type matches: :param context: :type context: :return: ...
Execute all rules from this rules list. All when condition with same priority will be performed before calling then actions. :param matches: :type matches: :param context: :type context: :return: :rtype:
def _set_gre_ttl(self, v, load=False): """ Setter method for gre_ttl, mapped from YANG variable /interface/tunnel/gre_ttl (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_gre_ttl is considered as a private method. Backends looking to populate this variable sh...
Setter method for gre_ttl, mapped from YANG variable /interface/tunnel/gre_ttl (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_gre_ttl is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_gre_ttl() d...
def _top_element(self): """Returns top XML element.""" attrs = {"project-id": self.config["polarion-project-id"]} document_relative_path = self.config.get("requirements-document-relative-path") if document_relative_path: attrs["document-relative-path"] = document_relative_pat...
Returns top XML element.
def namedb_state_mutation_sanity_check( opcode, op_data ): """ Make sure all mutate fields for this operation are present. Return True if so Raise exception if not """ # sanity check: each mutate field in the operation must be defined in op_data, even if it's null. missing = [] mutate_...
Make sure all mutate fields for this operation are present. Return True if so Raise exception if not
def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. ...
:param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_ma...
def plot_variability_thresholds(varthreshpkl, xmin_lcmad_stdev=5.0, xmin_stetj_stdev=2.0, xmin_iqr_stdev=2.0, xmin_inveta_stdev=2.0, lcformat='hat-sql', ...
This makes plots for the variability threshold distributions. Parameters ---------- varthreshpkl : str The pickle produced by the function above. xmin_lcmad_stdev,xmin_stetj_stdev,xmin_iqr_stdev,xmin_inveta_stdev : float or np.array Values of the threshold values to override the ones ...
def start( self ): """ Starts the thread in its own event loop if the local and global thread options are true, otherwise runs the thread logic in the main event loop. """ if ( self.localThreadingEnabled() and self.globalThreadingEnabled() ): super(XThread, se...
Starts the thread in its own event loop if the local and global thread options are true, otherwise runs the thread logic in the main event loop.
def estimator_spec_train(self, loss, num_async_replicas=1, use_tpu=False): """Constructs `tf.estimator.EstimatorSpec` for TRAIN (training) mode.""" train_op = self.optimize(loss, num_async_replicas=num_async_replicas, use_tpu=use_tpu) if use_tpu: if self._hparams.warm_sta...
Constructs `tf.estimator.EstimatorSpec` for TRAIN (training) mode.
def get_snpeff_info(snpeff_string, snpeff_header): """Make the vep annotations into a dictionaries A snpeff dictionary will have the snpeff column names as keys and the vep annotations as values. The dictionaries are stored in a list. One dictionary for each transcript. ...
Make the vep annotations into a dictionaries A snpeff dictionary will have the snpeff column names as keys and the vep annotations as values. The dictionaries are stored in a list. One dictionary for each transcript. Args: snpeff_string (string): A string with...
def udp_messenger(domain_name, UDP_IP, UDP_PORT, sock_timeout, message): """Send UDP messages to usage tracker asynchronously This multiprocessing based messenger was written to overcome the limitations of signalling/terminating a thread that is blocked on a system call. This messenger is created as a ...
Send UDP messages to usage tracker asynchronously This multiprocessing based messenger was written to overcome the limitations of signalling/terminating a thread that is blocked on a system call. This messenger is created as a separate process, and initialized with 2 queues, to_send to receive messages...
def _add_prefix(self, split_names, start_node, group_type_name): """Adds the correct sub branch prefix to a given name. Usually the prefix is the full name of the parent node. In case items are added directly to the trajectory the prefixes are chosen according to the matching subbranch. ...
Adds the correct sub branch prefix to a given name. Usually the prefix is the full name of the parent node. In case items are added directly to the trajectory the prefixes are chosen according to the matching subbranch. For example, this could be 'parameters' for parameters or 'results.run_000...
def get_element_dt(self, el_name, tz=None, el_idx=0): """Return the text of the selected element as a ``datetime.datetime`` object. The element text must be a ISO8601 formatted datetime Args: el_name : str Name of element to use. tz : datetime.tzinfo ...
Return the text of the selected element as a ``datetime.datetime`` object. The element text must be a ISO8601 formatted datetime Args: el_name : str Name of element to use. tz : datetime.tzinfo Timezone in which to return the datetime. - Withou...
def cctop_submit(seq_str): """Submit a protein sequence string to CCTOP and return the job ID. Args: seq_str (str): Protein sequence as a string Returns: dict: Job ID on the CCTOP server """ url = 'http://cctop.enzim.ttk.mta.hu/php/submit.php?sequence={}&tmFilter&signalPred'.forma...
Submit a protein sequence string to CCTOP and return the job ID. Args: seq_str (str): Protein sequence as a string Returns: dict: Job ID on the CCTOP server
def normalize_per_cell_weinreb16_deprecated( X, max_fraction=1, mult_with_mean=False, ) -> np.ndarray: """Normalize each cell [Weinreb17]_. This is a deprecated version. See `normalize_per_cell` instead. Normalize each cell by UMI count, so that every cell has the same total count. Pa...
Normalize each cell [Weinreb17]_. This is a deprecated version. See `normalize_per_cell` instead. Normalize each cell by UMI count, so that every cell has the same total count. Parameters ---------- X : np.ndarray Expression matrix. Rows correspond to cells and columns to genes. m...
def _validate_covars(covars, covariance_type, n_components): """Do basic checks on matrix covariance sizes and values.""" from scipy import linalg if covariance_type == 'spherical': if len(covars) != n_components: raise ValueError("'spherical' covars have length n_components") el...
Do basic checks on matrix covariance sizes and values.
def migrateFileFields(portal): """ This function walks over all attachment types and migrates their FileField fields. """ portal_types = [ "Attachment", "ARImport", "Instrument", "InstrumentCertification", "Method", "Multifile", "Report", ...
This function walks over all attachment types and migrates their FileField fields.
def get_delta(D, k): '''Calculate the k-th order trend filtering matrix given the oriented edge incidence matrix and the value of k.''' if k < 0: raise Exception('k must be at least 0th order.') result = D for i in range(k): result = D.T.dot(result) if i % 2 == 0 else D.dot(result) ...
Calculate the k-th order trend filtering matrix given the oriented edge incidence matrix and the value of k.
def get_element_ids(self, prefix_id): """ Returns a single or a list of element ids, one for each input widget of this field """ if isinstance(self.widget, widgets.MultiWidget): ids = ['{0}_{1}_{2}'.format(prefix_id, self.name, field_name) for field_name in self.widget] ...
Returns a single or a list of element ids, one for each input widget of this field
def set_cookie( # type: ignore self, key: str, value: AnyStr='', max_age: Optional[Union[int, timedelta]]=None, expires: Optional[datetime]=None, path: str='/', domain: Optional[str]=None, secure: bool=False, ht...
Set a cookie in the response headers. The arguments are the standard cookie morsels and this is a wrapper around the stdlib SimpleCookie code.
def _parse_notes_dict(sbase): """ Creates dictionary of COBRA notes. Parameters ---------- sbase : libsbml.SBase Returns ------- dict of notes """ notes = sbase.getNotesString() if notes and len(notes) > 0: pattern = r"<p>\s*(\w+\s*\w*)\s*:\s*([\w|\s]+)<" matche...
Creates dictionary of COBRA notes. Parameters ---------- sbase : libsbml.SBase Returns ------- dict of notes
def to_dict(self): """ to_dict: puts channel data into the format that Kolibri Studio expects Args: None Returns: dict of channel data """ return { "id": self.get_node_id().hex, "name": self.title, "thumbnail": self.thumbnail.filename i...
to_dict: puts channel data into the format that Kolibri Studio expects Args: None Returns: dict of channel data
def edit_release_notes(): """Use the default text $EDITOR to write release notes. If $EDITOR is not set, use 'nano'.""" from tempfile import mkstemp import os import shlex import subprocess text_editor = shlex.split(os.environ.get('EDITOR', 'nano')) fd, ...
Use the default text $EDITOR to write release notes. If $EDITOR is not set, use 'nano'.
def canintersect(self, other): ''' Intersection is not well-defined for all pairs of multipliers. For example: {2,3} & {3,4} = {3} {2,} & {1,7} = {2,7} {2} & {5} = ERROR ''' return not (self.max < other.min or other.max < self.min)
Intersection is not well-defined for all pairs of multipliers. For example: {2,3} & {3,4} = {3} {2,} & {1,7} = {2,7} {2} & {5} = ERROR
def get_failed_instruments(self): """Find invalid instruments - instruments who have failed QC tests - instruments whose certificate is out of date - instruments which are disposed until next calibration test Return a dictionary with all info about expired/invalid instruments ...
Find invalid instruments - instruments who have failed QC tests - instruments whose certificate is out of date - instruments which are disposed until next calibration test Return a dictionary with all info about expired/invalid instruments
def _make_intermediate_dirs(sftp_client, remote_directory): """ Create all the intermediate directories in a remote host :param sftp_client: A Paramiko SFTP client. :param remote_directory: Absolute Path of the directory containing the file :return: """ if remote_directory == '/': s...
Create all the intermediate directories in a remote host :param sftp_client: A Paramiko SFTP client. :param remote_directory: Absolute Path of the directory containing the file :return:
def digests_are_equal(digest1, digest2): """ <Purpose> While protecting against timing attacks, compare the hexadecimal arguments and determine if they are equal. <Arguments> digest1: The first hexadecimal string value to compare. digest2: The second hexadecimal string value to compa...
<Purpose> While protecting against timing attacks, compare the hexadecimal arguments and determine if they are equal. <Arguments> digest1: The first hexadecimal string value to compare. digest2: The second hexadecimal string value to compare. <Exceptions> securesystemslib.exceptio...
def trim_wav_pydub(in_path: Path, out_path: Path, start_time: int, end_time: int) -> None: """ Crops the wav file. """ logger.info( "Using pydub/ffmpeg to create {} from {}".format(out_path, in_path) + " using a start_time of {} and an end_time of {}".format(start_time, ...
Crops the wav file.
def _buildDict(self): ''' Builds the isle textfile into a dictionary for fast searching ''' lexDict = {} with io.open(self.islePath, "r", encoding='utf-8') as fd: wordList = [line.rstrip('\n') for line in fd] for row in wordList: word, pro...
Builds the isle textfile into a dictionary for fast searching
def ac_viz(acdata): ''' Adapted from Gerry Harp at SETI. Slightly massages the autocorrelated calculation result for better visualization. In particular, the natural log of the data are calculated and the values along the subband edges are set to the maximum value of the data, and the t=0 delay of the ...
Adapted from Gerry Harp at SETI. Slightly massages the autocorrelated calculation result for better visualization. In particular, the natural log of the data are calculated and the values along the subband edges are set to the maximum value of the data, and the t=0 delay of the autocorrelation result are s...
def ensure_parent_id(self): """If current trace_parent has no span_id, generate one, then return it This is used to generate a span ID which the RUM agent will use to correlate the RUM transaction with the backend transaction. """ if self.trace_parent.span_id == self.id: ...
If current trace_parent has no span_id, generate one, then return it This is used to generate a span ID which the RUM agent will use to correlate the RUM transaction with the backend transaction.
def expected_error_messages(*error_messages): """ Decorator expecting defined error messages at the end of test method. As param use what :py:meth:`~.WebdriverWrapperErrorMixin.get_error_messages` returns. .. versionadded:: 2.0 Before this decorator was called ``ShouldBeError``. """...
Decorator expecting defined error messages at the end of test method. As param use what :py:meth:`~.WebdriverWrapperErrorMixin.get_error_messages` returns. .. versionadded:: 2.0 Before this decorator was called ``ShouldBeError``.
def run_from_argv(self, argv): """Overriden in order to access the command line arguments.""" self.argv_string = ' '.join(argv) super(EmailNotificationCommand, self).run_from_argv(argv)
Overriden in order to access the command line arguments.
def install(editable=True): """Install this component (or remove and reinstall)""" try: __import__(package['name']) except ImportError: pass else: run("pip uninstall --quiet -y %s" % package['name'], warn=True) cmd = "pip install --quiet " cmd += "-e ." if editable else...
Install this component (or remove and reinstall)