code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
async def unsubscribe(self, container, *keys): ''' Unsubscribe specified channels. Every subscribed key should be unsubscribed exactly once, even if duplicated subscribed. :param container: routine container :param \*keys: subscribed channels ''' await s...
Unsubscribe specified channels. Every subscribed key should be unsubscribed exactly once, even if duplicated subscribed. :param container: routine container :param \*keys: subscribed channels
def _parse_to_recoverable_signature(sig): """ Returns a parsed recoverable signature of length 65 bytes """ # Buffer for getting values of signature object assert isinstance(sig, bytes) assert len(sig) == 65 # Make a recoverable signature of 65 bytes rec_sig = ffi.new("secp256k1_ecd...
Returns a parsed recoverable signature of length 65 bytes
def _get_machines_cache_from_srv(self, srv): """Fetch list of etcd-cluster member by resolving _etcd-server._tcp. SRV record. This record should contain list of host and peer ports which could be used to run 'GET http://{host}:{port}/members' request (peer protocol)""" ret = [] ...
Fetch list of etcd-cluster member by resolving _etcd-server._tcp. SRV record. This record should contain list of host and peer ports which could be used to run 'GET http://{host}:{port}/members' request (peer protocol)
def split_by_idxs(seq, idxs): '''A generator that returns sequence pieces, seperated by indexes specified in idxs. ''' last = 0 for idx in idxs: if not (-len(seq) <= idx < len(seq)): raise KeyError(f'Idx {idx} is out-of-bounds') yield seq[last:idx] last = idx yield seq[...
A generator that returns sequence pieces, seperated by indexes specified in idxs.
def handle_noargs(self, **options): """ By default this function runs on all objects. As we are using a publishing system it should only update draft objects which can be modified in the tree structure. Once published the tree preferences should remain the same to ensur...
By default this function runs on all objects. As we are using a publishing system it should only update draft objects which can be modified in the tree structure. Once published the tree preferences should remain the same to ensure the tree data structure is consistent with what was ...
def _initialized(self, partitioner): """Store the partitioner and reset the internal state. Now that we successfully got an actual :class:`kazoo.recipe.partitioner.SetPartitioner` object, we store it and reset our internal ``_state`` to ``None``, causing the ``state`` property t...
Store the partitioner and reset the internal state. Now that we successfully got an actual :class:`kazoo.recipe.partitioner.SetPartitioner` object, we store it and reset our internal ``_state`` to ``None``, causing the ``state`` property to defer to the partitioner's state.
def removeRef(self, attr): """Remove the given attribute from the Ref table maintained internally. """ if attr is None: attr__o = None else: attr__o = attr._o ret = libxml2mod.xmlRemoveRef(self._o, attr__o) return ret
Remove the given attribute from the Ref table maintained internally.
def connect_child(self, node): """Adds the given node as a child to this one. No new nodes are created, only connections are made. :param node: a ``Node`` object to connect """ if node.graph != self.graph: raise AttributeError('cannot connect nod...
Adds the given node as a child to this one. No new nodes are created, only connections are made. :param node: a ``Node`` object to connect
def get_account(self, address, id=None, endpoint=None): """ Look up an account on the blockchain. Sample output: Args: address: (str) address to lookup ( in format 'AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK') id: (int, optional) id to use for response tracking endp...
Look up an account on the blockchain. Sample output: Args: address: (str) address to lookup ( in format 'AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK') id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: ...
def send_request(ndex_service_url, params, is_json=True, use_get=False): """Send a request to the NDEx server. Parameters ---------- ndex_service_url : str The URL of the service to use for the request. params : dict A dictionary of parameters to send with the request. Parameter key...
Send a request to the NDEx server. Parameters ---------- ndex_service_url : str The URL of the service to use for the request. params : dict A dictionary of parameters to send with the request. Parameter keys differ based on the type of request. is_json : bool True i...
def json_encode(self, out, limit=None, sort_keys=False, indent=None): '''Encode the results of this paged response as JSON writing to the provided file-like `out` object. This function will iteratively read as many pages as present, streaming the contents out as JSON. :param file-like o...
Encode the results of this paged response as JSON writing to the provided file-like `out` object. This function will iteratively read as many pages as present, streaming the contents out as JSON. :param file-like out: an object with a `write` function :param int limit: optional maximum ...
def bind(self): """Bind the FBO. Anything drawn afterward will be stored in the FBO's texture.""" # This is called simply to deal with anything that might be currently bound (for example, Pyglet objects), gl.glBindTexture(gl.GL_TEXTURE_2D, 0) # Store current viewport size for later ...
Bind the FBO. Anything drawn afterward will be stored in the FBO's texture.
def monkey_patch_override_instance_method(instance): """ Override an instance method with a new version of the same name. The original method implementation is made available within the override method as `_original_<METHOD_NAME>`. """ def perform_override(override_fn): fn_name = overrid...
Override an instance method with a new version of the same name. The original method implementation is made available within the override method as `_original_<METHOD_NAME>`.
def url(self, key, includeToken=None): """ Build a URL string with proper token argument. Token will be appended to the URL if either includeToken is True or CONFIG.log.show_secrets is 'true'. """ if self._token and (includeToken or self._showSecrets): delim = '&' if '?'...
Build a URL string with proper token argument. Token will be appended to the URL if either includeToken is True or CONFIG.log.show_secrets is 'true'.
def get_fast_scanner(self): """ Return :class:`.FastScanner` for association scan. Returns ------- :class:`.FastScanner` Instance of a class designed to perform very fast association scan. """ terms = self._terms return KronFastScanner(self._Y...
Return :class:`.FastScanner` for association scan. Returns ------- :class:`.FastScanner` Instance of a class designed to perform very fast association scan.
def selected_attributes(self): """ Returns the selected attributes from the last run. :return: the Numpy array of 0-based indices :rtype: ndarray """ array = javabridge.call(self.jobject, "selectedAttributes", "()[I") if array is None: return None ...
Returns the selected attributes from the last run. :return: the Numpy array of 0-based indices :rtype: ndarray
def _structure(self, source_code): """return structure in ACDP format.""" # define cutter as a per block reader def cutter(seq, block_size): for index in range(0, len(seq), block_size): lexem = seq[index:index+block_size] if len(lexem) == block_size: ...
return structure in ACDP format.
def getInterfaceAddresses(self, node, interface): ''' Return the Ethernet and IP+mask addresses assigned to a given interface on a node. ''' intf = self.getNode(node)['nodeobj'].getInterface(interface) return intf.ethaddr,intf.ipaddr,intf.netmask
Return the Ethernet and IP+mask addresses assigned to a given interface on a node.
def fit(self, **kwargs): """ This will try to determine fit parameters using scipy.optimize.leastsq algorithm. This function relies on a previous call of set_data() and set_functions(). Notes ----- results of the fit algorithm are stored in self.results. ...
This will try to determine fit parameters using scipy.optimize.leastsq algorithm. This function relies on a previous call of set_data() and set_functions(). Notes ----- results of the fit algorithm are stored in self.results. See scipy.optimize.leastsq for more informa...
def calculate_reshape_output_shapes(operator): ''' Allowed input/output patterns are 1. [N, C, H, W] ---> [N, C', H', W'] Note that C*H*W should equal to C'*H'*W'. ''' check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1) check_input_and_output_types(operat...
Allowed input/output patterns are 1. [N, C, H, W] ---> [N, C', H', W'] Note that C*H*W should equal to C'*H'*W'.
def MakeCdf(self, steps=101): """Returns the CDF of this distribution.""" xs = [i / (steps - 1.0) for i in xrange(steps)] ps = [scipy.special.betainc(self.alpha, self.beta, x) for x in xs] cdf = Cdf(xs, ps) return cdf
Returns the CDF of this distribution.
def cluster(self, n, embed_dim=None, algo=mds.CLASSICAL, method=methods.KMEANS): """ Cluster the embedded coordinates using multidimensional scaling Parameters ---------- n: int The number of clusters to return embed_dim ...
Cluster the embedded coordinates using multidimensional scaling Parameters ---------- n: int The number of clusters to return embed_dim int The dimensionality of the underlying coordinates ...
def distribute_covar_matrix_to_match_covariance_type( tied_cv, covariance_type, n_components): """Create all the covariance matrices from a given template.""" if covariance_type == 'spherical': cv = np.tile(tied_cv.mean() * np.ones(tied_cv.shape[1]), (n_components, 1)) e...
Create all the covariance matrices from a given template.
def exists(self, workflow_id): """ Checks whether a document with the specified workflow id already exists. Args: workflow_id (str): The workflow id that should be checked. Raises: DataStoreNotConnected: If the data store is not connected to the server. Returns...
Checks whether a document with the specified workflow id already exists. Args: workflow_id (str): The workflow id that should be checked. Raises: DataStoreNotConnected: If the data store is not connected to the server. Returns: bool: ``True`` if a document ...
def main(): """Main function for :command:`fabulous-image`.""" import optparse parser = optparse.OptionParser() parser.add_option( "-w", "--width", dest="width", type="int", default=None, help=("Width of printed image in characters. Default: %default")) (options, args) = parser.pars...
Main function for :command:`fabulous-image`.
def getChild(self, name, request): """ Postpath needs to contain all segments of the url, if it is incomplete then that incomplete url will be passed on to the child resource (in this case our wsgi application). """ request.prepath = [] request.postpath.insert(0, ...
Postpath needs to contain all segments of the url, if it is incomplete then that incomplete url will be passed on to the child resource (in this case our wsgi application).
def login_with_api_token(api_token): """Login to Todoist using a user's api token. .. note:: It is up to you to obtain the api token. :param api_token: A Todoist user's api token. :type api_token: str :return: The Todoist user. :rtype: :class:`pytodoist.todoist.User` >>> from pytodoist im...
Login to Todoist using a user's api token. .. note:: It is up to you to obtain the api token. :param api_token: A Todoist user's api token. :type api_token: str :return: The Todoist user. :rtype: :class:`pytodoist.todoist.User` >>> from pytodoist import todoist >>> api_token = 'api_token'...
def find_consensus(bases): """ find consensus base based on nucleotide frequencies """ nucs = ['A', 'T', 'G', 'C', 'N'] total = sum([bases[nuc] for nuc in nucs if nuc in bases]) # save most common base as consensus (random nuc if there is a tie) try: top = max([bases[nuc] for nuc...
find consensus base based on nucleotide frequencies
def dump_json(d: dict) -> None: """Dump json when using tuples for dictionary keys Have to convert tuples to strings to dump out as json """ import json k = d.keys() v = d.values() k1 = [str(i) for i in k] return json.dumps(dict(zip(*[k1, v])), indent=4)
Dump json when using tuples for dictionary keys Have to convert tuples to strings to dump out as json
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cann...
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
def create(self, instance, cidr_mask, description, **kwargs): """Create an ACL entry for the specified instance. :param str instance: The name of the instance to associate the new ACL entry with. :param str cidr_mask: The IPv4 CIDR mask for the new ACL entry. :param str description: A s...
Create an ACL entry for the specified instance. :param str instance: The name of the instance to associate the new ACL entry with. :param str cidr_mask: The IPv4 CIDR mask for the new ACL entry. :param str description: A short description for the new ACL entry. :param collector kwargs: ...
def encrypt_dir(self, path, output_path=None, overwrite=False, stream=True, enable_verbose=True): """ Encrypt everything in a directory. :param path: path of the dir you need to encrypt :...
Encrypt everything in a directory. :param path: path of the dir you need to encrypt :param output_path: encrypted dir output path :param overwrite: if True, then silently overwrite output file if exists :param stream: if it is a very big file, stream mode can avoid using too m...
def html_dataset_type(is_binary, is_imbalanced): """ Return HTML report file dataset type. :param is_binary: is_binary flag (binary : True , multi-class : False) :type is_binary: bool :param is_imbalanced: is_imbalanced flag (imbalance : True , balance : False) :type is_imbalanced: bool :re...
Return HTML report file dataset type. :param is_binary: is_binary flag (binary : True , multi-class : False) :type is_binary: bool :param is_imbalanced: is_imbalanced flag (imbalance : True , balance : False) :type is_imbalanced: bool :return: dataset_type as str
def get_bip32_address(self, ecdh=False): """Compute BIP32 derivation address according to SLIP-0013/0017.""" index = struct.pack('<L', self.identity_dict.get('index', 0)) addr = index + self.to_bytes() log.debug('bip32 address string: %r', addr) digest = hashlib.sha256(addr).dige...
Compute BIP32 derivation address according to SLIP-0013/0017.
def revert_to_max(self): """ N.revert_to_max() Sets all N's stochastics to their MAP values. """ try: self._set_stochastics([self.mu[s] for s in self.stochastics]) except KeyError: self._set_stochastics(self.mu[self.stochastics])
N.revert_to_max() Sets all N's stochastics to their MAP values.
def get_cache(self, namespace, query_hash, length, start, end): """Get a cached value for the specified date range and query""" query = 'SELECT start, value FROM gauged_cache WHERE namespace = ? ' \ 'AND hash = ? AND length = ? AND start BETWEEN ? AND ?' cursor = self.cursor ...
Get a cached value for the specified date range and query
def get(self, container): """ Returns a Container matching the specified container name. If no such container exists, a NoSuchContainer exception is raised. """ name = utils.get_name(container) uri = "/%s" % name resp, resp_body = self.api.method_head(uri) ...
Returns a Container matching the specified container name. If no such container exists, a NoSuchContainer exception is raised.
def handle_receive_lock_expired( channel_state: NettingChannelState, state_change: ReceiveLockExpired, block_number: BlockNumber, ) -> TransitionResult[NettingChannelState]: """Remove expired locks from channel states.""" is_valid, msg, merkletree = is_valid_lock_expired( state_c...
Remove expired locks from channel states.
def format_help(self, ctx, formatter): """Writes the help into the formatter if it exists. This calls into the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog` """ self.format_u...
Writes the help into the formatter if it exists. This calls into the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog`
def timed(name=None, file=sys.stdout, callback=None, wall_clock=True): """ Context manager to make it easy to time the execution of a piece of code. This timer will never run your code several times and is meant more for simple in-production timing, instead of benchmarking. Reports the wall-clock ti...
Context manager to make it easy to time the execution of a piece of code. This timer will never run your code several times and is meant more for simple in-production timing, instead of benchmarking. Reports the wall-clock time (using `time.time`) and not the processor time. Parameters ---------- ...
def json(self): """Returns the json-encoded content of a response, if any.""" if not self.headers and len(self.content) > 3: encoding = get_encoding_from_headers(self.headers) if encoding is not None: return json.loads(self.content.decode(encoding)) retur...
Returns the json-encoded content of a response, if any.
def sum_table(records): """ Used to compute summaries. The records are assumed to have numeric fields, except the first field which is ignored, since it typically contains a label. Here is an example: >>> sum_table([('a', 1), ('b', 2)]) ['total', 3] """ size = len(records[0]) result...
Used to compute summaries. The records are assumed to have numeric fields, except the first field which is ignored, since it typically contains a label. Here is an example: >>> sum_table([('a', 1), ('b', 2)]) ['total', 3]
def bipole(src, rec, depth, res, freqtime, signal=None, aniso=None, epermH=None, epermV=None, mpermH=None, mpermV=None, msrc=False, srcpts=1, mrec=False, recpts=1, strength=0, xdirect=False, ht='fht', htarg=None, ft='sin', ftarg=None, opt=None, loop=None, verb=2): r"""Ret...
r"""Return the electromagnetic field due to an electromagnetic source. Calculate the electromagnetic frequency- or time-domain field due to arbitrary finite electric or magnetic bipole sources, measured by arbitrary finite electric or magnetic bipole receivers. By default, the electromagnetic response ...
def get_manual_intervention(self, project, release_id, manual_intervention_id): """GetManualIntervention. [Preview API] Get manual intervention for a given release and manual intervention id. :param str project: Project ID or project name :param int release_id: Id of the release. ...
GetManualIntervention. [Preview API] Get manual intervention for a given release and manual intervention id. :param str project: Project ID or project name :param int release_id: Id of the release. :param int manual_intervention_id: Id of the manual intervention. :rtype: :class:`...
def hash32(data: Any, seed=0) -> int: """ Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: signed 32-bit integer """ with MultiTimerContext(timer, TIMING_HASH): c_data = to_str(data) if mmh3: return mm...
Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: signed 32-bit integer
def read(self): """Read the brightness of the LED. Returns: int: Current brightness. Raises: LEDError: if an I/O or OS error occurs. """ # Read value try: buf = os.read(self._fd, 8) except OSError as e: raise LEDE...
Read the brightness of the LED. Returns: int: Current brightness. Raises: LEDError: if an I/O or OS error occurs.
def make_thematic_png(self, outpath=None): """ Convert a thematic map into png format with a legend :param outpath: if specified, will save the image instead of showing it """ from matplotlib.patches import Patch fig, previewax = plt.subplots() shape = self.thmap...
Convert a thematic map into png format with a legend :param outpath: if specified, will save the image instead of showing it
def validate_all_keys(obj_name, obj, validation_fun): """Validate all (nested) keys in `obj` by using `validation_fun`. Args: obj_name (str): name for `obj` being validated. obj (dict): dictionary object. validation_fun (function): function used to validate the value ...
Validate all (nested) keys in `obj` by using `validation_fun`. Args: obj_name (str): name for `obj` being validated. obj (dict): dictionary object. validation_fun (function): function used to validate the value of `key`. Returns: None: indica...
def encode_int(self, n): """ Encodes an integer into a short Base64 string. Example: ``encode_int(123)`` returns ``'B7'``. """ str = [] while True: n, r = divmod(n, self.BASE) str.append(self.ALPHABET[r]) if n == 0: break r...
Encodes an integer into a short Base64 string. Example: ``encode_int(123)`` returns ``'B7'``.
def list_public_containers(self): """ Returns a list of the names of all CDN-enabled containers. """ resp, resp_body = self.api.cdn_request("", "GET") return [cont["name"] for cont in resp_body]
Returns a list of the names of all CDN-enabled containers.
def _set_scores(self): """ Compute anomaly scores for the time series This algorithm just takes the diff of threshold with current value as anomaly score """ anom_scores = {} for i, (timestamp, value) in enumerate(self.time_series.items()): baseline_value = s...
Compute anomaly scores for the time series This algorithm just takes the diff of threshold with current value as anomaly score
def create_box_field(self, box_key, name, field_type, **kwargs): '''Creates a box field with the provided attributes. Args: box_key specifying the box to add the field to name required name string field_type required type string [TEXT_INPUT, DATE or PERSON] kwargs {} return (status code, fie...
Creates a box field with the provided attributes. Args: box_key specifying the box to add the field to name required name string field_type required type string [TEXT_INPUT, DATE or PERSON] kwargs {} return (status code, field dict)
def run(self, args): """ Download a project based on passed in args. :param args: Namespace arguments parsed from the command line. """ project_name_or_id = self.create_project_name_or_id_from_args(args) folder = args.folder # path to a folder to download d...
Download a project based on passed in args. :param args: Namespace arguments parsed from the command line.
def generate_single_seasonal_average(args): """ This function calculates the seasonal average for a single day of the year for all river segments """ qout_file = args[0] seasonal_average_file = args[1] day_of_year = args[2] mp_lock = args[3] min_day = day_of_year - 3 max_day = d...
This function calculates the seasonal average for a single day of the year for all river segments
def search_records(self, domain, record_type, name=None, data=None): """ Returns a list of all records configured for the specified domain that match the supplied search criteria. """ return domain.search_records(record_type=record_type, name=name, data=data)
Returns a list of all records configured for the specified domain that match the supplied search criteria.
def _parse_astorb_database_file( self, astorbgz): """* parse astorb database file* **Key Arguments:** - ``astorbgz`` -- path to the downloaded astorb database file **Return:** - ``astorbDictList`` -- the astorb database parsed as a list of dictio...
* parse astorb database file* **Key Arguments:** - ``astorbgz`` -- path to the downloaded astorb database file **Return:** - ``astorbDictList`` -- the astorb database parsed as a list of dictionaries
def getFeatureID(self, location): """ Returns the feature index associated with the provided location. In the case of a sphere, it is always the same if the location is valid. """ truthyFeature = self.contains(location) if not truthyFeature: return self.EMPTY_FEATURE elif truthyFeatur...
Returns the feature index associated with the provided location. In the case of a sphere, it is always the same if the location is valid.
def fuzzy_search_by_title(self, title, ignore_groups=None): """Find an entry by by fuzzy match. This will check things such as: * case insensitive matching * typo checks * prefix matches If the ``ignore_groups`` argument is provided, then any matching ...
Find an entry by by fuzzy match. This will check things such as: * case insensitive matching * typo checks * prefix matches If the ``ignore_groups`` argument is provided, then any matching entries in the ``ignore_groups`` list will not be returned. This ...
def render_pdf_file_to_image_files_pdftoppm_ppm(pdf_file_name, root_output_file_path, res_x=150, res_y=150, extra_args=None): """Use the pdftoppm program to render a PDF file to .png images. The root_output_file_path is prepended to all the output files, which have nu...
Use the pdftoppm program to render a PDF file to .png images. The root_output_file_path is prepended to all the output files, which have numbers and extensions added. Extra arguments can be passed as a list in extra_args. Return the command output.
def predict(self, n_periods=10, exogenous=None, return_conf_int=False, alpha=0.05, **kwargs): """Forecast future (transformed) values Generate predictions (forecasts) ``n_periods`` in the future. Note that if ``exogenous`` variables were used in the model fit, they will ...
Forecast future (transformed) values Generate predictions (forecasts) ``n_periods`` in the future. Note that if ``exogenous`` variables were used in the model fit, they will be expected for the predict procedure and will fail otherwise. Forecasts may be transformed by the endogenous ste...
def mass_3d(self, R, Rs, rho0, r_trunc): """ mass enclosed a 3d sphere or radius r :param r: :param Ra: :param Rs: :return: """ x = R * Rs ** -1 func = (r_trunc ** 2 * (-2 * x * (1 + r_trunc ** 2) + 4 * (1 + x) * r_trunc * np.arctan(x / r_trunc)...
mass enclosed a 3d sphere or radius r :param r: :param Ra: :param Rs: :return:
def to_schema(self): """Return process schema for this process.""" process_type = self.metadata.process_type if not process_type.endswith(':'): process_type = '{}:'.format(process_type) schema = { 'slug': self.metadata.slug, 'name': self.metadata.name...
Return process schema for this process.
def create_calc_dh_d_shape(estimator): """ Return the function that can be used in the various gradient and hessian calculations to calculate the derivative of the transformation with respect to the shape parameters. Parameters ---------- estimator : an instance of the estimation.LogitTypeE...
Return the function that can be used in the various gradient and hessian calculations to calculate the derivative of the transformation with respect to the shape parameters. Parameters ---------- estimator : an instance of the estimation.LogitTypeEstimator class. Should contain a `rows_to_a...
def wait_for(self, text, seconds): """ Returns True when the specified text has appeared in a line of the output, or False when the specified number of seconds have passed without that occurring. """ found = False stream = self.stream start_time = time.tim...
Returns True when the specified text has appeared in a line of the output, or False when the specified number of seconds have passed without that occurring.
def point_before_card(self, card, x, y): """Return whether ``(x, y)`` is somewhere before ``card``, given how I know cards to be arranged. If the cards are being stacked down and to the right, that means I'm testing whether ``(x, y)`` is above or to the left of the card. ...
Return whether ``(x, y)`` is somewhere before ``card``, given how I know cards to be arranged. If the cards are being stacked down and to the right, that means I'm testing whether ``(x, y)`` is above or to the left of the card.
def find_largest_contig(self): """ Determine the largest contig for each strain """ # for file_name, contig_lengths in contig_lengths_dict.items(): for sample in self.metadata: # As the list is sorted in descending order, the largest contig is the first entry in the l...
Determine the largest contig for each strain
def Stiel_Thodos(T, Tc, Pc, MW): r'''Calculates the viscosity of a gas using an emperical formula developed in [1]_. .. math:: TODO Parameters ---------- T : float Temperature of the fluid [K] Tc : float Critical temperature of the fluid [K] Pc : float C...
r'''Calculates the viscosity of a gas using an emperical formula developed in [1]_. .. math:: TODO Parameters ---------- T : float Temperature of the fluid [K] Tc : float Critical temperature of the fluid [K] Pc : float Critical pressure of the fluid [Pa] ...
def add(self, name, path=None, **kwargs): """add new project with given name and path to database if the path is not given, current working directory will be taken ...as default """ path = path or kwargs.pop('default_path', None) if not self._path_is_valid(path): ...
add new project with given name and path to database if the path is not given, current working directory will be taken ...as default
def get_dashboard_panels_visibility_by_section(section_name): """ Return a list of pairs as values that represents the role-permission view relation for the panel section passed in. :param section_name: the panels section id. :return: a list of tuples. """ registry_info = get_dashboard_regis...
Return a list of pairs as values that represents the role-permission view relation for the panel section passed in. :param section_name: the panels section id. :return: a list of tuples.
def _make_request(self, bbox, meta_info, timestamps): """ Make OGC request to create input for cloud detector classifier :param bbox: Bounding box :param meta_info: Meta-info dictionary of input eopatch :return: Requested data """ service_type = ServiceType(meta_info['se...
Make OGC request to create input for cloud detector classifier :param bbox: Bounding box :param meta_info: Meta-info dictionary of input eopatch :return: Requested data
def force_encoding(self, encoding): """Sets a fixed encoding. The change is emitted right away. From now one, this buffer will switch the code page anymore. However, it will still keep track of the current code page. """ if not encoding: self.disabled = False ...
Sets a fixed encoding. The change is emitted right away. From now one, this buffer will switch the code page anymore. However, it will still keep track of the current code page.
def calc_in_wc_v1(self): """Calculate the actual water release from the snow layer due to the exceedance of the snow layers capacity for (liquid) water. Required control parameters: |NmbZones| |ZoneType| |WHC| Required state sequence: |SP| Required flux sequence |TF|...
Calculate the actual water release from the snow layer due to the exceedance of the snow layers capacity for (liquid) water. Required control parameters: |NmbZones| |ZoneType| |WHC| Required state sequence: |SP| Required flux sequence |TF| Calculated fluxes sequence...
def fit(self, X, y, model_filename=None): """Fit FastText according to X, y Parameters: ---------- X : list of text each item is a text y: list each item is either a label (in multi class problem) or list of labels (in multi label problem) ...
Fit FastText according to X, y Parameters: ---------- X : list of text each item is a text y: list each item is either a label (in multi class problem) or list of labels (in multi label problem)
def random(self, shape, tf_fn, kwargs): """Call a random tf operation (e.g. tf.random.uniform). Args: shape: a Shape tf_fn: a function such as tf.random.uniform kwargs: kwargs to pass to tf_fn, except for seed Returns: a LaidOutTensor """ slice_shape = self.slice_shape(shap...
Call a random tf operation (e.g. tf.random.uniform). Args: shape: a Shape tf_fn: a function such as tf.random.uniform kwargs: kwargs to pass to tf_fn, except for seed Returns: a LaidOutTensor
def dist_between(h,seg1,seg2): """ Calculates the distance between two segments. I stole this function from a post by Michael Hines on the NEURON forum (www.neuron.yale.edu/phpbb/viewtopic.php?f=2&t=2114) """ h.distance(0, seg1.x, sec=seg1.sec) return h.distance(seg2.x, sec=seg2.sec)
Calculates the distance between two segments. I stole this function from a post by Michael Hines on the NEURON forum (www.neuron.yale.edu/phpbb/viewtopic.php?f=2&t=2114)
def doc_dir(self): """The absolute directory of the document""" from os.path import abspath if not self.ref: return None u = parse_app_url(self.ref) return abspath(dirname(u.path))
The absolute directory of the document
def _wait_for_macaroon(wait_url): ''' Returns a macaroon from a legacy wait endpoint. ''' headers = { BAKERY_PROTOCOL_HEADER: str(bakery.LATEST_VERSION) } resp = requests.get(url=wait_url, headers=headers) if resp.status_code != 200: raise InteractionError('cannot get {}'.format(...
Returns a macaroon from a legacy wait endpoint.
def tool_factory(clsname, name, driver, base=GromacsCommand): """ Factory for GromacsCommand derived types. """ clsdict = { 'command_name': name, 'driver': driver, '__doc__': property(base._get_gmx_docs) } return type(clsname, (base,), clsdict)
Factory for GromacsCommand derived types.
async def get_power_parameters_for( cls, system_ids: typing.Sequence[str]): """ Get a list of power parameters for specified systems. *WARNING*: This method is considered 'alpha' and may be modified in future. :param system_ids: The system IDs to get power parameters...
Get a list of power parameters for specified systems. *WARNING*: This method is considered 'alpha' and may be modified in future. :param system_ids: The system IDs to get power parameters for
def _to_url(self): """ Serialises this query into a request-able URL including parameters """ url = self._target_url params = collections.defaultdict(list, copy.deepcopy(self._filters)) if self._order_by is not None: params['sort'] = self._order_by for k, vl in self....
Serialises this query into a request-able URL including parameters
def is_table_existed(self, tablename): """ Check whether the given table name exists in this database. Return boolean. """ all_tablenames = self.list_tables() tablename = tablename.lower() if tablename in all_tablenames: return True else: ...
Check whether the given table name exists in this database. Return boolean.
def encode_plus(s): """ Literally encodes the plus sign input is a string returns the string with plus signs encoded """ regex = r"\+" pat = re.compile(regex) return pat.sub("%2B", s)
Literally encodes the plus sign input is a string returns the string with plus signs encoded
def popitem(self): """D.popitem() -> (k, v) Remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ try: value = next(iter(self)) key = value[self._keycol] except StopIteration: raise KeyErr...
D.popitem() -> (k, v) Remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty.
def canonicalize(cls, dataset, data, data_coords=None, virtual_coords=[]): """ Canonicalize takes an array of values as input and reorients and transposes it to match the canonical format expected by plotting functions. In certain cases the dimensions defined via the kdims of an ...
Canonicalize takes an array of values as input and reorients and transposes it to match the canonical format expected by plotting functions. In certain cases the dimensions defined via the kdims of an Element may not match the dimensions of the underlying data. A set of data_coords may b...
def get_buildroot(self, build_id): """ Build the buildroot entry of the metadata. :return: dict, partial metadata """ docker_info = self.tasker.get_info() host_arch, docker_version = get_docker_architecture(self.tasker) buildroot = { 'id': 1, ...
Build the buildroot entry of the metadata. :return: dict, partial metadata
def info(self): """Retrieve information about the SD interface. Args:: no argument Returns:: 2-element tuple holding: number of datasets inside the file number of file attributes C library equivalent : SDfileinfo ...
Retrieve information about the SD interface. Args:: no argument Returns:: 2-element tuple holding: number of datasets inside the file number of file attributes C library equivalent : SDfileinfo
def create_token_mapping(docgraph_with_old_names, docgraph_with_new_names, verbose=False): """ given two document graphs which annotate the same text and which use the same tokenization, creates a dictionary with a mapping from the token IDs used in the first graph to the token ...
given two document graphs which annotate the same text and which use the same tokenization, creates a dictionary with a mapping from the token IDs used in the first graph to the token IDs used in the second graph. Parameters ---------- docgraph_with_old_names : DiscourseDocumentGraph a docu...
def get_issue_comments(self): """ :calls: `GET /repos/:owner/:repo/issues/:number/comments <http://developer.github.com/v3/issues/comments>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.IssueComment.IssueComment` """ return github.PaginatedList.Paginated...
:calls: `GET /repos/:owner/:repo/issues/:number/comments <http://developer.github.com/v3/issues/comments>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.IssueComment.IssueComment`
def fn_from_str(name: str) -> Callable[..., Any]: """Returns a function object with the name given in string.""" try: module_name, fn_name = name.split(':') except ValueError: raise ConfigError('Expected function description in a `module.submodules:function_name` form, but got `{}`' ...
Returns a function object with the name given in string.
def to_new(self, data, k=None, sigma=None, return_distances=False): """Compute the affinities of new samples to the initial samples. This is necessary for embedding new data points into an existing embedding. Parameters ---------- data: np.ndarray The data p...
Compute the affinities of new samples to the initial samples. This is necessary for embedding new data points into an existing embedding. Parameters ---------- data: np.ndarray The data points to be added to the existing embedding. k: int The nu...
def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=regi...
Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document
def bounding_box(img): r""" Return the bounding box incorporating all non-zero values in the image. Parameters ---------- img : array_like An array containing non-zero objects. Returns ------- bbox : a list of slicer objects defining the bounding box """ loc...
r""" Return the bounding box incorporating all non-zero values in the image. Parameters ---------- img : array_like An array containing non-zero objects. Returns ------- bbox : a list of slicer objects defining the bounding box
def search_account_domains(self, domain=None, latitude=None, longitude=None, name=None): """ Search account domains. Returns a list of up to 5 matching account domains Partial match on name / domain are supported """ path = {} data = {} ...
Search account domains. Returns a list of up to 5 matching account domains Partial match on name / domain are supported
def ascend_bip32(bip32_pub_node, secret_exponent, child): """ Given a BIP32Node with public derivation child "child" with a known private key, return the secret exponent for the bip32_pub_node. """ i_as_bytes = struct.pack(">l", child) sec = public_pair_to_sec(bip32_pub_node.public_pair(), compr...
Given a BIP32Node with public derivation child "child" with a known private key, return the secret exponent for the bip32_pub_node.
def _get_next_available_channel_id(self): """Returns the next available available channel id. :raises AMQPConnectionError: Raises if there is no available channel. :rtype: int """ for index in compatibility.RANGE(self._last_channel_id or 1, ...
Returns the next available available channel id. :raises AMQPConnectionError: Raises if there is no available channel. :rtype: int
def scrypt_mcf_check(mcf, password): """Returns True if the password matches the given MCF hash""" if isinstance(password, unicode): password = password.encode('utf8') elif not isinstance(password, bytes): raise TypeError('password must be a unicode or byte string') if not isinstance(mcf...
Returns True if the password matches the given MCF hash
def clock(rpc): """ This task runs forever and notifies all clients subscribed to 'clock' once a second. """ while True: yield from rpc.notify('clock', str(datetime.datetime.now())) yield from asyncio.sleep(1)
This task runs forever and notifies all clients subscribed to 'clock' once a second.
def merge_dict(dict1, dict2): # type: (dict, dict) -> dict """Recursively merge dictionaries: dict2 on to dict1. This differs from dict.update() in that values that are dicts are recursively merged. Note that only dict value types are merged, not lists, etc. :param dict dict1: dictionary to merge t...
Recursively merge dictionaries: dict2 on to dict1. This differs from dict.update() in that values that are dicts are recursively merged. Note that only dict value types are merged, not lists, etc. :param dict dict1: dictionary to merge to :param dict dict2: dictionary to merge with :rtype: dict ...
def prime_field_inv(a: int, n: int) -> int: """ Extended euclidean algorithm to find modular inverses for integers """ if a == 0: return 0 lm, hm = 1, 0 low, high = a % n, n while low > 1: r = high // low nm, new = hm - lm * r, high - low * r lm, low, hm, high...
Extended euclidean algorithm to find modular inverses for integers
def init_logger(v_num: int): """ Call when initialize Jumeaux !! :return: """ logging.addLevelName(LogLevel.INFO_LV1.value, 'INFO_LV1') # type: ignore # Prevent for enum problem logging.addLevelName(LogLevel.INFO_LV2.value, 'INFO_LV2') # type: ignore # Prevent for enum problem logging.addL...
Call when initialize Jumeaux !! :return: