code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def reftrack_rtype_data(rt, role): """Return the data for the releasetype that is loaded by the reftrack :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns:...
Return the data for the releasetype that is loaded by the reftrack :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the releasetype :rtype: depe...
def is_binarized(self): """ Return True if the pianoroll is already binarized. Otherwise, return False. Returns ------- is_binarized : bool True if the pianoroll is already binarized; otherwise, False. """ is_binarized = np.issubdtype(self.pi...
Return True if the pianoroll is already binarized. Otherwise, return False. Returns ------- is_binarized : bool True if the pianoroll is already binarized; otherwise, False.
def parse(self, obj): """ Parse the object's properties according to its default types. """ for k, default in obj.__class__.defaults.items(): typ = type(default) if typ is str: continue v = getattr(obj, k) if typ is int: ...
Parse the object's properties according to its default types.
def run_with_graph_transformation(self) -> Iterable[BELGraph]: """Calculate scores for all leaves until there are none, removes edges until there are, and repeats until all nodes have been scored. Also, yields the current graph at every step so you can make a cool animation of how the graph chan...
Calculate scores for all leaves until there are none, removes edges until there are, and repeats until all nodes have been scored. Also, yields the current graph at every step so you can make a cool animation of how the graph changes throughout the course of the algorithm :return: An iterable o...
def zrem(self, key, *members): """Removes the specified members from the sorted set stored at key. Non existing members are ignored. An error is returned when key exists and does not hold a sorted set. .. note:: **Time complexity**: ``O(M*log(N))`` with ``N`` being the num...
Removes the specified members from the sorted set stored at key. Non existing members are ignored. An error is returned when key exists and does not hold a sorted set. .. note:: **Time complexity**: ``O(M*log(N))`` with ``N`` being the number of elements in the sorted s...
def resolve_movie(self, title, year=None): """Tries to find a movie with a given title and year""" r = self.search_movie(title) return self._match_results(r, title, year)
Tries to find a movie with a given title and year
def tararchive_opener(path, pattern='', verbose=False): """Opener that opens files from tar archive. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s). """ with tarfile.open(fileobj=io.BytesIO(urlopen(path).read())) if is_url(path) else tarfile.open(p...
Opener that opens files from tar archive. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s).
def ReadFile(self, definitions_registry, path): """Reads data type definitions from a file into the registry. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. path (str): path of the file to read from. """ with open(path, 'r') as file_objec...
Reads data type definitions from a file into the registry. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. path (str): path of the file to read from.
def encrypt(privkey, passphrase): """ BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey. :param privkey: Private key :type privkey: Base58 :param str passphrase: UTF-8 encoded passphrase for encryption :return: BIP0038 non-ec-multiply encrypted wif key :rtype: Base58 ""...
BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey. :param privkey: Private key :type privkey: Base58 :param str passphrase: UTF-8 encoded passphrase for encryption :return: BIP0038 non-ec-multiply encrypted wif key :rtype: Base58
def get_items(*indexes): """Return a callable that fetches the given indexes of an object Always return a tuple even when len(indexes) == 1. Similar to `operator.itemgetter`, but will insert `None` when the object does not have the desired index (instead of raising IndexError). """ return lambd...
Return a callable that fetches the given indexes of an object Always return a tuple even when len(indexes) == 1. Similar to `operator.itemgetter`, but will insert `None` when the object does not have the desired index (instead of raising IndexError).
def _is_region_extremely_sparse(self, start, end, base_state=None): """ Check whether the given memory region is extremely sparse, i.e., all bytes are the same value. :param int start: The beginning of the region. :param int end: The end of the region. :param base_state: The b...
Check whether the given memory region is extremely sparse, i.e., all bytes are the same value. :param int start: The beginning of the region. :param int end: The end of the region. :param base_state: The base state (optional). :return: True if the region is extremely sparse,...
def joint_torques(self): '''Get a list of all current joint torques in the skeleton.''' return as_flat_array(getattr(j, 'amotor', j).feedback[-1][:j.ADOF] for j in self.joints)
Get a list of all current joint torques in the skeleton.
def deep_reload_hook(m): """Replacement for reload().""" if not isinstance(m, ModuleType): raise TypeError("reload() argument must be module") name = m.__name__ if name not in sys.modules: raise ImportError("reload(): module %.200s not in sys.modules" % name) global modules_reload...
Replacement for reload().
def zlist(columns, items, print_columns=None, text="", title="", width=DEFAULT_WIDTH, height=ZLIST_HEIGHT, timeout=None): """ Display a list of values :param columns: a list of columns name :type columns: list of strings :param items: a list of values :type items: list of st...
Display a list of values :param columns: a list of columns name :type columns: list of strings :param items: a list of values :type items: list of strings :param print_columns: index of a column (return just the values from this column) :type print_columns: int (None if all the columns) :pa...
def img2wav(path, min_x, max_x, min_y, max_y, window_size=3): """Generate 1-D data ``y=f(x)`` from a black/white image. Suppose we have an image like that: .. image:: images/waveform.png :align: center Put some codes:: >>> from weatherlab.math.img2waveform import img2wav >>> ...
Generate 1-D data ``y=f(x)`` from a black/white image. Suppose we have an image like that: .. image:: images/waveform.png :align: center Put some codes:: >>> from weatherlab.math.img2waveform import img2wav >>> import matplotlib.pyplot as plt >>> x, y = img2wav(r"testdata...
def checkversion(version): """Checks foliadocserve version, returns 1 if the document is newer than the library, -1 if it is older, 0 if it is equal""" try: for refversion, responseversion in zip([int(x) for x in REQUIREFOLIADOCSERVE.split('.')], [int(x) for x in version.split('.')]): if res...
Checks foliadocserve version, returns 1 if the document is newer than the library, -1 if it is older, 0 if it is equal
def getTradeHistory(pair, connection=None, info=None, count=None): """Retrieve the trade history for the given pair. Returns a list of Trade instances. If count is not None, it should be an integer, and specifies the number of items from the trade history that will be processed and returned.""" i...
Retrieve the trade history for the given pair. Returns a list of Trade instances. If count is not None, it should be an integer, and specifies the number of items from the trade history that will be processed and returned.
def tags(self, id, service='facebook'): """ Get the existing analysis for a given hash :param id: The hash to get tag analysis for :type id: str :param service: The service for this API call (facebook, etc) :type service: str :return: dict of REST API...
Get the existing analysis for a given hash :param id: The hash to get tag analysis for :type id: str :param service: The service for this API call (facebook, etc) :type service: str :return: dict of REST API output with headers attached :rtype: :c...
def _extract_level(self, topic_str): """Turn 'engine.0.INFO.extra' into (logging.INFO, 'engine.0.extra')""" topics = topic_str.split('.') for idx,t in enumerate(topics): level = getattr(logging, t, None) if level is not None: break if leve...
Turn 'engine.0.INFO.extra' into (logging.INFO, 'engine.0.extra')
def validate(anchors, duplicate_tags, opts): """ Client facing validate function. Runs _validate() and returns True if anchors and duplicate_tags pass all validations. Handles exceptions automatically if _validate() throws any and exits the program. :param anchors: Dictionary mapping string file pa...
Client facing validate function. Runs _validate() and returns True if anchors and duplicate_tags pass all validations. Handles exceptions automatically if _validate() throws any and exits the program. :param anchors: Dictionary mapping string file path keys to dictionary values. The inner dictionar...
def mode(name, mode, quotatype): ''' Set the quota for the system name The filesystem to set the quota mode on mode Whether the quota system is on or off quotatype Must be ``user`` or ``group`` ''' ret = {'name': name, 'changes': {}, 'result':...
Set the quota for the system name The filesystem to set the quota mode on mode Whether the quota system is on or off quotatype Must be ``user`` or ``group``
def status(self, verbose=False): """ Checks the status of your CyREST server. """ try: response=api(url=self.__url, method="GET", verbose=verbose) except Exception as e: print('Could not get status from CyREST:\n\n' + str(e)) else: prin...
Checks the status of your CyREST server.
def scs2e(sc, sclkch): """ Convert a spacecraft clock string to ephemeris seconds past J2000 (ET). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scs2e_c.html :param sc: NAIF integer code for a spacecraft. :type sc: int :param sclkch: An SCLK string. :type sclkch: str :return:...
Convert a spacecraft clock string to ephemeris seconds past J2000 (ET). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scs2e_c.html :param sc: NAIF integer code for a spacecraft. :type sc: int :param sclkch: An SCLK string. :type sclkch: str :return: Ephemeris time, seconds past J2000...
def create_package_file(root, master_package, subroot, py_files, opts, subs): """Build the text of the file and write the file.""" text = format_heading(1, '%s' % makename(master_package, subroot)) if opts.modulefirst: text += format_directive(subroot, master_package) text += '\n' # bu...
Build the text of the file and write the file.
def main(): """ Sends an API AT command to read the lower-order address bits from an XBee Series 1 and looks for a response """ try: # Open serial port ser = serial.Serial('/dev/ttyUSB0', 9600) # Create XBee Series 1 object xbee = XBee(ser) # Send AT packe...
Sends an API AT command to read the lower-order address bits from an XBee Series 1 and looks for a response
def write(self, value): # type: (int) -> None """Write a raw byte to the LCD.""" # Get current position row, col = self._cursor_pos # Write byte if changed try: if self._content[row][col] != value: self._send_data(value) self._conten...
Write a raw byte to the LCD.
def _get_repr(obj, pretty=False, indent=1): """ Get string representation of an object :param obj: object :type obj: object :param pretty: use pretty formatting :type pretty: bool :param indent: indentation for pretty formatting :type indent: int ...
Get string representation of an object :param obj: object :type obj: object :param pretty: use pretty formatting :type pretty: bool :param indent: indentation for pretty formatting :type indent: int :return: string representation :rtype: str
def _add_data_to_general_stats(self, data): """ Add data for the general stats in a Picard-module specific manner """ headers = _get_general_stats_headers() self.general_stats_headers.update(headers) header_names = ('ERROR_count', 'WARNING_count', 'file_validation_status') general_dat...
Add data for the general stats in a Picard-module specific manner
def GetParsers(cls, parser_filter_expression=None): """Retrieves the registered parsers and plugins. Retrieves a dictionary of all registered parsers and associated plugins from a parser filter string. The filter string can contain direct names of parsers, presets or plugins. The filter string can also...
Retrieves the registered parsers and plugins. Retrieves a dictionary of all registered parsers and associated plugins from a parser filter string. The filter string can contain direct names of parsers, presets or plugins. The filter string can also negate selection if prepended with an exclamation poin...
def open_slots(self, session): """ Returns the number of slots open at the moment """ from airflow.models.taskinstance import \ TaskInstance as TI # Avoid circular import used_slots = session.query(func.count()).filter(TI.pool == self.pool).filter( TI.st...
Returns the number of slots open at the moment
def _update(self, sock_info, criteria, document, upsert=False, check_keys=True, multi=False, manipulate=False, write_concern=None, op_id=None, ordered=True, bypass_doc_val=False, collation=None, array_filters=None, session=None, retryable_write=False): ...
Internal update / replace helper.
def generate_repo_files(self, release): """Dynamically generate our yum repo configuration""" repo_tmpl = pkg_resources.resource_string(__name__, 'templates/repo.mako') repo_file = os.path.join(release['git_dir'], '%s.repo' % release['repo']) with file(repo_file, 'w') as repo: ...
Dynamically generate our yum repo configuration
def angact_ho(x,omega): """ Calculate angle and action variable in sho potential with parameter omega """ action = (x[3:]**2+(omega*x[:3])**2)/(2.*omega) angle = np.array([np.arctan(-x[3+i]/omega[i]/x[i]) if x[i]!=0. else -np.sign(x[3+i])*np.pi/2. for i in range(3)]) for i in range(3): if(x[...
Calculate angle and action variable in sho potential with parameter omega
def nvmlDeviceSetPowerManagementLimit(handle, limit): r""" /** * Set new power limit of this device. * * For Kepler &tm; or newer fully supported devices. * Requires root/admin permissions. * * See \ref nvmlDeviceGetPowerManagementLimitConstraints to check the allowed ranges of val...
r""" /** * Set new power limit of this device. * * For Kepler &tm; or newer fully supported devices. * Requires root/admin permissions. * * See \ref nvmlDeviceGetPowerManagementLimitConstraints to check the allowed ranges of values. * * \note Limit is not persistent across re...
def get_assessment_ids(self): """Gets the Ids of any assessments associated with this activity. return: (osid.id.IdList) - list of assessment Ids raise: IllegalState - is_assessment_based_activity() is false compliance: mandatory - This method must be implemented. """ ...
Gets the Ids of any assessments associated with this activity. return: (osid.id.IdList) - list of assessment Ids raise: IllegalState - is_assessment_based_activity() is false compliance: mandatory - This method must be implemented.
def add_layout(self, obj, place='center'): ''' Adds an object to the plot in a specified place. Args: obj (Renderer) : the object to add to the Plot place (str, optional) : where to add the object (default: 'center') Valid places are: 'left', 'right', 'above', 'b...
Adds an object to the plot in a specified place. Args: obj (Renderer) : the object to add to the Plot place (str, optional) : where to add the object (default: 'center') Valid places are: 'left', 'right', 'above', 'below', 'center'. Returns: None
def citedReferences(self, uid, count=100, offset=1, retrieveParameters=None): """The citedReferences operation returns references cited by an article identified by a unique identifier. You may specify only one identifier per request. :uid: Thomson Reuters unique ...
The citedReferences operation returns references cited by an article identified by a unique identifier. You may specify only one identifier per request. :uid: Thomson Reuters unique record identifier :count: Number of records to display in the result. Cannot be less than ...
def get_default_frame(self): '''default frame for waypoints''' if self.settings.terrainalt == 'Auto': if self.get_mav_param('TERRAIN_FOLLOW',0) == 1: return mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT return mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT i...
default frame for waypoints
def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.u...
Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output.
def retrieve_file_from_RCSB(http_connection, resource, silent = True): '''Retrieve a file from the RCSB.''' if not silent: colortext.printf("Retrieving %s from RCSB" % os.path.split(resource)[1], color = "aqua") return http_connection.get(resource)
Retrieve a file from the RCSB.
async def upload_sticker_file(self, user_id: base.Integer, png_sticker: base.InputFile) -> types.File: """ Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Source: https://core.telegram.or...
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Source: https://core.telegram.org/bots/api#uploadstickerfile :param user_id: User identifier of sticker file owner :type user_id: :obj:`ba...
def fromtext(source=None, encoding=None, errors='strict', strip=None, header=('lines',)): """ Extract a table from lines in the given text file. E.g.:: >>> import petl as etl >>> # setup example file ... text = 'a,1\\nb,2\\nc,2\\n' >>> with open('example.txt', 'w') ...
Extract a table from lines in the given text file. E.g.:: >>> import petl as etl >>> # setup example file ... text = 'a,1\\nb,2\\nc,2\\n' >>> with open('example.txt', 'w') as f: ... f.write(text) ... 12 >>> table1 = etl.fromtext('example.txt') ...
def normalized_nodes_on_bdry(nodes_on_bdry, length): """Return a list of 2-tuples of bool from the input parameter. This function is intended to normalize a ``nodes_on_bdry`` parameter that can be given as a single boolean (global) or as a sequence (per axis). Each entry of the sequence can either be a...
Return a list of 2-tuples of bool from the input parameter. This function is intended to normalize a ``nodes_on_bdry`` parameter that can be given as a single boolean (global) or as a sequence (per axis). Each entry of the sequence can either be a single boolean (global for the axis) or a boolean seque...
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return QS_Function(key) if key not in QS_Function._member_map_: extend_enum(QS_Function, key, default) return QS_Function[key]
Backport support for original codes.
def parse_host(host): """Parses host name and port number from a string. """ if re.match(r'^(\d+)$', host) is not None: return ("0.0.0.0", int(host)) if re.match(r'^(\w+)://', host) is None: host = "//" + host o = parse.urlparse(host) hostname = o.hostname or "0.0.0.0" port =...
Parses host name and port number from a string.
def filesize(num_bytes): """Return a string containing an approximate representation of *num_bytes* using a small number and decimal SI prefix.""" for prefix in '-KMGTEPZY': if num_bytes < 999.9: break num_bytes /= 1000.0 if prefix == '-': return '{} B'.format(num_byt...
Return a string containing an approximate representation of *num_bytes* using a small number and decimal SI prefix.
def get_ceph_pool_sample(self, sentry_unit, pool_id=0): """Take a sample of attributes of a ceph pool, returning ceph pool name, object count and disk space used for the specified pool ID number. :param sentry_unit: Pointer to amulet sentry instance (juju unit) :param pool_id: C...
Take a sample of attributes of a ceph pool, returning ceph pool name, object count and disk space used for the specified pool ID number. :param sentry_unit: Pointer to amulet sentry instance (juju unit) :param pool_id: Ceph pool ID :returns: List of pool name, object count, kb d...
def unregister_service(self, name): """ Implementation of :meth:`twitcher.api.IRegistry.unregister_service`. """ try: self.store.delete_service(name=name) except Exception: LOGGER.exception('unregister failed') return False else: ...
Implementation of :meth:`twitcher.api.IRegistry.unregister_service`.
def setup_logging( config='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG' ): """Setup logging configuration """ path = config value = os.getenv(env_key, None) if value: path = value if path.exists(): with open(path, 'rt') as f: config = yaml...
Setup logging configuration
def ajIrreguliers(self): """ Chargement des formes irrégulières du fichier data/irregs.la """ lignes = lignesFichier(self.path("irregs.la")) for lin in lignes: try: irr = self.parse_irreg(lin) self.lemmatiseur._irregs[deramise(irr.gr())].append...
Chargement des formes irrégulières du fichier data/irregs.la
def is_primitive(value): """ Checks if value has primitive type. Primitive types are: numbers, strings, booleans, date and time. Complex (non-primitive types are): objects, maps and arrays :param value: a value to check :return: true if the value has primitive type and...
Checks if value has primitive type. Primitive types are: numbers, strings, booleans, date and time. Complex (non-primitive types are): objects, maps and arrays :param value: a value to check :return: true if the value has primitive type and false if value type is complex.
def absence_count(self): """Return the user's absence count. If the user has no absences or is not a signup user, returns 0. """ # FIXME: remove recursive dep from ..eighth.models import EighthSignup return EighthSignup.objects.filter(user=self, was_absent=True...
Return the user's absence count. If the user has no absences or is not a signup user, returns 0.
def create_unique_autosave_filename(self, filename, autosave_dir): """ Create unique autosave file name for specified file name. Args: filename (str): original file name autosave_dir (str): directory in which autosave files are stored """ basename = osp.b...
Create unique autosave file name for specified file name. Args: filename (str): original file name autosave_dir (str): directory in which autosave files are stored
def get_next_input(self): """ Returns the next line of input :return: string of input """ # TODO: could override input if we get input coming in at the same time all_input = Deployment.objects.get(pk=self.id).input or '' lines = all_input.splitlines() fir...
Returns the next line of input :return: string of input
def _fw_delete(self, drvr_name, data): """Firewall Delete routine. This function calls routines to remove FW from fabric and device. It also updates its local cache. """ fw_id = data.get('firewall_id') tenant_id = self.tenant_db.get_fw_tenant(fw_id) if tenant_id...
Firewall Delete routine. This function calls routines to remove FW from fabric and device. It also updates its local cache.
def delete_invalid_tickets(self): """ Delete consumed or expired ``Ticket``s that are not referenced by other ``Ticket``s. Invalid tickets are no longer valid for authentication and can be safely deleted. A custom management command is provided that executes this method ...
Delete consumed or expired ``Ticket``s that are not referenced by other ``Ticket``s. Invalid tickets are no longer valid for authentication and can be safely deleted. A custom management command is provided that executes this method on all applicable models by running ``manage.py cleanu...
def rpc_put_zonefiles( self, zonefile_datas, **con_info ): """ Replicate one or more zonefiles, given as serialized strings. Only stores zone files whose zone file hashes were announced on the blockchain (i.e. not subdomain zone files) Returns {'status': True, 'saved': [0|1]'} on success...
Replicate one or more zonefiles, given as serialized strings. Only stores zone files whose zone file hashes were announced on the blockchain (i.e. not subdomain zone files) Returns {'status': True, 'saved': [0|1]'} on success ('saved' is a vector of success/failure) Returns {'error': ...} on err...
async def await_reply(self, correlation_id, timeout=None): """Wait for a reply to a given correlation id. If a timeout is provided, it will raise a asyncio.TimeoutError. """ try: result = await asyncio.wait_for( self._futures[correlation_id], timeout=timeout)...
Wait for a reply to a given correlation id. If a timeout is provided, it will raise a asyncio.TimeoutError.
def map_parameters(cls, params): """Maps parameters to form field names""" d = {} for k, v in six.iteritems(params): d[cls.FIELD_MAP.get(k.lower(), k)] = v return d
Maps parameters to form field names
def list_leases(self, prefix): """Retrieve a list of lease ids. Supported methods: LIST: /sys/leases/lookup/{prefix}. Produces: 200 application/json :param prefix: Lease prefix to filter list by. :type prefix: str | unicode :return: The JSON response of the request....
Retrieve a list of lease ids. Supported methods: LIST: /sys/leases/lookup/{prefix}. Produces: 200 application/json :param prefix: Lease prefix to filter list by. :type prefix: str | unicode :return: The JSON response of the request. :rtype: dict
def _run_select(self): """ Run the query as a "select" statement against the connection. :return: The result :rtype: list """ return self._connection.select( self.to_sql(), self.get_bindings(), not self._use_write_connection )
Run the query as a "select" statement against the connection. :return: The result :rtype: list
def set_crypttab( name, device, password='none', options='', config='/etc/crypttab', test=False, match_on='name'): ''' Verify that this device is represented in the crypttab, change the device to match the name passed, or add the name if it is not pres...
Verify that this device is represented in the crypttab, change the device to match the name passed, or add the name if it is not present. CLI Example: .. code-block:: bash salt '*' cryptdev.set_crypttab foo /dev/sdz1 mypassword swap,size=256
def ignore(code): """Should this code be ignored. :param str code: Error code (e.g. D201). :return: True if code should be ignored, False otherwise. :rtype: bool """ if code in Main.options['ignore']: return True if any(c in code for c in Main.options['ignore']): return Tru...
Should this code be ignored. :param str code: Error code (e.g. D201). :return: True if code should be ignored, False otherwise. :rtype: bool
def unrate_url(obj): """ Generates a link to "un-rate" the given object - this can be used as a form target or for POSTing via Ajax. """ return reverse('ratings_unrate_object', args=( ContentType.objects.get_for_model(obj).pk, obj.pk, ))
Generates a link to "un-rate" the given object - this can be used as a form target or for POSTing via Ajax.
def action_filter(method_name, *args, **kwargs): """ Creates an effect that will call the action's method with the current value and specified arguments and keywords. @param method_name: the name of method belonging to the action. @type method_name: str """ def action_filter(value, context,...
Creates an effect that will call the action's method with the current value and specified arguments and keywords. @param method_name: the name of method belonging to the action. @type method_name: str
def parse_declaration_expressn_operator(self, lhsAST, rhsAST, es, operator): """ Simply joins the left and right hand arguments lhs and rhs with an operator. :param lhsAST: :param rhsAST: :param es: :param operator: :return: """ if isinstance(lhsA...
Simply joins the left and right hand arguments lhs and rhs with an operator. :param lhsAST: :param rhsAST: :param es: :param operator: :return:
def OnNodeActivated(self, event): """We have double-clicked for hit enter on a node refocus squaremap to this node""" try: node = self.sorted[event.GetIndex()] except IndexError, err: log.warn(_('Invalid index in node activated: %(index)s'), index=eve...
We have double-clicked for hit enter on a node refocus squaremap to this node
def reset(self): """Reset openthread device, not equivalent to stop and start """ logger.debug('DUT> reset') self._log and self.pause() self._sendline('reset') self._read() self._log and self.resume()
Reset openthread device, not equivalent to stop and start
def create_uinput_device(mapping): """Creates a uinput device.""" if mapping not in _mappings: raise DeviceError("Unknown device mapping: {0}".format(mapping)) try: mapping = _mappings[mapping] device = UInputDevice(mapping) except UInputError as err: raise DeviceError(e...
Creates a uinput device.
def generate_ref(self): """ Ref can be link to remote or local definition. .. code-block:: python {'$ref': 'http://json-schema.org/draft-04/schema#'} { 'properties': { 'foo': {'type': 'integer'}, 'bar': {'$ref': '#...
Ref can be link to remote or local definition. .. code-block:: python {'$ref': 'http://json-schema.org/draft-04/schema#'} { 'properties': { 'foo': {'type': 'integer'}, 'bar': {'$ref': '#/properties/foo'} } ...
def parse_reaction_file(path, default_compartment=None): """Open and parse reaction file based on file extension Path can be given as a string or a context. """ context = FilePathContext(path) format = resolve_format(None, context.filepath) if format == 'tsv': logger.debug('Parsing re...
Open and parse reaction file based on file extension Path can be given as a string or a context.
def _add_active_assets(specs): """ This function adds an assets key to the specs, which is filled in with a dictionary of all assets defined by apps and libs in the specs """ specs['assets'] = {} for spec in specs.get_apps_and_libs(): for asset in spec['assets']: if not specs...
This function adds an assets key to the specs, which is filled in with a dictionary of all assets defined by apps and libs in the specs
def account_following(self, id, max_id=None, min_id=None, since_id=None, limit=None): """ Fetch users the given user is following. Returns a list of `user dicts`_. """ id = self.__unpack_id(id) if max_id != None: max_id = self.__unpack_id(max_id) ...
Fetch users the given user is following. Returns a list of `user dicts`_.
def build_disagg_matrix(bdata, bin_edges, sid, mon=Monitor): """ :param bdata: a dictionary of probabilities of no exceedence :param bin_edges: bin edges :param sid: site index :param mon: a Monitor instance :returns: a dictionary key -> matrix|pmf for each key in bdata """ with mon('bui...
:param bdata: a dictionary of probabilities of no exceedence :param bin_edges: bin edges :param sid: site index :param mon: a Monitor instance :returns: a dictionary key -> matrix|pmf for each key in bdata
def _read_packet(f, pos, n_smp, n_allchan, abs_delta): """ Read a packet of compressed data Parameters ---------- f : instance of opened file erd file pos : int index of the start of the packet in the file (in bytes from beginning of the file) n_smp : int num...
Read a packet of compressed data Parameters ---------- f : instance of opened file erd file pos : int index of the start of the packet in the file (in bytes from beginning of the file) n_smp : int number of samples to read n_allchan : int number of channe...
def text_response(self, contents, code=200, headers={}): """shortcut to return simple plain/text messages in the response. :param contents: a string with the response contents :param code: the http status code :param headers: a dict with optional headers :returns: a :py:class:`f...
shortcut to return simple plain/text messages in the response. :param contents: a string with the response contents :param code: the http status code :param headers: a dict with optional headers :returns: a :py:class:`flask.Response` with the ``text/plain`` **Content-Type** header.
def insert_record_by_dict(self, table: str, valuedict: Dict[str, Any]) -> Optional[int]: """Inserts a record into database, table "table", using a dictionary containing field/value mappings. Returns the new PK (or None).""" if not value...
Inserts a record into database, table "table", using a dictionary containing field/value mappings. Returns the new PK (or None).
def version(): ''' Return imgadm version CLI Example: .. code-block:: bash salt '*' imgadm.version ''' ret = {} cmd = 'imgadm --version' res = __salt__['cmd.run'](cmd).splitlines() ret = res[0].split() return ret[-1]
Return imgadm version CLI Example: .. code-block:: bash salt '*' imgadm.version
def getRAM(self,ram=None): """This function grabs the atari RAM. ram MUST be a numpy array of uint8/int8. This can be initialized like so: ram = np.array(ram_size,dtype=uint8) Notice: It must be ram_size where ram_size can be retrieved via the getRAMSize function. If it is None, ...
This function grabs the atari RAM. ram MUST be a numpy array of uint8/int8. This can be initialized like so: ram = np.array(ram_size,dtype=uint8) Notice: It must be ram_size where ram_size can be retrieved via the getRAMSize function. If it is None, then this function will initialize it.
def post_shared_file(self, image_file=None, source_link=None, shake_id=None, title=None, description=None): """ Upload an image. TODO: Don't have a pro account to test (o...
Upload an image. TODO: Don't have a pro account to test (or even write) code to upload a shared filed to a particular shake. Args: image_file (str): path to an image (jpg/gif) on your computer. source_link (str): URL of a source (youtube/vine/etc.) s...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'exclude') and self.exclude is not None: _dict['exclude'] = self.exclude if hasattr(self, 'include') and self.include is not None: _dict['include'] = self.inclu...
Return a json dictionary representing this model.
def select_radio_button(self, key): """Helper to select a radio button with key. :param key: The key of the radio button. :type key: str """ key_index = list(self._parameter.options.keys()).index(key) radio_button = self.input_button_group.button(key_index) radio...
Helper to select a radio button with key. :param key: The key of the radio button. :type key: str
def WritePreprocessingInformation(self, knowledge_base): """Writes preprocessing information. Args: knowledge_base (KnowledgeBase): contains the preprocessing information. Raises: IOError: if the storage type does not support writing preprocess information or the storage file is clos...
Writes preprocessing information. Args: knowledge_base (KnowledgeBase): contains the preprocessing information. Raises: IOError: if the storage type does not support writing preprocess information or the storage file is closed or read-only. OSError: if the storage type does not sup...
def nextSunrise(jd, lat, lon): """ Returns the JD of the next sunrise. """ return swe.sweNextTransit(const.SUN, jd, lat, lon, 'RISE')
Returns the JD of the next sunrise.
def in_check(self, position, location=None): """ Finds if the king is in check or if both kings are touching. :type: position: Board :return: bool """ location = location or self.location for piece in position: if piece is not None and piece.color !=...
Finds if the king is in check or if both kings are touching. :type: position: Board :return: bool
def more_like_this(self, q, mltfl, handler='mlt', **kwargs): """ Finds and returns results similar to the provided query. Returns ``self.results_cls`` class object (defaults to ``pysolr.Results``) Requires Solr 1.3+. Usage:: similar = solr.more_like_this('...
Finds and returns results similar to the provided query. Returns ``self.results_cls`` class object (defaults to ``pysolr.Results``) Requires Solr 1.3+. Usage:: similar = solr.more_like_this('id:doc_234', 'text')
def message(self, level, *args): """ Format the message of the logger. You can rewrite this method to format your own message:: class MyLogger(Logger): def message(self, level, *args): msg = ' '.join(args) if level == 'error...
Format the message of the logger. You can rewrite this method to format your own message:: class MyLogger(Logger): def message(self, level, *args): msg = ' '.join(args) if level == 'error': return terminal.red(msg) ...
def order(self): """Produce a flatten list of the partition, ordered by classes """ return [x.val for theclass in self.classes for x in theclass.items]
Produce a flatten list of the partition, ordered by classes
def _might_have_parameter(fn_or_cls, arg_name): """Returns True if `arg_name` might be a valid parameter for `fn_or_cls`. Specifically, this means that `fn_or_cls` either has a parameter named `arg_name`, or has a `**kwargs` parameter. Args: fn_or_cls: The function or class to check. arg_name: The nam...
Returns True if `arg_name` might be a valid parameter for `fn_or_cls`. Specifically, this means that `fn_or_cls` either has a parameter named `arg_name`, or has a `**kwargs` parameter. Args: fn_or_cls: The function or class to check. arg_name: The name fo the parameter. Returns: Whether `arg_name...
def end(self): """End of the Glances server session.""" if not self.args.disable_autodiscover: self.autodiscover_client.close() self.server.end()
End of the Glances server session.
def message(self, text): """ Public message. """ self.client.publish(self.keys.external, '{}: {}'.format(self.resource, text))
Public message.
def get_upcoming_events(self, days_to_look_ahead): '''Returns the events from the calendar for the next days_to_look_ahead days.''' now = datetime.now(tz=self.timezone) # timezone? start_time = datetime(year=now.year, month=now.month, day=now.day, hour=now.hour, minute=now.minute, second=now.sec...
Returns the events from the calendar for the next days_to_look_ahead days.
def _get_mean(self, imt, mag, hypo_depth, rrup, d): """ Return mean value as defined in equation 3.5.1-1 page 148 """ # clip magnitude at 8.3 as per note at page 3-36 in table Table 3.3.2-6 # in "Technical Reports on National Seismic Hazard Maps for Japan" mag = min(mag, ...
Return mean value as defined in equation 3.5.1-1 page 148
def _hbf_handle_child_elements(self, obj, ntl): """ Indirect recursion through _gen_hbf_el """ # accumulate a list of the children names in ko, and # the a dictionary of tag to xml elements. # repetition of a tag means that it will map to a list of # xml eleme...
Indirect recursion through _gen_hbf_el
def create_dockwidget(self): """Add to parent QMainWindow as a dock widget""" # Creating dock widget dock = SpyderDockWidget(self.get_plugin_title(), self.main) # Set properties dock.setObjectName(self.__class__.__name__+"_dw") dock.setAllowedAreas(self.ALLOWED_AREAS) ...
Add to parent QMainWindow as a dock widget
def rename(script, label='blank', layer_num=None): """ Rename layer label Can be useful for outputting mlp files, as the output file names use the labels. Args: script: the mlx.FilterScript object or script filename to write the filter to. label (str): new label for the mes...
Rename layer label Can be useful for outputting mlp files, as the output file names use the labels. Args: script: the mlx.FilterScript object or script filename to write the filter to. label (str): new label for the mesh layer layer_num (int): layer number to rename. De...
def substitute(self, index, func_grp, bond_order=1): """ Substitute atom at index with a functional group. Args: index (int): Index of atom to substitute. func_grp: Substituent molecule. There are two options: 1. Providing an actual Molecule as the input...
Substitute atom at index with a functional group. Args: index (int): Index of atom to substitute. func_grp: Substituent molecule. There are two options: 1. Providing an actual Molecule as the input. The first atom must be a DummySpecie X, indicating t...
def yaml_filter(element, doc, tag=None, function=None, tags=None, strict_yaml=False): ''' Convenience function for parsing code blocks with YAML options This function is useful to create a filter that applies to code blocks that have specific classes. It is used as an argument of `...
Convenience function for parsing code blocks with YAML options This function is useful to create a filter that applies to code blocks that have specific classes. It is used as an argument of ``run_filter``, with two additional options: ``tag`` and ``function``. Using this is equivalent to having ...
def to_csv(self, dest:str)->None: "Save `self.to_df()` to a CSV file in `self.path`/`dest`." self.to_df().to_csv(self.path/dest, index=False)
Save `self.to_df()` to a CSV file in `self.path`/`dest`.
def create_api_method(restApiId, resourcePath, httpMethod, authorizationType, apiKeyRequired=False, requestParameters=None, requestModels=None, region=None, key=None, keyid=None, profile=None): ''' Creates API method for a resource in the given API CLI Example: ...
Creates API method for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_method restApiId resourcePath, httpMethod, authorizationType, \\ apiKeyRequired=False, requestParameters='{"name", "value"}', requestModels='{"content-type", "valu...