code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _fetch_all(cls, api_key, endpoint=None, offset=0, limit=25, **kwargs): """ Call `self._fetch_page` for as many pages as exist. TODO: should be extended to do async page fetches if API allows it via exposing total value. Returns a list of `cls` instances. """ ...
Call `self._fetch_page` for as many pages as exist. TODO: should be extended to do async page fetches if API allows it via exposing total value. Returns a list of `cls` instances.
def random(cls, length, bit_prob=.5): """Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=....
Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=.1) Arguments: length: An int...
def to_wire_dict (self): """Return a simplified transport object for logging and caching. The transport object must contain these attributes: - url_data.valid: bool Indicates if URL is valid - url_data.result: unicode Result string - url_data.warnings: list o...
Return a simplified transport object for logging and caching. The transport object must contain these attributes: - url_data.valid: bool Indicates if URL is valid - url_data.result: unicode Result string - url_data.warnings: list of tuples (tag, warning message) ...
def _read(self, stream, text, byte_order): ''' Read the actual data from a PLY file. ''' dtype = self.dtype(byte_order) if text: self._read_txt(stream) elif _can_mmap(stream) and not self._have_list: # Loading the data is straightforward. We will...
Read the actual data from a PLY file.
def free(self, connection): """Free the connection from use by the session that was using it. :param connection: The connection to free :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError """ LOGGER.debug('Pool %s freeing connection %s', se...
Free the connection from use by the session that was using it. :param connection: The connection to free :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError
def get_gcd(a, b): "Return greatest common divisor for a and b." while a: a, b = b % a, a return b
Return greatest common divisor for a and b.
def _next_page(self): """ Fetch the next page of the query. """ if self._last_page_seen: raise StopIteration new, self._last_page_seen = self.conn.query_multiple(self.object_type, self._next_page_index, self...
Fetch the next page of the query.
def list_instances(self): """List instances owned by the project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_instances] :end-before: [END bigtable_list_instances] :rtype: tuple :returns: (instances, faile...
List instances owned by the project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_instances] :end-before: [END bigtable_list_instances] :rtype: tuple :returns: (instances, failed_locations), where 'instances' is li...
def search(self, CorpNum, DType, SDate, EDate, State, ItemCode, Page, PerPage, Order, UserID=None, QString=None): """ λͺ©λ‘ 쑰회 args CorpNum : νŒλΉŒνšŒμ› μ‚¬μ—…μžλ²ˆν˜Έ DType : μΌμžμœ ν˜•, R-λ“±λ‘μΌμ‹œ, W-μž‘μ„±μΌμž, I-λ°œν–‰μΌμ‹œ 쀑 택 1 SDate : μ‹œμž‘μΌμž, ν‘œμ‹œν˜•μ‹(yyyyMMdd) EDate : ...
λͺ©λ‘ 쑰회 args CorpNum : νŒλΉŒνšŒμ› μ‚¬μ—…μžλ²ˆν˜Έ DType : μΌμžμœ ν˜•, R-λ“±λ‘μΌμ‹œ, W-μž‘μ„±μΌμž, I-λ°œν–‰μΌμ‹œ 쀑 택 1 SDate : μ‹œμž‘μΌμž, ν‘œμ‹œν˜•μ‹(yyyyMMdd) EDate : μ’…λ£ŒμΌμž, ν‘œμ‹œν˜•μ‹(yyyyMMdd) State : μƒνƒœμ½”λ“œ, 2,3번째 μžλ¦¬μ— μ™€μΌλ“œμΉ΄λ“œ(*) μ‚¬μš©κ°€λŠ₯ ItemCode : λͺ…μ„Έμ„œ μ’…λ₯˜μ½”λ“œ λ°°μ—΄, 121-λͺ…μ„Έμ„œ, 1...
def _MergeEntities(self, a, b): """Merges two agencies. To be merged, they are required to have the same id, name, url and timezone. The remaining language attribute is taken from the new agency. Args: a: The first agency. b: The second agency. Returns: The merged agency. R...
Merges two agencies. To be merged, they are required to have the same id, name, url and timezone. The remaining language attribute is taken from the new agency. Args: a: The first agency. b: The second agency. Returns: The merged agency. Raises: MergeError: The agencies c...
def hide_defaults(self): """Removes fields' values that are the same as default values.""" for k in list(self.fields.keys()): if k in self.default_fields: if self.default_fields[k] == self.fields[k]: del(self.fields[k]) self.payload.hide_defaults()
Removes fields' values that are the same as default values.
def command(self, outfile, configfile, pix): """ Generate the command for running the likelihood scan. """ params = dict(script=self.config['scan']['script'], config=configfile, outfile=outfile, nside=self.nside_likelihood, pix=pix, ...
Generate the command for running the likelihood scan.
def find_and_modify(self, query=None, update=None): """ Finds documents in this collection that match a given query and updates them """ update = update or {} for document in self.find(query=query): document.update(update) self.update(document)
Finds documents in this collection that match a given query and updates them
async def write_message_data(self, data: bytes, timeout: NumType = None) -> None: """ Encode and write email message data. Automatically quotes lines beginning with a period per RFC821. Lone \\\\r and \\\\n characters are converted to \\\\r\\\\n characters. """ d...
Encode and write email message data. Automatically quotes lines beginning with a period per RFC821. Lone \\\\r and \\\\n characters are converted to \\\\r\\\\n characters.
def get_node_values( self, feature=None, show_root=False, show_tips=False, ): """ Returns node values from tree object in node plot order. To modify values you must modify the .treenode object directly by setting new 'features'. For example ...
Returns node values from tree object in node plot order. To modify values you must modify the .treenode object directly by setting new 'features'. For example for node in ttree.treenode.traverse(): node.add_feature("PP", 100) By default node and tip values are hidden (set t...
def get_fun(returner, fun): ''' Return info about last time fun was called on each minion CLI Example: .. code-block:: bash salt '*' ret.get_fun mysql network.interfaces ''' returners = salt.loader.returners(__opts__, __salt__) return returners['{0}.get_fun'.format(returner)](fun)
Return info about last time fun was called on each minion CLI Example: .. code-block:: bash salt '*' ret.get_fun mysql network.interfaces
def fingerprint(channel_samples: list, Fs: int = DEFAULT_FS, wsize: int = DEFAULT_WINDOW_SIZE, wratio: Union[int, float] = DEFAULT_OVERLAP_RATIO, fan_value: int = DEFAULT_FAN_VALUE, amp_min: Union[int, float] = DEFAULT_AMP_MIN)-> Iterator[tuple]: """ ...
FFT the channel, log transform output, find local maxima, then return locally sensitive hashes. #
def set_classifier_interface_params(spec, features, class_labels, model_accessor_for_class_labels, output_features = None): """ Common utilities to set the regression interface params. """ # Normalize the features list. features = _fm.process_or_validate_features(features) if class_labe...
Common utilities to set the regression interface params.
def enable_asynchronous(self): """Check if socket have been monkey patched by gevent""" def is_monkey_patched(): try: from gevent import monkey, socket except ImportError: return False if hasattr(monkey, "saved"): retur...
Check if socket have been monkey patched by gevent
def get_extra_path(name): """ :param name: name in format helper.path_name sip.default_sip_dir """ # Paths are cached in path_cache helper_name, _, key = name.partition(".") helper = path_helpers.get(helper_name) if not helper: raise ValueError("Helper '{0}' not found.".format(h...
:param name: name in format helper.path_name sip.default_sip_dir
def handleOACK(self, pkt): """This method handles an OACK from the server, syncing any accepted options.""" if len(pkt.options.keys()) > 0: if pkt.match_options(self.context.options): log.info("Successful negotiation of options") # Set options to OACK ...
This method handles an OACK from the server, syncing any accepted options.
def set_path(self, path): """Set the path of the file.""" if os.path.isabs(path): path = os.path.normpath(os.path.join(self.cwd, path)) self.path = path self.relative = os.path.relpath(self.path, self.base)
Set the path of the file.
def snippets(self): '''Get all snippets in this DAP''' return [strip_suffix(f, '.yaml') for f in self._stripped_files if self._snippets_pattern.match(f)]
Get all snippets in this DAP
def download(self, overwrite=True): """ Download the zipcodes CSV file. If ``overwrite`` is set to False, the file won't be downloaded if it already exists. """ if overwrite or not os.path.exists(self.file_path): _, f = tempfile.mkstemp() try: ...
Download the zipcodes CSV file. If ``overwrite`` is set to False, the file won't be downloaded if it already exists.
def render(self, progress, width=None, status=None): """Render the widget.""" current_pct = int(progress * 100 + 0.1) return RenderResult(rendered="%3d%%" % current_pct, next_progress=(current_pct + 1) / 100)
Render the widget.
def set_stream_stats(self, rx_ports=None, tx_ports=None, start_offset=40, sequence_checking=True, data_integrity=True, timestamp=True): """ Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX pgs. If empty set for all ports. :type po...
Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX pgs. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_ports: list of streams to set TX pgs. If empty set for all streams. :type tx_ports: dict[ixexplorer.ixe_por...
def output_is_valid(self, process_data): """ Check whether process output is allowed with output driver. Parameters ---------- process_data : raw process output Returns ------- True or False """ if self.METADATA["data_type"] == "raster": ...
Check whether process output is allowed with output driver. Parameters ---------- process_data : raw process output Returns ------- True or False
def fraction(value, allow_empty = False, minimum = None, maximum = None, **kwargs): """Validate that ``value`` is a :class:`Fraction <python:fractions.Fraction>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <p...
Validate that ``value`` is a :class:`Fraction <python:fractions.Fraction>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises a :class:`EmptyValueError <validator_collection.error...
def normalize_cjk_fullwidth_ascii(seq: str) -> str: """ Conver fullwith ASCII to halfwidth ASCII. See https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms """ def convert(char: str) -> str: code_point = ord(char) if not 0xFF01 <= code_point <= 0xFF5E: return char ...
Conver fullwith ASCII to halfwidth ASCII. See https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms
def guess_payload_class(self, payload): """ the type of the payload encapsulation is given be the outer TZSP layers attribute encapsulation_protocol # noqa: E501 """ under_layer = self.underlayer tzsp_header = None while under_layer: if isinstance(under_lay...
the type of the payload encapsulation is given be the outer TZSP layers attribute encapsulation_protocol # noqa: E501
def _set_static_ip(name, session, vm_): ''' Set static IP during create() if defined ''' ipv4_cidr = '' ipv4_gw = '' if 'ipv4_gw' in vm_.keys(): log.debug('ipv4_gw is found in keys') ipv4_gw = vm_['ipv4_gw'] if 'ipv4_cidr' in vm_.keys(): log.debug('ipv4_cidr is found ...
Set static IP during create() if defined
def _check_chn_type(channels, available_channels): """ Function used for checking weather the elements in "channels" input are coincident with the available channels. ---------- Parameters ---------- channels : list [[mac_address_1_channel_1 <int>, mac_address_1_channel_2 <int>...], ...
Function used for checking weather the elements in "channels" input are coincident with the available channels. ---------- Parameters ---------- channels : list [[mac_address_1_channel_1 <int>, mac_address_1_channel_2 <int>...], [mac_address_2_channel_1 <int>...]...] Fro...
def get_suggested_repositories(self): """Method to procure suggested repositories for the user. :return: Iterator to procure suggested repositories for the user. """ if self.suggested_repositories is None: # Procure repositories to suggest to user. repository_set...
Method to procure suggested repositories for the user. :return: Iterator to procure suggested repositories for the user.
def get_instruments(self, name=None): """ :returns: sorted list of (mount, instrument) """ if name: return self.get_instruments_by_name(name) return sorted( self._instruments.items(), key=lambda s: s[0].lower())
:returns: sorted list of (mount, instrument)
def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() index = 0 with io.open(vocab_file, 'r') as reader: while True: token = reader.readline() if not token: break token = token.strip() ...
Loads a vocabulary file into a dictionary.
def find_npolfile(flist,detector,filters): """ Search a list of files for one that matches the configuration of detector and filters used. """ npolfile = None for f in flist: fdet = fits.getval(f, 'detector', memmap=False) if fdet == detector: filt1 = fits.getval(f, '...
Search a list of files for one that matches the configuration of detector and filters used.
def import_eit_fzj(self, filename, configfile, correction_file=None, timestep=None, **kwargs): """EIT data import for FZJ Medusa systems""" # we get not electrode positions (dummy1) and no topography data # (dummy2) df_emd, dummy1, dummy2 = eit_fzj.read_3p_data( ...
EIT data import for FZJ Medusa systems
def strip_metadata(report): """ Duplicates org_name, org_email and report_id into JSON root and removes report_metadata key to bring it more inline with Elastic output. """ report['org_name'] = report['report_metadata']['org_name'] report['org_email'] = repo...
Duplicates org_name, org_email and report_id into JSON root and removes report_metadata key to bring it more inline with Elastic output.
def take_function_register(self, rtype = SharedData.TYPES.NO_TYPE): """Reserves register for function return value and sets its type""" reg = SharedData.FUNCTION_REGISTER if reg not in self.free_registers: self.error("function register already taken") self.free_registers...
Reserves register for function return value and sets its type
def merge_validator_config(configs): """ Given a list of ValidatorConfig objects, merges them into a single ValidatorConfig, giving priority in the order of the configs (first has highest priority). """ bind_network = None bind_component = None bind_consensus = None endpoint = None ...
Given a list of ValidatorConfig objects, merges them into a single ValidatorConfig, giving priority in the order of the configs (first has highest priority).
def split_input(cls, mapper_spec): """Inherit docs.""" shard_count = mapper_spec.shard_count query_spec = cls._get_query_spec(mapper_spec) if not property_range.should_shard_by_property_range(query_spec.filters): return super(DatastoreInputReader, cls).split_input(mapper_spec) # Artificially...
Inherit docs.
def generate_random_128bit_string(): """Returns a 128 bit UTF-8 encoded string. Follows the same conventions as generate_random_64bit_string(). The upper 32 bits are the current time in epoch seconds, and the lower 96 bits are random. This allows for AWS X-Ray `interop <https://github.com/openzipki...
Returns a 128 bit UTF-8 encoded string. Follows the same conventions as generate_random_64bit_string(). The upper 32 bits are the current time in epoch seconds, and the lower 96 bits are random. This allows for AWS X-Ray `interop <https://github.com/openzipkin/zipkin/issues/1754>`_ :returns: 32-ch...
def get_auth(): """Get authorization token for https """ import getpass from requests.auth import HTTPDigestAuth #This binds raw_input to input for Python 2 input_func = input try: input_func = raw_input except NameError: pass uname = input_func("MODSCAG Username:") ...
Get authorization token for https
def exclude(*what): """ Blacklist *what*. :param what: What to blacklist. :type what: :class:`list` of classes or :class:`attr.Attribute`\\ s. :rtype: :class:`callable` """ cls, attrs = _split_what(what) def exclude_(attribute, value): return value.__class__ not in cls and att...
Blacklist *what*. :param what: What to blacklist. :type what: :class:`list` of classes or :class:`attr.Attribute`\\ s. :rtype: :class:`callable`
def as_action_description(self): """ Get the action description. Returns a dictionary describing the action. """ description = { self.name: { 'href': self.href_prefix + self.href, 'timeRequested': self.time_requested, '...
Get the action description. Returns a dictionary describing the action.
def is_dn(s): """Return True if s is a LDAP DN.""" if s == '': return True rm = DN_REGEX.match(s) return rm is not None and rm.group(0) == s
Return True if s is a LDAP DN.
def _residual_soil(self): """ Methodology source: FEH, Vol. 3, p. 14 """ return self.catchment.descriptors.bfihost \ + 1.3 * (0.01 * self.catchment.descriptors.sprhost) \ - 0.987
Methodology source: FEH, Vol. 3, p. 14
def decode(message): """ Convert a generic JSON message * The entire message is converted to JSON and treated as the message data * The timestamp of the message is the time that the message is RECEIVED """ try: data = json.loads(message.payload.decode...
Convert a generic JSON message * The entire message is converted to JSON and treated as the message data * The timestamp of the message is the time that the message is RECEIVED
def setup_admin_on_rest_handlers(admin, admin_handler): """ Initialize routes. """ add_route = admin.router.add_route add_static = admin.router.add_static static_folder = str(PROJ_ROOT / 'static') a = admin_handler add_route('GET', '', a.index_page, name='admin.index') add_route('PO...
Initialize routes.
def plot_2(data, *args): """Plot 2. Running best score (scatter plot)""" df_all = pd.DataFrame(data) df_params = nonconstant_parameters(data) x = [df_all['id'][0]] y = [df_all['mean_test_score'][0]] params = [df_params.loc[0]] for i in range(len(df_all)): if df_all['mean_test_score']...
Plot 2. Running best score (scatter plot)
def get_insight(self, project_key, insight_id, **kwargs): """Retrieve an insight :param project_key: Project identifier, in the form of projectOwner/projectid :type project_key: str :param insight_id: Insight unique identifier. :type insight_id: str :returns: Ins...
Retrieve an insight :param project_key: Project identifier, in the form of projectOwner/projectid :type project_key: str :param insight_id: Insight unique identifier. :type insight_id: str :returns: Insight definition, with all attributes :rtype: object :...
def find_files(sequencepath): """ Use glob to find all FASTA files in the provided sequence path. NOTE: FASTA files must have an extension such as .fasta, .fa, or .fas. Extensions of .fsa, .tfa, ect. are not currently supported :param sequencepath: path of folder containing FASTA genomes :return: li...
Use glob to find all FASTA files in the provided sequence path. NOTE: FASTA files must have an extension such as .fasta, .fa, or .fas. Extensions of .fsa, .tfa, ect. are not currently supported :param sequencepath: path of folder containing FASTA genomes :return: list of FASTA files
def create_shipping_address(self, shipping_address): """Creates a shipping address on an existing account. If you are creating an account, you can embed the shipping addresses with the request""" url = urljoin(self._url, '/shipping_addresses') return shipping_address.post(url)
Creates a shipping address on an existing account. If you are creating an account, you can embed the shipping addresses with the request
def datetime(self): 'εˆ†ι’ŸηΊΏη»“ζž„θΏ”ε›ždatetime ζ—₯ηΊΏη»“ζž„θΏ”ε›ždate' index = self.data.index.remove_unused_levels() return pd.to_datetime(index.levels[0])
εˆ†ι’ŸηΊΏη»“ζž„θΏ”ε›ždatetime ζ—₯ηΊΏη»“ζž„θΏ”ε›ždate
def get_dir_backup(): """ retrieves directory backup """ args = parser.parse_args() s3_get_dir_backup( args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name, args.s3_folder, args.zip_backups_dir, args.project)
retrieves directory backup
def get_neutron_endpoint(cls, json_resp): """ Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service Sends a CRITICAL service check when none are found registered in the Catalog """ catalog = json_resp.get('token', {}).get('catalog', [...
Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service Sends a CRITICAL service check when none are found registered in the Catalog
def redirect(self, pid): """Redirect persistent identifier to another persistent identifier. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` where redirect the PID. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not registered or is...
Redirect persistent identifier to another persistent identifier. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` where redirect the PID. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not registered or is not already redirecting to another ...
def artist(self, spotify_id): """Get a spotify artist by their ID. Parameters ---------- spotify_id : str The spotify_id to search by. """ route = Route('GET', '/artists/{spotify_id}', spotify_id=spotify_id) return self.request(route)
Get a spotify artist by their ID. Parameters ---------- spotify_id : str The spotify_id to search by.
def ast_scan_file(filename, re_fallback=True): '''Scans a file for imports using AST. In addition to normal imports, try to get imports via `__import__` or `import_module` calls. The AST parser should be able to resolve simple variable assignments in cases where these functions are called with vari...
Scans a file for imports using AST. In addition to normal imports, try to get imports via `__import__` or `import_module` calls. The AST parser should be able to resolve simple variable assignments in cases where these functions are called with variables instead of strings.
def delete_bond(self, n, m): """ implementation of bond removing """ self.remove_edge(n, m) self.flush_cache()
implementation of bond removing
def write(self, file): """Write the image to the open file object. See `.save()` if you have a filename. In general, you can only call this method once; after it has been called the first time the PNG image is written, the source data will have been streamed, and cannot...
Write the image to the open file object. See `.save()` if you have a filename. In general, you can only call this method once; after it has been called the first time the PNG image is written, the source data will have been streamed, and cannot be streamed again.
def set_default_content_type(application, content_type, encoding=None): """ Store the default content type for an application. :param tornado.web.Application application: the application to modify :param str content_type: the content type to default to :param str|None encoding: encoding to use when...
Store the default content type for an application. :param tornado.web.Application application: the application to modify :param str content_type: the content type to default to :param str|None encoding: encoding to use when one is unspecified
def get_bin(self): """Return the binary notation of the address/netmask.""" return _convert(self._ip_dec, notation=IP_BIN, inotation=IP_DEC, _check=False, _isnm=self._isnm)
Return the binary notation of the address/netmask.
def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" return self.get_json(self.USER_INFO_URL, method="POST", headers=self._get_headers(access_token))
Loads user data from service
def delete_glossary( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns NOT\_...
Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns NOT\_FOUND, if the glossary doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() ...
def gen_batches(iterable, batch_size): ''' Returns a generator object that yields batches from `iterable`. See `iter_batches` for more details and caveats. Note that `iter_batches` returns an iterator, which never supports `len()`, `gen_batches` returns an iterable which supports `len()` if and onl...
Returns a generator object that yields batches from `iterable`. See `iter_batches` for more details and caveats. Note that `iter_batches` returns an iterator, which never supports `len()`, `gen_batches` returns an iterable which supports `len()` if and only if `iterable` does. This *may* be an iterator...
def authenticate(self, _=None): # TODO: remove unused var ''' Authenticate with the master, this method breaks the functional paradigm, it will update the master information from a fresh sign in, signing in can occur as often as needed to keep up with the revolving master AES ke...
Authenticate with the master, this method breaks the functional paradigm, it will update the master information from a fresh sign in, signing in can occur as often as needed to keep up with the revolving master AES key. :rtype: Crypticle :returns: A crypticle used for encryption...
def direct_messages_sent(self, since_id=None, max_id=None, count=None, include_entities=None, page=None): """ Gets the 20 most recent direct messages sent by the authenticating user. https://dev.twitter.com/docs/api/1.1/get/direct_messages/sent :par...
Gets the 20 most recent direct messages sent by the authenticating user. https://dev.twitter.com/docs/api/1.1/get/direct_messages/sent :param str since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the numb...
def get_or_load_name(self, type_, id_, method): """ read-through cache for a type of object's name. If we don't have a cached name for this type/id, then we will query the live Koji server and store the value before returning. :param type_: str, "user" or "tag" :param i...
read-through cache for a type of object's name. If we don't have a cached name for this type/id, then we will query the live Koji server and store the value before returning. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :param method: function to call if this ...
def _special_method_cache(method, cache_wrapper): """ Because Python treats special methods differently, it's not possible to use instance attributes to implement the cached methods. Instead, install the wrapper method under a different name and return a simple proxy to that wrapper. https://github.com/jaraco/...
Because Python treats special methods differently, it's not possible to use instance attributes to implement the cached methods. Instead, install the wrapper method under a different name and return a simple proxy to that wrapper. https://github.com/jaraco/jaraco.functools/issues/5
def parse_ppi_graph(path: str, min_edge_weight: float = 0.0) -> Graph: """Build an undirected graph of gene interactions from edgelist file. :param str path: The path to the edgelist file :param float min_edge_weight: Cutoff to keep/remove the edges, default is 0, but could also be 0.63. :return Graph:...
Build an undirected graph of gene interactions from edgelist file. :param str path: The path to the edgelist file :param float min_edge_weight: Cutoff to keep/remove the edges, default is 0, but could also be 0.63. :return Graph: Protein-protein interaction graph
def async_alert(self, alert_msg: str, new_prompt: Optional[str] = None) -> None: # pragma: no cover """ Display an important message to the user while they are at the prompt in between commands. To the user it appears as if an alert message is printed above the prompt and their current input ...
Display an important message to the user while they are at the prompt in between commands. To the user it appears as if an alert message is printed above the prompt and their current input text and cursor location is left alone. IMPORTANT: This function will not print an alert unless it can acq...
def contract(self, process): """ this contracts the current node to its parent and then either caclulates the params and values if all child data exists, OR uses the default parent data. (In real terms it returns the parent and recalculates) TODO = processes need to be ...
this contracts the current node to its parent and then either caclulates the params and values if all child data exists, OR uses the default parent data. (In real terms it returns the parent and recalculates) TODO = processes need to be recalculated
def update( self, kb_id, update_kb, custom_headers=None, raw=False, **operation_config): """Asynchronous operation to modify a knowledgebase. :param kb_id: Knowledgebase id. :type kb_id: str :param update_kb: Post body of the request. :type update_kb: ~azure...
Asynchronous operation to modify a knowledgebase. :param kb_id: Knowledgebase id. :type kb_id: str :param update_kb: Post body of the request. :type update_kb: ~azure.cognitiveservices.knowledge.qnamaker.models.UpdateKbOperationDTO :param dict custom_headers: headers th...
def set_alpha_value(self, value): ''' setter Learning rate. ''' if isinstance(value, float) is False: raise TypeError("The type of __alpha_value must be float.") self.__alpha_value = value
setter Learning rate.
def health_check(self): """ Verify that device is accessible over CLI by sending ENTER for cli session """ api_response = 'Online' result = 'Health check on resource {}'.format(self._resource_name) try: health_check_flow = RunCommandFlow(self.cli_handler, self._logger) ...
Verify that device is accessible over CLI by sending ENTER for cli session
def _process_cache(self, d, path=()): """Recusively walk a nested recon cache dict to obtain path/values""" for k, v in d.iteritems(): if not isinstance(v, dict): self.metrics.append((path + (k,), v)) else: self._process_cache(v, path + (k,))
Recusively walk a nested recon cache dict to obtain path/values
def parse_item(self, location: str, item_type: Type[T], item_name_for_log: str = None, file_mapping_conf: FileMappingConfiguration = None, options: Dict[str, Dict[str, Any]] = None) -> T: """ Main method to parse an item of type item_type :param location: :param item_...
Main method to parse an item of type item_type :param location: :param item_type: :param item_name_for_log: :param file_mapping_conf: :param options: :return:
def _build(self, inputs): """Connects the SliceByDim module into the graph. Args: inputs: `Tensor` to slice. Its rank must be greater than the maximum dimension specified in `dims` (plus one as python is 0 indexed). Returns: The sliced tensor. Raises: ValueError: If `input...
Connects the SliceByDim module into the graph. Args: inputs: `Tensor` to slice. Its rank must be greater than the maximum dimension specified in `dims` (plus one as python is 0 indexed). Returns: The sliced tensor. Raises: ValueError: If `inputs` tensor has insufficient rank.
def summarize_entity_person(person): """ assume person entity using cnschma person vocabulary, http://cnschema.org/Person """ ret = [] value = person.get("name") if not value: return False ret.append(value) prop = "courtesyName" value = json_get_first_item(person, prop) ...
assume person entity using cnschma person vocabulary, http://cnschema.org/Person
def fit_interval_censoring( self, lower_bound, upper_bound, event_observed=None, timeline=None, label=None, alpha=None, ci_labels=None, show_progress=False, entry=None, weights=None, ): # pylint: disable=too-many-arguments ...
Fit the model to an interval censored dataset. Parameters ---------- lower_bound: an array, or pd.Series length n, the start of the period the subject experienced the event in. upper_bound: an array, or pd.Series length n, the end of the period the subject experience...
def _connectionLost(self, reason): """Called when the protocol connection is lost - Log the disconnection. - Mark any outstanding requests as unsent so they will be sent when a new connection is made. - If closing the broker client, mark completion of that process. :p...
Called when the protocol connection is lost - Log the disconnection. - Mark any outstanding requests as unsent so they will be sent when a new connection is made. - If closing the broker client, mark completion of that process. :param reason: Failure that indicate...
def fit_allele_specific_predictors( self, n_models, architecture_hyperparameters_list, allele, peptides, affinities, inequalities=None, train_rounds=None, models_dir_for_save=None, verbose=0, ...
Fit one or more allele specific predictors for a single allele using one or more neural network architectures. The new predictors are saved in the Class1AffinityPredictor instance and will be used on subsequent calls to `predict`. Parameters ---------- n...
def _convert_file_records(self, file_records): """ Apply _notebook_model_from_db or _file_model_from_db to each entry in file_records, depending on the result of `guess_type`. """ for record in file_records: type_ = self.guess_type(record['name'], allow_directory=Fals...
Apply _notebook_model_from_db or _file_model_from_db to each entry in file_records, depending on the result of `guess_type`.
def update_assessment_taken(self, assessment_taken_form): """Updates an existing assessment taken. arg: assessment_taken_form (osid.assessment.AssessmentTakenForm): the form containing the elements to be updated raise: IllegalState - ``assessment_taken_form``...
Updates an existing assessment taken. arg: assessment_taken_form (osid.assessment.AssessmentTakenForm): the form containing the elements to be updated raise: IllegalState - ``assessment_taken_form`` already used in an update transaction raise:...
def _actionsFreqs(self,*args,**kwargs): """ NAME: actionsFreqs (_actionsFreqs) PURPOSE: evaluate the actions and frequencies (jr,lz,jz,Omegar,Omegaphi,Omegaz) INPUT: Either: a) R,vR,vT,z,vz[,phi]: 1) floats: phase-space valu...
NAME: actionsFreqs (_actionsFreqs) PURPOSE: evaluate the actions and frequencies (jr,lz,jz,Omegar,Omegaphi,Omegaz) INPUT: Either: a) R,vR,vT,z,vz[,phi]: 1) floats: phase-space value for single object (phi is optional) (each can be a Quantit...
def monkeycache(apis): """ Feed this a dictionary of api bananas, it spits out processed cache """ if isinstance(type(apis), type(None)) or apis is None: return {} verbs = set() cache = {} cache['count'] = apis['count'] cache['asyncapis'] = [] apilist = apis['api'] if a...
Feed this a dictionary of api bananas, it spits out processed cache
def nt2codon_rep(ntseq): """Represent nucleotide sequence by sequence of codon symbols. 'Translates' the nucleotide sequence into a symbolic representation of 'amino acids' where each codon gets its own unique character symbol. These characters should be reserved only for representing the 64 individua...
Represent nucleotide sequence by sequence of codon symbols. 'Translates' the nucleotide sequence into a symbolic representation of 'amino acids' where each codon gets its own unique character symbol. These characters should be reserved only for representing the 64 individual codons --- note that this...
def id(self, id): """ Sets the id of this Shift. UUID for this object :param id: The id of this Shift. :type: str """ if id is None: raise ValueError("Invalid value for `id`, must not be `None`") if len(id) > 255: raise ValueError...
Sets the id of this Shift. UUID for this object :param id: The id of this Shift. :type: str
def toarray(vari): """ Convert polynomial array into a numpy.asarray of polynomials. Args: vari (Poly, numpy.ndarray): Input data. Returns: (numpy.ndarray): A numpy array with ``Q.shape==A.shape``. Examples: >>> poly = cp.prange(3) >>> print...
Convert polynomial array into a numpy.asarray of polynomials. Args: vari (Poly, numpy.ndarray): Input data. Returns: (numpy.ndarray): A numpy array with ``Q.shape==A.shape``. Examples: >>> poly = cp.prange(3) >>> print(poly) [1, q0, q0^2] ...
def __on_download_progress_update(self, blocknum, blocksize, totalsize): """ Prints some download progress information :param blocknum: :param blocksize: :param totalsize: :return: """ if not self.__show_download_progress: return reads...
Prints some download progress information :param blocknum: :param blocksize: :param totalsize: :return:
def create_equipamento_roteiro(self): """Get an instance of equipamento_roteiro services facade.""" return EquipamentoRoteiro( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of equipamento_roteiro services facade.
def get_times_modified(self): """ :returns: The total number of times increment_times_modified has been called for this resource by all processes. :rtype: int """ times_modified = self.conn.client.get(self.times_modified_key) if times_modified is None: return ...
:returns: The total number of times increment_times_modified has been called for this resource by all processes. :rtype: int
def faces_to_path(mesh, face_ids=None, **kwargs): """ Given a mesh and face indices find the outline edges and turn them into a Path3D. Parameters --------- mesh : trimesh.Trimesh Triangulated surface in 3D face_ids : (n,) int Indexes referencing mesh.faces Returns ----...
Given a mesh and face indices find the outline edges and turn them into a Path3D. Parameters --------- mesh : trimesh.Trimesh Triangulated surface in 3D face_ids : (n,) int Indexes referencing mesh.faces Returns --------- kwargs : dict Kwargs for Path3D constructor
def mkrngs(self): """ Transform boolean arrays into list of limit pairs. Gets Time limits of signal/background boolean arrays and stores them as sigrng and bkgrng arrays. These arrays can be saved by 'save_ranges' in the analyse object. """ bbool = bool_2_indices...
Transform boolean arrays into list of limit pairs. Gets Time limits of signal/background boolean arrays and stores them as sigrng and bkgrng arrays. These arrays can be saved by 'save_ranges' in the analyse object.
def unvectorize_args(fn): """ See Also -------- revrand.utils.decorators.vectorize_args Examples -------- The Rosenbrock function is commonly used as a performance test problem for optimization algorithms. It and its derivatives are included in `scipy.optimize` and is implemented...
See Also -------- revrand.utils.decorators.vectorize_args Examples -------- The Rosenbrock function is commonly used as a performance test problem for optimization algorithms. It and its derivatives are included in `scipy.optimize` and is implemented as expected by the family of opti...
def get_count(self, unique_identifier, metric, start_date=None, end_date=None, **kwargs): """ Gets the count for the ``metric`` for ``unique_identifier``. You can specify a ``start_date`` and an ``end_date``, to only get metrics within that time range. :param unique_identifier: Unique s...
Gets the count for the ``metric`` for ``unique_identifier``. You can specify a ``start_date`` and an ``end_date``, to only get metrics within that time range. :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A unique name for the metric you want t...
def start(self, labels=None): """Start specified timer(s). Parameters ---------- labels : string or list, optional (default None) Specify the label(s) of the timer(s) to be started. If it is ``None``, start the default timer with label specified by the ``df...
Start specified timer(s). Parameters ---------- labels : string or list, optional (default None) Specify the label(s) of the timer(s) to be started. If it is ``None``, start the default timer with label specified by the ``dfltlbl`` parameter of :meth:`__init__`.
def split_semicolon(line, maxsplit=None): r"""Split a line on semicolons characters but not on the escaped semicolons :param line: line to split :type line: str :param maxsplit: maximal number of split (if None, no limit) :type maxsplit: None | int :return: split line :rtype: list >>> ...
r"""Split a line on semicolons characters but not on the escaped semicolons :param line: line to split :type line: str :param maxsplit: maximal number of split (if None, no limit) :type maxsplit: None | int :return: split line :rtype: list >>> split_semicolon('a,b;c;;g') ['a,b', 'c', '...
def _convert_unsigned(data, fmt): """Convert data from signed to unsigned in bulk.""" num = len(data) return struct.unpack( "{}{}".format(num, fmt.upper()).encode("utf-8"), struct.pack("{}{}".format(num, fmt).encode("utf-8"), *data) )
Convert data from signed to unsigned in bulk.