code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def convertforoutput(self,outputfile): """Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Sourcefile is a CLAMOutputFile instance.""" assert isinstance(outputfile, CLAMOutputFile) #metadata of the destination file (file to be generated here)...
Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Sourcefile is a CLAMOutputFile instance.
def tag(self, tag): """Get a release by tag """ url = '%s/tags/%s' % (self, tag) response = self.http.get(url, auth=self.auth) response.raise_for_status() return response.json()
Get a release by tag
def sealedbox_encrypt(data, **kwargs): ''' Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-ca...
Encrypt data using a public key generated from `nacl.keygen`. The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key. CLI Examples: .. code-block:: bash salt-run nacl.sealedbox_encrypt datatoenc salt-call --local nacl.sealedbox_encrypt datatoenc pk_file...
def addMenuItem( self, newItem, atItem ): """ Adds a new menu item at the given item. :param newItem | <QTreeWidgetItem> atItem | <QTreeWidgetItem> """ tree = self.uiMenuTREE if ( not atItem ): tree.addTopLevelItem(n...
Adds a new menu item at the given item. :param newItem | <QTreeWidgetItem> atItem | <QTreeWidgetItem>
def simplex_projection(v, b=1): r"""Projection vectors to the simplex domain Implemented according to the paper: Efficient projections onto the l1-ball for learning in high dimensions, John Duchi, et al. ICML 2008. Implementation Time: 2011 June 17 by Bin@libin AT pmail.ntu.edu.sg Optimization Prob...
r"""Projection vectors to the simplex domain Implemented according to the paper: Efficient projections onto the l1-ball for learning in high dimensions, John Duchi, et al. ICML 2008. Implementation Time: 2011 June 17 by Bin@libin AT pmail.ntu.edu.sg Optimization Problem: min_{w}\| w - v \|_{2}^{2} ...
def nucnorm(x0, rho, gamma): """ Proximal operator for the nuclear norm (sum of the singular values of a matrix) Parameters ---------- x0 : array_like The starting or initial point used in the proximal update step rho : float Momentum parameter for the proximal step (larger val...
Proximal operator for the nuclear norm (sum of the singular values of a matrix) Parameters ---------- x0 : array_like The starting or initial point used in the proximal update step rho : float Momentum parameter for the proximal step (larger value -> stays closer to x0) gamma : fl...
def add_rec_new(self, k, val): """Recursively add a new value and its children to me, and assign a variable to it. Args: k (str): The name of the variable to assign. val (LispVal): The value to be added and assigned. Returns: LispVal: The added value...
Recursively add a new value and its children to me, and assign a variable to it. Args: k (str): The name of the variable to assign. val (LispVal): The value to be added and assigned. Returns: LispVal: The added value.
def set_web_master(self): """Parses the feed's webmaster and sets value""" try: self.web_master = self.soup.find('webmaster').string except AttributeError: self.web_master = None
Parses the feed's webmaster and sets value
def _set_mode(self, v, load=False): """ Setter method for mode, mapped from YANG variable /interface/tunnel/mode (container) If this variable is read-only (config: false) in the source YANG file, then _set_mode is considered as a private method. Backends looking to populate this variable should ...
Setter method for mode, mapped from YANG variable /interface/tunnel/mode (container) If this variable is read-only (config: false) in the source YANG file, then _set_mode is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_mode() directly.
def _add_gmaf(self, variant_obj, info_dict): """Add the gmaf frequency Args: variant_obj (puzzle.models.Variant) info_dict (dict): A info dictionary """ ##TODO search for max freq in info dict for transcript in variant_obj.transcripts: ...
Add the gmaf frequency Args: variant_obj (puzzle.models.Variant) info_dict (dict): A info dictionary
def formatdt(date: datetime.date, include_time: bool = True) -> str: """ Formats a ``datetime.date`` to ISO-8601 basic format, to minute accuracy with no timezone (or, if ``include_time`` is ``False``, omit the time). """ if include_time: return date.strftime("%Y-%m-%dT%H:%M") else: ...
Formats a ``datetime.date`` to ISO-8601 basic format, to minute accuracy with no timezone (or, if ``include_time`` is ``False``, omit the time).
def plot_oneD(dataset, vars, filename, bins=60): """ Plot 1D marginalised posteriors for the 'vars' of interest.""" n = len(vars) fig, axes = plt.subplots(nrows=n, ncols=1, sharex=False, sharey=False) for i, x in en...
Plot 1D marginalised posteriors for the 'vars' of interest.
def load_observations((observations, regex, rename), path, filenames): """ Returns a provisional name based dictionary of observations of the object. Each observations is keyed on the date. ie. a dictionary of dictionaries. @param path: the directory where filenames are. @type path str @param f...
Returns a provisional name based dictionary of observations of the object. Each observations is keyed on the date. ie. a dictionary of dictionaries. @param path: the directory where filenames are. @type path str @param filenames: list of files in path. @type filenames list @rtype None
def configure_flair(self, subreddit, flair_enabled=False, flair_position='right', flair_self_assign=False, link_flair_enabled=False, link_flair_position='left', link_flair_self_assign=False): ...
Configure the flair setting for the given subreddit. :returns: The json response from the server.
def notifyObservers(self, arg=None): '''If 'changed' indicates that this object has changed, notify all its observers, then call clearChanged(). Each observer has its update() called with two arguments: this observable object and the generic 'arg'.''' self.mutex.acquire(...
If 'changed' indicates that this object has changed, notify all its observers, then call clearChanged(). Each observer has its update() called with two arguments: this observable object and the generic 'arg'.
def sg_min(tensor, opt): r"""Computes the minimum of elements across axis of a tensor. See `tf.reduce_min()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, retai...
r"""Computes the minimum of elements across axis of a tensor. See `tf.reduce_min()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis : A tuple/list of integers or an integer. The axis to reduce. keep_dims: If true, retains reduced dimensions with le...
def _verify_jws(self, payload, key): """Verify the given JWS payload with the given key and return the payload""" jws = JWS.from_compact(payload) try: alg = jws.signature.combined.alg.name except KeyError: msg = 'No alg value found in header' raise Su...
Verify the given JWS payload with the given key and return the payload
def delete(self, worker_id): ''' Stop and remove a worker ''' code = 200 if worker_id in self.jobs: # NOTE pop it if done ? self.jobs[worker_id]['worker'].revoke(terminate=True) report = { 'id': worker_id, 'revoked': True ...
Stop and remove a worker
def match(self, location): """ Check if the given location "matches". :param location: The :class:`Location` object to try to match. :returns: :data:`True` if the two locations are on the same system and the :attr:`directory` can be matched as a filename pattern or ...
Check if the given location "matches". :param location: The :class:`Location` object to try to match. :returns: :data:`True` if the two locations are on the same system and the :attr:`directory` can be matched as a filename pattern or a literal match on the normalize...
async def get_user_groups(request): """Returns the groups that the user in this request has access to. This function gets the user id from the auth.get_auth function, and passes it to the ACL callback function to get the groups. Args: request: aiohttp Request object Returns: If th...
Returns the groups that the user in this request has access to. This function gets the user id from the auth.get_auth function, and passes it to the ACL callback function to get the groups. Args: request: aiohttp Request object Returns: If the ACL callback function returns None, this ...
def get_range_slices(self, column_parent, predicate, range, consistency_level): """ returns a subset of columns for a contiguous range of keys. Parameters: - column_parent - predicate - range - consistency_level """ self._seqid += 1 d = self._reqs[self._seqid] = defer.Deferr...
returns a subset of columns for a contiguous range of keys. Parameters: - column_parent - predicate - range - consistency_level
def extract_ape (archive, compression, cmd, verbosity, interactive, outdir): """Decompress an APE archive to a WAV file.""" outfile = util.get_single_outfile(outdir, archive, extension=".wav") return [cmd, archive, outfile, '-d']
Decompress an APE archive to a WAV file.
def get_pytorch_link(ft)->str: "Returns link to pytorch docs of `ft`." name = ft.__name__ ext = '.html' if name == 'device': return f'{PYTORCH_DOCS}tensor_attributes{ext}#torch-device' if name == 'Tensor': return f'{PYTORCH_DOCS}tensors{ext}#torch-tensor' if name.startswith('torchvision'): ...
Returns link to pytorch docs of `ft`.
def delete(self): """Deleting any existing copy of this object from the cache.""" key = self._key(self._all_keys()) _cache.delete(key)
Deleting any existing copy of this object from the cache.
def write( self, mi_cmd_to_write, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC, raise_error_on_timeout=True, read_response=True, ): """Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec. Args: mi_cmd_to_write (str or ...
Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec. Args: mi_cmd_to_write (str or list): String to write to gdb. If list, it is joined by newlines. timeout_sec (float): Maximum number of seconds to wait for response before exiting. Must be >= 0. ...
def names_in_chains(stream_item, aligner_data): ''' Convert doc-level Rating object into a Label, and add that Label to all Token in all coref chains identified by aligner_data["chain_selector"] :param stream_item: document that has a doc-level Rating to translate into token-level Labels. :para...
Convert doc-level Rating object into a Label, and add that Label to all Token in all coref chains identified by aligner_data["chain_selector"] :param stream_item: document that has a doc-level Rating to translate into token-level Labels. :param aligner_data: dict containing: chain_selector: ALL o...
def get_project_children(self, project_id, name_contains, exclude_response_fields=None): """ Send GET to /projects/{project_id}/children filtering by a name. :param project_id: str uuid of the project :param name_contains: str name to filter folders by (if not None this method works recu...
Send GET to /projects/{project_id}/children filtering by a name. :param project_id: str uuid of the project :param name_contains: str name to filter folders by (if not None this method works recursively) :param exclude_response_fields: [str]: list of fields to exclude in the response items ...
def create_empty(self, name=None, renderers=None, RootNetworkList=None, verbose=False): """ Create a new, empty network. The new network may be created as part of an existing network collection or a new network collection. :param name (string, optional): Enter the name of the new networ...
Create a new, empty network. The new network may be created as part of an existing network collection or a new network collection. :param name (string, optional): Enter the name of the new network. :param renderers (string, optional): Select the renderer to use for the new network v...
def visit_default(self, node): """check the node line number and check it if not yet done""" if not node.is_statement: return if not node.root().pure_python: return # XXX block visit of child nodes prev_sibl = node.previous_sibling() if prev_sibl is not N...
check the node line number and check it if not yet done
def rollback(self): """ Rollback this context: - Position the consumer at the initial offsets. """ self.logger.info("Rolling back context: %s", self.initial_offsets) self.update_consumer_offsets(self.initial_offsets)
Rollback this context: - Position the consumer at the initial offsets.
def map(source, func, *more_sources, ordered=True, task_limit=None): """Apply a given function to the elements of one or several asynchronous sequences. Each element is used as a positional argument, using the same order as their respective sources. The generation continues until the shortest seque...
Apply a given function to the elements of one or several asynchronous sequences. Each element is used as a positional argument, using the same order as their respective sources. The generation continues until the shortest sequence is exhausted. The function can either be synchronous or asynchronous...
def get_symbol(units) -> str: """Get default symbol type. Parameters ---------- units_str : string Units. Returns ------- string LaTeX formatted symbol. """ if kind(units) == "energy": d = {} d["nm"] = r"\lambda" d["wn"] = r"\bar\nu" ...
Get default symbol type. Parameters ---------- units_str : string Units. Returns ------- string LaTeX formatted symbol.
def tohdf5(table, source, where=None, name=None, create=False, drop=False, description=None, title='', filters=None, expectedrows=10000, chunkshape=None, byteorder=None, createparents=False, sample=1000): """ Write to an HDF5 table. If `create` is `False`, assumes the table ...
Write to an HDF5 table. If `create` is `False`, assumes the table already exists, and attempts to truncate it before loading. If `create` is `True`, a new table will be created, and if `drop` is True, any existing table will be dropped first. If `description` is `None`, the description will be guessed. ...
def get_ids(a): """ make copy of sequences with short identifier """ a_id = '%s.id.fa' % (a.rsplit('.', 1)[0]) a_id_lookup = '%s.id.lookup' % (a.rsplit('.', 1)[0]) if check(a_id) is True: return a_id, a_id_lookup a_id_f = open(a_id, 'w') a_id_lookup_f = open(a_id_lookup, 'w') ...
make copy of sequences with short identifier
def subtask(self, func, *args, **kw): """ Helper function for tasks needing to run subthreads. Takes care of remembering that the subtask is running, and of cleaning up after it. Example starting a simple.Task(): backend.subtask(task.ignore, 1, 'a', verbose=False) ...
Helper function for tasks needing to run subthreads. Takes care of remembering that the subtask is running, and of cleaning up after it. Example starting a simple.Task(): backend.subtask(task.ignore, 1, 'a', verbose=False) *args and **kw will be propagated to `func`.
def view_change_started(self, viewNo: int): """ Notifies primary decider about the fact that view changed to let it prepare for election, which then will be started from outside by calling decidePrimaries() """ if viewNo <= self.viewNo: logger.warning("{}Provi...
Notifies primary decider about the fact that view changed to let it prepare for election, which then will be started from outside by calling decidePrimaries()
def _write_with_fallback(s, write, fileobj): """Write the supplied string with the given write function like ``write(s)``, but use a writer for the locale's preferred encoding in case of a UnicodeEncodeError. Failing that attempt to write with 'utf-8' or 'latin-1'. """ if IPythonIOStream is no...
Write the supplied string with the given write function like ``write(s)``, but use a writer for the locale's preferred encoding in case of a UnicodeEncodeError. Failing that attempt to write with 'utf-8' or 'latin-1'.
def tag_exists(self, version): """Check if a tag has already been created with the name of the version. """ for tag in self.available_tags(): if tag == version: return True return False
Check if a tag has already been created with the name of the version.
def delete_tenant(self, tenant): """ ADMIN ONLY. Removes the tenant from the system. There is no 'undo' available, so you should be certain that the tenant specified is the tenant you wish to delete. """ tenant_id = utils.get_id(tenant) uri = "tenants/%s" % tenant...
ADMIN ONLY. Removes the tenant from the system. There is no 'undo' available, so you should be certain that the tenant specified is the tenant you wish to delete.
def group_children( index, shared, min_kids=10, stop_types=STOP_TYPES, delete_children=True ): """Collect like-type children into sub-groups of objects for objects with long children-lists Only group if: * there are more than X children of type Y * children are "simple" * i...
Collect like-type children into sub-groups of objects for objects with long children-lists Only group if: * there are more than X children of type Y * children are "simple" * individual children have no children themselves * individual children have no other parents...
def from_array(array): """ Deserialize a new StickerMessage from a given dictionary. :return: new StickerMessage instance. :rtype: StickerMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, paramet...
Deserialize a new StickerMessage from a given dictionary. :return: new StickerMessage instance. :rtype: StickerMessage
def _fitImg(self, img): ''' fit perspective and size of the input image to the reference image ''' img = imread(img, 'gray') if self.bg is not None: img = cv2.subtract(img, self.bg) if self.lens is not None: img = self.lens.correct(img, k...
fit perspective and size of the input image to the reference image
def _init_libcrypto(): ''' Set up libcrypto argtypes and initialize the library ''' libcrypto = _load_libcrypto() try: libcrypto.OPENSSL_init_crypto() except AttributeError: # Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L) libcrypto.OPENSSL_no_config() ...
Set up libcrypto argtypes and initialize the library
async def upload_file( self, file, *, part_size_kb=None, file_name=None, use_cache=None, progress_callback=None): """ Uploads the specified file and returns a handle (an instance of :tl:`InputFile` or :tl:`InputFileBig`, as required) which can be later used before...
Uploads the specified file and returns a handle (an instance of :tl:`InputFile` or :tl:`InputFileBig`, as required) which can be later used before it expires (they are usable during less than a day). Uploading a file will simply return a "handle" to the file stored remotely in the Teleg...
def commit(self, sha): """Get a single (repo) commit. See :func:`git_commit` for the Git Data Commit. :param str sha: (required), sha of the commit :returns: :class:`RepoCommit <github3.repos.commit.RepoCommit>` if successful, otherwise None """ url = self._b...
Get a single (repo) commit. See :func:`git_commit` for the Git Data Commit. :param str sha: (required), sha of the commit :returns: :class:`RepoCommit <github3.repos.commit.RepoCommit>` if successful, otherwise None
def pttl(self, key): """ Emulate pttl :param key: key for which pttl is requested. :returns: the number of milliseconds till timeout, None if the key does not exist or if the key has no timeout(as per the redis-py lib behavior). """ """ Returns ...
Emulate pttl :param key: key for which pttl is requested. :returns: the number of milliseconds till timeout, None if the key does not exist or if the key has no timeout(as per the redis-py lib behavior).
def get_realtime_alarm(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object...
Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class ...
def run_duplicated_samples(in_prefix, in_type, out_prefix, base_dir, options): """Runs step1 (duplicated samples). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param op...
Runs step1 (duplicated samples). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options: the options needed. :type in_prefix: str :type in_type: str :type ...
def validate_request_table(self, request): ''' Validates that all requests have the same table name. Set the table name if it is the first request for the batch operation. request: the request to insert, update or delete entity ''' if self.batch_table: ...
Validates that all requests have the same table name. Set the table name if it is the first request for the batch operation. request: the request to insert, update or delete entity
def __run_pre_all(self): """Execute the pre-all.py and pre-all.sql files if they exist""" # if the list of delta dirs is [delta1, delta2] the pre scripts of delta2 are # executed before the pre scripts of delta1 for d in reversed(self.dirs): pre_all_py_path = os.path.join(d...
Execute the pre-all.py and pre-all.sql files if they exist
def plotstat(data, circleinds=None, crossinds=None, edgeinds=None, url_path=None, fileroot=None, tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400): """ Make a light-weight stat figure """ fields = ['imkur', 'specstd', 'sizes', 'colors', 'snrs', 'key'] if not...
Make a light-weight stat figure
def request_camera_sensors(blink, network, camera_id): """ Request camera sensor info for one camera. :param blink: Blink instance. :param network: Sync module network id. :param camera_id: Camera ID of camera to request sesnor info from. """ url = "{}/network/{}/camera/{}/signals".format(b...
Request camera sensor info for one camera. :param blink: Blink instance. :param network: Sync module network id. :param camera_id: Camera ID of camera to request sesnor info from.
def prompt_save_images(args): """Prompt user to save images when crawling (for pdf and HTML formats).""" if args['images'] or args['no_images']: return if (args['pdf'] or args['html']) and (args['crawl'] or args['crawl_all']): save_msg = ('Choosing to save images will greatly slow the' ...
Prompt user to save images when crawling (for pdf and HTML formats).
def build_calmjs_artifacts(dist, key, value, cmdclass=BuildCommand): """ Trigger the artifact build process through the setuptools. """ if value is not True: return build_cmd = dist.get_command_obj('build') if not isinstance(build_cmd, cmdclass): logger.error( "'bui...
Trigger the artifact build process through the setuptools.
def update(self, client=None, unique_writer_identity=False): """API call: update sink configuration via a PUT request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update :type client: :class:`~google.cloud.logging.client.Client` or ...
API call: update sink configuration via a PUT request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update :type client: :class:`~google.cloud.logging.client.Client` or ``NoneType`` :param client: the client to use. If not passed,...
def get_signature(func): """ :type func: Callable :rtype: str """ try: return object.__getattribute__(func, '__tri_declarative_signature') except AttributeError: pass try: if sys.version_info[0] < 3: # pragma: no mutate names, _, varkw, defaults ...
:type func: Callable :rtype: str
def contact(request): """Displays the contact form and sends the email""" form = ContactForm(request.POST or None) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] sender = form.cleaned_data['sender'] cc_myself = form.cleaned_d...
Displays the contact form and sends the email
def calc_detection_voc_prec_rec(gt_boxlists, pred_boxlists, iou_thresh=0.5): """Calculate precision and recall based on evaluation code of PASCAL VOC. This function calculates precision and recall of predicted bounding boxes obtained from a dataset which has :math:`N` images. The code is based on th...
Calculate precision and recall based on evaluation code of PASCAL VOC. This function calculates precision and recall of predicted bounding boxes obtained from a dataset which has :math:`N` images. The code is based on the evaluation code used in PASCAL VOC Challenge.
def add_file(self, filepath, gzip=False, cache_name=None): """Load a static file in the cache. .. note:: Items are stored with the filepath as is (relative or absolute) as the key. :param str|unicode filepath: :param bool gzip: Use gzip compression. :param str|unicode cache_n...
Load a static file in the cache. .. note:: Items are stored with the filepath as is (relative or absolute) as the key. :param str|unicode filepath: :param bool gzip: Use gzip compression. :param str|unicode cache_name: If not set, default will be used.
def _get_mixing_indices(size, seed=None, name=None): """Generates an array of indices suitable for mutation operation. The mutation operation in differential evolution requires that for every element of the population, three distinct other elements be chosen to produce a trial candidate. This function generate...
Generates an array of indices suitable for mutation operation. The mutation operation in differential evolution requires that for every element of the population, three distinct other elements be chosen to produce a trial candidate. This function generates an array of shape [size, 3] satisfying the properties ...
def post_translation(self, query, bug): """ Convert the results of getbug back to the ancient RHBZ value formats """ ignore = query # RHBZ _still_ returns component and version as lists, which # deviates from upstream. Copy the list values to components #...
Convert the results of getbug back to the ancient RHBZ value formats
def setValue(self, key, value): """ Sets the value for the given key to the inputed value. :param key | <str> value | <variant> """ if self._customFormat: self._customFormat.setValue(key, value) else: sup...
Sets the value for the given key to the inputed value. :param key | <str> value | <variant>
def getXY(self, debug=False): ''' Returns the I{screen} coordinates of this C{View}. WARNING: Don't call self.getX() or self.getY() inside this method or it will enter an infinite loop @return: The I{screen} coordinates of this C{View} ''' if DEBUG_COORDS or de...
Returns the I{screen} coordinates of this C{View}. WARNING: Don't call self.getX() or self.getY() inside this method or it will enter an infinite loop @return: The I{screen} coordinates of this C{View}
def patch_config(config, data): """recursively 'patch' `config` with `data` :returns: `!True` if the `config` was changed""" is_changed = False for name, value in data.items(): if value is None: if config.pop(name, None) is not None: is_changed = True elif nam...
recursively 'patch' `config` with `data` :returns: `!True` if the `config` was changed
def do_filter(self, arg): """Sets the filter for the test cases to include in the plot/table by name. Only those test cases that include this text are included in plots, tables etc.""" if arg == "list": msg.info("TEST CASE FILTERS") for f in self.curargs["tfilter"]: ...
Sets the filter for the test cases to include in the plot/table by name. Only those test cases that include this text are included in plots, tables etc.
def ListLanguageIdentifiers(self): """Lists the language identifiers.""" table_view = views.ViewsFactory.GetTableView( self._views_format_type, column_names=['Identifier', 'Language'], title='Language identifiers') for language_id, value_list in sorted( language_ids.LANGUAGE_IDENTIFI...
Lists the language identifiers.
def _sanitize_column(self, key, value, **kwargs): """ Creates a new SparseArray from the input value. Parameters ---------- key : object value : scalar, Series, or array-like kwargs : dict Returns ------- sanitized_column : SparseArray ...
Creates a new SparseArray from the input value. Parameters ---------- key : object value : scalar, Series, or array-like kwargs : dict Returns ------- sanitized_column : SparseArray
def fit_mle(self, data, b=None): """%(super)s b : float The upper bound of the distribution. If None, fixed at sum(data) """ data = np.array(data) length = len(data) if not b: b = np.sum(data) return _trunc_logser_solver(length, b), b
%(super)s b : float The upper bound of the distribution. If None, fixed at sum(data)
def search(query, medium, credentials): """Searches MyAnimeList for a [medium] matching the keyword(s) given by query. :param query The keyword(s) to search with. :param medium Anime or manga (tokens.Medium.ANIME or tokens.Medium.MANGA). :return A list of all items that are of type [medium] and match t...
Searches MyAnimeList for a [medium] matching the keyword(s) given by query. :param query The keyword(s) to search with. :param medium Anime or manga (tokens.Medium.ANIME or tokens.Medium.MANGA). :return A list of all items that are of type [medium] and match the given keywords, or, an empty li...
def discover_by_name(input_directory, output_directory): """ Auto discover metric types from the files that exist in input_directory and return a list of metrics :param: input_directory: The location to scan for log files :param: output_directory: The location for the report """ metric_list = [] log_files...
Auto discover metric types from the files that exist in input_directory and return a list of metrics :param: input_directory: The location to scan for log files :param: output_directory: The location for the report
def train(self, inputData, numIterations, reset=False): """ Trains the SparseNet, with the provided data. The reset parameter can be set to False if the network should not be reset before training (for example for continuing a previous started training). :param inputData: (array) Input data...
Trains the SparseNet, with the provided data. The reset parameter can be set to False if the network should not be reset before training (for example for continuing a previous started training). :param inputData: (array) Input data, of dimension (inputDim, numPoints) :param numIterations: (int)...
def flip(self,inplace=False): """ NAME: flip PURPOSE: 'flip' an orbit's initial conditions such that the velocities are minus the original velocities; useful for quick backward integration; returns a new Orbit instance INPUT: inplace= (False) if True...
NAME: flip PURPOSE: 'flip' an orbit's initial conditions such that the velocities are minus the original velocities; useful for quick backward integration; returns a new Orbit instance INPUT: inplace= (False) if True, flip the orbit in-place, that is, without return...
def replies(self): """Return a list of the comment replies to this comment. If the comment is not from a submission, :meth:`replies` will always be an empty list unless you call :meth:`refresh() before calling :meth:`replies` due to a limitation in reddit's API. """ ...
Return a list of the comment replies to this comment. If the comment is not from a submission, :meth:`replies` will always be an empty list unless you call :meth:`refresh() before calling :meth:`replies` due to a limitation in reddit's API.
def transaction_search_query(self, transaction_type, **kwargs): """ Query the Yelp Transaction Search API. documentation: https://www.yelp.com/developers/documentation/v3/transactions_search required parameters: * transaction_type - t...
Query the Yelp Transaction Search API. documentation: https://www.yelp.com/developers/documentation/v3/transactions_search required parameters: * transaction_type - transaction type * one of either: * location - text s...
def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=p...
Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup
def set_sort_function(sortable, callback, column=0): """ *sortable* is a :class:`gtk.TreeSortable` instance. *callback* will be passed two items and must return a value like the built-in `cmp`. *column* is an integer adressing the column that holds items. This will re-sort even if *callback* ...
*sortable* is a :class:`gtk.TreeSortable` instance. *callback* will be passed two items and must return a value like the built-in `cmp`. *column* is an integer adressing the column that holds items. This will re-sort even if *callback* is the same as before. .. note:: When sorting a `List...
def user_post_save(sender, **kwargs): """ After User.save is called we check to see if it was a created user. If so, we check if the User object wants account creation. If all passes we create an Account object. We only run on user creation to avoid having to check for existence on each call to...
After User.save is called we check to see if it was a created user. If so, we check if the User object wants account creation. If all passes we create an Account object. We only run on user creation to avoid having to check for existence on each call to User.save.
def experiments_fmri_upsert_property(self, experiment_id, properties): """Upsert property of fMRI data object associated with given experiment. Raises ValueError if given property dictionary results in an illegal operation. Parameters ---------- experiment_id : string ...
Upsert property of fMRI data object associated with given experiment. Raises ValueError if given property dictionary results in an illegal operation. Parameters ---------- experiment_id : string Unique experiment identifier properties : Dictionary() ...
def extend(self, definitions): """ Add several definitions at once. Existing definitions are replaced silently. :param definitions: The names and definitions. :type definitions: a :term:`mapping` or an :term:`iterable` with two-value :class:`tuple` s """ ...
Add several definitions at once. Existing definitions are replaced silently. :param definitions: The names and definitions. :type definitions: a :term:`mapping` or an :term:`iterable` with two-value :class:`tuple` s
def create_new_client(self, filename=None, give_focus=True): """Create a new notebook or load a pre-existing one.""" # Generate the notebook name (in case of a new one) if not filename: if not osp.isdir(NOTEBOOK_TMPDIR): os.makedirs(NOTEBOOK_TMPDIR) ...
Create a new notebook or load a pre-existing one.
def read_json(fp, local_files, dir_files, name_bytes): """ Read json properties from the zip file :param fp: a file pointer :param local_files: the local files structure :param dir_files: the directory headers :param name: the name of the json file to read :return: t...
Read json properties from the zip file :param fp: a file pointer :param local_files: the local files structure :param dir_files: the directory headers :param name: the name of the json file to read :return: the json properites as a dictionary, if found The file pointer ...
def is_eligible(self, segment): """ A segment is eligible to have its children subsegments streamed if it is sampled and it breaches streaming threshold. """ if not segment or not segment.sampled: return False return segment.get_total_subsegments_size() > sel...
A segment is eligible to have its children subsegments streamed if it is sampled and it breaches streaming threshold.
def unflagging_question(self, id, attempt, validation_token, quiz_submission_id, access_code=None): """ Unflagging a question. Remove the flag that you previously set on a quiz question after you've returned to it. """ path = {} data = {} params ...
Unflagging a question. Remove the flag that you previously set on a quiz question after you've returned to it.
def int_bytes(cls, string): '''Convert string describing size to int.''' if string[-1] in ('k', 'm'): value = cls.int_0_inf(string[:-1]) unit = string[-1] if unit == 'k': value *= 2 ** 10 else: value *= 2 ** 20 r...
Convert string describing size to int.
def getaddrinfo(node, service=0, family=0, socktype=0, protocol=0, flags=0, timeout=30): """Resolve an Internet *node* name and *service* into a socket address. The *family*, *socktype* and *protocol* are optional arguments that specify the address family, socket type and protocol, respectively. The *flags...
Resolve an Internet *node* name and *service* into a socket address. The *family*, *socktype* and *protocol* are optional arguments that specify the address family, socket type and protocol, respectively. The *flags* argument allows you to pass flags to further modify the resolution process. See the :f...
def attached_socket(self, *args, **kwargs): """Opens a raw socket in a ``with`` block to write data to Splunk. The arguments are identical to those for :meth:`attach`. The socket is automatically closed at the end of the ``with`` block, even if an exception is raised in the block. ...
Opens a raw socket in a ``with`` block to write data to Splunk. The arguments are identical to those for :meth:`attach`. The socket is automatically closed at the end of the ``with`` block, even if an exception is raised in the block. :param host: The host value for events written to t...
async def blow_out(self, mount): """ Force any remaining liquid to dispense. The liquid will be dispensed at the current location of pipette """ this_pipette = self._attached_instruments[mount] if not this_pipette: raise top_types.PipetteNotAttachedError( ...
Force any remaining liquid to dispense. The liquid will be dispensed at the current location of pipette
def hash_input(inpt, algo=HASH_SHA256): """Generates a hash from a given String with a specified algorithm and returns the hash in hexadecimal form. Default: sha256.""" if (algo == HASH_MD5): hashcode = hashlib.md5() elif (algo == HASH_SHA1): hashcode = hashlib.sha1() elif (algo ...
Generates a hash from a given String with a specified algorithm and returns the hash in hexadecimal form. Default: sha256.
def profile_poly2o(data, mask): """Fit a 2D 2nd order polynomial to `data[mask]`""" # lmfit params = lmfit.Parameters() params.add(name="mx", value=0) params.add(name="my", value=0) params.add(name="mxy", value=0) params.add(name="ax", value=0) params.add(name="ay", value=0) params.a...
Fit a 2D 2nd order polynomial to `data[mask]`
def to_dict(self): """ Returns: dict: Concise represented as a dictionary. """ final_res = { "param": self._param, "unused_param": self.unused_param, "execution_time": self._exec_time, "output": {"accuracy": self.get_accuracy(),...
Returns: dict: Concise represented as a dictionary.
def get_extended_attrtext(value): """attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%') This is a special parsing routine so that we get a value that includes % escapes as a single string (which we decode as a single string later). """ m = _non_extended_attribute_end_matcher(value) i...
attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%') This is a special parsing routine so that we get a value that includes % escapes as a single string (which we decode as a single string later).
def add_column_xsd(self, tb, column, attrs): """ Add the XSD for a column to tb (a TreeBuilder) """ if column.nullable: attrs['minOccurs'] = str(0) attrs['nillable'] = 'true' for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES): if isinstance(column.type,...
Add the XSD for a column to tb (a TreeBuilder)
def find_environment(env_id=None, env_name=None): """ find the environment according environment id (prioritary) or environment name :param env_id: the environment id :param env_name: the environment name :return: found environment or None if not found """ LOGGER....
find the environment according environment id (prioritary) or environment name :param env_id: the environment id :param env_name: the environment name :return: found environment or None if not found
def gen_sites(path): " Seek sites by path. " for root, _, _ in walklevel(path, 2): try: yield Site(root) except AssertionError: continue
Seek sites by path.
def get_config_dict(config): ''' 获取配置数据字典 对传入的配置包进行格式化处理,生成一个字典对象 :param object config: 配置模块 :return: 配置数据字典 :rtype: dict ''' dst = {} tmp = config.__dict__ key_list = dir(config) key_list.remove('os') for k, v in tmp.items(): if k in key_list and not k.startswi...
获取配置数据字典 对传入的配置包进行格式化处理,生成一个字典对象 :param object config: 配置模块 :return: 配置数据字典 :rtype: dict
def flatten(d, parent_key='', separator='__'): """ Flatten a nested dictionary. Parameters ---------- d: dict_like Dictionary to flatten. parent_key: string, optional Concatenated names of the parent keys. separator: string, optional Separator between the names of th...
Flatten a nested dictionary. Parameters ---------- d: dict_like Dictionary to flatten. parent_key: string, optional Concatenated names of the parent keys. separator: string, optional Separator between the names of the each key. The default separator is '_'. Exam...
def ul( self, text): """*convert plain-text to MMD unordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD unordered list **Return:** - ``ul`` -- the MMD unordered list **Usage:** To convert text to a MMD...
*convert plain-text to MMD unordered list* **Key Arguments:** - ``text`` -- the text to convert to MMD unordered list **Return:** - ``ul`` -- the MMD unordered list **Usage:** To convert text to a MMD unordered list: .. code-block:: python ...
def features(sender=''): '''Returns a list of signature features.''' return [ # This one isn't from paper. # Meant to match companies names, sender's names, address. many_capitalized_words, # This one is not from paper. # Line is too long. # This one is less aggre...
Returns a list of signature features.
def alpha_beta(returns, factor_returns, risk_free=0.0, period=DAILY, annualization=None, out=None): """Calculates annualized alpha and beta. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncum...
Calculates annualized alpha and beta. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series Daily noncumulative returns of the factor to which beta is ...
def get_note(self, noteid): """Fetch a single note :param folderid: The UUID of the note """ if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpo...
Fetch a single note :param folderid: The UUID of the note