code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def getchild(self, name, parent): """ get a child by name """ #log.debug('searching parent (%s) for (%s)', Repr(parent), name) if name.startswith('@'): return parent.get_attribute(name[1:]) else: return parent.get_child(name)
get a child by name
def tgread_date(self): """Reads and converts Unix time (used by Telegram) into a Python datetime object. """ value = self.read_int() if value == 0: return None else: return datetime.fromtimestamp(value, tz=timezone.utc)
Reads and converts Unix time (used by Telegram) into a Python datetime object.
def gev_expval(xi, mu=0, sigma=1): """ Expected value of generalized extreme value distribution. """ return mu - (sigma / xi) + (sigma / xi) * flib.gamfun(1 - xi)
Expected value of generalized extreme value distribution.
def transformer_from_metric(metric, tol=None): """Returns the transformation matrix from the Mahalanobis matrix. Returns the transformation matrix from the Mahalanobis matrix, i.e. the matrix L such that metric=L.T.dot(L). Parameters ---------- metric : symmetric `np.ndarray`, shape=(d x d) T...
Returns the transformation matrix from the Mahalanobis matrix. Returns the transformation matrix from the Mahalanobis matrix, i.e. the matrix L such that metric=L.T.dot(L). Parameters ---------- metric : symmetric `np.ndarray`, shape=(d x d) The input metric, from which we want to extract a tran...
def add_arguments(self, parser): """ Add arguments to the command parser. Uses argparse syntax. See documentation at https://docs.python.org/3/library/argparse.html. """ parser.add_argument( '--start', '-s', default=0, type=int, ...
Add arguments to the command parser. Uses argparse syntax. See documentation at https://docs.python.org/3/library/argparse.html.
def make_router(*routings): """Return a WSGI application that dispatches requests to controllers """ routes = [] for routing in routings: methods, regex, app = routing[:3] if isinstance(methods, basestring): methods = (methods,) vars = routing[3] if len(routing) >= 4 else...
Return a WSGI application that dispatches requests to controllers
def get_grade_entries_for_gradebook_column_on_date(self, gradebook_column_id, from_, to): """Gets a ``GradeEntryList`` for the given gradebook column and effective during the entire given date range inclusive but not confined to the date range. arg: gradebook_column_id (osid.id.Id): a gradebook colu...
Gets a ``GradeEntryList`` for the given gradebook column and effective during the entire given date range inclusive but not confined to the date range. arg: gradebook_column_id (osid.id.Id): a gradebook column ``Id`` arg: from (osid.calendaring.DateTime): start of date range ...
def substr(requestContext, seriesList, start=0, stop=0): """ Takes one metric or a wildcard seriesList followed by 1 or 2 integers. Assume that the metric name is a list or array, with each element separated by dots. Prints n - length elements of the array (if only one integer n is passed) or n - m ...
Takes one metric or a wildcard seriesList followed by 1 or 2 integers. Assume that the metric name is a list or array, with each element separated by dots. Prints n - length elements of the array (if only one integer n is passed) or n - m elements of the array (if two integers n and m are passed). The l...
def raw_data(self, event): """Handles incoming raw sensor data :param event: Raw sentences incoming data """ self.log('Received raw data from bus', lvl=events) if not parse: return nmea_time = event.data[0] try: parsed_data = parse(event....
Handles incoming raw sensor data :param event: Raw sentences incoming data
def _prepare_request(self, url, method, headers, data): """Prepare HTTP request. :param str url: request URL. :param str method: request method. :param dict headers: request headers. :param object data: JSON-encodable object. :rtype: httpclient.HTTPRequest """ ...
Prepare HTTP request. :param str url: request URL. :param str method: request method. :param dict headers: request headers. :param object data: JSON-encodable object. :rtype: httpclient.HTTPRequest
def create(cls, pid_type=None, pid_value=None, object_type=None, object_uuid=None, status=None, **kwargs): """Create a new instance for the given type and pid. :param pid_type: Persistent identifier type. (Default: None). :param pid_value: Persistent identifier value. (Default: N...
Create a new instance for the given type and pid. :param pid_type: Persistent identifier type. (Default: None). :param pid_value: Persistent identifier value. (Default: None). :param status: Current PID status. (Default: :attr:`invenio_pidstore.models.PIDStatus.NEW`) :param ...
def _read_country_names(self, countries_file=None): """Read list of countries from specified country file or default file.""" if not countries_file: countries_file = os.path.join(os.path.dirname(__file__), self.COUNTRY_FILE_DEFAULT) with open(countries_file) as f: countri...
Read list of countries from specified country file or default file.
def _read_layers(self, layers, image_id): """ Reads the JSON metadata for specified layer / image id """ for layer in self.docker.history(image_id): layers.append(layer['Id'])
Reads the JSON metadata for specified layer / image id
def get_behave_args(self, argv=sys.argv): """ Get a list of those command line arguments specified with the management command that are meant as arguments for running behave. """ parser = BehaveArgsHelper().create_parser('manage.py', 'behave') args, unknown = parser.parse...
Get a list of those command line arguments specified with the management command that are meant as arguments for running behave.
def _config_params(base_config, assoc_files, region, out_file, items): """Add parameters based on configuration variables, associated files and genomic regions. """ params = [] dbsnp = assoc_files.get("dbsnp") if dbsnp: params += ["--dbsnp", dbsnp] cosmic = assoc_files.get("cosmic") ...
Add parameters based on configuration variables, associated files and genomic regions.
def get_foreign_key_base_declaration_sql(self, foreign_key): """ Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint of a field declaration to be used in statements like CREATE TABLE. :param foreign_key: The foreign key :type foreign_key: ForeignKeyCo...
Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint of a field declaration to be used in statements like CREATE TABLE. :param foreign_key: The foreign key :type foreign_key: ForeignKeyConstraint :rtype: str
def blksize(self): """The test blksize.""" self._blksize = self.lib.iperf_get_test_blksize(self._test) return self._blksize
The test blksize.
def enable_messaging(message_viewer, sender=dispatcher.Any): """Set up the dispatcher for messaging. :param message_viewer: A message viewer to show the message. :type message_viewer: MessageViewer :param sender: Sender of the message signal. Default to Any object. :type sender: object """ ...
Set up the dispatcher for messaging. :param message_viewer: A message viewer to show the message. :type message_viewer: MessageViewer :param sender: Sender of the message signal. Default to Any object. :type sender: object
def disconnect(self, callback=None, sender=None, senders=None, key=None, keys=None, weak=True): ''' *This method is a coroutine.* Disconnects the callback from the signal. If no arguments are supplied for ``sender``, ``senders``, ``key``, or ``keys`` -- the callback is completel...
*This method is a coroutine.* Disconnects the callback from the signal. If no arguments are supplied for ``sender``, ``senders``, ``key``, or ``keys`` -- the callback is completely disconnected. Otherwise, only the supplied ``senders`` and ``keys`` are disconnected for the callback. ...
def v_unique_name_defintions(ctx, stmt): """Make sure that all top-level definitions in a module are unique""" defs = [('typedef', 'TYPE_ALREADY_DEFINED', stmt.i_typedefs), ('grouping', 'GROUPING_ALREADY_DEFINED', stmt.i_groupings)] def f(s): for (keyword, errcode, dict) in defs: ...
Make sure that all top-level definitions in a module are unique
def _contextualise_connection(self, connection): """ Add a connection to the appcontext so it can be freed/unbound at a later time if an exception occured and it was not freed. Args: connection (ldap3.Connection): Connection to add to the appcontext """ ctx...
Add a connection to the appcontext so it can be freed/unbound at a later time if an exception occured and it was not freed. Args: connection (ldap3.Connection): Connection to add to the appcontext
def list_row_sparse_data(self, row_id): """Returns copies of the 'row_sparse' parameter on all contexts, in the same order as creation. The copy only retains rows whose ids occur in provided row ids. The parameter must have been initialized before. Parameters ---------- ...
Returns copies of the 'row_sparse' parameter on all contexts, in the same order as creation. The copy only retains rows whose ids occur in provided row ids. The parameter must have been initialized before. Parameters ---------- row_id: NDArray Row ids to retain for t...
def load_itasser_folder(self, ident, itasser_folder, organize=False, outdir=None, organize_name=None, set_as_representative=False, representative_chain='X', force_rerun=False): """Load the results folder from an I-TASSER run (local, not from the website) and copy relevant files over ...
Load the results folder from an I-TASSER run (local, not from the website) and copy relevant files over to the protein structures directory. Args: ident (str): I-TASSER ID itasser_folder (str): Path to results folder organize (bool): If select files from modeling sho...
def parse_doc_str(text=None, is_untabbed=True, is_stripped=True, tab=None, split_character="::"): """ Returns a str of the parsed doc for example the following would return 'a:A\nb:B' :: a:A b:B :param text: str of the text to parse, by ...
Returns a str of the parsed doc for example the following would return 'a:A\nb:B' :: a:A b:B :param text: str of the text to parse, by default uses calling function doc :param is_untabbed: bool if True will untab the text :param is_stripped: ...
def _autorestart_components(self, bundle): # type: (Bundle) -> None """ Restart the components of the given bundle :param bundle: A Bundle object """ with self.__instances_lock: instances = self.__auto_restart.get(bundle) if not instances: ...
Restart the components of the given bundle :param bundle: A Bundle object
def _parse_current_member(self, previous_rank, values): """ Parses the column texts of a member row into a member dictionary. Parameters ---------- previous_rank: :class:`dict`[int, str] The last rank present in the rows. values: tuple[:class:`str`] ...
Parses the column texts of a member row into a member dictionary. Parameters ---------- previous_rank: :class:`dict`[int, str] The last rank present in the rows. values: tuple[:class:`str`] A list of row contents.
def snapshot(self): """Return a dictionary of current slots by reference.""" return dict((n, self._slots[n].get()) for n in self._slots.keys())
Return a dictionary of current slots by reference.
def get_historical_data(self, uuid, start, end, average_by=0): """ Get the data from one device for a specified time range. .. note:: Can fetch a maximum of 42 days of data. To speed up query processing, you can use a combination of average factor multiple of...
Get the data from one device for a specified time range. .. note:: Can fetch a maximum of 42 days of data. To speed up query processing, you can use a combination of average factor multiple of 1H in seconds (e.g. 3600), and o'clock start and end times :param uuid: I...
def calc_glmelt_in_v1(self): """Calculate melting from glaciers which are actually not covered by a snow layer and add it to the water release of the snow module. Required control parameters: |NmbZones| |ZoneType| |GMelt| Required state sequence: |SP| Required flux sequenc...
Calculate melting from glaciers which are actually not covered by a snow layer and add it to the water release of the snow module. Required control parameters: |NmbZones| |ZoneType| |GMelt| Required state sequence: |SP| Required flux sequence: |TC| Calculated fluxes...
def split_in_blocks(sequence, hint, weight=lambda item: 1, key=nokey): """ Split the `sequence` in a number of WeightedSequences close to `hint`. :param sequence: a finite sequence of items :param hint: an integer suggesting the number of subsequences to generate :param weight: a function returning...
Split the `sequence` in a number of WeightedSequences close to `hint`. :param sequence: a finite sequence of items :param hint: an integer suggesting the number of subsequences to generate :param weight: a function returning the weigth of a given item :param key: a function returning the key of a given...
def check_time(value): """check that it's a value like 03:45 or 1:1""" try: h, m = value.split(':') h = int(h) m = int(m) if h >= 24 or h < 0: raise ValueError if m >= 60 or m < 0: raise ValueError except ValueError: raise TimeDefinitio...
check that it's a value like 03:45 or 1:1
def _post(self, url_suffix, data, content_type=ContentType.json): """ Send POST request to API at url_suffix with post_data. Raises error if x-total-pages is contained in the response. :param url_suffix: str URL path we are sending a POST to :param data: object data we are sendin...
Send POST request to API at url_suffix with post_data. Raises error if x-total-pages is contained in the response. :param url_suffix: str URL path we are sending a POST to :param data: object data we are sending :param content_type: str from ContentType that determines how we format the ...
def keystroke_toggled(self, settings, key, user_data): """If the gconf var scroll_keystroke be changed, this method will be called and will set the scroll_on_keystroke in all terminals open. """ for i in self.guake.notebook_manager.iter_terminals(): i.set_scroll_on_ke...
If the gconf var scroll_keystroke be changed, this method will be called and will set the scroll_on_keystroke in all terminals open.
def mol(self): """ Return record in MOL format """ if self._mol is None: apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=false&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) self._mol = t...
Return record in MOL format
def resample(self, rate): """Resample this `StateVector` to a new rate Because of the nature of a state-vector, downsampling is done by taking the logical 'and' of all original samples in each new sampling interval, while upsampling is achieved by repeating samples. Par...
Resample this `StateVector` to a new rate Because of the nature of a state-vector, downsampling is done by taking the logical 'and' of all original samples in each new sampling interval, while upsampling is achieved by repeating samples. Parameters ---------- ra...
def ExpandArg(self, **_): """Expand the args as a section.parameter from the config.""" # This function is called when we see close ) and the stack depth has to # exactly match the number of (. if len(self.stack) <= 1: raise lexer.ParseError( "Unbalanced parenthesis: Can not expand '%s'"...
Expand the args as a section.parameter from the config.
def popular(category=None, sortOption = "title"): """Return a search result containing torrents appearing on the KAT home page. Can be categorized. Cannot be sorted or contain multiple pages""" s = Search() s.popular(category, sortOption) return s
Return a search result containing torrents appearing on the KAT home page. Can be categorized. Cannot be sorted or contain multiple pages
def subscribe(self, topic, callback, qos): """Subscribe to an MQTT topic.""" if topic in self.topics: return def _message_callback(mqttc, userdata, msg): """Callback added to callback list for received message.""" callback(msg.topic, msg.payload.decode('utf-8...
Subscribe to an MQTT topic.
def maskedConvolve(arr, kernel, mask, mode='reflect'): ''' same as scipy.ndimage.convolve but is only executed on mask==True ... which should speed up everything ''' arr2 = extendArrayForConvolution(arr, kernel.shape, modex=mode, modey=mode) print(arr2.shape) out = np.zeros_like(arr) ...
same as scipy.ndimage.convolve but is only executed on mask==True ... which should speed up everything
def remove_none_value(data): """remove item from dict if value is None. return new dict. """ return dict((k, v) for k, v in data.items() if v is not None)
remove item from dict if value is None. return new dict.
def get_id(page): """Extract the id from a page. Args: page: a string Returns: an integer """ start_pos = page.find("<id>") end_pos = page.find("</id>") assert start_pos != -1 assert end_pos != -1 start_pos += len("<id>") return int(page[start_pos:end_pos])
Extract the id from a page. Args: page: a string Returns: an integer
def scale_transform(t, scale): """ Apply a scale to a transform :param t: The transform [[x, y, z], [x, y, z, w]] to be scaled OR the position [x, y, z] to be scaled :param scale: the scale of type float OR the scale [scale_x, scale_y, scale_z] :return: The scaled """ if isinstance(scale, fl...
Apply a scale to a transform :param t: The transform [[x, y, z], [x, y, z, w]] to be scaled OR the position [x, y, z] to be scaled :param scale: the scale of type float OR the scale [scale_x, scale_y, scale_z] :return: The scaled
def delete(self, table): """Deletes record in table >>> yql.delete('yql.storage').where(['name','=','store://YEl70PraLLMSMuYAauqNc7']) """ self._table = table self._limit = None self._query = "DELETE FROM {0}".format(self._table) return self
Deletes record in table >>> yql.delete('yql.storage').where(['name','=','store://YEl70PraLLMSMuYAauqNc7'])
def document_iter(self, context): """ Iterates over all the elements in an iterparse context (here: <document> elements) and yields an URMLDocumentGraph instance for each of them. For efficiency, the elements are removed from the DOM / main memory after processing them. ...
Iterates over all the elements in an iterparse context (here: <document> elements) and yields an URMLDocumentGraph instance for each of them. For efficiency, the elements are removed from the DOM / main memory after processing them. If ``self.debug`` is set to ``True`` (in the ``__init_...
def create_from_yamlfile(cls, yamlfile): """Create a Castro data object from a yaml file contains the likelihood data.""" data = load_yaml(yamlfile) nebins = len(data) emin = np.array([data[i]['emin'] for i in range(nebins)]) emax = np.array([data[i]['emax'] for i in rang...
Create a Castro data object from a yaml file contains the likelihood data.
def daily(target_coll, source_coll, interp_days=32, interp_method='linear'): """Generate daily ETa collection from ETo and ETf collections Parameters ---------- target_coll : ee.ImageCollection Source images will be interpolated to each target image time_start. Target images should have...
Generate daily ETa collection from ETo and ETf collections Parameters ---------- target_coll : ee.ImageCollection Source images will be interpolated to each target image time_start. Target images should have a daily time step. This will typically be the reference ET (ETr) collectio...
def array2tabledef(data, table_type='binary', write_bitcols=False): """ Similar to descr2tabledef but if there are object columns a type and max length will be extracted and used for the tabledef """ is_ascii = (table_type == 'ascii') if data.dtype.fields is None: raise ValueError("data...
Similar to descr2tabledef but if there are object columns a type and max length will be extracted and used for the tabledef
def get_breadcrumbs(url, request=None): """ Given a url returns a list of breadcrumbs, which are each a tuple of (name, url). """ from wave.reverse import preserve_builtin_query_params from wave.settings import api_settings from wave.views import APIView view_name_func = api_settings.VI...
Given a url returns a list of breadcrumbs, which are each a tuple of (name, url).
def kill(self, sig): '''Sends a Unix signal to the subprocess. Use constants from the :mod:`signal` module to specify which signal. ''' if sys.platform == 'win32': if sig in [signal.SIGINT, signal.CTRL_C_EVENT]: sig = signal.CTRL_C_EVENT elif sig ...
Sends a Unix signal to the subprocess. Use constants from the :mod:`signal` module to specify which signal.
def angle2vecs(vec1, vec2): """angle between two vectors""" # vector a * vector b = |a|*|b|* cos(angle between vector a and vector b) dot = np.dot(vec1, vec2) vec1_modulus = np.sqrt(np.multiply(vec1, vec1).sum()) vec2_modulus = np.sqrt(np.multiply(vec2, vec2).sum()) if (vec1_modulus * vec2_modul...
angle between two vectors
def getUniqueFilename(dir=None, base=None): """ DESCRP: Generate a filename in the directory <dir> which is unique (i.e. not in use at the moment) PARAMS: dir -- the directory to look in. If None, use CWD base -- use this as the base name for the filename RETURN: string -- the fil...
DESCRP: Generate a filename in the directory <dir> which is unique (i.e. not in use at the moment) PARAMS: dir -- the directory to look in. If None, use CWD base -- use this as the base name for the filename RETURN: string -- the filename generated
def to_buffer(f): """ Decorator converting all strings and iterators/iterables into Buffers. """ @functools.wraps(f) def wrap(*args, **kwargs): iterator = kwargs.get('iterator', args[0]) if not isinstance(iterator, Buffer): iterator = Buffer(iterator) return f(ite...
Decorator converting all strings and iterators/iterables into Buffers.
def makedirs(directory): """ Resursively create a named directory. """ parent = os.path.dirname(os.path.abspath(directory)) if not os.path.exists(parent): makedirs(parent) os.mkdir(directory)
Resursively create a named directory.
def debug(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None: """ Logs a message to the Pulumi CLI's debug channel, associating it with a resource and stream_id if provided. :param str msg: The message to send to the Pulumi CLI. :param Optional[Resource] resou...
Logs a message to the Pulumi CLI's debug channel, associating it with a resource and stream_id if provided. :param str msg: The message to send to the Pulumi CLI. :param Optional[Resource] resource: If provided, associate this message with the given resource in the Pulumi CLI. :param Optional[int] stre...
def plot_pseudosection_type2(self, mid, **kwargs): """Create a pseudosection plot of type 2. For a given measurement data set, create plots that graphically show the data in a 2D color plot. Hereby, x and y coordinates in the plot are determined by the current dipole (x-axis) and voltag...
Create a pseudosection plot of type 2. For a given measurement data set, create plots that graphically show the data in a 2D color plot. Hereby, x and y coordinates in the plot are determined by the current dipole (x-axis) and voltage dipole (y-axis) of the corresponding measurement con...
def StartFlowAndWait(client_id, token=None, timeout=DEFAULT_TIMEOUT, **flow_args): """Runs a flow and waits for it to finish. Args: client_id: The client id of the client to run on. token: The datastore access token. timeout: How long to wa...
Runs a flow and waits for it to finish. Args: client_id: The client id of the client to run on. token: The datastore access token. timeout: How long to wait for a flow to complete, maximum. **flow_args: Pass through to flow. Returns: The urn of the flow that was run.
def configure_health(graph): """ Configure the health endpoint. :returns: a handle to the `Health` object, allowing other components to manipulate health state. """ ns = Namespace( subject=Health, ) include_build_info = strtobool(graph.config.health_convention.include...
Configure the health endpoint. :returns: a handle to the `Health` object, allowing other components to manipulate health state.
def ovsdb_server_port(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ovsdb_server = ET.SubElement(config, "ovsdb-server", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(ovsdb_server, "name") name_key.text = kwargs.pop('na...
Auto Generated Code
def verify_fft_options(opt,parser): """Parses the FFT options and verifies that they are reasonable. Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes. parser : object OptionParser instance. ...
Parses the FFT options and verifies that they are reasonable. Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes. parser : object OptionParser instance.
def get_huc8(prefix): """ Return all HUC8s matching the given prefix (e.g. 1801) or basin name (e.g. Klamath) """ if not prefix.isdigit(): # Look up hucs by name name = prefix prefix = None for row in hucs: if row.basin.lower() == name.lower(): ...
Return all HUC8s matching the given prefix (e.g. 1801) or basin name (e.g. Klamath)
def dcdict2rdfpy(dc_dict): """Convert a DC dictionary into an RDF Python object.""" ark_prefix = 'ark: ark:' uri = URIRef('') # Create the RDF Python object. rdf_py = ConjunctiveGraph() # Set DC namespace definition. DC = Namespace('http://purl.org/dc/elements/1.1/') # Get the ark for th...
Convert a DC dictionary into an RDF Python object.
def aggregate_data(self, start, end, aggregation, keys=[], tags=[], attrs={}, rollup=None, period=None, interpolationf=None, interpolation_period=None, tz=None, limit=1000): """Read data from multiple series according to a filter and apply a function across ...
Read data from multiple series according to a filter and apply a function across all the returned series to put the datapoints together into one aggregrate series. See the :meth:`list_series` method for a description of how the filter criteria are applied, and the :meth:`read_data` meth...
def create_dbinstance_read_replica(self, id, source_id, instance_class=None, port=3306, availability_zone=None, auto_minor_version_upgrade=None): """ ...
Create a new DBInstance Read Replica. :type id: str :param id: Unique identifier for the new instance. Must contain 1-63 alphanumeric characters. First character must be a letter. May not end with a hyphen or contain two consecutive hyphens ...
def del_role(self, role): """ deletes a group """ target = AuthGroup.objects(role=role, creator=self.client).first() if target: target.delete() return True else: return False
deletes a group
def propagate_averages(self, n, tv, bv, var, outgroup=False): """ This function implements the propagation of the means, variance, and covariances along a branch. It operates both towards the root and tips. Parameters ---------- n : (node) the branch...
This function implements the propagation of the means, variance, and covariances along a branch. It operates both towards the root and tips. Parameters ---------- n : (node) the branch connecting this node to its parent is used for propagation t...
def bits_to_bytes(bits): """Convert the bit list into bytes. (Assumes bits is a list whose length is a multiple of 8) """ if len(bits) % 8 != 0: raise Exception("num bits must be multiple of 8") res = "" for x in six.moves.range(0, len(bits), 8): byte_bits = bits[x:x+8] ...
Convert the bit list into bytes. (Assumes bits is a list whose length is a multiple of 8)
def hook_inform(self, inform_name, callback): """Hookup a function to be called when an inform is received. Useful for interface-changed and sensor-status informs. Parameters ---------- inform_name : str The name of the inform. callback : function ...
Hookup a function to be called when an inform is received. Useful for interface-changed and sensor-status informs. Parameters ---------- inform_name : str The name of the inform. callback : function The function to be called.
def _call(self, method, **kwargs): """ Вызов метода API """ kwargs.update(dict( partnerid=self.partner_id, partnerkey=self.partner_key, method=method, )) url = options.ENDPOINT_URL + '?' + parse.urlencode(kwargs) try: raw_j...
Вызов метода API
def get_root_directory(self, timestamp=None): """ A helper method that supplies the root directory name given a timestamp. """ if timestamp is None: timestamp = self.timestamp if self.timestamp_format is not None: root_name = (time.strftime(self.timestamp_for...
A helper method that supplies the root directory name given a timestamp.
def default(self): """Return default contents""" import json import ambry.bundle.default_files as df import os path = os.path.join(os.path.dirname(df.__file__), 'notebook.ipynb') if six.PY2: with open(path, 'rb') as f: content_str = f.read()...
Return default contents
def getUpdatedFields(self, cascadeObjects=False): ''' getUpdatedFields - See changed fields. @param cascadeObjects <bool> default False, if True will check if any foreign linked objects themselves have unsaved changes (recursively). Otherwise, will just check if the pk has changed. @return - a dicti...
getUpdatedFields - See changed fields. @param cascadeObjects <bool> default False, if True will check if any foreign linked objects themselves have unsaved changes (recursively). Otherwise, will just check if the pk has changed. @return - a dictionary of fieldName : tuple(old, new). fieldName may be ...
def _add_stats_box(h1: Histogram1D, ax: Axes, stats: Union[str, bool] = "all"): """Insert a small legend-like box with statistical information. Parameters ---------- stats : "all" | "total" | True What info to display Note ---- Very basic implementation. """ # place a text...
Insert a small legend-like box with statistical information. Parameters ---------- stats : "all" | "total" | True What info to display Note ---- Very basic implementation.
def extract(self, node, condition, skip=0): """ Extract a single node that matches the provided condition, otherwise a TypeError is raised. An optional skip parameter can be provided to specify how many matching nodes are to be skipped over. """ for child in sel...
Extract a single node that matches the provided condition, otherwise a TypeError is raised. An optional skip parameter can be provided to specify how many matching nodes are to be skipped over.
def _user_mdata(mdata_list=None, mdata_get=None): ''' User Metadata ''' grains = {} if not mdata_list: mdata_list = salt.utils.path.which('mdata-list') if not mdata_get: mdata_get = salt.utils.path.which('mdata-get') if not mdata_list or not mdata_get: return grain...
User Metadata
def get(self, tag, nth=1): """Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if th...
Return n-th value for tag. :param tag: FIX field tag number. :param nth: Index of tag if repeating, first is 1. :return: None if nothing found, otherwise value matching tag. Defaults to returning the first matching value of 'tag', but if the 'nth' parameter is overridden, can g...
def retry_with_delay(f, delay=60): """ Retry the wrapped requests.request function in case of ConnectionError. Optionally limit the number of retries or set the delay between retries. """ @wraps(f) def inner(*args, **kwargs): kwargs['timeout'] = 5 remaining = get_retries() + 1 ...
Retry the wrapped requests.request function in case of ConnectionError. Optionally limit the number of retries or set the delay between retries.
def institutes(): """Display a list of all user institutes.""" institute_objs = user_institutes(store, current_user) institutes = [] for ins_obj in institute_objs: sanger_recipients = [] for user_mail in ins_obj.get('sanger_recipients',[]): user_obj = store.user(user_mail) ...
Display a list of all user institutes.
def legacy(**kwargs): """ Compute options for using the PHOEBE 1.0 legacy backend (must be installed). Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_compute` Please see :func:`phoebe.backend.backends.legacy` for a list of sources to ...
Compute options for using the PHOEBE 1.0 legacy backend (must be installed). Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_compute` Please see :func:`phoebe.backend.backends.legacy` for a list of sources to cite when using this backend. ...
def read(fname, merge_duplicate_shots=False, encoding='windows-1252'): """Read a PocketTopo .TXT file and produce a `TxtFile` object which represents it""" return PocketTopoTxtParser(fname, merge_duplicate_shots, encoding).parse()
Read a PocketTopo .TXT file and produce a `TxtFile` object which represents it
def __extend_uri(prefixes, short): """ Extend a prefixed uri with the help of a specific dictionary of prefixes :param prefixes: Dictionary of prefixes :param short: Prefixed uri to be extended :return: """ for prefix in prefixes: if short.startswith(prefix): return short...
Extend a prefixed uri with the help of a specific dictionary of prefixes :param prefixes: Dictionary of prefixes :param short: Prefixed uri to be extended :return:
def as_tuple(self): """ :return: Rows of the table. :rtype: list of |namedtuple| :Sample Code: .. code:: python from tabledata import TableData records = TableData( "sample", ["a", "b"], ...
:return: Rows of the table. :rtype: list of |namedtuple| :Sample Code: .. code:: python from tabledata import TableData records = TableData( "sample", ["a", "b"], [[1, 2], [3.3, 4.4]] ...
def get_weakref(func): """Get a weak reference to bound or unbound `func`. If `func` is unbound (i.e. has no __self__ attr) get a weakref.ref, otherwise get a wrapper that simulates weakref.ref. """ if func is None: raise ValueError if not hasattr(func, '__self__'): return weakr...
Get a weak reference to bound or unbound `func`. If `func` is unbound (i.e. has no __self__ attr) get a weakref.ref, otherwise get a wrapper that simulates weakref.ref.
def export(self, metadata, **kwargs): """ Export metadata as YAML. This uses yaml.SafeDumper by default. """ kwargs.setdefault('Dumper', SafeDumper) kwargs.setdefault('default_flow_style', False) kwargs.setdefault('allow_unicode', True) metadata = yaml.dump(metad...
Export metadata as YAML. This uses yaml.SafeDumper by default.
def start(self): """Starts the `PrawOAuth2Server` server. It will open the default web browser and it will take you to Reddit's authorization page, asking you to authorize your Reddit account(or account of the bot's) with your app(or bot script). Once authorized successfully, it will ...
Starts the `PrawOAuth2Server` server. It will open the default web browser and it will take you to Reddit's authorization page, asking you to authorize your Reddit account(or account of the bot's) with your app(or bot script). Once authorized successfully, it will show `successful` messa...
def check_message(keywords, message): """Checks an exception for given keywords and raises a new ``ActionError`` with the desired message if the keywords are found. This allows selective control over API error messages. """ exc_type, exc_value, exc_traceback = sys.exc_info() if set(str(exc_value...
Checks an exception for given keywords and raises a new ``ActionError`` with the desired message if the keywords are found. This allows selective control over API error messages.
def init(scope): """ Copy all values of scope into the class SinonGlobals Args: scope (eg. locals() or globals()) Return: SinonGlobals instance """ class SinonGlobals(object): #pylint: disable=too-few-public-methods """ A fully empty class External can pus...
Copy all values of scope into the class SinonGlobals Args: scope (eg. locals() or globals()) Return: SinonGlobals instance
def post(cond): """ Add a postcondition check to the annotated method. The condition is passed the return value of the annotated method. """ source = inspect.getsource(cond).strip() def inner(f): if enabled: # deal with the real function, not a wrapper f = geta...
Add a postcondition check to the annotated method. The condition is passed the return value of the annotated method.
def initialize_page(title, style, script, header=None): """ A function that returns a markup.py page object with the required html header. """ page = markup.page(mode="strict_html") page._escape = False page.init(title=title, css=style, script=script, header=header) return page
A function that returns a markup.py page object with the required html header.
def end_position(variant_obj): """Calculate end position for a variant.""" alt_bases = len(variant_obj['alternative']) num_bases = max(len(variant_obj['reference']), alt_bases) return variant_obj['position'] + (num_bases - 1)
Calculate end position for a variant.
def quantile(arg, quantile, interpolation='linear'): """ Return value at the given quantile, a la numpy.percentile. Parameters ---------- quantile : float/int or array-like 0 <= quantile <= 1, the quantile(s) to compute interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'...
Return value at the given quantile, a la numpy.percentile. Parameters ---------- quantile : float/int or array-like 0 <= quantile <= 1, the quantile(s) to compute interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} This optional parameter specifies the interpolation me...
def hash(pii_csv, keys, schema, clk_json, quiet, no_header, check_header, validate): """Process data to create CLKs Given a file containing CSV data as PII_CSV, and a JSON document defining the expected schema, verify the schema, then hash the data to create CLKs writing them as JSON to CLK_JSON. Note ...
Process data to create CLKs Given a file containing CSV data as PII_CSV, and a JSON document defining the expected schema, verify the schema, then hash the data to create CLKs writing them as JSON to CLK_JSON. Note the CSV file should contain a header row - however this row is not used by this tool...
def get_rich_menu(self, rich_menu_id, timeout=None): """Call get rich menu API. https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu :param str rich_menu_id: ID of the rich menu :param timeout: (optional) How long to wait for the server to send data bef...
Call get rich menu API. https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu :param str rich_menu_id: ID of the rich menu :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a (connect timeout, re...
def set_level(self, level): """ Sets :attr:loglevel to @level @level: #str one or several :attr:levels """ if not level: return None self.levelmap = set() for char in level: self.levelmap = self.levelmap.union(self.levels[char]) self.l...
Sets :attr:loglevel to @level @level: #str one or several :attr:levels
def get_range_response(self, range_start, range_end, sort_order=None, sort_target='key', **kwargs): """Get a range of keys.""" range_request = self._build_get_range_request( key=range_start, range_end=range_end, sort_order=sort_order, ...
Get a range of keys.
def get_tensors_by_names(names): """ Get a list of tensors in the default graph by a list of names. Args: names (list): """ ret = [] G = tfv1.get_default_graph() for n in names: opn, varn = get_op_tensor_name(n) ret.append(G.get_tensor_by_name(varn)) return ret
Get a list of tensors in the default graph by a list of names. Args: names (list):
def get_catalog(mid): """Return catalog entry for the specified ID. `mid` should be either a UUID or a 32 digit hex number. """ if isinstance(mid, _uuid.UUID): mid = mid.hex return _get_catalog(mid)
Return catalog entry for the specified ID. `mid` should be either a UUID or a 32 digit hex number.
def get_file(self, name, save_to, add_to_cache=True, force_refresh=False, _lock_exclusive=False): """Retrieves file identified by ``name``. The file is saved as ``save_to``. If ``add_to_cache`` is ``True``, the file is added to the local store. If ``force_refresh`` is ...
Retrieves file identified by ``name``. The file is saved as ``save_to``. If ``add_to_cache`` is ``True``, the file is added to the local store. If ``force_refresh`` is ``True``, local cache is not examined if a remote store is configured. If a remote store is con...
def download_artist_by_search(self, artist_name): """Download a artist's top50 songs by his/her name. :params artist_name: artist name. """ try: artist = self.crawler.search_artist(artist_name, self.quiet) except RequestException as exception: click.echo...
Download a artist's top50 songs by his/her name. :params artist_name: artist name.
def _is_cache_dir_appropriate(cache_dir, cache_file): """ Determine if a directory is acceptable for building. A directory is suitable if any of the following are true: - it doesn't exist - it is empty - it contains an existing build cache """ if os.path.exists(cache_dir): ...
Determine if a directory is acceptable for building. A directory is suitable if any of the following are true: - it doesn't exist - it is empty - it contains an existing build cache
def build_from_entities(self, tax_benefit_system, input_dict): """ Build a simulation from a Python dict ``input_dict`` fully specifying entities. Examples: >>> simulation_builder.build_from_entities({ 'persons': {'Javier': { 'salary': {'2018-11': 2000}}}, ...
Build a simulation from a Python dict ``input_dict`` fully specifying entities. Examples: >>> simulation_builder.build_from_entities({ 'persons': {'Javier': { 'salary': {'2018-11': 2000}}}, 'households': {'household': {'parents': ['Javier']}} })