code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def load_data(cr, module_name, filename, idref=None, mode='init'): """ Load an xml, csv or yml data file from your post script. The usual case for this is the occurrence of newly added essential or useful data in the module that is marked with "noupdate='1'" and without "forcecreate='1'" so that it ...
Load an xml, csv or yml data file from your post script. The usual case for this is the occurrence of newly added essential or useful data in the module that is marked with "noupdate='1'" and without "forcecreate='1'" so that it will not be loaded by the usual upgrade mechanism. Leaving the 'mode' argum...
def set_beeper_mode(self, state): """ :param state: a boolean of ture (on) or false ('off') :return: nothing """ values = {"desired_state": {"beeper_enabled": state}} response = self.api_interface.set_device_state(self, values) self._update_state_from_respo...
:param state: a boolean of ture (on) or false ('off') :return: nothing
def validate_bands(bands): """Validate bands parameter.""" if not isinstance(bands, list): raise TypeError('Parameter bands must be a "list"') valid_bands = list(range(1, 12)) + ['BQA'] for band in bands: if band not in valid_bands: raise InvalidBa...
Validate bands parameter.
def make_break(lineno, p): """ Checks if --enable-break is set, and if so, calls BREAK keyboard interruption for this line if it has not been already checked """ global last_brk_linenum if not OPTIONS.enableBreak.value or lineno == last_brk_linenum or is_null(p): return None last_brk_l...
Checks if --enable-break is set, and if so, calls BREAK keyboard interruption for this line if it has not been already checked
def cache(self): """Return a cache instance.""" cache = self._cache or self.app.config.get('COLLECTIONS_CACHE') return import_string(cache) if isinstance(cache, six.string_types) \ else cache
Return a cache instance.
def freqpoly_plot(data): """make freqpoly plot of merged read lengths""" rel_data = OrderedDict() for key, val in data.items(): tot = sum(val.values(), 0) rel_data[key] = {k: v / tot for k, v in val.items()} fplotconfig = { 'data_labels': [ ...
make freqpoly plot of merged read lengths
def datafield(*path, **kwargs): """A decorator that defines a field for data within a :class:`DataStruct` The decorated function becomes the parser for a :class:`DataField` which will be assigned to a data structure under the function's defined name. Parameters ---------- path: tuple T...
A decorator that defines a field for data within a :class:`DataStruct` The decorated function becomes the parser for a :class:`DataField` which will be assigned to a data structure under the function's defined name. Parameters ---------- path: tuple The path to a value within a raw piece o...
def verify_sc_url(url: str) -> bool: """Verify signature certificate URL against Amazon Alexa requirements. Each call of Agent passes incoming utterances batch through skills filter, agent skills, skills processor. Batch of dialog IDs can be provided, in other case utterances indexes in incoming batch ...
Verify signature certificate URL against Amazon Alexa requirements. Each call of Agent passes incoming utterances batch through skills filter, agent skills, skills processor. Batch of dialog IDs can be provided, in other case utterances indexes in incoming batch are used as dialog IDs. Args: u...
def write_word(self, cmd, value): """ Writes a 16-bit word to the specified command register """ self.bus.write_word_data(self.address, cmd, value) self.log.debug( "write_word: Wrote 0x%04X to command register 0x%02X" % ( value, cmd ) ...
Writes a 16-bit word to the specified command register
def encode(self, value): ''' :param value: value to encode ''' kassert.is_of_types(value, Bits) if len(value) % 8 != 0: raise KittyException('this encoder cannot encode bits that are not byte aligned') return self._encoder.encode(value.bytes)
:param value: value to encode
def split_list(alist, wanted_parts=1): """ A = [0,1,2,3,4,5,6,7,8,9] print split_list(A, wanted_parts=1) print split_list(A, wanted_parts=2) print split_list(A, wanted_parts=8) """ length = len(alist) return [ alist[i * length // wanted_parts:(i + 1) * length // wanted_parts] ...
A = [0,1,2,3,4,5,6,7,8,9] print split_list(A, wanted_parts=1) print split_list(A, wanted_parts=2) print split_list(A, wanted_parts=8)
def child(self, offset256): """ Derive new public key from this key and a sha256 "offset" """ a = bytes(self) + offset256 s = hashlib.sha256(a).digest() return self.add(s)
Derive new public key from this key and a sha256 "offset"
def render_svg(self, render_id, words, arcs): """Render SVG. render_id (int): Unique ID, typically index of document. words (list): Individual words and their tags. arcs (list): Individual arcs and their start, end, direction and label. RETURNS (unicode): Rendered SVG markup. ...
Render SVG. render_id (int): Unique ID, typically index of document. words (list): Individual words and their tags. arcs (list): Individual arcs and their start, end, direction and label. RETURNS (unicode): Rendered SVG markup.
def __imap_search(self, ** criteria_dict): """ Searches for query in the given IMAP criteria and returns the message numbers that match as a list of strings. Criteria without values (eg DELETED) should be keyword args with KEY=True, or else not passed. Criteria with values should ...
Searches for query in the given IMAP criteria and returns the message numbers that match as a list of strings. Criteria without values (eg DELETED) should be keyword args with KEY=True, or else not passed. Criteria with values should be keyword args of the form KEY="VALUE" where KEY is ...
def inverted(self): """Return the inverse of the transform.""" # This is a bit of hackery so that we can put a single "inverse" # function here. If we just made "self._inverse_type" point to the class # in question, it wouldn't be defined yet. This way, it's done at # at runtime ...
Return the inverse of the transform.
def get_volumes(self): """ Return a list of all Volumes in this Storage Pool """ vols = [self.find_volume(name) for name in self.virsp.listVolumes()] return vols
Return a list of all Volumes in this Storage Pool
def _determine_auth_mechanism(username, password, delegation): """ if the username contains at '@' sign we will use kerberos if the username contains a '/ we will use ntlm either NTLM or Kerberos. In fact its basically always Negotiate. """ if re.match('(.*)@(.+)', userna...
if the username contains at '@' sign we will use kerberos if the username contains a '/ we will use ntlm either NTLM or Kerberos. In fact its basically always Negotiate.
def markup_fragment(source, encoding=None): ''' Parse a fragment if markup in HTML mode, and return a bindery node Warning: if you pass a string, you must make sure it's a byte string, not a Unicode object. You might also want to wrap it with amara.lib.inputsource.text if it's not obviously XML or HTML (f...
Parse a fragment if markup in HTML mode, and return a bindery node Warning: if you pass a string, you must make sure it's a byte string, not a Unicode object. You might also want to wrap it with amara.lib.inputsource.text if it's not obviously XML or HTML (for example it could be confused with a file name) f...
def _validate_method_decoration(meta, class_): """Validate the usage of ``@override`` and ``@final`` modifiers on methods of the given ``class_``. """ # TODO(xion): employ some code inspection tricks to serve ClassErrors # as if they were thrown at the offending class's/method's ...
Validate the usage of ``@override`` and ``@final`` modifiers on methods of the given ``class_``.
def setmonitor(self, enable=True): """Alias for setmode('monitor') or setmode('managed') Only available with Npcap""" # We must reset the monitor cache if enable: res = self.setmode('monitor') else: res = self.setmode('managed') if not res: ...
Alias for setmode('monitor') or setmode('managed') Only available with Npcap
def login(config, username=None, password=None, email=None, url=None, client=None, *args, **kwargs): ''' Wrapper to the docker.py login method ''' try: c = (_get_client(config) if not client else client) lg = c.login(username, password, email, url) print "%s logged to %s"%(userna...
Wrapper to the docker.py login method
def update(self): """Update the charging state of the Tesla Vehicle.""" self._controller.update(self._id, wake_if_asleep=False) data = self._controller.get_charging_params(self._id) if data and (time.time() - self.__manual_update_time > 60): if data['charging_state'] != "Char...
Update the charging state of the Tesla Vehicle.
def _apply_mt(self, doc_loader, parallelism, **kwargs): """Run the UDF multi-threaded using python multiprocessing""" if not Meta.postgres: raise ValueError("Fonduer must use PostgreSQL as a database backend.") def fill_input_queue(in_queue, doc_loader, terminal_signal): ...
Run the UDF multi-threaded using python multiprocessing
def artist_commentary_revert(self, id_, version_id): """Revert artist commentary (Requires login) (UNTESTED). Parameters: id_ (int): The artist commentary id. version_id (int): The artist commentary version id to revert to. """ param...
Revert artist commentary (Requires login) (UNTESTED). Parameters: id_ (int): The artist commentary id. version_id (int): The artist commentary version id to revert to.
def getaccountaddress(self, user_id=""): """Get the coin address associated with a user id. If the specified user id does not yet have an address for this coin, then generate one. Args: user_id (str): this user's unique identifier Returns: str: Base58Check ...
Get the coin address associated with a user id. If the specified user id does not yet have an address for this coin, then generate one. Args: user_id (str): this user's unique identifier Returns: str: Base58Check address for this account
def config(name, reset=False, **kwargs): ''' Modify configuration options for a given port. Multiple options can be specified. To see the available options for a port, use :mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`. name The port name, in ``category/name`` format re...
Modify configuration options for a given port. Multiple options can be specified. To see the available options for a port, use :mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`. name The port name, in ``category/name`` format reset : False If ``True``, runs a ``make rmconf...
def validate_sceneInfo(self): """Check whether sceneInfo is valid to download from AWS Storage.""" if self.sceneInfo.prefix not in self.__prefixesValid: raise WrongSceneNameError('AWS: Prefix of %s (%s) is invalid' % (self.sceneInfo.name, self.sceneInfo.prefix))
Check whether sceneInfo is valid to download from AWS Storage.
def _responsify(api_spec, error, status): """Take a bravado-core model representing an error, and return a Flask Response with the given error code and error instance as body""" result_json = api_spec.model_to_json(error) r = jsonify(result_json) r.status_code = status return r
Take a bravado-core model representing an error, and return a Flask Response with the given error code and error instance as body
def get_disabled(): ''' .. versionadded:: 2014.7.0 Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' services = [] for daemon, is_enabled in six.iteritems(_get_rc()): if not is_enabled: ...
.. versionadded:: 2014.7.0 Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled
def get_minimum_span(low, high, span): """ If lower and high values are equal ensures they are separated by the defined span. """ if is_number(low) and low == high: if isinstance(low, np.datetime64): span = span * np.timedelta64(1, 's') low, high = low-span, high+span ...
If lower and high values are equal ensures they are separated by the defined span.
def read_folder(folder): """Read all files of `folder` and return a list of HandwrittenData objects. Parameters ---------- folder : string Path to a folder Returns ------- list : A list of all .ink files in the given folder. """ recordings = [] for filename ...
Read all files of `folder` and return a list of HandwrittenData objects. Parameters ---------- folder : string Path to a folder Returns ------- list : A list of all .ink files in the given folder.
def EXPGauss(w_F, compute_uncertainty=True, is_timeseries=False): """Estimate free energy difference using gaussian approximation to one-sided (unidirectional) exponential averaging. Parameters ---------- w_F : np.ndarray, float w_F[t] is the forward work value from snapshot t. t = 0...(T-1) ...
Estimate free energy difference using gaussian approximation to one-sided (unidirectional) exponential averaging. Parameters ---------- w_F : np.ndarray, float w_F[t] is the forward work value from snapshot t. t = 0...(T-1) Length T is deduced from vector. compute_uncertainty : bool, optional...
def setup(self, redis_conn=None, host='localhost', port=6379): ''' Set up the counting manager class @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port ''' AbstractCounter.setup(self, re...
Set up the counting manager class @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port
def prepare_stack_for_update(self, stack, tags): """Prepare a stack for updating It may involve deleting the stack if is has failed it's initial creation. The deletion is only allowed if: - The stack contains all the tags configured in the current context; - The stack is in ...
Prepare a stack for updating It may involve deleting the stack if is has failed it's initial creation. The deletion is only allowed if: - The stack contains all the tags configured in the current context; - The stack is in one of the statuses considered safe to re-create -...
def u_shape(units: tf.Tensor, n_hidden_list: List, filter_width=7, use_batch_norm=False, training_ph=None): """ Network architecture inspired by One Hundred layer Tiramisu. https://arxiv.org/abs/1611.09326. U-Net like. Args: units: a tenso...
Network architecture inspired by One Hundred layer Tiramisu. https://arxiv.org/abs/1611.09326. U-Net like. Args: units: a tensorflow tensor with dimensionality [None, n_tokens, n_features] n_hidden_list: list with number of hidden units at the ouput of each layer fil...
def deactivate(self): """ Stop heating/cooling and turn off the fan """ if self._driver and self._driver.is_connected(): self._driver.deactivate()
Stop heating/cooling and turn off the fan
def _from_binary_objid(cls, binary_stream): """See base class.""" uid_size = ObjectID._UUID_SIZE #some entries might not have all four ids, this line forces #to always create 4 elements, so contruction is easier uids = [UUID(bytes_le=binary_stream[i*uid_size:(i+1)*uid_size].tobytes()) if i * uid_si...
See base class.
def baseurl(url): """ return baseurl of given url """ parsed_url = urlparse.urlparse(url) if not parsed_url.netloc or parsed_url.scheme not in ("http", "https"): raise ValueError('bad url') service_url = "%s://%s%s" % (parsed_url.scheme, parsed_url.netloc, parsed_url.path.strip()) re...
return baseurl of given url
def _images_succeeded(cls, session): """Clears the :attr:`_stored_images` set and deletes actual files that are marked as deleted in the storage if the ongoing transaction has committed. """ for image, store in cls._deleted_images: for stored_image, _ in cls._stored_...
Clears the :attr:`_stored_images` set and deletes actual files that are marked as deleted in the storage if the ongoing transaction has committed.
def select(self, node): """ Translate a select node into a latex qtree node. :param node: a treebrd node :return: a qtree subtree rooted at the node """ child = self.translate(node.child) return '[.${op}_{{{conditions}}}$ {child} ]'\ .format(op=latex_o...
Translate a select node into a latex qtree node. :param node: a treebrd node :return: a qtree subtree rooted at the node
def GetValue(self, row, col, table=None): """Return the result value of a cell, line split if too much data""" if table is None: table = self.grid.current_table try: cell_code = self.code_array((row, col, table)) except IndexError: cell_code = None ...
Return the result value of a cell, line split if too much data
def unwrap(self, value, session=None): ''' Expects a list of dictionaries with ``k`` and ``v`` set to the keys and values that will be unwrapped into the output python dictionary should have. Validates the input and then constructs the dictionary from the list. ''' ...
Expects a list of dictionaries with ``k`` and ``v`` set to the keys and values that will be unwrapped into the output python dictionary should have. Validates the input and then constructs the dictionary from the list.
def save(thing, url_or_handle, **kwargs): """Save object to file on CNS. File format is inferred from path. Use save_img(), save_npy(), or save_json() if you need to force a particular format. Args: obj: object to save. path: CNS path. Raises: RuntimeError: If file extension not...
Save object to file on CNS. File format is inferred from path. Use save_img(), save_npy(), or save_json() if you need to force a particular format. Args: obj: object to save. path: CNS path. Raises: RuntimeError: If file extension not supported.
def _setup_crontab(): """Sets up the crontab if it hasn't already been setup.""" from crontab import CronTab #Since CI works out of a virtualenv anyway, the `ci.py` script will be #installed in the bin already, so we can call it explicitly. command = '/bin/bash -c "source ~/.cron_profile; workon {};...
Sets up the crontab if it hasn't already been setup.
def get_prefix_envname(self, name, log=False): """Return full prefix path of environment defined by `name`.""" prefix = None if name == 'root': prefix = self.ROOT_PREFIX # envs, error = self.get_envs().communicate() envs = self.get_envs() for p in envs: ...
Return full prefix path of environment defined by `name`.
async def run_task(self) -> None: '''Execute the task inside the asyncio event loop. Track the time it takes to run, and log when it starts/stops. After `INTERVAL` seconds, if/once the task has finished running, run it again until `stop()` is called.''' while self.running: ...
Execute the task inside the asyncio event loop. Track the time it takes to run, and log when it starts/stops. After `INTERVAL` seconds, if/once the task has finished running, run it again until `stop()` is called.
def CheckGlobalStatic(filename, clean_lines, linenum, error): """Check for unsafe global or static objects. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors ...
Check for unsafe global or static objects. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
def find_by_ids(self, _ids, projection=None, **kwargs): """ Does a big _id:$in query on any iterator """ id_list = [ObjectId(_id) for _id in _ids] if len(_ids) == 0: return [] # FIXME : this should be an empty cursor ! # Optimized path when only fetchi...
Does a big _id:$in query on any iterator
def delete(self, *args, **kwargs): """ Delete the image, along with any generated thumbnails. """ source_cache = self.get_source_cache() # First, delete any related thumbnails. self.delete_thumbnails(source_cache) # Next, delete the source image. super(Thu...
Delete the image, along with any generated thumbnails.
def animation(self, animation): """Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner """ self._animation = animation self._text = self._get_text(self._text['original'])
Setter for animation property. Parameters ---------- animation: str Defines the animation of the spinner
def _call_one_middleware(self, middleware): ''' Evaluate arguments and execute the middleware function ''' args = {} for arg in middleware['args']: if hasattr(self, arg): # same as eval() but safer for arbitrary code execution args[arg] = reduce(getatt...
Evaluate arguments and execute the middleware function
async def export_wallet(self, von_wallet: Wallet, path: str) -> None: """ Export an existing VON anchor wallet. Raise WalletState if wallet is closed. :param von_wallet: open wallet :param path: path to which to export wallet """ LOGGER.debug('WalletManager.export_walle...
Export an existing VON anchor wallet. Raise WalletState if wallet is closed. :param von_wallet: open wallet :param path: path to which to export wallet
def distance(self, clr): """ Returns the Euclidean distance between two colors (0.0-1.0). Consider colors arranged on the color wheel: - hue is the angle of a color along the center - saturation is the distance of a color from the center - brightness is the elevation of ...
Returns the Euclidean distance between two colors (0.0-1.0). Consider colors arranged on the color wheel: - hue is the angle of a color along the center - saturation is the distance of a color from the center - brightness is the elevation of a color from the center (i.e. we're...
def reset(self): """Reset the service to its' initial state.""" logger.debug('StackInABoxService ({0}): Reset' .format(self.__id, self.name)) self.base_url = '/{0}'.format(self.name) logger.debug('StackInABoxService ({0}): Hosting Service {1}' .f...
Reset the service to its' initial state.
def reverse(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitu...
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :pa...
def process_vts_params(self, scanner_vts): """ Receive an XML object with the Vulnerability Tests an their parameters to be use in a scan and return a dictionary. @param: XML element with vt subelements. Each vt has an id attribute. Optional parameters can be included ...
Receive an XML object with the Vulnerability Tests an their parameters to be use in a scan and return a dictionary. @param: XML element with vt subelements. Each vt has an id attribute. Optional parameters can be included as vt child. Example form: ...
def library_sequencing_results(self): """ Generates a dict. where each key is a Library ID on the SequencingRequest and each value is the associated SequencingResult. Libraries that aren't yet with a SequencingResult are not inlcuded in the dict. """ sres_ids = self.seque...
Generates a dict. where each key is a Library ID on the SequencingRequest and each value is the associated SequencingResult. Libraries that aren't yet with a SequencingResult are not inlcuded in the dict.
def closeSession(self): """ C_CloseSession """ rv = self.lib.C_CloseSession(self.session) if rv != CKR_OK: raise PyKCS11Error(rv)
C_CloseSession
def filter_resources(tables, relationships, include_tables=None, include_columns=None, exclude_tables=None, exclude_columns=None): """ Include the following: 1. Tables and relationships with tables present in the include_tables (lst of str, tables names) ...
Include the following: 1. Tables and relationships with tables present in the include_tables (lst of str, tables names) 2. Columns (of whichever table) present in the include_columns (lst of str, columns names) Exclude the following: 1. Tables and relationships with tables present in the exc...
def add_to_capabilities(self, capabilities): """ Adds proxy information as capability in specified capabilities. :Args: - capabilities: The capabilities to which proxy will be added. """ proxy_caps = {} proxy_caps['proxyType'] = self.proxyType['string'] ...
Adds proxy information as capability in specified capabilities. :Args: - capabilities: The capabilities to which proxy will be added.
def get_vmpolicy_macaddr_output_vmpolicy_macaddr_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vmpolicy_macaddr = ET.Element("get_vmpolicy_macaddr") config = get_vmpolicy_macaddr output = ET.SubElement(get_vmpolicy_macaddr, "output") ...
Auto Generated Code
def prior_names(self): """ get the prior information names Returns ------- prior_names : list a list of prior information names """ return list(self.prior_information.groupby( self.prior_information.index).groups.keys())
get the prior information names Returns ------- prior_names : list a list of prior information names
def next_token(expected_type, data): """ Based on the expected next type, consume the next token returning the type found and an updated buffer with the found token removed :param expected_type: :param data: :return: (TokenType, str) tuple where TokenType is the type of the next token expected ...
Based on the expected next type, consume the next token returning the type found and an updated buffer with the found token removed :param expected_type: :param data: :return: (TokenType, str) tuple where TokenType is the type of the next token expected
def getpaths(struct): """ Maps all Tasks in a structured data object to their .output(). """ if isinstance(struct, Task): return struct.output() elif isinstance(struct, dict): return struct.__class__((k, getpaths(v)) for k, v in six.iteritems(struct)) elif isinstance(struct, (lis...
Maps all Tasks in a structured data object to their .output().
def resplit_datasets(dataset, other_dataset, random_seed=None, split=None): """Deterministic shuffle and split algorithm. Given the same two datasets and the same ``random_seed``, the split happens the same exact way every call. Args: dataset (lib.datasets.Dataset): First dataset. othe...
Deterministic shuffle and split algorithm. Given the same two datasets and the same ``random_seed``, the split happens the same exact way every call. Args: dataset (lib.datasets.Dataset): First dataset. other_dataset (lib.datasets.Dataset): Another dataset. random_seed (int, option...
def validate_username_for_new_account(person, username): """ Validate the new username for a new account. If the username is invalid or in use, raises :py:exc:`UsernameInvalid` or :py:exc:`UsernameTaken`. :param person: Owner of new account. :param username: Username to validate. """ # This is...
Validate the new username for a new account. If the username is invalid or in use, raises :py:exc:`UsernameInvalid` or :py:exc:`UsernameTaken`. :param person: Owner of new account. :param username: Username to validate.
def read_from(self, provider, **options): """ All :class:`Pointer` fields in the `Structure` read the necessary number of bytes from the data :class:`Provider` for their referenced :attr:`~Pointer.data` object. Null pointer are ignored. :param Provider provider: data :class:`Provider`. ...
All :class:`Pointer` fields in the `Structure` read the necessary number of bytes from the data :class:`Provider` for their referenced :attr:`~Pointer.data` object. Null pointer are ignored. :param Provider provider: data :class:`Provider`. :keyword bool nested: if ``True`` all :class:`...
def get_current_m2m_diff(self, instance, new_objects): """ :param instance: Versionable object :param new_objects: objects which are about to be associated with instance :return: (being_removed id list, being_added id list) :rtype : tuple """ new_ids =...
:param instance: Versionable object :param new_objects: objects which are about to be associated with instance :return: (being_removed id list, being_added id list) :rtype : tuple
def group_add_user_action(model, request): """Add user to group. """ user_id = request.params.get('id') if not user_id: user_ids = request.params.getall('id[]') else: user_ids = [user_id] try: group = model.model validate_add_users_to_groups(model, user_ids, [grou...
Add user to group.
def fromBinaryString(value): """Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111' """ bitNo = 8 byte = 0 r = [] for v in value: if bitNo: ...
Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111'
def cli(ctx, feature_id, start, end, organism="", sequence=""): """Set the boundaries of a genomic feature Output: A standard apollo feature dictionary ({"features": [{...}]}) """ return ctx.gi.annotations.set_boundaries(feature_id, start, end, organism=organism, sequence=sequence)
Set the boundaries of a genomic feature Output: A standard apollo feature dictionary ({"features": [{...}]})
def _sanitize_url_components(comp_list, field): ''' Recursive function to sanitize each component of the url. ''' if not comp_list: return '' elif comp_list[0].startswith('{0}='.format(field)): ret = '{0}=XXXXXXXXXX&'.format(field) comp_list.remove(comp_list[0]) retur...
Recursive function to sanitize each component of the url.
def import_categories(self, category_nodes): """ Import all the categories from 'wp:category' nodes, because categories in 'item' nodes are not necessarily all the categories and returning it in a dict for database optimizations. """ self.write_out(self.style.STEP...
Import all the categories from 'wp:category' nodes, because categories in 'item' nodes are not necessarily all the categories and returning it in a dict for database optimizations.
def sync(self, *sids): """ Synchronise data Parameters ---------- sids : list of str SensorIDs to sync Optional, leave empty to sync everything """ if sids == (): sids = [sid for (sid,) in self.dbcur.execute(SQL_SENSOR_ALL)] ...
Synchronise data Parameters ---------- sids : list of str SensorIDs to sync Optional, leave empty to sync everything
def get_avg_price_fifo(self) -> Decimal: """ Calculates the average price paid for the security. security = Commodity Returns Decimal value. """ balance = self.get_quantity() if not balance: return Decimal(0) paid = Decimal(0) accounts...
Calculates the average price paid for the security. security = Commodity Returns Decimal value.
def unit_is_related(self, location, worksheet): ''' Checks for relationship between a unit location and this block. Returns: True if the location is related to this block. ''' same_worksheet = worksheet == self.worksheet if isinstance(location, (tuple, list))...
Checks for relationship between a unit location and this block. Returns: True if the location is related to this block.
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs): """ {_gate_plot_doc} """ if ax == None: ax = pl.gca() if ax_channels is not None: flip = self._find_orientation(ax_channels) plot_func = ax.axes.axhline if flip else ax.axes....
{_gate_plot_doc}
def validate_steps(self, request, workflow, start, end): """Validates the workflow steps from ``start`` to ``end``, inclusive. Returns a dict describing the validation state of the workflow. """ errors = {} for step in workflow.steps[start:end + 1]: if not step.actio...
Validates the workflow steps from ``start`` to ``end``, inclusive. Returns a dict describing the validation state of the workflow.
def fcast(value: float) -> TensorLike: """Cast to float tensor""" newvalue = tf.cast(value, FTYPE) if DEVICE == 'gpu': newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover return newvalue
Cast to float tensor
def contains (self, p): """Returns True if point is contained inside this Polygon, False otherwise. This method uses the Ray Casting algorithm. Examples: >>> p = Polygon() >>> p.vertices = [Point(1, 1), Point(1, -1), Point(-1, -1), Point(-1, 1)] >>> p.contains( Point(0, 0) ) True...
Returns True if point is contained inside this Polygon, False otherwise. This method uses the Ray Casting algorithm. Examples: >>> p = Polygon() >>> p.vertices = [Point(1, 1), Point(1, -1), Point(-1, -1), Point(-1, 1)] >>> p.contains( Point(0, 0) ) True >>> p.contains( Point(2, ...
def import_medusa_data(mat_filename, config_file): """Import measurement data (a .mat file) of the FZJ EIT160 system. This data format is identified as 'FZJ-EZ-2017'. Parameters ---------- mat_filename: string filename to the .mat data file. Note that only MNU0 single-potentials are...
Import measurement data (a .mat file) of the FZJ EIT160 system. This data format is identified as 'FZJ-EZ-2017'. Parameters ---------- mat_filename: string filename to the .mat data file. Note that only MNU0 single-potentials are supported! config_file: string filename for c...
def set_digital_latch(self, pin, threshold_type, cb=None): """ This method "arms" a digital pin for its data to be latched and saved in the latching table If a callback method is provided, when latching criteria is achieved, the callback function is called with latching data notification...
This method "arms" a digital pin for its data to be latched and saved in the latching table If a callback method is provided, when latching criteria is achieved, the callback function is called with latching data notification. In that case, the latching table is not updated. :param pin: Digital...
def surviors_are_inconsistent(survivor_mapping: Mapping[BaseEntity, Set[BaseEntity]]) -> Set[BaseEntity]: """Check that there's no transitive shit going on.""" victim_mapping = set() for victim in itt.chain.from_iterable(survivor_mapping.values()): if victim in survivor_mapping: victim_m...
Check that there's no transitive shit going on.
def get_outliers(self): ''' Performs iterative sigma clipping to get outliers. ''' log.info("Clipping outliers...") log.info('Iter %d/%d: %d outliers' % (0, self.oiter, len(self.outmask))) def M(x): return np.delete(x, np.concatenate( [self...
Performs iterative sigma clipping to get outliers.
def initialize_renderer(extensions=None): """ Initializes the renderer by setting up the extensions (taking a comma separated string or iterable of extensions). These extensions are added alongside with the configured always-on extensions. Returns a markdown renderer instance. """ if extens...
Initializes the renderer by setting up the extensions (taking a comma separated string or iterable of extensions). These extensions are added alongside with the configured always-on extensions. Returns a markdown renderer instance.
def delete_subscription(self, subscription_id): """ Deleting an existing subscription :param subscription_id: is the subscription the client wants to delete """ self._validate_uuid(subscription_id) url = "/notification/v1/subscription/{}".format(subscription_id) ...
Deleting an existing subscription :param subscription_id: is the subscription the client wants to delete
def boolbox(msg="Shall I continue?", title=" ", choices=("[Y]es", "[N]o"), image=None, default_choice='Yes', cancel_choice='No'): """ Display a boolean msgbox. The returned value is calculated this way:: if the first choice is chosen, or if the dialog is cancelled: ...
Display a boolean msgbox. The returned value is calculated this way:: if the first choice is chosen, or if the dialog is cancelled: returns True else: returns False :param str msg: the msg to be displayed :param str title: the window title :param list choices: ...
def set_computer_desc(desc=None): ''' Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc...
Set the Windows computer description Args: desc (str): The computer description Returns: str: Description if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!'
def _expand_authorized_keys_path(path, user, home): ''' Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5) ''' converted_path = '' had_escape = False for char in path: if had_escape: had_escape = False if char == '%': converted...
Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5)
def get_file_list(): """Return a list of strings corresponding to file names supplied by drag and drop or standard input.""" if len(sys.argv) > 1: file_list = list(sys.argv[1:]) # make copy else: files_str = input('Select the files you want to process and drag and drop them onto this windo...
Return a list of strings corresponding to file names supplied by drag and drop or standard input.
def local(self, *args, **kwargs): ''' Run :ref:`execution modules <all-salt.modules>` synchronously See :py:meth:`salt.client.LocalClient.cmd` for all available parameters. Sends a command from the master to the targeted minions. This is the same interface that Salt's o...
Run :ref:`execution modules <all-salt.modules>` synchronously See :py:meth:`salt.client.LocalClient.cmd` for all available parameters. Sends a command from the master to the targeted minions. This is the same interface that Salt's own CLI uses. Note the ``arg`` and ``kwarg`` pa...
def from_cif_file(cif_file, source='', comment=''): """ Static method to create Header object from cif_file Args: cif_file: cif_file path and name source: User supplied identifier, i.e. for Materials Project this would be the material ID number ...
Static method to create Header object from cif_file Args: cif_file: cif_file path and name source: User supplied identifier, i.e. for Materials Project this would be the material ID number comment: User comment that goes in header Returns: ...
def shard_data(source_fnames: List[str], target_fname: str, source_vocabs: List[vocab.Vocab], target_vocab: vocab.Vocab, num_shards: int, buckets: List[Tuple[int, int]], length_ratio_mean: float, length_ratio_std: f...
Assign int-coded source/target sentence pairs to shards at random. :param source_fnames: The path to the source text (and optional token-parallel factor files). :param target_fname: The file name of the target file. :param source_vocabs: Source vocabulary (and optional source factor vocabularies). :par...
def from_file(filename, use_cores=True, thresh=1.e-4): """ Reads an xr-formatted file to create an Xr object. Args: filename (str): name of file to read from. use_cores (bool): use core positions and discard shell positions if set to True (default). ...
Reads an xr-formatted file to create an Xr object. Args: filename (str): name of file to read from. use_cores (bool): use core positions and discard shell positions if set to True (default). Otherwise, use shell positions and discard core positio...
def get_synset_xml(self,syn_id): """ call cdb_syn with synset identifier -> returns the synset xml; """ http, resp, content = self.connect() params = "" fragment = "" path = "cdb_syn" if self.debug: printf( "cornettodb/views/query_remote_s...
call cdb_syn with synset identifier -> returns the synset xml;
def setDataFrame(self, dataFrame): """setter function to _dataFrame. Holds all data. Note: It's not implemented with python properties to keep Qt conventions. Raises: TypeError: if dataFrame is not of type pandas.core.frame.DataFrame. Args: dataFram...
setter function to _dataFrame. Holds all data. Note: It's not implemented with python properties to keep Qt conventions. Raises: TypeError: if dataFrame is not of type pandas.core.frame.DataFrame. Args: dataFrame (pandas.core.frame.DataFrame): assign dataFr...
def notch_fir(self, f1, f2, order, beta=5.0, remove_corrupted=True): """ notch filter the time series using an FIR filtered generated from the ideal response passed through a time-domain kaiser window (beta = 5.0) The suppression of the notch filter is related to the bandwidth and ...
notch filter the time series using an FIR filtered generated from the ideal response passed through a time-domain kaiser window (beta = 5.0) The suppression of the notch filter is related to the bandwidth and the number of samples in the filter length. For a few Hz bandwidth, a ...
def normalize(s, replace_spaces=True): """Normalize non-ascii characters to their closest ascii counterparts """ whitelist = (' -' + string.ascii_letters + string.digits) if type(s) == six.binary_type: s = six.text_type(s, 'utf-8', 'ignore') table = {} for ch in [ch for ch in s if ch n...
Normalize non-ascii characters to their closest ascii counterparts
def find_comp_by_target(self, target): '''Finds a component using a TargetComponent or one of its subclasses. @param A @ref TargetComponent object or subclass of @ref TargetComponent. @return A Component object matching the target. @raises MissingComponentError ''' ...
Finds a component using a TargetComponent or one of its subclasses. @param A @ref TargetComponent object or subclass of @ref TargetComponent. @return A Component object matching the target. @raises MissingComponentError
def remove_thumbnail(self, thumbnail): """Remove thumbnail.""" if thumbnail in self._thumbnails: index = self._thumbnails.index(thumbnail) self._thumbnails.remove(thumbnail) self.layout().removeWidget(thumbnail) thumbnail.deleteLater() thumbnail.sig_canvas...
Remove thumbnail.