code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def datetime_to_timestamp(dt): """Convert timezone-aware `datetime` to POSIX timestamp and return seconds since UNIX epoch. Note: similar to `datetime.timestamp()` in Python 3.3+. """ epoch = datetime.utcfromtimestamp(0).replace(tzinfo=UTC) return (dt - epoch).total_seconds()
Convert timezone-aware `datetime` to POSIX timestamp and return seconds since UNIX epoch. Note: similar to `datetime.timestamp()` in Python 3.3+.
def intersects(self, geometry, crs=None): """Select geometries that intersect with a GeoJSON geometry. Geospatial operator: {$geoIntersects: {...}} Documentation: https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects { $geoIntersects: { $geometry: <geometry; a Ge...
Select geometries that intersect with a GeoJSON geometry. Geospatial operator: {$geoIntersects: {...}} Documentation: https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects { $geoIntersects: { $geometry: <geometry; a GeoJSON object> } }
def one_of(inners, arg): """At least one of the inner validators must pass""" for inner in inners: with suppress(com.IbisTypeError, ValueError): return inner(arg) rules_formatted = ', '.join(map(repr, inners)) raise com.IbisTypeError( 'Arg passes neither of the following rul...
At least one of the inner validators must pass
def _param_grad_helper(self,dL_dK,X,X2,target): """derivative of the covariance matrix with respect to the parameters.""" AX = np.dot(X,self.transform) if X2 is None: X2 = X ZX2 = AX else: AX2 = np.dot(X2, self.transform) self.k._param_grad_hel...
derivative of the covariance matrix with respect to the parameters.
def clean_up_dangling_images(self): """ Clean up all dangling images. """ cargoes = Image.all(client=self._client_session, filters={'dangling': True}) for id, cargo in six.iteritems(cargoes): logger.info("Removing dangling image: {0}".format(id)) cargo.del...
Clean up all dangling images.
def addBiosample(self): """ Adds a new biosample into this repo """ self._openRepo() dataset = self._repo.getDatasetByName(self._args.datasetName) biosample = bio_metadata.Biosample( dataset, self._args.biosampleName) biosample.populateFromJson(self._a...
Adds a new biosample into this repo
def dict_match(d, key, default=None): """Like __getitem__ but works as if the keys() are all filename patterns. Returns the value of any dict key that matches the passed key. Args: d (dict): A dict with filename patterns as keys key (str): A key potentially matching any of the keys ...
Like __getitem__ but works as if the keys() are all filename patterns. Returns the value of any dict key that matches the passed key. Args: d (dict): A dict with filename patterns as keys key (str): A key potentially matching any of the keys default (object): The object to return if no ...
def commented_out_code_lines(source): """Return line numbers of comments that are likely code. Commented-out code is bad practice, but modifying it just adds even more clutter. """ line_numbers = [] try: for t in generate_tokens(source): token_type = t[0] token_...
Return line numbers of comments that are likely code. Commented-out code is bad practice, but modifying it just adds even more clutter.
def _items_to_rela_paths(self, items): """Returns a list of repo-relative paths from the given items which may be absolute or relative paths, entries or blobs""" paths = [] for item in items: if isinstance(item, (BaseIndexEntry, (Blob, Submodule))): paths.appe...
Returns a list of repo-relative paths from the given items which may be absolute or relative paths, entries or blobs
def autoscan(): """autoscan will check all of the serial ports to see if they have a matching VID:PID for a MicroPython board. """ for port in serial.tools.list_ports.comports(): if is_micropython_usb_device(port): connect_serial(port[0])
autoscan will check all of the serial ports to see if they have a matching VID:PID for a MicroPython board.
def handle(cls, value, provider=None, **kwargs): """Fetch an output from the designated stack. Args: value (str): string with the following format: <stack_name>::<output_name>, ie. some-stack::SomeOutput provider (:class:`stacker.provider.base.BaseProvider`): sub...
Fetch an output from the designated stack. Args: value (str): string with the following format: <stack_name>::<output_name>, ie. some-stack::SomeOutput provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider Returns:...
def pipe(self, target): """ Pipes this Recver to *target*. *target* can either be `Sender`_ (or `Pair`_) or a callable. If *target* is a Sender, the two pairs are rewired so that sending on this Recver's Sender will now be directed to the target's Recver:: sender1, ...
Pipes this Recver to *target*. *target* can either be `Sender`_ (or `Pair`_) or a callable. If *target* is a Sender, the two pairs are rewired so that sending on this Recver's Sender will now be directed to the target's Recver:: sender1, recver1 = h.pipe() sender2, recv...
def leaky_twice_relu6(x, alpha_low=0.2, alpha_high=0.2, name="leaky_relu6"): """:func:`leaky_twice_relu6` can be used through its shortcut: :func:`:func:`tl.act.ltrelu6`. This activation function is a modified version :func:`leaky_relu` introduced by the following paper: `Rectifier Nonlinearities Improve N...
:func:`leaky_twice_relu6` can be used through its shortcut: :func:`:func:`tl.act.ltrelu6`. This activation function is a modified version :func:`leaky_relu` introduced by the following paper: `Rectifier Nonlinearities Improve Neural Network Acoustic Models [A. L. Maas et al., 2013] <https://ai.stanford.edu/~am...
def approx_min_num_components(nodes, negative_edges): """ Find approximate minimum number of connected components possible Each edge represents that two nodes must be separated This code doesn't solve the problem. The problem is NP-complete and reduces to minimum clique cover (MCC). This is only an...
Find approximate minimum number of connected components possible Each edge represents that two nodes must be separated This code doesn't solve the problem. The problem is NP-complete and reduces to minimum clique cover (MCC). This is only an approximate solution. Not sure what the approximation ratio i...
def _sync_last_sale_prices(self, dt=None): """Sync the last sale prices on the metrics tracker to a given datetime. Parameters ---------- dt : datetime The time to sync the prices to. Notes ----- This call is cached by the datetime. Repeated ...
Sync the last sale prices on the metrics tracker to a given datetime. Parameters ---------- dt : datetime The time to sync the prices to. Notes ----- This call is cached by the datetime. Repeated calls in the same bar are cheap.
def translate_features_to_letter_annotations(protein, more_sites=None): """Store select uniprot features (sites) as letter annotations with the key as the type of site and the values as a list of booleans""" from ssbio.databases.uniprot import longname_sites from collections import defau...
Store select uniprot features (sites) as letter annotations with the key as the type of site and the values as a list of booleans
def check_file_encoding(self, input_file_path): """ Check whether the given file is UTF-8 encoded. :param string input_file_path: the path of the file to be checked :rtype: :class:`~aeneas.validator.ValidatorResult` """ self.log([u"Checking encoding of file '%s'", input_...
Check whether the given file is UTF-8 encoded. :param string input_file_path: the path of the file to be checked :rtype: :class:`~aeneas.validator.ValidatorResult`
def abs(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the abs function. Args: x: The input fluent. Returns: A TensorFluent wrapping the abs function. ''' return cls._unary_op(x, tf.abs, tf.float32)
Returns a TensorFluent for the abs function. Args: x: The input fluent. Returns: A TensorFluent wrapping the abs function.
def clear(self): ''' Method which resets any variables held by this class, so that the parser can be used again :return: Nothing ''' self.tags = [] '''the current list of tags which have been opened in the XML file''' self.chars = {} '''the chars held by...
Method which resets any variables held by this class, so that the parser can be used again :return: Nothing
def instantiate_by_name(self, object_name): """ Instantiate object from the environment, possibly giving some extra arguments """ if object_name not in self.instances: instance = self.instantiate_from_data(self.environment[object_name]) self.instances[object_name] = instance ...
Instantiate object from the environment, possibly giving some extra arguments
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 self.schema.tostr...
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 total_surface_energy(self): """ Total surface energy of the Wulff shape. Returns: (float) sum(surface_energy_hkl * area_hkl) """ tot_surface_energy = 0 for hkl in self.miller_energy_dict.keys(): tot_surface_energy += self.miller_energy_dict[hk...
Total surface energy of the Wulff shape. Returns: (float) sum(surface_energy_hkl * area_hkl)
def inflate_bbox(self): """ Realign the left and right edges of the bounding box such that they are inflated to align modulo 4. This method is optional, and used mainly to accommodate devices with COM/SEG GDDRAM structures that store pixels in 4-bit nibbles. """ ...
Realign the left and right edges of the bounding box such that they are inflated to align modulo 4. This method is optional, and used mainly to accommodate devices with COM/SEG GDDRAM structures that store pixels in 4-bit nibbles.
def reload(name=DEFAULT, all_names=False): """Reload one or all :class:`ConfigNamespace`. Reload clears the cache of :mod:`staticconf.schema` and :mod:`staticconf.getters`, allowing them to pickup the latest values in the namespace. Defaults to reloading just the DEFAULT namespace. :param name: th...
Reload one or all :class:`ConfigNamespace`. Reload clears the cache of :mod:`staticconf.schema` and :mod:`staticconf.getters`, allowing them to pickup the latest values in the namespace. Defaults to reloading just the DEFAULT namespace. :param name: the name of the :class:`ConfigNamespace` to reload ...
def tune(runner, kernel_options, device_options, tuning_options): """ Find the best performing kernel configuration in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type...
Find the best performing kernel configuration in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type kernel_options: dict :param device_options: A dictionary with all op...
def add_transcript(self, transcript): """Add the information transcript This adds a transcript dict to variant['transcripts'] Args: transcript (dict): A transcript dictionary """ logger.debug("Adding transcript {0} to variant {1}".format( tra...
Add the information transcript This adds a transcript dict to variant['transcripts'] Args: transcript (dict): A transcript dictionary
def stops(self): """Return stops served by this route.""" serves = set() for trip in self.trips(): for stop_time in trip.stop_times(): serves |= stop_time.stops() return serves
Return stops served by this route.
def chunker(f, n): """ Utility function to split iterable `f` into `n` chunks """ f = iter(f) x = [] while 1: if len(x) < n: try: x.append(f.next()) except StopIteration: if len(x) > 0: yield tuple(x) ...
Utility function to split iterable `f` into `n` chunks
async def write_register(self, address, value, skip_encode=False): """Write a modbus register.""" await self._request('write_registers', address, value, skip_encode=skip_encode)
Write a modbus register.
def getViews(self, path, year=None, month=None, day=None, hour=None): """Use this method to get the number of views for a Telegraph article. :param path: Required. Path to the Telegraph page (in the format Title-12-31, where 12 is the month and 31 the day the article was first published). ...
Use this method to get the number of views for a Telegraph article. :param path: Required. Path to the Telegraph page (in the format Title-12-31, where 12 is the month and 31 the day the article was first published). :type path: str :param year: Required if month is passed. ...
def wait_until_element_visible(self, element, timeout=None): """Search element and wait until it is visible :param element: PageElement or element locator as a tuple (locator_type, locator_value) to be found :param timeout: max time to wait :returns: the web element if it is visible ...
Search element and wait until it is visible :param element: PageElement or element locator as a tuple (locator_type, locator_value) to be found :param timeout: max time to wait :returns: the web element if it is visible :rtype: selenium.webdriver.remote.webelement.WebElement or appium.w...
async def _into_id_set(client, chats): """Helper util to turn the input chat or chats into a set of IDs.""" if chats is None: return None if not utils.is_list_like(chats): chats = (chats,) result = set() for chat in chats: if isinstance(chat, int): if chat < 0: ...
Helper util to turn the input chat or chats into a set of IDs.
def guess_headers(self): """ Attempt to guess what headers may be required in order to use this type. Returns `guess_headers` of all children recursively. * If the typename is in the :const:`KNOWN_TYPES` dictionary, use the header specified there * If it's an STL typ...
Attempt to guess what headers may be required in order to use this type. Returns `guess_headers` of all children recursively. * If the typename is in the :const:`KNOWN_TYPES` dictionary, use the header specified there * If it's an STL type, include <{type}> * If it exists in...
def stream_sample(self, md5, kwargs=None): """ Stream the sample by giving back a generator, typically used on 'logs'. Args: md5: the md5 of the sample kwargs: a way of specifying subsets of samples (None for all) max_rows: the maximum number of ro...
Stream the sample by giving back a generator, typically used on 'logs'. Args: md5: the md5 of the sample kwargs: a way of specifying subsets of samples (None for all) max_rows: the maximum number of rows to return Returns: A gen...
def _encode_char(char, charmap, defaultchar): """ Encode a single character with the given encoding map :param char: char to encode :param charmap: dictionary for mapping characters in this code page """ if ord(char) < 128: return ord(char) if char in charmap...
Encode a single character with the given encoding map :param char: char to encode :param charmap: dictionary for mapping characters in this code page
def get_printable(iterable): """ Get printable characters from the specified string. Note that str.isprintable() is not available in Python 2. """ if iterable: return ''.join(i for i in iterable if i in string.printable) return ''
Get printable characters from the specified string. Note that str.isprintable() is not available in Python 2.
def _replace_bm(self): """Replace ``_block_matcher`` with current values.""" self._block_matcher = cv2.StereoBM(preset=self._bm_preset, ndisparities=self._search_range, SADWindowSize=self._window_size)
Replace ``_block_matcher`` with current values.
def print_licences(params, metadata): """Print licenses. :param argparse.Namespace params: parameter :param bootstrap_py.classifier.Classifiers metadata: package metadata """ if hasattr(params, 'licenses'): if params.licenses: _pp(metadata.licenses_desc()) sys.exit(0)
Print licenses. :param argparse.Namespace params: parameter :param bootstrap_py.classifier.Classifiers metadata: package metadata
def _RawGlobPathSpecWithNumericSchema( file_system, parent_path_spec, segment_format, location, segment_number): """Globs for path specifications according to a numeric naming schema. Args: file_system (FileSystem): file system. parent_path_spec (PathSpec): parent path specification. segment_format...
Globs for path specifications according to a numeric naming schema. Args: file_system (FileSystem): file system. parent_path_spec (PathSpec): parent path specification. segment_format (str): naming schema of the segment file location. location (str): the base segment file location string. segment...
def socket_recv(self): """ Called by TelnetServer when recv data is ready. """ try: data = self.sock.recv(2048) except socket.error, ex: print ("?? socket.recv() error '%d:%s' from %s" % (ex[0], ex[1], self.addrport())) raise Bo...
Called by TelnetServer when recv data is ready.
def get_hdrgos_g_usrgos(self, usrgos): """Return hdrgos which contain the usrgos.""" hdrgos_for_usrgos = set() hdrgos_all = self.get_hdrgos() usrgo2hdrgo = self.get_usrgo2hdrgo() for usrgo in usrgos: if usrgo in hdrgos_all: hdrgos_for_usrgos.add(usrgo)...
Return hdrgos which contain the usrgos.
def point_in_polygon(points, x, y): """ Ray casting algorithm. Determines how many times a horizontal ray starting from the point intersects with the sides of the polygon. If it is an even number of times, the point is outside, if odd, inside. The algorithm does not always repor...
Ray casting algorithm. Determines how many times a horizontal ray starting from the point intersects with the sides of the polygon. If it is an even number of times, the point is outside, if odd, inside. The algorithm does not always report correctly when the point is very close to t...
def get_supported_file_loaders_2(force=False): """Returns a list of file-based module loaders. Each item is a tuple (loader, suffixes). """ if force or (2, 7) <= sys.version_info < (3, 4): # valid until which py3 version ? import imp loaders = [] for suffix, mode, type in imp...
Returns a list of file-based module loaders. Each item is a tuple (loader, suffixes).
def get_service(self): """ Returns a BigQuery service object. """ http_authorized = self._authorize() return build( 'bigquery', 'v2', http=http_authorized, cache_discovery=False)
Returns a BigQuery service object.
def pad(self, pad_length): """ Pad the pianoroll with zeros at the end along the time axis. Parameters ---------- pad_length : int The length to pad with zeros along the time axis. """ self.pianoroll = np.pad( self.pianoroll, ((0, pad_len...
Pad the pianoroll with zeros at the end along the time axis. Parameters ---------- pad_length : int The length to pad with zeros along the time axis.
def post_create_app(cls, app, **settings): """Register the errorhandler for the AppException to the passed in App. Args: app (fleaker.base.BaseApplication): A Flask application that extends the Fleaker Base Application, such that the hooks are impleme...
Register the errorhandler for the AppException to the passed in App. Args: app (fleaker.base.BaseApplication): A Flask application that extends the Fleaker Base Application, such that the hooks are implemented. Kwargs: register_errorhandl...
def probe_plugins(): """Runs uWSGI to determine what plugins are available and prints them out. Generic plugins come first then after blank line follow request plugins. """ plugins = UwsgiRunner().get_plugins() for plugin in sorted(plugins.generic): click.secho(plugin) click.secho(''...
Runs uWSGI to determine what plugins are available and prints them out. Generic plugins come first then after blank line follow request plugins.
def service_upsert(path, service_name, definition): ''' Create or update the definition of a docker-compose service This does not pull or up the service This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces path Path where the docker-compose file is stored ...
Create or update the definition of a docker-compose service This does not pull or up the service This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces path Path where the docker-compose file is stored on the server service_name Name of the service to cr...
def LOO(self, kern, X, Y, likelihood, posterior, Y_metadata=None, K=None): """ Leave one out error as found in "Bayesian leave-one-out cross-validation approximations for Gaussian latent variable models" Vehtari et al. 2014. """ g = posterior.woodbury_vector c = p...
Leave one out error as found in "Bayesian leave-one-out cross-validation approximations for Gaussian latent variable models" Vehtari et al. 2014.
def new_driver(self, testname=None): ''' Used at a start of a test to get a new instance of WebDriver. If the 'resuebrowser' setting is true, it will use a recycled WebDriver instance with delete_all_cookies() called. Kwargs: testname (str) - Optional test name to ...
Used at a start of a test to get a new instance of WebDriver. If the 'resuebrowser' setting is true, it will use a recycled WebDriver instance with delete_all_cookies() called. Kwargs: testname (str) - Optional test name to pass to Selenium Grid. Helpful for ...
def images(self): """Instance depends on the API version: * 2016-04-30-preview: :class:`ImagesOperations<azure.mgmt.compute.v2016_04_30_preview.operations.ImagesOperations>` * 2017-03-30: :class:`ImagesOperations<azure.mgmt.compute.v2017_03_30.operations.ImagesOperations>` * 20...
Instance depends on the API version: * 2016-04-30-preview: :class:`ImagesOperations<azure.mgmt.compute.v2016_04_30_preview.operations.ImagesOperations>` * 2017-03-30: :class:`ImagesOperations<azure.mgmt.compute.v2017_03_30.operations.ImagesOperations>` * 2017-12-01: :class:`ImagesOpera...
def get_default_config(self): """ Returns the default collector settings """ config = super(UsersCollector, self).get_default_config() config.update({ 'path': 'users', 'utmp': None, }) return config
Returns the default collector settings
def get_metric_by_name(name: str) -> Callable[..., Any]: """Returns a metric callable with a corresponding name.""" if name not in _REGISTRY: raise ConfigError(f'"{name}" is not registered as a metric') return fn_from_str(_REGISTRY[name])
Returns a metric callable with a corresponding name.
def name(self): """ The UI name of this style. """ name = self._element.name_val if name is None: return None return BabelFish.internal2ui(name)
The UI name of this style.
def _load_key(key_object): """ Common code to load public and private keys into PublicKey and PrivateKey objects :param key_object: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :raises: ValueError - when any of the parameters contain an invalid ...
Common code to load public and private keys into PublicKey and PrivateKey objects :param key_object: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of t...
def highshelf(self, gain=-20.0, frequency=3000, slope=0.5): """highshelf takes 3 parameters: a signed number for gain or attenuation in dB, filter frequency in Hz and slope (default=0.5). Beware of clipping when using positive gain. """ self.command.append('treble') self...
highshelf takes 3 parameters: a signed number for gain or attenuation in dB, filter frequency in Hz and slope (default=0.5). Beware of clipping when using positive gain.
def is_condition_met(self, hand, *args): """ The hand contains four sets of winds :param hand: list of hand's sets :return: boolean """ pon_sets = [x for x in hand if is_pon(x)] if len(pon_sets) != 4: return False count_wind_sets = 0 w...
The hand contains four sets of winds :param hand: list of hand's sets :return: boolean
def auth_request_url(self, client_id=None, redirect_uris="urn:ietf:wg:oauth:2.0:oob", scopes=__DEFAULT_SCOPES, force_login=False): """ Returns the url that a client needs to request an oauth grant from the server. To log in with oauth, send your user to this URL...
Returns the url that a client needs to request an oauth grant from the server. To log in with oauth, send your user to this URL. The user will then log in and get a code which you can pass to log_in. scopes are as in `log_in()`_, redirect_uris is where the user should be redire...
def collect_analysis(self): ''' :return: a dictionary which is used to get the serialized analyzer definition from the analyzer class. ''' analysis = {} for field in self.fields.values(): for analyzer_name in ('analyzer', 'index_analyzer', 'search_analyzer'): ...
:return: a dictionary which is used to get the serialized analyzer definition from the analyzer class.
def database_list_folder(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /database-xxxx/listFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Databases#API-method%3A-%2Fdatabase-xxxx%2FlistFolder """ return DXHTTPRequest('/%s/listFol...
Invokes the /database-xxxx/listFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Databases#API-method%3A-%2Fdatabase-xxxx%2FlistFolder
def kl_divergence(self, logits_q, logits_p): """ Categorical distribution KL divergence calculation KL(Q || P) = sum Q_i log (Q_i / P_i) When talking about logits this is: sum exp(Q_i) * (Q_i - P_i) """ return (torch.exp(logits_q) * (logits_q - logits_p)).sum(1, k...
Categorical distribution KL divergence calculation KL(Q || P) = sum Q_i log (Q_i / P_i) When talking about logits this is: sum exp(Q_i) * (Q_i - P_i)
def assign_types_to_resources(resource_types,**kwargs): """ Assign new types to list of resources. This function checks if the necessary attributes are present and adds them if needed. Non existing attributes are also added when the type is already assigned. This means that this ...
Assign new types to list of resources. This function checks if the necessary attributes are present and adds them if needed. Non existing attributes are also added when the type is already assigned. This means that this function can also be used to update resources, when a resource type ...
def run(self, cell, is_full_fc=False, parse_fc=True): """Make supercell force constants readable for phonopy Note ---- Born effective charges and dielectric constant tensor are read from QE output file if they exist. But this means dipole-dipole contributions are removed...
Make supercell force constants readable for phonopy Note ---- Born effective charges and dielectric constant tensor are read from QE output file if they exist. But this means dipole-dipole contributions are removed from force constants and this force constants matrix is ...
def wait_turns(self, turns, cb=None): """Call ``self.app.engine.next_turn()`` ``n`` times, waiting ``self.app.turn_length`` in between Disables input for the duration. :param turns: number of turns to wait :param cb: function to call when done waiting, optional :return: ``None`...
Call ``self.app.engine.next_turn()`` ``n`` times, waiting ``self.app.turn_length`` in between Disables input for the duration. :param turns: number of turns to wait :param cb: function to call when done waiting, optional :return: ``None``
def _get_notmuch_message(self, mid): """returns :class:`notmuch.database.Message` with given id""" mode = Database.MODE.READ_ONLY db = Database(path=self.path, mode=mode) try: return db.find_message(mid) except: errmsg = 'no message with id %s exists!' % m...
returns :class:`notmuch.database.Message` with given id
def delete_table_records(self, table, query_column, ids_to_delete): """ Responsys.deleteTableRecords call Accepts: InteractObject table string query_column possible values: 'RIID'|'EMAIL_ADDRESS'|'CUSTOMER_ID'|'MOBILE_NUMBER' list ids_to_delete ...
Responsys.deleteTableRecords call Accepts: InteractObject table string query_column possible values: 'RIID'|'EMAIL_ADDRESS'|'CUSTOMER_ID'|'MOBILE_NUMBER' list ids_to_delete Returns a list of DeleteResult instances
def create_signed_pair(self, name, ca_name, cert_type=crypto.TYPE_RSA, bits=2048, years=5, alt_names=None, serial=0, overwrite=False): """ Create a key-cert pair Arguments: name - The name of the key-cert pair ca_name ...
Create a key-cert pair Arguments: name - The name of the key-cert pair ca_name - The name of the CA to sign this cert cert_type - The type of the cert. TYPE_RSA or TYPE_DSA bits - The number of bits to use alt_names - An arra...
def transform_literals(rdf, literalmap): """Transform literal properties of Concepts, as defined by config file.""" affected_types = (SKOS.Concept, SKOS.Collection, SKOSEXT.DeprecatedConcept) props = set() for t in affected_types: for conc in rdf.subjects(RDF.type, t): ...
Transform literal properties of Concepts, as defined by config file.
def netdevs(): ''' RX and TX bytes for each of the network devices ''' with open('/proc/net/dev') as f: net_dump = f.readlines() device_data={} data = namedtuple('data',['rx','tx']) for line in net_dump[2:]: line = line.split(':') if line[0].strip() != 'lo': ...
RX and TX bytes for each of the network devices
def drop_words(text, threshold=2, to_lower=True, delimiters=DEFAULT_DELIMITERS, stop_words=None): ''' Remove words that occur below a certain number of times in an SArray. This is a common method of cleaning text before it is used, and can increase the quality and explainability of the mo...
Remove words that occur below a certain number of times in an SArray. This is a common method of cleaning text before it is used, and can increase the quality and explainability of the models learned on the transformed data. RareWordTrimmer can be applied to all the string-, dictionary-, and list-typed ...
def filter_geoquiet(sat, maxKp=None, filterTime=None, kpData=None, kp_inst=None): """Filters pysat.Instrument data for given time after Kp drops below gate. Loads Kp data for the same timeframe covered by sat and sets sat.data to NaN for times when Kp > maxKp and for filterTime after Kp drops below max...
Filters pysat.Instrument data for given time after Kp drops below gate. Loads Kp data for the same timeframe covered by sat and sets sat.data to NaN for times when Kp > maxKp and for filterTime after Kp drops below maxKp. Parameters ---------- sat : pysat.Instrument Instrument to b...
def creationTime(item): """ Returns the creation time of the given item. """ forThisItem = _CreationTime.createdItem == item return item.store.findUnique(_CreationTime, forThisItem).timestamp
Returns the creation time of the given item.
def apply_all_rules(self, *args, **kwargs): """cycle through all rules and apply them all without regard to success or failure returns: True - since success or failure is ignored""" for x in self.rules: self._quit_check() if self.config.chatty_rules:...
cycle through all rules and apply them all without regard to success or failure returns: True - since success or failure is ignored
def completion(): """Output completion (to be eval'd). For bash or zsh, add the following to your .bashrc or .zshrc: eval "$(doitlive completion)" For fish, add the following to ~/.config/fish/completions/doitlive.fish: eval (doitlive completion) """ shell = env.get("SHELL", None...
Output completion (to be eval'd). For bash or zsh, add the following to your .bashrc or .zshrc: eval "$(doitlive completion)" For fish, add the following to ~/.config/fish/completions/doitlive.fish: eval (doitlive completion)
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'feedback_id') and self.feedback_id is not None: _dict['feedback_id'] = self.feedback_id if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_i...
Return a json dictionary representing this model.
def GetTemplateID(alias,location,name): """Given a template name return the unique OperatingSystem ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param name: template name """ if alias is None: alias = clc.v...
Given a template name return the unique OperatingSystem ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param name: template name
def subbrick(dset,label,coef=False,tstat=False,fstat=False,rstat=False,number_only=False): ''' returns a string referencing the given subbrick within a dset This method reads the header of the dataset ``dset``, finds the subbrick whose label matches ``label`` and returns a string of type ``dataset[X]``, wh...
returns a string referencing the given subbrick within a dset This method reads the header of the dataset ``dset``, finds the subbrick whose label matches ``label`` and returns a string of type ``dataset[X]``, which can be used by most AFNI programs to refer to a subbrick within a file The options coe...
def _translate_dst_register_oprnd(self, operand): """Translate destination register operand to SMT expr. """ reg_info = self._arch_alias_mapper.get(operand.name, None) parent_reg_constrs = [] if reg_info: var_base_name, offset = reg_info var_name_old = ...
Translate destination register operand to SMT expr.
def p_ident_parts(self, p): """ ident_parts : ident_part | selector | filter_group """ if not isinstance(p[1], list): p[1] = [p[1]] p[0] = p[1]
ident_parts : ident_part | selector | filter_group
def dropEvent(self, event: QDropEvent): items = [item for item in self.items(event.scenePos()) if isinstance(item, GraphicsItem) and item.acceptDrops()] item = None if len(items) == 0 else items[0] if len(event.mimeData().urls()) > 0: self.files_dropped.emit(event.mimeData().urls()) ...
:type: list of ProtocolTreeItem
def upload_resumable(self, fd, filesize, filehash, unit_hash, unit_id, unit_size, quick_key=None, action_on_duplicate=None, mtime=None, version_control=None, folder_key=None, filedrop_key=None, path=None, previous_hash=None): """upload/r...
upload/resumable http://www.mediafire.com/developers/core_api/1.3/upload/#resumable
def attend_fight(self, mappings, node_ip, predictions, ntp): """ This function is for starting and managing a fight once the details are known. It also handles the task of returning any valid connections (if any) that may be returned from threads in the simultaneous_fight fu...
This function is for starting and managing a fight once the details are known. It also handles the task of returning any valid connections (if any) that may be returned from threads in the simultaneous_fight function.
def analyze(self, mode=None, timesteps=None): """Analyzes the grid by power flow analysis Analyze the grid for violations of hosting capacity. Means, perform a power flow analysis and obtain voltages at nodes (load, generator, stations/transformers and branch tees) and active/reactive p...
Analyzes the grid by power flow analysis Analyze the grid for violations of hosting capacity. Means, perform a power flow analysis and obtain voltages at nodes (load, generator, stations/transformers and branch tees) and active/reactive power at lines. The power flow analysis c...
def reload(self, **kwargs): """Reload the document""" frame = self.one({'_id': self._id}, **kwargs) self._document = frame._document
Reload the document
def _decrypt_data_key(self, encrypted_data_key, algorithm, encryption_context=None): """Decrypts an encrypted data key and returns the plaintext. :param data_key: Encrypted data key :type data_key: aws_encryption_sdk.structures.EncryptedDataKey :type algorithm: `aws_encryption_sdk.ident...
Decrypts an encrypted data key and returns the plaintext. :param data_key: Encrypted data key :type data_key: aws_encryption_sdk.structures.EncryptedDataKey :type algorithm: `aws_encryption_sdk.identifiers.Algorithm` (not used for KMS) :param dict encryption_context: Encryption context ...
def saveNetworkToFile(self, filename, makeWrapper = 1, mode = "pickle", counter = None): """ Deprecated. """ if "?" in filename: # replace ? pattern in filename with epoch number import re char = "?" match = re.search(re.escape(char) + "+", filename) ...
Deprecated.
def StyleFactory(style_elm): """ Return a style object of the appropriate |BaseStyle| subclass, according to the type of *style_elm*. """ style_cls = { WD_STYLE_TYPE.PARAGRAPH: _ParagraphStyle, WD_STYLE_TYPE.CHARACTER: _CharacterStyle, WD_STYLE_TYPE.TABLE: _TableStyle, ...
Return a style object of the appropriate |BaseStyle| subclass, according to the type of *style_elm*.
def __QueryFeed(self, path, type, id, result_fn, create_fn, query, options=None, partition_key_range_id=None): """Query for more than one Azure Cosmos r...
Query for more than one Azure Cosmos resources. :param str path: :param str type: :param str id: :param function result_fn: :param function create_fn: :param (str or dict) query: :param dict options: The request options for the request. :param...
def toxml(self): """ Exports this object into a LEMS XML object """ return '<Constant' +\ (' name = "{0}"'.format(self.name) if self.name else '') +\ (' symbol = "{0}"'.format(self.symbol) if self.symbol else '') +\ (' value = "{0}"'.format(self.value) if s...
Exports this object into a LEMS XML object
def authenticate_direct_credentials(self, username, password): """ Performs a direct bind, however using direct credentials. Can be used if interfacing with an Active Directory domain controller which authenticates using username@domain.com directly. Performing this kind of look...
Performs a direct bind, however using direct credentials. Can be used if interfacing with an Active Directory domain controller which authenticates using username@domain.com directly. Performing this kind of lookup limits the information we can get from ldap. Instead we can only deduce ...
def describe_instance_health(self, load_balancer_name, instances=None): """ Get current state of all Instances registered to an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :par...
Get current state of all Instances registered to an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :param instances: The instance ID's of the EC2 instances to return sta...
def decr(name, value=1, rate=1, tags=None): """Decrement a metric by value. >>> import statsdecor >>> statsdecor.decr('my.metric') """ client().decr(name, value, rate, tags)
Decrement a metric by value. >>> import statsdecor >>> statsdecor.decr('my.metric')
def available(name): ''' .. versionadded:: 2014.7.0 Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' path = '/etc/rc.d/{0}'.format(name) return os.path.isfile(path) a...
.. versionadded:: 2014.7.0 Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd
def start_capture(self, port_number, output_file, data_link_type="DLT_EN10MB"): """ Starts a packet capture. :param port_number: allocated port number :param output_file: PCAP destination file for the capture :param data_link_type: PCAP data link type (DLT_*), default is DLT_EN1...
Starts a packet capture. :param port_number: allocated port number :param output_file: PCAP destination file for the capture :param data_link_type: PCAP data link type (DLT_*), default is DLT_EN10MB
def _Execute(self, options): """Handles security groups operations.""" whitelist = dict( name=options["name"], description=options.get("description", "<empty>")) return self._agent.client.compute.security_groups.create(**whitelist)
Handles security groups operations.
def union(self, other): """ Makes a striplog of all unions. Args: Striplog. The striplog instance to union with. Returns: Striplog. The result of the union. """ if not isinstance(other, self.__class__): m = "You can only union striplo...
Makes a striplog of all unions. Args: Striplog. The striplog instance to union with. Returns: Striplog. The result of the union.
def createSystem(self, topology, nonbondedMethod=NoCutoff, nonbondedCutoff=1.0 * u.nanometer, constraints=None, rigidWater=True, removeCMMotion=True, hydrogenMass=None, **args): """Construct an OpenMM System representing a Topology with this force f...
Construct an OpenMM System representing a Topology with this force field. Parameters ---------- topology : Topology The Topology for which to create a System nonbondedMethod : object=NoCutoff The method to use for nonbonded interactions. Allowed values are ...
def select_key(self, key, bucket_name=None, expression='SELECT * FROM S3Object', expression_type='SQL', input_serialization=None, output_serialization=None): """ Reads a key with S3 Select. :param key: S3 key that will ...
Reads a key with S3 Select. :param key: S3 key that will point to the file :type key: str :param bucket_name: Name of the bucket in which the file is stored :type bucket_name: str :param expression: S3 Select expression :type expression: str :param expression_typ...
def paste_to_current_cell(self, tl_key, data, freq=None): """Pastes data into grid from top left cell tl_key Parameters ---------- ul_key: Tuple \key of top left cell of paste area data: iterable of iterables where inner iterable returns string \tThe outer itera...
Pastes data into grid from top left cell tl_key Parameters ---------- ul_key: Tuple \key of top left cell of paste area data: iterable of iterables where inner iterable returns string \tThe outer iterable represents rows freq: Integer, defaults to None \...
def cli(env, sortby, columns, datacenter, username, storage_type): """List file storage.""" file_manager = SoftLayer.FileStorageManager(env.client) file_volumes = file_manager.list_file_volumes(datacenter=datacenter, username=username, ...
List file storage.