code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def address_offset(self): """ Byte address offset of this node relative to it's parent If this node is an array, it's index must be known Raises ------ ValueError If this property is referenced on a node whose array index is not fully defined ...
Byte address offset of this node relative to it's parent If this node is an array, it's index must be known Raises ------ ValueError If this property is referenced on a node whose array index is not fully defined
def oauth_login(self, provider, id_column, id, attrs, defaults, redirect_url=None): """Execute a login via oauth. If no user exists, oauth_signup() will be called """ user = self.query.filter(**dict([(id_column, id)])).first() if not redirect_url: redirect_url = request.args....
Execute a login via oauth. If no user exists, oauth_signup() will be called
def log(cls, event=None, actor=None, data=None): """Generate and insert a new event Args: event (str): Action performed actor (str): Actor (user or subsystem) triggering the event data (dict): Any extra data necessary for describing the event Returns: ...
Generate and insert a new event Args: event (str): Action performed actor (str): Actor (user or subsystem) triggering the event data (dict): Any extra data necessary for describing the event Returns: `None`
def request(self): """ Returns an OAuth2 Session to be used to make requests. Returns None if a token hasn't yet been received.""" headers = {'Accept': 'application/json'} # Use API Key if possible if self.api_key: headers['X-API-KEY'] = self.api_key ret...
Returns an OAuth2 Session to be used to make requests. Returns None if a token hasn't yet been received.
def push(package, is_public=False, is_team=False, reupload=False, hash=None): """ Push a Quilt data package to the server """ team, owner, pkg, subpath = parse_package(package, allow_subpath=True) _check_team_id(team) session = _get_session(team) store, pkgroot = PackageStore.find_package(t...
Push a Quilt data package to the server
def _parse_status(self, output): ''' Unit testing is so much easier when Vagrant is removed from the equation. ''' parsed = self._parse_machine_readable_output(output) statuses = [] # group tuples by target name # assuming tuples are sorted by target name,...
Unit testing is so much easier when Vagrant is removed from the equation.
def find_genome_length(self): """ Determine the total length of all the contigs for each strain """ for sample in self.metadata: # Use the sum() method to add all the contig lengths in the list sample[self.analysistype].genome_length = sum(sample[self.analysistype...
Determine the total length of all the contigs for each strain
def _set_formatter(self): """ Inspects config and sets the name of the formatter to either "json" or "text" as instance attr. If not present in config, default is "text" """ if hasattr(self._config, "formatter") and self._config.formatter == "json": self._formatter = ...
Inspects config and sets the name of the formatter to either "json" or "text" as instance attr. If not present in config, default is "text"
def set_nest_transactions_with_savepoints(self, nest_transactions_with_savepoints): """Sets if nested transactions should use savepoints. :param nest_transactions_with_savepoints: `True` or `False` """ if self._transaction_nesting_level > 0: raise DBALConnectionError.may_not...
Sets if nested transactions should use savepoints. :param nest_transactions_with_savepoints: `True` or `False`
def _run_runner(self): ''' Actually execute specific runner :return: ''' import salt.minion ret = {} low = {'fun': self.opts['fun']} try: # Allocate a jid async_pub = self._gen_async_pub() self.jid = async_pub['jid'] ...
Actually execute specific runner :return:
def convert_all(cls, records): """Convert the list of bibrecs into one MARCXML. >>> from harvestingkit.bibrecord import BibRecordPackage >>> from harvestingkit.inspire_cds_package import Inspire2CDS >>> bibrecs = BibRecordPackage("inspire.xml") >>> bibrecs.parse() >>> xm...
Convert the list of bibrecs into one MARCXML. >>> from harvestingkit.bibrecord import BibRecordPackage >>> from harvestingkit.inspire_cds_package import Inspire2CDS >>> bibrecs = BibRecordPackage("inspire.xml") >>> bibrecs.parse() >>> xml = Inspire2CDS.convert_all(bibrecs.get_re...
def varify_user_lock(repository_path, session_token): """ Verify that a returning user has a valid token and their lock has not expired """ with open(cpjoin(repository_path, 'user_file'), 'r') as fd2: content = fd2.read() if len(content) == 0: return False try: res = json.loads(content)...
Verify that a returning user has a valid token and their lock has not expired
def is_pickle_file(abspath): """Parse file extension. - *.pickle: uncompressed, utf-8 encode pickle file - *.gz: compressed, utf-8 encode pickle file """ abspath = abspath.lower() fname, ext = os.path.splitext(abspath) if ext in [".pickle", ".pk", ".p"]: is_pickle = True eli...
Parse file extension. - *.pickle: uncompressed, utf-8 encode pickle file - *.gz: compressed, utf-8 encode pickle file
def cmd_log(self, reopen=False, rotate=False): """Allows managing of uWSGI log related stuff :param bool reopen: Reopen log file. Could be required after third party rotation. :param bool rotate: Trigger built-in log rotation. """ cmd = b'' if reopen: cmd +...
Allows managing of uWSGI log related stuff :param bool reopen: Reopen log file. Could be required after third party rotation. :param bool rotate: Trigger built-in log rotation.
def _which_display(self, log: str, output: str) -> HTML: """ Determines if the log or lst should be returned as the results for the cell based on parsing the log looking for errors and the presence of lst output. :param log: str log from code submission :param output: None or st...
Determines if the log or lst should be returned as the results for the cell based on parsing the log looking for errors and the presence of lst output. :param log: str log from code submission :param output: None or str lst output if there was any :return: The correct results based on l...
def hdf5_cache(filepath=None, parent=None, group=None, names=None, typed=False, hashed_key=False, **h5dcreate_kwargs): """HDF5 cache decorator. Parameters ---------- filepath : string, optional Path to HDF5 file. If None a temporary file name will be used. parent : string, op...
HDF5 cache decorator. Parameters ---------- filepath : string, optional Path to HDF5 file. If None a temporary file name will be used. parent : string, optional Path to group within HDF5 file to use as parent. If None the root group will be used. group : string, optional ...
def _read(self, source): """ Reads and parses the config source :param file/str source: Config source URL (http/https), or string, file name, or file pointer. """ if source.startswith('http://') or source.startswith('https://'): source = url_content(source, cache...
Reads and parses the config source :param file/str source: Config source URL (http/https), or string, file name, or file pointer.
def _star_comparison(filter_value, tested_value): """ Tests a filter containing a joker """ if not is_string(tested_value): # Unhandled value type... return False parts = filter_value.split("*") i = 0 last_part = len(parts) - 1 idx = 0 for part in parts: # ...
Tests a filter containing a joker
def get_spaces(self): """ Return a flat list of the names for spaces in the organization. """ self.spaces = [] for resource in self._get_spaces()['resources']: self.spaces.append(resource['entity']['name']) return self.spaces
Return a flat list of the names for spaces in the organization.
def serialize(self, pid, record, links_factory=None): """Serialize a single record and persistent identifier. :param pid: Persistent identifier instance. :param record: Record instance. :param links_factory: Factory function for record links. """ return simpledc.tostring...
Serialize a single record and persistent identifier. :param pid: Persistent identifier instance. :param record: Record instance. :param links_factory: Factory function for record links.
def _swap_on_miss(partition_result): """ Given a partition_dict result, if the partition missed, swap the before and after. """ before, item, after = partition_result return (before, item, after) if item else (after, item, before)
Given a partition_dict result, if the partition missed, swap the before and after.
def _symbol_extract(self, regex, plus = True, brackets=False): """Extracts a symbol or full symbol from the current line, optionally including the character under the cursor. :arg regex: the compiled regular expression to use for extraction. :arg plus: when true, the character under th...
Extracts a symbol or full symbol from the current line, optionally including the character under the cursor. :arg regex: the compiled regular expression to use for extraction. :arg plus: when true, the character under the cursor *is* included. :arg brackets: when true, matching pairs o...
def compute(self): """Run the SuperSmoother.""" self._compute_primary_smooths() self._smooth_the_residuals() self._select_best_smooth_at_each_point() self._enhance_bass() self._smooth_best_span_estimates() self._apply_best_spans_to_primaries() self._smooth...
Run the SuperSmoother.
def smooth_magseries_savgol(mags, windowsize, polyorder=2): '''This smooths the magseries with a Savitsky-Golay filter. Parameters ---------- mags : np.array The input mags/flux time-series to smooth. windowsize : int This is a odd integer containing the smoothing window size. ...
This smooths the magseries with a Savitsky-Golay filter. Parameters ---------- mags : np.array The input mags/flux time-series to smooth. windowsize : int This is a odd integer containing the smoothing window size. polyorder : int This is an integer containing the polynom...
def lxc_path(cls, *join_paths): """Returns the LXC path (default on ubuntu is /var/lib/lxc)""" response = subwrap.run(['lxc-ls', '-d']) output = response.std_out lxc_path = output.splitlines()[0] lxc_path = lxc_path.strip() return os.path.join(lxc_path, *join_paths)
Returns the LXC path (default on ubuntu is /var/lib/lxc)
def get_member_named(self, name): """Returns the first member found that matches the name provided. The name can have an optional discriminator argument, e.g. "Jake#0001" or "Jake" will both do the lookup. However the former will give a more precise result. Note that the discriminator m...
Returns the first member found that matches the name provided. The name can have an optional discriminator argument, e.g. "Jake#0001" or "Jake" will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to wor...
def _css_helper(self): """ Add CSS links for the current page and for the plugins """ entries = [entry for entry in self._plugin_manager.call_hook("css") if entry is not None] # Load javascript for the current page entries += self._get_ctx()["css"] entries = ["<link href='" + ent...
Add CSS links for the current page and for the plugins
def get_argparser(): """ Get the command line argument parser. """ parser = argparse.ArgumentParser("twarc") parser.add_argument('command', choices=commands) parser.add_argument('query', nargs='?', default=None) parser.add_argument("--log", dest="log", default="twarc...
Get the command line argument parser.
def set_window_class(self, window, name, class_): """ Change the window's classname and or class. :param name: The new class name. If ``None``, no change. :param class_: The new class. If ``None``, no change. """ _libxdo.xdo_set_window_class(self._xdo, window, name, clas...
Change the window's classname and or class. :param name: The new class name. If ``None``, no change. :param class_: The new class. If ``None``, no change.
def _prepare_args(log_likelihood_fn, state, log_likelihood=None, description='log_likelihood'): """Processes input args to meet list-like assumptions.""" state_parts = list(state) if mcmc_util.is_list_like(state) else [state] state_parts = [tf.convert_to_tensor(s, name='current_state') ...
Processes input args to meet list-like assumptions.
def yieldOutput(self): """ Generate the text output for the table. @rtype: generator of str @return: Text output. """ width = self.__width if width: num_cols = len(width) fmt = ['%%%ds' % -w for w in width] if width[-1] > 0: ...
Generate the text output for the table. @rtype: generator of str @return: Text output.
def execute_lines(self, lines): """Execute lines and give focus to shell""" self.shell.execute_lines(to_text_string(lines)) self.shell.setFocus()
Execute lines and give focus to shell
def to_glyphs_guidelines(self, ufo_obj, glyphs_obj): """Set guidelines.""" if not ufo_obj.guidelines: return for guideline in ufo_obj.guidelines: new_guideline = self.glyphs_module.GSGuideLine() name = guideline.name # Locked if name is not None and name.endswith(LOCK...
Set guidelines.
def notify(self, msgtype, method, params): """Handle an incoming notify request.""" self.dispatch.call(method, params)
Handle an incoming notify request.
def _send_delete_request(self, path, headers): """ Sends the DELETE request to the Route53 endpoint. :param str path: The path to tack on to the endpoint URL for the query. :param dict headers: A dict of headers to send with the request. :rtype: str :returns:...
Sends the DELETE request to the Route53 endpoint. :param str path: The path to tack on to the endpoint URL for the query. :param dict headers: A dict of headers to send with the request. :rtype: str :returns: The body of the response.
def format_value(value): """ Integers are numeric values that do not include a decimal and are followed by a trailing i when inserted (e.g. 1i, 345i, 2015i, -10i). Note that all values must have a trailing i. If they do not they will be written as floats. Floats are numeric values that are not foll...
Integers are numeric values that do not include a decimal and are followed by a trailing i when inserted (e.g. 1i, 345i, 2015i, -10i). Note that all values must have a trailing i. If they do not they will be written as floats. Floats are numeric values that are not followed by a trailing i. (e.g. 1, 1.0, -...
def create_ustar_header(self, info, encoding, errors): """Return the object as a ustar header block. """ info["magic"] = POSIX_MAGIC if len(info["linkname"]) > LENGTH_LINK: raise ValueError("linkname is too long") if len(info["name"]) > LENGTH_NAME: info...
Return the object as a ustar header block.
def visit_BoolOp(self, node): """ Merge BoolOp operand type. BoolOp are "and" and "or" and may return any of these results so all operands should have the combinable type. """ # Visit subnodes self.generic_visit(node) # Merge all operands types. [...
Merge BoolOp operand type. BoolOp are "and" and "or" and may return any of these results so all operands should have the combinable type.
def send(self): """ Send the message to each user on the queryset. Create SentDrip for each user that gets a message. Returns count of created SentDrips. """ if not self.from_email: self.from_email = getattr(settings, 'DRIP_FROM_EMAIL', settings.DEFAULT_FRO...
Send the message to each user on the queryset. Create SentDrip for each user that gets a message. Returns count of created SentDrips.
def gpg_fetch_key( key_url, key_id=None, config_dir=None ): """ Fetch a GPG public key from the given URL. Supports anything urllib2 supports. If the URL has no scheme, then assume it's a PGP key server, and use GPG to go get it. The key is not accepted into any keyrings. Return the key data on ...
Fetch a GPG public key from the given URL. Supports anything urllib2 supports. If the URL has no scheme, then assume it's a PGP key server, and use GPG to go get it. The key is not accepted into any keyrings. Return the key data on success. If key_id is given, verify the key matches. Return None on...
def extract_arguments(text): """ Returns the argument after the command. Examples: extract_arguments("/get name"): 'name' extract_arguments("/get"): '' extract_arguments("/get@botName name"): 'name' :param text: String to extract the arguments from a command :return: the argume...
Returns the argument after the command. Examples: extract_arguments("/get name"): 'name' extract_arguments("/get"): '' extract_arguments("/get@botName name"): 'name' :param text: String to extract the arguments from a command :return: the arguments if `text` is a command (according to ...
def rotate_scale(im, angle, scale, borderValue=0, interp=cv2.INTER_CUBIC): """Rotates and scales the image Parameters ---------- im: 2d array The image angle: number The angle, in radians, to rotate scale: positive number The scale factor borderValue: number, default...
Rotates and scales the image Parameters ---------- im: 2d array The image angle: number The angle, in radians, to rotate scale: positive number The scale factor borderValue: number, default 0 The value for the pixels outside the border (default 0) Returns ...
def get_packages(self, show): """ Return list of Distributions filtered by active status or all @param show: Type of package(s) to show; active, non-active or all @type show: string: "active", "non-active", "all" @returns: list of pkg_resources Distribution objects """ ...
Return list of Distributions filtered by active status or all @param show: Type of package(s) to show; active, non-active or all @type show: string: "active", "non-active", "all" @returns: list of pkg_resources Distribution objects
def phase_estimation(U: np.ndarray, accuracy: int, reg_offset: int = 0) -> Program: """ Generate a circuit for quantum phase estimation. :param U: A unitary matrix. :param accuracy: Number of bits of accuracy desired. :param reg_offset: Where to start writing measurements (default 0). :return: ...
Generate a circuit for quantum phase estimation. :param U: A unitary matrix. :param accuracy: Number of bits of accuracy desired. :param reg_offset: Where to start writing measurements (default 0). :return: A Quil program to perform phase estimation.
def _deshuffle_field(self, *args): """ Return to original ordering """ ip = self._invpermutation fields = [] for arg in args: fields.append( arg[ip] ) if len(fields) == 1: return fields[0] else: return fields
Return to original ordering
def _run_atexit(): '''Hook frameworks must invoke this after the main hook body has successfully completed. Do not invoke it if the hook fails.''' global _atexit for callback, args, kwargs in reversed(_atexit): callback(*args, **kwargs) del _atexit[:]
Hook frameworks must invoke this after the main hook body has successfully completed. Do not invoke it if the hook fails.
def create(self, model_name): """Create a model. Args: model_name: the short name of the model, such as "iris". Returns: If successful, returns informaiton of the model, such as {u'regions': [u'us-central1'], u'name': u'projects/myproject/models/mymodel'} Raises: If the model cr...
Create a model. Args: model_name: the short name of the model, such as "iris". Returns: If successful, returns informaiton of the model, such as {u'regions': [u'us-central1'], u'name': u'projects/myproject/models/mymodel'} Raises: If the model creation failed.
async def has_started(self): """ Whether the handler has completed all start up processes such as establishing the connection, session, link and authentication, and is not ready to process messages. **This function is now deprecated and will be removed in v2.0+.** :rtype...
Whether the handler has completed all start up processes such as establishing the connection, session, link and authentication, and is not ready to process messages. **This function is now deprecated and will be removed in v2.0+.** :rtype: bool
def is_less_than(self, other): """ Ensures :attr:`subject` is less than *other*. """ try: unittest_case.assertTrue(self._subject < other) except self._catch as err: raise self._error_factory(_format("Expected {} to be less than {}", self._subject, other)) ...
Ensures :attr:`subject` is less than *other*.
def _parse_entry(self, dom): """Sigh....""" entry = {} for tag in self._cap_tags: # we need to handle the geocodes a bit differently if tag == 'cap:geocode': try: geotypes = [] # FIXME: this will parse VTEC and add i...
Sigh....
def list_tasks(collector): """List the available_tasks""" print("Usage: aws_syncr <environment> <task>") print("") print("Available environments to choose from are") print("-----------------------------------------") print("") for environment in os.listdir(collector.configuration_folder): ...
List the available_tasks
def fix_windows_stdout_stderr(): """ Processes can't write to stdout/stderr on frozen windows apps because they do not exist here if process tries it anyway we get a nasty dialog window popping up, so we redirect the streams to a dummy see https://github.com/jopohl/urh/issues/370 """ if hasattr...
Processes can't write to stdout/stderr on frozen windows apps because they do not exist here if process tries it anyway we get a nasty dialog window popping up, so we redirect the streams to a dummy see https://github.com/jopohl/urh/issues/370
def file_hash(fname): """ Calculate the SHA256 hash of a given file. Useful for checking if a file has changed or been corrupted. Parameters ---------- fname : str The name of the file. Returns ------- hash : str The hash of the file. Examples -------- ...
Calculate the SHA256 hash of a given file. Useful for checking if a file has changed or been corrupted. Parameters ---------- fname : str The name of the file. Returns ------- hash : str The hash of the file. Examples -------- >>> fname = "test-file-for-hash....
def new_multidigraph(self, name, data=None, **attr): """Return a new instance of type MultiDiGraph, initialized with the given data if provided. :arg name: a name for the graph :arg data: dictionary or NetworkX graph object providing initial state """ self._init_graph(n...
Return a new instance of type MultiDiGraph, initialized with the given data if provided. :arg name: a name for the graph :arg data: dictionary or NetworkX graph object providing initial state
def _set_raw_return(self, sep): """Set the output raw return section :param sep: the separator of current style """ raw = '' if self.dst.style['out'] == 'numpydoc': raw += '\n' spaces = ' ' * 4 with_space = lambda s: '\n'.join([self.docs['out...
Set the output raw return section :param sep: the separator of current style
def save(self, obj, run_id): """ Save a workflow obj - instance of a workflow to save run_id - unique id to give the run """ id_code = self.generate_save_identifier(obj, run_id) self.store.save(obj, id_code)
Save a workflow obj - instance of a workflow to save run_id - unique id to give the run
def similar_movies(self, **kwargs): """ Get the similar movies for a specific movie id. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. append_to_response: (optional) Comma separated, any movie me...
Get the similar movies for a specific movie id. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. append_to_response: (optional) Comma separated, any movie method. Returns: A dict representatio...
def create_from_root(self, root_source): """Return a populated Object Root from dictionnary datas """ root_dto = ObjectRoot() root_dto.configuration = root_source.configuration root_dto.versions = [Version(x) for x in root_source.versions.values()] for version in sorte...
Return a populated Object Root from dictionnary datas
def create(self, request): """ Read the GeoJSON feature collection from the request body and create new objects in the database. """ if self.readonly: return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'}) collection = loads(request.body, object_hook=GeoJSON.to_insta...
Read the GeoJSON feature collection from the request body and create new objects in the database.
def is_valid(self): """Return True if all widget contents are valid""" for lineedit in self.lineedits: if lineedit in self.validate_data and lineedit.isEnabled(): validator, invalid_msg = self.validate_data[lineedit] text = to_text_string(lineedit.text())...
Return True if all widget contents are valid
def guess_codec(file, errors="strict", require_char=False): """Look at file contents and guess its correct encoding. File must be open in binary mode and positioned at offset 0. If BOM record is present then it is assumed to be UTF-8 or UTF-16 encoded file. GEDCOM header is searched for CHAR record and...
Look at file contents and guess its correct encoding. File must be open in binary mode and positioned at offset 0. If BOM record is present then it is assumed to be UTF-8 or UTF-16 encoded file. GEDCOM header is searched for CHAR record and encoding name is extracted from it, if BOM record is present t...
def _percentile(N, percent, key=lambda x:x): """ Find the percentile of a list of values. @parameter N - is a list of values. Note N MUST BE already sorted. @parameter percent - a float value from 0.0 to 1.0. @parameter key - optional key function to compute value from each element of N. @retu...
Find the percentile of a list of values. @parameter N - is a list of values. Note N MUST BE already sorted. @parameter percent - a float value from 0.0 to 1.0. @parameter key - optional key function to compute value from each element of N. @return - the percentile of the values
def argument(self) -> bool: """Parse statement argument. Return ``True`` if the argument is followed by block of substatements. """ next = self.peek() if next == "'": quoted = True self.sq_argument() elif next == '"': quoted = True ...
Parse statement argument. Return ``True`` if the argument is followed by block of substatements.
def load_bernoulli_mnist_dataset(directory, split_name): """Returns Hugo Larochelle's binary static MNIST tf.data.Dataset.""" amat_file = download(directory, FILE_TEMPLATE.format(split=split_name)) dataset = tf.data.TextLineDataset(amat_file) str_to_arr = lambda string: np.array([c == b"1" for c in string.split...
Returns Hugo Larochelle's binary static MNIST tf.data.Dataset.
def lowpass(ts, cutoff_hz, order=3): """forward-backward butterworth low-pass filter""" orig_ndim = ts.ndim if ts.ndim is 1: ts = ts[:, np.newaxis] channels = ts.shape[1] fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0]) nyq = 0.5 * fs cutoff = cutoff_hz/nyq b, a = signal.butte...
forward-backward butterworth low-pass filter
def supercell_composite(mucape, effective_storm_helicity, effective_shear): r"""Calculate the supercell composite parameter. The supercell composite parameter is designed to identify environments favorable for the development of supercells, and is calculated using the formula developed by [Thompson...
r"""Calculate the supercell composite parameter. The supercell composite parameter is designed to identify environments favorable for the development of supercells, and is calculated using the formula developed by [Thompson2004]_: .. math:: \text{SCP} = \frac{\text{MUCAPE}}{1000 \text{J/kg}} * ...
def sleep(self, ms=1): """ Pauses the current green thread for *ms* milliseconds:: p = h.pipe() @h.spawn def _(): p.send('1') h.sleep(50) p.send('2') p.recv() # returns '1' p.recv() # returns '...
Pauses the current green thread for *ms* milliseconds:: p = h.pipe() @h.spawn def _(): p.send('1') h.sleep(50) p.send('2') p.recv() # returns '1' p.recv() # returns '2' after 50 ms
def save_log_to_html(self): """Helper to write the log out as an html file.""" html = html_header() html += ( '<img src="file:///%s/img/logos/inasafe-logo-url.png" ' 'title="InaSAFE Logo" alt="InaSAFE Logo" />' % resources_path()) html += ('<h5 class="info"><i cla...
Helper to write the log out as an html file.
def instantiate(self, params): """ Allows you to fetch the map tiles of a created map :param params: The json with the styling info for the named map :type params: dict :return: :raise: CartoException """ try: self.send(self.Meta.collection_...
Allows you to fetch the map tiles of a created map :param params: The json with the styling info for the named map :type params: dict :return: :raise: CartoException
def get_movielens(variant="20m"): """ Gets movielens datasets Parameters --------- variant : string Which version of the movielens dataset to download. Should be one of '20m', '10m', '1m' or '100k'. Returns ------- movies : ndarray An array of the movie titles. ...
Gets movielens datasets Parameters --------- variant : string Which version of the movielens dataset to download. Should be one of '20m', '10m', '1m' or '100k'. Returns ------- movies : ndarray An array of the movie titles. ratings : csr_matrix A sparse matr...
def infer_gtr(self, print_raw=False, marginal=False, normalized_rate=True, fixed_pi=None, pc=5.0, **kwargs): """ Calculates a GTR model given the multiple sequence alignment and the tree. It performs ancestral sequence inferrence (joint or marginal), followed by the bra...
Calculates a GTR model given the multiple sequence alignment and the tree. It performs ancestral sequence inferrence (joint or marginal), followed by the branch lengths optimization. Then, the numbers of mutations are counted in the optimal tree and related to the time within the mutation happen...
def smoothed_joint(seg0, seg1, maxjointsize=3, tightness=1.99): """ See Andy's notes on Smoothing Bezier Paths for an explanation of the method. Input: two segments seg0, seg1 such that seg0.end==seg1.start, and jointsize, a positive number Output: seg0_trimmed, elbow, seg1_trimmed, where elbow is ...
See Andy's notes on Smoothing Bezier Paths for an explanation of the method. Input: two segments seg0, seg1 such that seg0.end==seg1.start, and jointsize, a positive number Output: seg0_trimmed, elbow, seg1_trimmed, where elbow is a cubic bezier object that smoothly connects seg0_trimmed and se...
def team(self, team_id): """Returns Team object with information about team specified by ``team_id``. :param int team_id: (required), unique id for the team :returns: :class:`Team <Team>` """ json = None if int(team_id) > 0: url = self._build_url('tea...
Returns Team object with information about team specified by ``team_id``. :param int team_id: (required), unique id for the team :returns: :class:`Team <Team>`
def greedy_mapping(self, reference, hypothesis, uem=None): """Greedy label mapping Parameters ---------- reference : Annotation hypothesis : Annotation Reference and hypothesis diarization uem : Timeline Evaluation map Returns ---...
Greedy label mapping Parameters ---------- reference : Annotation hypothesis : Annotation Reference and hypothesis diarization uem : Timeline Evaluation map Returns ------- mapping : dict Mapping between hypothesis (ke...
def slice_by_size(seq, size): """Slice a sequence into chunks, return as a generation of chunks with `size`.""" filling = null for it in zip(*(itertools_chain(seq, [filling] * size),) * size): if filling in it: it = tuple(i for i in it if i is not filling) if it: yiel...
Slice a sequence into chunks, return as a generation of chunks with `size`.
def _save_params(self): """ Saves model parameters at current checkpoint and optionally cleans up older parameter files to save disk space. """ self.model.save_params_to_file(self.current_params_fname) utils.cleanup_params_files(self.model.output_dir, self.max_params_files_to_kee...
Saves model parameters at current checkpoint and optionally cleans up older parameter files to save disk space.
def remove_from_model(self, remove_orphans=False): """Removes the reaction from a model. This removes all associations between a reaction the associated model, metabolites and genes. The change is reverted upon exit when using the model as a context. Parameters -------...
Removes the reaction from a model. This removes all associations between a reaction the associated model, metabolites and genes. The change is reverted upon exit when using the model as a context. Parameters ---------- remove_orphans : bool Remove orphaned ...
def get_alarms_list(self, num_items=100, params=None): """ Get alarms as list of dictionaries :param int num_items: Max items to retrieve :param dict params: Additional params dictionary according to: https://www.alienvault.com/documentation/api/usm-anywhere-api.htm#/alarms ...
Get alarms as list of dictionaries :param int num_items: Max items to retrieve :param dict params: Additional params dictionary according to: https://www.alienvault.com/documentation/api/usm-anywhere-api.htm#/alarms :returns list: list of alarms
def chatToId(url): """ Extract the conversation ID from a conversation URL. Matches addresses containing ``conversations/<chat>``. Args: url (str): Skype API URL Returns: str: extracted identifier """ match = re.search(r"conversations/([...
Extract the conversation ID from a conversation URL. Matches addresses containing ``conversations/<chat>``. Args: url (str): Skype API URL Returns: str: extracted identifier
def generic_filename(path): ''' Extract filename of given path os-indepently, taking care of known path separators. :param path: path :return: filename :rtype: str or unicode (depending on given path) ''' for sep in common_path_separators: if sep in path: _, path = ...
Extract filename of given path os-indepently, taking care of known path separators. :param path: path :return: filename :rtype: str or unicode (depending on given path)
def parse(self, lines): """Parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines. """ # states: # 0: start state # 1: saw user-agent line # 2: saw an allow or disallow line ...
Parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.
def edit(text, pos, key): """ Process a key input in the context of a line, and return the resulting text and cursor position. `text' and `key' must be of type str or unicode, and `pos' must be an int in the range [0, len(text)]. If `key' is in keys(), the corresponding command is executed on ...
Process a key input in the context of a line, and return the resulting text and cursor position. `text' and `key' must be of type str or unicode, and `pos' must be an int in the range [0, len(text)]. If `key' is in keys(), the corresponding command is executed on the line. Otherwise, if `key' is a...
def _save_results(self, zipdata, outdir, module, gmt, rank_metric, permutation_type): """reformat gsea results, and save to txt""" res = OrderedDict() for gs, gseale, ind, RES in zipdata: rdict = OrderedDict() rdict['es'] = gseale[0] rdict['nes'] = gseale[1] ...
reformat gsea results, and save to txt
def delay_1(year): '''Test for delay of start of new year and to avoid''' # Sunday, Wednesday, and Friday as start of the new year. months = trunc(((235 * year) - 234) / 19) parts = 12084 + (13753 * months) day = trunc((months * 29) + parts / 25920) if ((3 * (day + 1)) % 7) < 3: day += ...
Test for delay of start of new year and to avoid
def get_auth(self, username, password, authoritative_source, auth_options=None): """ Returns an authentication object. Examines the auth backend given after the '@' in the username and returns a suitable instance of a subclass of the BaseAuth class. * `username` [string...
Returns an authentication object. Examines the auth backend given after the '@' in the username and returns a suitable instance of a subclass of the BaseAuth class. * `username` [string] Username to authenticate as. * `password` [string] ...
def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, ...
Generate the XML string to define a libvirt storage pool
def gss(args): """ %prog gss fastafile plateMapping Generate sequence files and metadata templates suited for gss submission. The FASTA file is assumed to be exported from the JCVI data delivery folder which looks like: >1127963806024 /library_name=SIL1T054-B-01-120KB /clear_start=0 /clear...
%prog gss fastafile plateMapping Generate sequence files and metadata templates suited for gss submission. The FASTA file is assumed to be exported from the JCVI data delivery folder which looks like: >1127963806024 /library_name=SIL1T054-B-01-120KB /clear_start=0 /clear_end=839 /primer_id=1049000...
def subrouters(self): """ Generator of sub-routers (middleware inheriting from Router) contained within this router. """ yield from filter(lambda mw: isinstance(mw.func, Router), self.mw_list)
Generator of sub-routers (middleware inheriting from Router) contained within this router.
def blackbox_network(): """A micro-network to demonstrate blackboxing. Diagram:: +----------+ +-------------------->+ A (COPY) + <---------------+ | +----------+ | | +----------+ ...
A micro-network to demonstrate blackboxing. Diagram:: +----------+ +-------------------->+ A (COPY) + <---------------+ | +----------+ | | +----------+ | | +---------...
def BVirial_Pitzer_Curl(T, Tc, Pc, omega, order=0): r'''Calculates the second virial coefficient using the model in [1]_. Designed for simple calculations. .. math:: B_r=B^{(0)}+\omega B^{(1)} B^{(0)}=0.1445-0.33/T_r-0.1385/T_r^2-0.0121/T_r^3 B^{(1)} = 0.073+0.46/T_r-0.5/T_r^2 -0....
r'''Calculates the second virial coefficient using the model in [1]_. Designed for simple calculations. .. math:: B_r=B^{(0)}+\omega B^{(1)} B^{(0)}=0.1445-0.33/T_r-0.1385/T_r^2-0.0121/T_r^3 B^{(1)} = 0.073+0.46/T_r-0.5/T_r^2 -0.097/T_r^3 - 0.0073/T_r^8 Parameters ---------- ...
def send_subscribe(self, dup, topics): """Send subscribe COMMAND to server.""" pkt = MqttPkt() pktlen = 2 + sum([2+len(topic)+1 for (topic, qos) in topics]) pkt.command = NC.CMD_SUBSCRIBE | (dup << 3) | (1 << 1) pkt.remaining_length = pktlen ret = pkt.al...
Send subscribe COMMAND to server.
def stop_all(self): """Halts both the analog output and input tasks""" if self.aotask is not None: self.aotask.stop() self.aitask.stop() self.daq_lock.release() self.aitask = None self.aotask = None
Halts both the analog output and input tasks
def do_results(args): """ Write the results output file """ config,name,label,coord = args filenames = make_filenames(config,label) srcfile = filenames['srcfile'] samples = filenames['samfile'] if not exists(srcfile): logger.warning("Couldn't find %s; skipping..."%srcfile) retu...
Write the results output file
def duplicate_nodes(self): """ Return a sequence of node keys of identical meshes. Will combine meshes duplicated by copying in space with different keys in self.geometry, as well as meshes repeated by self.nodes. Returns ----------- duplicates: (m) sequence of ...
Return a sequence of node keys of identical meshes. Will combine meshes duplicated by copying in space with different keys in self.geometry, as well as meshes repeated by self.nodes. Returns ----------- duplicates: (m) sequence of keys to self.nodes that represent ...
def simOnePeriod(self): ''' Simulates one period for this type. Calls the methods getMortality(), getShocks() or readShocks, getStates(), getControls(), and getPostStates(). These should be defined for AgentType subclasses, except getMortality (define its components simDeath and simBir...
Simulates one period for this type. Calls the methods getMortality(), getShocks() or readShocks, getStates(), getControls(), and getPostStates(). These should be defined for AgentType subclasses, except getMortality (define its components simDeath and simBirth instead) and readShocks. ...
def copy(self): """Creates a copy of this :class:`Group`.""" ret = super().copy() for cmd in self.commands: ret.add_command(cmd.copy()) return ret
Creates a copy of this :class:`Group`.
def plot_ts(fignum, dates, ts): """ plot the geomagnetic polarity time scale Parameters __________ fignum : matplotlib figure number dates : bounding dates for plot ts : time scale ck95, gts04, or gts12 """ vertical_plot_init(fignum, 10, 3) TS, Chrons = pmag.get_ts(ts) p = 1...
plot the geomagnetic polarity time scale Parameters __________ fignum : matplotlib figure number dates : bounding dates for plot ts : time scale ck95, gts04, or gts12
def rgb_view(qimage, byteorder = 'big'): """Returns RGB view of a given 32-bit color QImage_'s memory. Similarly to byte_view(), the result is a 3D numpy.uint8 array, but reduced to the rgb dimensions (without alpha), and reordered (using negative strides in the last dimension) to have the usual [R,...
Returns RGB view of a given 32-bit color QImage_'s memory. Similarly to byte_view(), the result is a 3D numpy.uint8 array, but reduced to the rgb dimensions (without alpha), and reordered (using negative strides in the last dimension) to have the usual [R,G,B] order. The image must have 32 bit pixel si...
def normalize_fragment(text, encoding='utf-8'): '''Normalize a fragment. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode(text, encoding=encoding, encode_set=FRAGMENT_ENCODE_SET) return uppercase_percent_encoding(path)
Normalize a fragment. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
def milestone(self, extra_params=None): """ The Milestone that the Ticket is a part of """ if self.get('milestone_id', None): milestones = self.space.milestones(id=self['milestone_id'], extra_params=extra_params) if milestones: return milestones[0]
The Milestone that the Ticket is a part of