code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_primary_contributors(self, permitted=True): """ Returns a list of primary contributors, with primary being defined as those contributors that have the highest role assigned(in terms of priority). When permitted is set to True only permitted contributors are returned. """ primary_...
Returns a list of primary contributors, with primary being defined as those contributors that have the highest role assigned(in terms of priority). When permitted is set to True only permitted contributors are returned.
def merge(move, output_dir, sources): """ Merge multiple results folder into one, by copying the results over to a new folder. For a faster operation (which on the other hand destroys the campaign data if interrupted), the move option can be used to directly move results to the new folder. """ ...
Merge multiple results folder into one, by copying the results over to a new folder. For a faster operation (which on the other hand destroys the campaign data if interrupted), the move option can be used to directly move results to the new folder.
def process_request(self, request): """ Reloads glitter URL patterns if page URLs change. Avoids having to restart the server to recreate the glitter URLs being used by Django. """ global _urlconf_pages page_list = list( Page.objects.exclude(glitter_app_name...
Reloads glitter URL patterns if page URLs change. Avoids having to restart the server to recreate the glitter URLs being used by Django.
def popitem(self, dict_name, priority_min='-inf', priority_max='+inf'): '''Select an item and remove it. The item comes from `dict_name`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `dict_name` and return it. ...
Select an item and remove it. The item comes from `dict_name`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `dict_name` and return it. This runs as a single atomic operation but still requires a session lock...
def get (self, feature): """ Returns all values of 'feature'. """ if type(feature) == type([]): feature = feature[0] if not isinstance(feature, b2.build.feature.Feature): feature = b2.build.feature.get(feature) assert isinstance(feature, b2.build.feature.F...
Returns all values of 'feature'.
def get_stp_mst_detail_output_msti_port_interface_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ms...
Auto Generated Code
def format_signed(feature, # type: Dict[str, Any] formatter=None, # type: Callable[..., str] **kwargs ): # type: (...) -> str """ Format unhashed feature with sign. >>> format_signed({'name': 'foo', 'sign': 1}) 'foo' >>> format_signed({'na...
Format unhashed feature with sign. >>> format_signed({'name': 'foo', 'sign': 1}) 'foo' >>> format_signed({'name': 'foo', 'sign': -1}) '(-)foo' >>> format_signed({'name': ' foo', 'sign': -1}, lambda x: '"{}"'.format(x)) '(-)" foo"'
def _releaseModifiers(self, modifiers, globally=False): """Release given modifiers (provided in list form). Parameters: modifiers list Returns: None """ # Release them in reverse order from pressing them: modifiers.reverse() modFlags = self._pressModifiers(modifi...
Release given modifiers (provided in list form). Parameters: modifiers list Returns: None
def default_config(): ''' Linux hosts using systemd 207 or later ignore ``/etc/sysctl.conf`` and only load from ``/etc/sysctl.d/*.conf``. This function will do the proper checks and return a default config file which will be valid for the Minion. Hosts running systemd >= 207 will use ``/etc/sysctl.d...
Linux hosts using systemd 207 or later ignore ``/etc/sysctl.conf`` and only load from ``/etc/sysctl.d/*.conf``. This function will do the proper checks and return a default config file which will be valid for the Minion. Hosts running systemd >= 207 will use ``/etc/sysctl.d/99-salt.conf``. CLI Example:...
def post(self): '''return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result. ''' ## format sql data = request.get_json() options, sql_raw = dat...
return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result.
def exclude_samples(in_file, out_file, to_exclude, ref_file, config, filters=None): """Exclude specific samples from an input VCF file. """ include, exclude = _get_exclude_samples(in_file, to_exclude) # can use the input sample, all exclusions already gone if len(exclude) == 0: out_file = in...
Exclude specific samples from an input VCF file.
def ocr(img, mrz_mode=True, extra_cmdline_params=''): """Runs Tesseract on a given image. Writes an intermediate tempfile and then runs the tesseract command on the image. This is a simplified modification of image_to_string from PyTesseract, which is adapted to SKImage rather than PIL. In principle we co...
Runs Tesseract on a given image. Writes an intermediate tempfile and then runs the tesseract command on the image. This is a simplified modification of image_to_string from PyTesseract, which is adapted to SKImage rather than PIL. In principle we could have reimplemented it just as well - there are some appar...
def timer(logger=None, level=logging.INFO, fmt="function %(function_name)s execution time: %(execution_time).3f", *func_or_func_args, **timer_kwargs): """ Function decorator displaying the function execution time All kwargs are the arguments taken by the Timer class constructor. """ ...
Function decorator displaying the function execution time All kwargs are the arguments taken by the Timer class constructor.
def write_id (self): """Write ID for current URL.""" self.writeln(u"<tr>") self.writeln(u'<td>%s</td>' % self.part("id")) self.write(u"<td>%d</td></tr>" % self.stats.number)
Write ID for current URL.
def load(json_src, save=False): """Load any json serialized cinderlib object.""" if isinstance(json_src, six.string_types): json_src = json_lib.loads(json_src) if isinstance(json_src, list): return [getattr(objects, obj['class']).load(obj, save) for obj in json_src] ret...
Load any json serialized cinderlib object.
def _reduce_logsumexp(input_tensor, axis=None, keepdims=False, name=None): # pylint: disable=unused-argument """Computes `log(sum(exp(input_tensor))) along the specified axis.""" try: return scipy_special.logsumexp( input_tensor, axis=_astuple(axis), keepdims=keepdims) except NotImplementedError: ...
Computes `log(sum(exp(input_tensor))) along the specified axis.
def comic_archive_compress(args): """ Called back by every optimization inside a comic archive. When they're all done it creates the new archive and cleans up. """ try: filename, old_format, settings, nag_about_gifs = args Settings.update(settings) tmp_dir = _get_archive_tmp...
Called back by every optimization inside a comic archive. When they're all done it creates the new archive and cleans up.
def remove_defaults(self, *args): ''' cplan.remove_defaults(a, b...) yields a new caclulation plan identical to cplan except without default values for any of the given parameter names. An exception is raised if any default value given is not found in cplan. ''' for arg ...
cplan.remove_defaults(a, b...) yields a new caclulation plan identical to cplan except without default values for any of the given parameter names. An exception is raised if any default value given is not found in cplan.
def _parse_http_header(h): """ Parses a typical multi-valued and parametrised HTTP header (e.g. Accept headers) and returns a list of values and parameters. For non-standard or broken input, this implementation may return partial results. :param h: A header string (e.g. ``text/html,text/plain;q=0.9,*/*;...
Parses a typical multi-valued and parametrised HTTP header (e.g. Accept headers) and returns a list of values and parameters. For non-standard or broken input, this implementation may return partial results. :param h: A header string (e.g. ``text/html,text/plain;q=0.9,*/*;q=0.8``) :return: List of (valu...
def convert_float_to_two_registers(floatValue): """ Convert 32 Bit real Value to two 16 Bit Value to send as Modbus Registers floatValue: Value to be converted return: 16 Bit Register values int[] """ myList = list() s = bytearray(struct.pack('<f', floatValue) ) #little endian myL...
Convert 32 Bit real Value to two 16 Bit Value to send as Modbus Registers floatValue: Value to be converted return: 16 Bit Register values int[]
def rollup(self, freq, **kwargs): """Downsample `self` through geometric linking. Parameters ---------- freq : {'D', 'W', 'M', 'Q', 'A'} The frequency of the result. **kwargs Passed to `self.resample()`. Returns ------- TSeries ...
Downsample `self` through geometric linking. Parameters ---------- freq : {'D', 'W', 'M', 'Q', 'A'} The frequency of the result. **kwargs Passed to `self.resample()`. Returns ------- TSeries Example ------- # Deri...
def get_task_ops(task_type=TaskType.ALG_CTRL): """Returns an operations list based on the specified task index. Args: task_type: indicates the task type used. Returns: List of the eligible ops. """ try: return LearnToExecuteState.TASK_TYPE_OPS[task_type] except KeyError: ...
Returns an operations list based on the specified task index. Args: task_type: indicates the task type used. Returns: List of the eligible ops.
def player_stats(game_id): """Return dictionary of individual stats of a game with matching id. The additional pitching/batting is mostly the same stats, except it contains some useful stats such as groundouts/flyouts per pitcher (go/ao). MLB decided to have two box score files, thus we return...
Return dictionary of individual stats of a game with matching id. The additional pitching/batting is mostly the same stats, except it contains some useful stats such as groundouts/flyouts per pitcher (go/ao). MLB decided to have two box score files, thus we return the data from both.
def load_from_stream(self, group): """Load a Group from an NCStream object.""" self._unpack_attrs(group.atts) self.name = group.name for dim in group.dims: new_dim = Dimension(self, dim.name) self.dimensions[dim.name] = new_dim new_dim.load_from_strea...
Load a Group from an NCStream object.
def require(self, entity_type, attribute_name=None): """ The intent parser should require an entity of the provided type. Args: entity_type(str): an entity type attribute_name(str): the name of the attribute on the parsed intent. Defaults to match entity_type. R...
The intent parser should require an entity of the provided type. Args: entity_type(str): an entity type attribute_name(str): the name of the attribute on the parsed intent. Defaults to match entity_type. Returns: self: to continue modifications.
def rpc_get_all_names( self, offset, count, **con_info ): """ Get all unexpired names, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error """ if not check_offset(offset): return {'error': 'invalid offset', 'http_status'...
Get all unexpired names, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error
def _add_unitary_two(self, gate, qubit0, qubit1): """Apply a two-qubit unitary matrix. Args: gate (matrix_like): a the two-qubit gate matrix qubit0 (int): gate qubit-0 qubit1 (int): gate qubit-1 """ # Convert to complex rank-4 tensor gate_ten...
Apply a two-qubit unitary matrix. Args: gate (matrix_like): a the two-qubit gate matrix qubit0 (int): gate qubit-0 qubit1 (int): gate qubit-1
def output_influx(data): """Print data using influxDB format.""" for contract in data: # Pop yesterdays data yesterday_data = data[contract]['yesterday_hourly_consumption'] del data[contract]['yesterday_hourly_consumption'] # Print general data out = "pyhydroquebec,cont...
Print data using influxDB format.
def getSubjectObjectsByPredicate(self, predicate): """ Args: predicate : str Predicate for which to return subject, object tuples. Returns: list of subject, object tuples: All subject/objects with ``predicate``. Notes: Equivalent SPARQL: .. highlight: sql :...
Args: predicate : str Predicate for which to return subject, object tuples. Returns: list of subject, object tuples: All subject/objects with ``predicate``. Notes: Equivalent SPARQL: .. highlight: sql :: SELECT DISTINCT ?s ?o WHERE {{ ?s {0} ...
def to_nnf(self): """Return an equivalent expression is negation normal form.""" node = self.node.to_nnf() if node is self.node: return self else: return _expr(node)
Return an equivalent expression is negation normal form.
def fit( self, df, duration_col, event_col=None, ancillary_df=None, show_progress=False, timeline=None, weights_col=None, robust=False, initial_point=None, entry_col=None, ): """ Fit the accelerated failure time ...
Fit the accelerated failure time model to a right-censored dataset. Parameters ---------- df: DataFrame a Pandas DataFrame with necessary columns `duration_col` and `event_col` (see below), covariates columns, and special columns (weights). `duration_col` ref...
def _validate_inputs(self, inputdict): """ Validate input links. """ # Check inputdict try: parameters = inputdict.pop(self.get_linkname('parameters')) except KeyError: raise InputValidationError("No parameters specified for this " ...
Validate input links.
def matchToString(aaMatch, read1, read2, indent='', offsets=None): """ Format amino acid sequence match as a string. @param aaMatch: A C{dict} returned by C{compareAaReads}. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read} instance or an instance of ...
Format amino acid sequence match as a string. @param aaMatch: A C{dict} returned by C{compareAaReads}. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read} instance or an instance of one of its subclasses. @param indent: A C{str} to indent all returned lines...
def get_parameter(name, withdecryption=False, resp_json=False, region=None, key=None, keyid=None, profile=None): ''' Retrives a parameter from SSM Parameter Store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.get_parameter test-param withdescription=True ''' conn = __...
Retrives a parameter from SSM Parameter Store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.get_parameter test-param withdescription=True
def eigh_robust(a, b=None, eigvals=None, eigvals_only=False, overwrite_a=False, overwrite_b=False, turbo=True, check_finite=True): """Robustly solve the Hermitian generalized eigenvalue problem This function robustly solves the Hermetian generalized eigenvalue problem ``A v ...
Robustly solve the Hermitian generalized eigenvalue problem This function robustly solves the Hermetian generalized eigenvalue problem ``A v = lambda B v`` in the case that B is not strictly positive definite. When B is strictly positive-definite, the result is equivalent to scipy.linalg.eigh() within ...
def get_tile_info(tile, time, aws_index=None, all_tiles=False): """ Get basic information about image tile :param tile: tile name (e.g. ``'T10UEV'``) :type tile: str :param time: A single date or a time interval, times have to be in ISO 8601 string :type time: str or (str, str) :param aws_index...
Get basic information about image tile :param tile: tile name (e.g. ``'T10UEV'``) :type tile: str :param time: A single date or a time interval, times have to be in ISO 8601 string :type time: str or (str, str) :param aws_index: index of tile on AWS :type aws_index: int or None :param all_t...
def authenticated_user(self, auth): """ Returns the user authenticated by ``auth`` :param auth.Authentication auth: authentication for user to retrieve :return: user authenticated by the provided authentication :rtype: GogsUser :raises NetworkFailure: if there is an err...
Returns the user authenticated by ``auth`` :param auth.Authentication auth: authentication for user to retrieve :return: user authenticated by the provided authentication :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFail...
def _add_raster_layer(self, raster_layer, layer_name, save_style=False): """Add a raster layer to the folder. :param raster_layer: The layer to add. :type raster_layer: QgsRasterLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :par...
Add a raster layer to the folder. :param raster_layer: The layer to add. :type raster_layer: QgsRasterLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. :type save_st...
def show_args(): ''' Show which arguments map to which flags and options. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' logadm.show_args ''' mapping = {'flags': {}, 'options': {}} for flag, arg in option_toggles.items(): mapping['flags'][flag] ...
Show which arguments map to which flags and options. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' logadm.show_args
def update(self, instance, oldValue, newValue): """Updates the aggregate based on a change in the child value.""" self.__set__(instance, self.__get__(instance, None) + newValue - (oldValue or 0))
Updates the aggregate based on a change in the child value.
async def create( cls, node: Union[Node, str], cache_device: Union[BlockDevice, Partition]): """ Create a BcacheCacheSet on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param cache_device: Block device or partition to...
Create a BcacheCacheSet on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param cache_device: Block device or partition to create the cache set on. :type cache_device: `BlockDevice` or `Partition`
def _set_history_control_entry(self, v, load=False): """ Setter method for history_control_entry, mapped from YANG variable /interface/fortygigabitethernet/rmon/collection/history_control_entry (list) If this variable is read-only (config: false) in the source YANG file, then _set_history_control_entry ...
Setter method for history_control_entry, mapped from YANG variable /interface/fortygigabitethernet/rmon/collection/history_control_entry (list) If this variable is read-only (config: false) in the source YANG file, then _set_history_control_entry is considered as a private method. Backends looking to popula...
def setData(self, index, value, role=Qt.EditRole): """ Sets the role data for the item at index to value. Returns true if successful; otherwise returns false. The dataChanged and sigItemChanged signals will be emitted if the data was successfully set. Descendant...
Sets the role data for the item at index to value. Returns true if successful; otherwise returns false. The dataChanged and sigItemChanged signals will be emitted if the data was successfully set. Descendants should typically override setItemData function instead of set...
def remove_prefix(self, prefix): """Removes prefix from this set. This is a no-op if the prefix doesn't exist in it. """ if prefix not in self.__prefix_map: return ni = self.__lookup_prefix(prefix) ni.prefixes.discard(prefix) del self.__prefix_map[pr...
Removes prefix from this set. This is a no-op if the prefix doesn't exist in it.
def otp(scope, password, seed, seqs): """ Calculates a one-time password hash using the given password, seed, and sequence number and returns it. Uses the md4/sixword algorithm as supported by TACACS+ servers. :type password: string :param password: A password. :type seed: string :par...
Calculates a one-time password hash using the given password, seed, and sequence number and returns it. Uses the md4/sixword algorithm as supported by TACACS+ servers. :type password: string :param password: A password. :type seed: string :param seed: A username. :type seqs: int :par...
def from_xml(xml): """ Convert :class:`.MARCXMLRecord` object to :class:`.EPublication` namedtuple. Args: xml (str/MARCXMLRecord): MARC XML which will be converted to EPublication. In case of str, ``<record>`` tag is required. Returns: st...
Convert :class:`.MARCXMLRecord` object to :class:`.EPublication` namedtuple. Args: xml (str/MARCXMLRecord): MARC XML which will be converted to EPublication. In case of str, ``<record>`` tag is required. Returns: structure: :class:`.EPublication` namedtu...
def get_method_analysis(self, method): """ Returns the crossreferencing object for a given Method. Beware: the similar named function :meth:`~get_method()` will return a :class:`MethodAnalysis` object, while this function returns a :class:`MethodClassAnalysis` object! This Meth...
Returns the crossreferencing object for a given Method. Beware: the similar named function :meth:`~get_method()` will return a :class:`MethodAnalysis` object, while this function returns a :class:`MethodClassAnalysis` object! This Method will only work after a run of :meth:`~create_xref()` ...
def getInterval(self): """Vocabulary of date intervals to calculate the "To" field date based from the "From" field date. """ items = ( ("", _(u"Not set")), ("1", _(u"daily")), ("7", _(u"weekly")), ("30", _(u"monthly")), ("90", ...
Vocabulary of date intervals to calculate the "To" field date based from the "From" field date.
def startLogin(): """ If we are not logged in, this generates the redirect URL to the OIDC provider and returns the redirect response :return: A redirect response to the OIDC provider """ flask.session["state"] = oic.oauth2.rndstr(SECRET_KEY_LENGTH) flask.session["nonce"] = oic.oauth2.rndstr...
If we are not logged in, this generates the redirect URL to the OIDC provider and returns the redirect response :return: A redirect response to the OIDC provider
def shakespeare(chunk_size): """Downloads Shakespeare, converts it into ASCII codes and chunks it. Args: chunk_size: The dataset is broken down so that it is shaped into batches x chunk_size. Returns: A numpy array of ASCII codes shaped into batches x chunk_size. """ file_name = maybe_download(...
Downloads Shakespeare, converts it into ASCII codes and chunks it. Args: chunk_size: The dataset is broken down so that it is shaped into batches x chunk_size. Returns: A numpy array of ASCII codes shaped into batches x chunk_size.
def get_needed_fieldnames(arr, names): """Given a FieldArray-like array and a list of names, determines what fields are needed from the array so that using the names does not result in an error. Parameters ---------- arr : instance of a FieldArray or similar The array from which to dete...
Given a FieldArray-like array and a list of names, determines what fields are needed from the array so that using the names does not result in an error. Parameters ---------- arr : instance of a FieldArray or similar The array from which to determine what fields to get. names : (list of...
def input_file(filename): """ Run all checks on a Python source file. """ if excluded(filename) or not filename_match(filename): return {} if options.verbose: message('checking ' + filename) options.counters['files'] = options.counters.get('files', 0) + 1 errors = Checker(fil...
Run all checks on a Python source file.
def extract(dump_files, extractors=ALL_EXTRACTORS): """ Extracts cites from a set of `dump_files`. :Parameters: dump_files : str | `file` A set of files MediaWiki XML dump files (expects: pages-meta-history) extractors : `list`(`extractor`) A list of extr...
Extracts cites from a set of `dump_files`. :Parameters: dump_files : str | `file` A set of files MediaWiki XML dump files (expects: pages-meta-history) extractors : `list`(`extractor`) A list of extractors to apply to the text :Returns: `iterable` --...
def handle_aliases_in_calls(name, import_alias_mapping): """Returns either None or the handled alias. Used in add_module. """ for key, val in import_alias_mapping.items(): # e.g. Foo == Foo # e.g. Foo.Bar startswith Foo. if name == key or \ name.startswith(key + '...
Returns either None or the handled alias. Used in add_module.
def on_timer(self): """Executes flush(). Ignores any errors to make sure one exception doesn't halt the whole flushing process. """ try: self.flush() except Exception as e: log.exception('Error while flushing: %s', e) self._set_timer()
Executes flush(). Ignores any errors to make sure one exception doesn't halt the whole flushing process.
def map_val(dest, src, key, default=None, src_key=None): """Will ensure a dict has values sourced from either another dict or based on the provided default""" if not src_key: src_key = key if src_key in src: dest[key] = src[src_key] else: if default is not None: ...
Will ensure a dict has values sourced from either another dict or based on the provided default
def logout_service_description(self): """Logout service description.""" label = 'Logout from ' + self.name if (self.auth_type): label = label + ' (' + self.auth_type + ')' return({"@id": self.logout_uri, "profile": self.profile_base + 'logout', ...
Logout service description.
def rar3_s2k(psw, salt): """String-to-key hash for RAR3. """ if not isinstance(psw, unicode): psw = psw.decode('utf8') seed = bytearray(psw.encode('utf-16le') + salt) h = Rar3Sha1(rarbug=True) iv = EMPTY for i in range(16): for j in range(0x4000): cnt = S_LONG.pac...
String-to-key hash for RAR3.
def to_string(cls, error_code): """Returns the string message for the given ``error_code``. Args: cls (JLinkEraseErrors): the ``JLinkEraseErrors`` class error_code (int): error code to convert Returns: An error string corresponding to the error code. Rais...
Returns the string message for the given ``error_code``. Args: cls (JLinkEraseErrors): the ``JLinkEraseErrors`` class error_code (int): error code to convert Returns: An error string corresponding to the error code. Raises: ValueError: if the error code...
def verify_directory(verbose=True, max_size_mb=50): """Ensure that the current directory looks like a Dallinger experiment, and does not appear to have unintended contents that will be copied on deployment. """ # Check required files ok = True mb_to_bytes = 1000 * 1000 expected_files = [...
Ensure that the current directory looks like a Dallinger experiment, and does not appear to have unintended contents that will be copied on deployment.
def add_key_val(keyname, keyval, keytype, filename, extnum): """Add/replace FITS key Add/replace the key keyname with value keyval of type keytype in filename. Parameters: ---------- keyname : str FITS Keyword name. keyval : str FITS keyword value. keytype: str FITS...
Add/replace FITS key Add/replace the key keyname with value keyval of type keytype in filename. Parameters: ---------- keyname : str FITS Keyword name. keyval : str FITS keyword value. keytype: str FITS keyword type: int, float, str or bool. filaname : str F...
def present(name, password, permission): ''' Ensure the user exists on the Dell DRAC name: The users username password The password used to authenticate permission The permissions that should be assigned to a user ''' ret = {'name': name, 'result': True,...
Ensure the user exists on the Dell DRAC name: The users username password The password used to authenticate permission The permissions that should be assigned to a user
def confirm_authorization_request(self): """When consumer confirm the authrozation.""" server = self.server uri, http_method, body, headers = extract_params() try: realms, credentials = server.get_realms_and_credentials( uri, http_method=http_method, body=bod...
When consumer confirm the authrozation.
def merge(self, other): """Merge two recipes together, returning a single recipe containing all nodes. Note: This does NOT yet return a minimal recipe. :param other: A Recipe object that should be merged with the current Recipe object. :return: A new Recipe ...
Merge two recipes together, returning a single recipe containing all nodes. Note: This does NOT yet return a minimal recipe. :param other: A Recipe object that should be merged with the current Recipe object. :return: A new Recipe object containing information from ...
def _ppf(self, q, left, right, cache): """ Point percentile function. Example: >>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9])) [0.1 0.2 0.9] >>> print(chaospy.Trunc(chaospy.Uniform(), 0.4).inv([0.1, 0.2, 0.9])) [0.04 0.08 0.36] >>> p...
Point percentile function. Example: >>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9])) [0.1 0.2 0.9] >>> print(chaospy.Trunc(chaospy.Uniform(), 0.4).inv([0.1, 0.2, 0.9])) [0.04 0.08 0.36] >>> print(chaospy.Trunc(0.6, chaospy.Uniform()).inv([0.1, 0.2, 0...
def resample_waveforms(Y_dict): """ INPUT: - Dictionary of waveforms loaded from text file - ALSO, Dictionary of timeseries indexed by name OUTPUT: - Y_dict: resampled, normalized waveforms, ready for FFT - new parameters: +...
INPUT: - Dictionary of waveforms loaded from text file - ALSO, Dictionary of timeseries indexed by name OUTPUT: - Y_dict: resampled, normalized waveforms, ready for FFT - new parameters: + fs = 4096 + time durati...
def substitute_infinitives_as_subjects(sent_str): """If an infinitive is used as a subject, substitute the gerund.""" sent_doc = textacy.Doc(sent_str, lang='en_core_web_lg') #inf_pattern = r'<PART><VERB>+' # To aux/auxpass* csubj inf_pattern = r'<PART><VERB>' # To aux/auxpass* csubj infinitives = te...
If an infinitive is used as a subject, substitute the gerund.
def print_help(self, script_name: str): '''print a help message from the script''' textWidth = max(60, shutil.get_terminal_size((80, 20)).columns) if len(script_name) > 20: print(f'usage: sos run {script_name}') print( ' [workflow_name | -t ...
print a help message from the script
def run_nose(self, params): """ :type params: Params """ thread.set_index(params.thread_index) log.debug("[%s] Starting nose iterations: %s", params.worker_index, params) assert isinstance(params.tests, list) # argv.extend(['--with-apiritif', '--nocapture', '--exe...
:type params: Params
def modify_no_rollback(self, dn: str, mod_list: dict): """ Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ _debug("modify_no_rollback", self, dn, mod_list) result = self._do_with_retry(lambda obj: obj.modify_s(dn, m...
Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled.
def windowed_df(pos, ac1, ac2, size=None, start=None, stop=None, step=None, windows=None, is_accessible=None, fill=np.nan): """Calculate the density of fixed differences between two populations in windows over a single chromosome/contig. Parameters ---------- pos : array_like, int,...
Calculate the density of fixed differences between two populations in windows over a single chromosome/contig. Parameters ---------- pos : array_like, int, shape (n_items,) Variant positions, using 1-based coordinates, in ascending order. ac1 : array_like, int, shape (n_variants, n_alleles...
def get_data_matches(text, delim_pos, dxproj, folderpath, classname=None, typespec=None, visibility=None): ''' :param text: String to be tab-completed; still in escaped form :type text: string :param delim_pos: index of last unescaped "/" or ":" in text :type delim_pos: int ...
:param text: String to be tab-completed; still in escaped form :type text: string :param delim_pos: index of last unescaped "/" or ":" in text :type delim_pos: int :param dxproj: DXProject handler to use :type dxproj: DXProject :param folderpath: Unescaped path in which to search for data object...
def sample_id(self, lon): ''' Return the corresponding sample Args: lon (int): longidute in degree Returns: Correponding sample ''' if self.grid == 'WAC': sample = np.rint(float(self.SAMPLE_PROJECTION_OFFSET) + 1.0 + ...
Return the corresponding sample Args: lon (int): longidute in degree Returns: Correponding sample
def csi(self, capname, *args): """Return the escape sequence for the selected Control Sequence.""" value = curses.tigetstr(capname) if value is None: return b'' else: return curses.tparm(value, *args)
Return the escape sequence for the selected Control Sequence.
def find_best_question(X, y, criterion): """Find the best question to ask by iterating over every feature / value and calculating the information gain. """ measure_impurity = gini_impurity if criterion == "gini" else entropy current_impurity = measure_impurity(y) best_info_gain = 0 bes...
Find the best question to ask by iterating over every feature / value and calculating the information gain.
def get_cpu_props(cls, family, arch='x86'): """ Get CPU info XML Args: family(str): CPU family arch(str): CPU arch Returns: lxml.etree.Element: CPU xml Raises: :exc:`~LagoException`: If no such CPU family exists """ ...
Get CPU info XML Args: family(str): CPU family arch(str): CPU arch Returns: lxml.etree.Element: CPU xml Raises: :exc:`~LagoException`: If no such CPU family exists
def wetdays(pr, thresh='1.0 mm/day', freq='YS'): r"""Wet days Return the total number of days during period with precipitation over threshold. Parameters ---------- pr : xarray.DataArray Daily precipitation [mm] thresh : str Precipitation value over which a day is considered wet. D...
r"""Wet days Return the total number of days during period with precipitation over threshold. Parameters ---------- pr : xarray.DataArray Daily precipitation [mm] thresh : str Precipitation value over which a day is considered wet. Default: '1 mm/day'. freq : str, optional Re...
def from_connection_string(cls, conn_str, *, loop=None, **kwargs): """Create a Service Bus client from a connection string. :param conn_str: The connection string. :type conn_str: str Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py ...
Create a Service Bus client from a connection string. :param conn_str: The connection string. :type conn_str: str Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py :start-after: [START create_async_servicebus_client_connstr] ...
def ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ=None): """ Ensure we have benchmark data for `symbol` from `first_date` to `last_date` Parameters ---------- symbol : str The symbol for the benchmark to load. first_date : pd.Ti...
Ensure we have benchmark data for `symbol` from `first_date` to `last_date` Parameters ---------- symbol : str The symbol for the benchmark to load. first_date : pd.Timestamp First required date for the cache. last_date : pd.Timestamp Last required date for the cache. no...
def remove_observing_method(self, prop_names, method): """ Remove dynamic notifications. *method* a callable that was registered with :meth:`observe`. *prop_names* a sequence of strings. This need not correspond to any one `observe` call. .. note:: This can...
Remove dynamic notifications. *method* a callable that was registered with :meth:`observe`. *prop_names* a sequence of strings. This need not correspond to any one `observe` call. .. note:: This can revert even the effects of decorator `observe` at runtime. Don'...
def send_message(msg: 'EFBMsg') -> Optional['EFBMsg']: """ Deliver a message to the destination channel. Args: msg (EFBMsg): The message Returns: The message sent by the destination channel, includes the updated message ID from there. Returns ``None`` if the message is ...
Deliver a message to the destination channel. Args: msg (EFBMsg): The message Returns: The message sent by the destination channel, includes the updated message ID from there. Returns ``None`` if the message is not sent.
def load_key(self, key_path, password): """ Creates paramiko rsa key :type key_path: str :param key_path: path to rsa key :type password: str :param password: password to try if rsa key is encrypted """ try: return paramiko.RSAKey.from_privat...
Creates paramiko rsa key :type key_path: str :param key_path: path to rsa key :type password: str :param password: password to try if rsa key is encrypted
def makeRequests(callable_, args_list, callback=None, exc_callback=_handle_thread_exception): """Create several work requests for same callable with different arguments. Convenience function for creating several work requests for the same callable where each invocation of the callable rece...
Create several work requests for same callable with different arguments. Convenience function for creating several work requests for the same callable where each invocation of the callable receives different values for its arguments. ``args_list`` contains the parameters for each invocation of callabl...
def set_cookie(response, key, value, max_age): """ Set the cookie ``key`` on ``response`` with value ``value`` valid for ``max_age`` secondes :param django.http.HttpResponse response: a django response where to set the cookie :param unicode key: the cookie key :param unicode value: ...
Set the cookie ``key`` on ``response`` with value ``value`` valid for ``max_age`` secondes :param django.http.HttpResponse response: a django response where to set the cookie :param unicode key: the cookie key :param unicode value: the cookie value :param int max_age: the maximum validi...
def animate(func: types.AnyFunction = None, *, animation: types.AnimationGenerator = _default_animation(), step: float = 0.1) -> types.AnyFunction: """Wrapper function for the _Animate wrapper class. Args: func: A function to run while animation is showing. ...
Wrapper function for the _Animate wrapper class. Args: func: A function to run while animation is showing. animation: An AnimationGenerator that yields animation frames. step: Approximate timestep (in seconds) between frames. Returns: An animated version of func if func is n...
def parse(cls, filepath, filecontent, parser): """Parses a source for addressable Serializable objects. No matter the parser used, the parsed and mapped addressable objects are all 'thin'; ie: any objects they point to in other namespaces or even in the same namespace but from a seperate source are lef...
Parses a source for addressable Serializable objects. No matter the parser used, the parsed and mapped addressable objects are all 'thin'; ie: any objects they point to in other namespaces or even in the same namespace but from a seperate source are left as unresolved pointers. :param string filepath:...
def set_creation_date(self, p_date=date.today()): """ Sets the creation date of a todo. Should be passed a date object. """ self.fields['creationDate'] = p_date # not particularly pretty, but inspired by # http://bugs.python.org/issue1519638 non-existent matches trigger ...
Sets the creation date of a todo. Should be passed a date object.
def stepper_request_library_version(self): """ Request the stepper library version from the Arduino. To retrieve the version after this command is called, call get_stepper_version """ data = [self.STEPPER_LIBRARY_VERSION] self._command_handler.send_sysex(self._com...
Request the stepper library version from the Arduino. To retrieve the version after this command is called, call get_stepper_version
def help_text(cls): """Return a slack-formatted list of commands with their usage.""" docs = [cmd_func.__doc__ for cmd_func in cls.commands.values()] # Don't want to include 'usage: ' or explanation. usage_lines = [doc.partition('\n')[0] for doc in docs] terse_lines = [line[len(...
Return a slack-formatted list of commands with their usage.
def mols_from_file(path, no_halt=True, assign_descriptors=True): """Compound supplier from CTAB text file (.mol, .sdf)""" with open(path, 'rb') as f: fd = (tx.decode(line) for line in f) for c in mol_supplier(fd, no_halt, assign_descriptors): yield c
Compound supplier from CTAB text file (.mol, .sdf)
def decode_consumermetadata_response(cls, data): """ Decode bytes to a ConsumerMetadataResponse :param bytes data: bytes to decode """ (correlation_id, error_code, node_id), cur = \ relative_unpack('>ihi', data, 0) host, cur = read_short_ascii(data, cur) ...
Decode bytes to a ConsumerMetadataResponse :param bytes data: bytes to decode
def bbox(self): """ Bounding box tuple (left, top, right, bottom) in relative coordinates, where top-left corner is (0., 0.) and bottom-right corner is (1., 1.). :return: `tuple` """ from itertools import chain knots = [ (knot.anchor[1], knot.anchor[0...
Bounding box tuple (left, top, right, bottom) in relative coordinates, where top-left corner is (0., 0.) and bottom-right corner is (1., 1.). :return: `tuple`
def cmap_center_adjust(cmap, center_ratio): """ Returns a new colormap based on the one given but adjusted so that the old center point higher (>0.5) or lower (<0.5) :param cmap: colormap instance (e.g., cm.jet) :param center_ratio: """ if not (0. < center_ratio) & (center_ratio < 1.):...
Returns a new colormap based on the one given but adjusted so that the old center point higher (>0.5) or lower (<0.5) :param cmap: colormap instance (e.g., cm.jet) :param center_ratio:
def _break_reads(self, contig, position, fout, min_read_length=250): '''Get all reads from contig, but breaks them all at given position (0-based) in the reference. Writes to fout. Currently pproximate where it breaks (ignores indels in the alignment)''' sam_reader = pysam.Samfile(self.bam, "rb") ...
Get all reads from contig, but breaks them all at given position (0-based) in the reference. Writes to fout. Currently pproximate where it breaks (ignores indels in the alignment)
def parse_conference_address(address_string): """Parse a conference address. This is a pretty dummy address parser. It only extracts country and state (for US) and should be replaced with something better, like Google Geocoding. """ geo_elements = address_string.split(',') city = geo_eleme...
Parse a conference address. This is a pretty dummy address parser. It only extracts country and state (for US) and should be replaced with something better, like Google Geocoding.
def get_appliance_stats_by_location(self, location_id, start, end, granularity=None, per_page=None, page=None, min_power=None): """Get appliance usage data for a given location within a given time range. Stats are generated by fetching appliance events that match the suppli...
Get appliance usage data for a given location within a given time range. Stats are generated by fetching appliance events that match the supplied criteria and then aggregating them together based on the granularity specified with the request. Note: This endpoint uses the location's time zone when...
def load_data(self, df): """ Wraps the LOAD DATA DDL statement. Loads data into an MapD table from pandas.DataFrame or pyarrow.Table Parameters ---------- df: pandas.DataFrame or pyarrow.Table Returns ------- query : MapDQuery """ ...
Wraps the LOAD DATA DDL statement. Loads data into an MapD table from pandas.DataFrame or pyarrow.Table Parameters ---------- df: pandas.DataFrame or pyarrow.Table Returns ------- query : MapDQuery
def dest_fpath(self, source_fpath: str) -> str: """Calculates full path for end json-api file from source file full path.""" relative_fpath = os.path.join(*source_fpath.split(os.sep)[1:]) relative_dirpath = os.path.dirname(relative_fpath) source_fname = relative_fpath.split(os.s...
Calculates full path for end json-api file from source file full path.
def append(self, obj): """ If it is a list it will append the obj, if it is a dictionary it will convert it to a list and append :param obj: dict or list of the object to append :return: None """ if isinstance(obj, dict) and self._col_names: obj = [obj...
If it is a list it will append the obj, if it is a dictionary it will convert it to a list and append :param obj: dict or list of the object to append :return: None
def scalar(name, data, step=None, description=None): """Write a scalar summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes. data: A real numeric scalar value, convertible to a `float32` Tensor. step: Explicit...
Write a scalar summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes. data: A real numeric scalar value, convertible to a `float32` Tensor. step: Explicit `int64`-castable monotonic step value for this summary. I...