code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def fake2db_mysql_initiator(self, host, port, password, username, number_of_rows, name=None, custom=None): '''Main handler for the operation ''' rows = number_of_rows if name: cursor, conn = self.database_caller_creator(host, port, password, username, name) else: ...
Main handler for the operation
def save_config( self, cmd="save configuration primary", confirm=False, confirm_response="" ): """Saves configuration.""" return super(ExtremeExosBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Saves configuration.
def view_plugins(category=None): """ return a view of the loaded plugin names and descriptions Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, ...
return a view of the loaded plugin names and descriptions Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {}} >>> c...
def publish_message(self, exchange, routing_key, properties, body, no_serialization=False, no_encoding=False, channel=None, conn...
Publish a message to RabbitMQ on the same channel the original message was received on. By default, if you pass a non-string object to the body and the properties have a supported ``content_type`` set, the body will be auto-serialized in the specified ``content_type``. If the p...
def set_editor_doc(self, doc, force_refresh=False): """ Use the help plugin to show docstring dictionary computed with introspection plugin from the Editor plugin """ if (self.locked and not force_refresh): return self.switch_to_editor_source() ...
Use the help plugin to show docstring dictionary computed with introspection plugin from the Editor plugin
def is_valid_ip_pattern(ip): """Check whether a string matches the outline of an IPv4 address, allowing "*" as a wildcard""" ip = ip.replace('*', '1') try: socket.inet_aton(ip) return True except socket.error: # Not a valid IPv4 address pattern return False
Check whether a string matches the outline of an IPv4 address, allowing "*" as a wildcard
def draw(self): """ Renders ROC-AUC plot. Called internally by score, possibly more than once Returns ------- ax : the axis with the plotted figure """ colors = self.colors[0:len(self.classes_)] n_classes = len(colors) # If it's a binary ...
Renders ROC-AUC plot. Called internally by score, possibly more than once Returns ------- ax : the axis with the plotted figure
def fmt_number(p): """Format a number. It will be printed as a fraction if the denominator isn't too big and as a decimal otherwise. """ formatted = '{:n}'.format(p) if not config.PRINT_FRACTIONS: return formatted fraction = Fraction(p) nice = fraction.limit_denominator(128) ...
Format a number. It will be printed as a fraction if the denominator isn't too big and as a decimal otherwise.
def clear_callbacks(obj): """Remove all callbacks from an object.""" callbacks = obj._callbacks if isinstance(callbacks, dllist): # Help the garbage collector by clearing all links. callbacks.clear() obj._callbacks = None
Remove all callbacks from an object.
def get_option(self, key, subkey, in_path_none=False): """Get the current value of the option. :param str key: First identifier of the option. :param str subkey: Second identifier of the option. :param bool in_path_none: Allows for ``in_path`` values of :data:`None` to be re...
Get the current value of the option. :param str key: First identifier of the option. :param str subkey: Second identifier of the option. :param bool in_path_none: Allows for ``in_path`` values of :data:`None` to be retrieved. :return: Current value of the option (type varie...
def save_hdf(self,filename,path=''): """Save to .h5 file. """ self.orbpop_long.save_hdf(filename,'{}/long'.format(path)) self.orbpop_short.save_hdf(filename,'{}/short'.format(path))
Save to .h5 file.
def entity_delete(args): """ Delete entity in a workspace. """ msg = "WARNING: this will delete {0} {1} in {2}/{3}".format( args.entity_type, args.entity, args.project, args.workspace) if not (args.yes or _confirm_prompt(msg)): return json_body=[{"entityType": args.entity_type, ...
Delete entity in a workspace.
def t_heredocvar_ENCAPSED_AND_WHITESPACE(t): r'( [^\n\\${] | \\. | \$(?![A-Za-z_{]) | \{(?!\$) )+\n? | \\?\n' t.lexer.lineno += t.value.count("\n") t.lexer.pop_state() return t
r'( [^\n\\${] | \\. | \$(?![A-Za-z_{]) | \{(?!\$) )+\n? | \\?\n
def append_to_arg_count(self, data): """ Add digit to the input argument. :param data: the typed digit as string """ assert data in '-0123456789' current = self._arg if data == '-': assert current is None or current == '-' result = data ...
Add digit to the input argument. :param data: the typed digit as string
def validate(self): """ Validates the state of this XBlock. Subclasses should override validate_field_data() to validate fields and override this only for validation not related to this block's field values. """ validation = super(StudioEditableXBlockMixin, self).validat...
Validates the state of this XBlock. Subclasses should override validate_field_data() to validate fields and override this only for validation not related to this block's field values.
def flash(self, duration=0.0): """ Flash a group. :param duration: How quickly to flash (in seconds). """ for _ in range(2): self.on = not self.on time.sleep(duration)
Flash a group. :param duration: How quickly to flash (in seconds).
def fetch_post_data(self): ''' fetch post accessed data. post_data, and ext_dic. ''' post_data = {} ext_dic = {} for key in self.request.arguments: if key.startswith('def_'): ext_dic[key] = self.get_argument(key) else: ...
fetch post accessed data. post_data, and ext_dic.
def process_entry(self, defect_entry): """ Process a given Defect entry with qualifiers given from initialization of class. Order of processing is: 1) perform all possible defect corrections with information given 2) consider delocalization analyses based on qualifier met...
Process a given Defect entry with qualifiers given from initialization of class. Order of processing is: 1) perform all possible defect corrections with information given 2) consider delocalization analyses based on qualifier metrics given initialization of class. If delocali...
def hashdata(self, subject): _data = bytearray() if isinstance(subject, six.string_types): subject = subject.encode('charmap') """ All signatures are formed by producing a hash over the signature data, and then using the resulting hash in the signature algorithm. ...
All signatures are formed by producing a hash over the signature data, and then using the resulting hash in the signature algorithm.
def local_filename( self, url=None, filename=None, decompress=False): """ What local filename will we use within the cache directory for the given URL/filename/decompress options. """ return common.build_local_filename(url, filename...
What local filename will we use within the cache directory for the given URL/filename/decompress options.
def correspondent_id(self): """ :returns: The id assigned to the correspondent of this message. """ try: return int(self._thread_element.attrib['data-personid']) except (ValueError, KeyError): try: return int(self.correspondent_profile.id) ...
:returns: The id assigned to the correspondent of this message.
def hourly_solar_radiation(self): """Three data collections containing hourly direct normal, diffuse horizontal, and global horizontal radiation. """ dir_norm, diff_horiz, glob_horiz = \ self._sky_condition.radiation_values(self._location) dir_norm_data = self._get_d...
Three data collections containing hourly direct normal, diffuse horizontal, and global horizontal radiation.
def write_gtiff_file(f_name, n_rows, n_cols, data, geotransform, srs, nodata_value, gdal_type=GDT_Float32): """Output Raster to GeoTiff format file. Args: f_name: output gtiff file name. n_rows: Row count. n_cols: Col count. data:...
Output Raster to GeoTiff format file. Args: f_name: output gtiff file name. n_rows: Row count. n_cols: Col count. data: 2D array data. geotransform: geographic transformation. srs: coordinate system. nodata_value: nodata value....
def is_valid_catalog(catalog, validator=None): """Valida que un archivo `data.json` cumpla con el schema definido. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la estructura definida en el schema. Args: catalog ...
Valida que un archivo `data.json` cumpla con el schema definido. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la estructura definida en el schema. Args: catalog (str o dict): Catálogo (dict, JSON o XLSX) a ser valid...
def _fix_next_url(next_url): """Remove max=null parameter from URL. Patch for Webex Teams Defect: 'next' URL returned in the Link headers of the responses contain an errant 'max=null' parameter, which causes the next request (to this URL) to fail if the URL is requested as-is. This patch parses t...
Remove max=null parameter from URL. Patch for Webex Teams Defect: 'next' URL returned in the Link headers of the responses contain an errant 'max=null' parameter, which causes the next request (to this URL) to fail if the URL is requested as-is. This patch parses the next_url to remove the max=null p...
def get_region(self, ip): ''' Get region ''' rec = self.get_all(ip) return rec and rec.region
Get region
def choose_type(cls, content_type): """Choose object type from content type.""" return cls.type_cls.SUBDIR if content_type in cls.subdir_types \ else cls.type_cls.FILE
Choose object type from content type.
def plot_eeg_erp_topo(all_epochs, colors=None): """ Plot butterfly plot. DOCS INCOMPLETE :( """ all_evokeds = eeg_to_all_evokeds(all_epochs) data = {} for participant, epochs in all_evokeds.items(): for cond, epoch in epochs.items(): data[cond] = [] for participant,...
Plot butterfly plot. DOCS INCOMPLETE :(
def gcp_conn(service, service_type='client', future_expiration_minutes=15): """ service_type: not currently used. """ def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): # Import here to avoid circular import issue from cloudaux.gcp.auth import g...
service_type: not currently used.
def get_target_dimensions(self): """ Returns the target dimensions and calculates them if necessary. The target dimensions are display independent. :return: Target dimensions as a tuple (width, height) :rtype: (int, int) """ if self.target_height is None: ...
Returns the target dimensions and calculates them if necessary. The target dimensions are display independent. :return: Target dimensions as a tuple (width, height) :rtype: (int, int)
def __parse_config(self): """ Invoke the config file parser. """ if self.should_parse_config and (self.args.config or self.config_file): self.config = ConfigParser.SafeConfigParser() self.config.read(self.args.config or self.config_file)
Invoke the config file parser.
def lkendalltau(x,y): """ Calculates Kendall's tau ... correlation of ordinal data. Adapted from function kendl1 in Numerical Recipies. Needs good test-routine.@@@ Usage: lkendalltau(x,y) Returns: Kendall's tau, two-tailed p-value """ n1 = 0 n2 = 0 iss = 0 for j in range(len(x)-1): for ...
Calculates Kendall's tau ... correlation of ordinal data. Adapted from function kendl1 in Numerical Recipies. Needs good test-routine.@@@ Usage: lkendalltau(x,y) Returns: Kendall's tau, two-tailed p-value
def get_bel_versions() -> List[str]: """Get BEL Language versions supported Get the list of all BEL Language versions supported. The file this depends on is generated by belspec_yaml2json and is kept up to date using `make update_ebnf` or `make update_parsers`. You can also run `belspec_yaml2json` ...
Get BEL Language versions supported Get the list of all BEL Language versions supported. The file this depends on is generated by belspec_yaml2json and is kept up to date using `make update_ebnf` or `make update_parsers`. You can also run `belspec_yaml2json` directly as it's added as a command by pip...
def export(self, top=True): """Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist ...
Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be expor...
def split_data(self): """ Split data according to baseline and projection time period values. """ try: # Extract data ranging in time_period1 time_period1 = (slice(self.baseline_period[0], self.baseline_period[1])) self.baseline_in = self.original_data.loc[time_perio...
Split data according to baseline and projection time period values.
def check_engine(handle): """Check availability of requested template engine.""" if handle == 'help': dump_engines() sys.exit(0) if handle not in engines.engines: print('Engine "%s" is not available.' % (handle,), file=sys.stderr) sys.exit(1)
Check availability of requested template engine.
def _checkpoint_and_erase(self, trial): """Checkpoints the model and erases old checkpoints if needed. Parameters ---------- trial : trial to save """ with warn_if_slow("save_to_disk"): trial._checkpoint.value = ray.get(trial.runner.save.remot...
Checkpoints the model and erases old checkpoints if needed. Parameters ---------- trial : trial to save
def sample_given_context(self, c, c_dims): ''' Sample the region with max progress among regions that have the same context c: context value on c_dims dimensions c_dims: w.r.t sensory space dimensions ''' index = self.discrete_progress.sample_given_context(c, c_di...
Sample the region with max progress among regions that have the same context c: context value on c_dims dimensions c_dims: w.r.t sensory space dimensions
def registration(uri): """Responses handler registration. Registers a handler for a given URI with Responses so that it can be intercepted and handed to Stack-In-A-Box. :param uri: URI used for the base of the HTTP requests :returns: n/a """ # log the URI that is used to access the S...
Responses handler registration. Registers a handler for a given URI with Responses so that it can be intercepted and handed to Stack-In-A-Box. :param uri: URI used for the base of the HTTP requests :returns: n/a
def normalize(X, mean=None, std=None): """ Normalize X. If mean OR std is None, normalizes X to have mean 0 and std 1. """ if mean is None or std is None: mean = X.mean(0) std = X.std(0) return (X - mean) / std
Normalize X. If mean OR std is None, normalizes X to have mean 0 and std 1.
def column_max_width(self, column_number): """Return the maximum width of a column based on the current terminal width. :param int column_number: The column number to query. :return: The max width of the column. :rtype: int """ inner_widths = max_dimensions(self.table_d...
Return the maximum width of a column based on the current terminal width. :param int column_number: The column number to query. :return: The max width of the column. :rtype: int
def inflate_analysis_group(self, identifier, definition): """ Inflate a whole analysis group. An analysis group is a section defined in the YAML file. Args: identifier (str): the group identifier. definition (list/dict): the group definition. Returns: ...
Inflate a whole analysis group. An analysis group is a section defined in the YAML file. Args: identifier (str): the group identifier. definition (list/dict): the group definition. Returns: AnalysisGroup: an instance of AnalysisGroup. Raises: ...
def enqueue_task(self, task): """Enqueues a task directly. This is used when a task is retried or if a task was manually created. Note that this does not store the task. """ data = dumps(task) if self._async: self.publisher_client.publish(self.topic_path, da...
Enqueues a task directly. This is used when a task is retried or if a task was manually created. Note that this does not store the task.
def get_wegobject_by_id(self, id): ''' Retrieve a `Wegobject` by the Id. :param integer id: the Id of the `Wegobject` :rtype: :class:`Wegobject` ''' def creator(): res = crab_gateway_request( self.client, 'GetWegobjectByIdentificatorWegobject'...
Retrieve a `Wegobject` by the Id. :param integer id: the Id of the `Wegobject` :rtype: :class:`Wegobject`
def data_request(self, payload, timeout=TIMEOUT): """Perform a data_request and return the result.""" request_url = self.base_url + "/data_request" return requests.get(request_url, timeout=timeout, params=payload)
Perform a data_request and return the result.
def libvlc_audio_set_mute(p_mi, status): '''Set mute status. @param p_mi: media player. @param status: If status is true then mute, otherwise unmute @warning This function does not always work. If there are no active audio playback stream, the mute status might not be available. If digital pass-through (S/P...
Set mute status. @param p_mi: media player. @param status: If status is true then mute, otherwise unmute @warning This function does not always work. If there are no active audio playback stream, the mute status might not be available. If digital pass-through (S/PDIF, HDMI...) is in use, muting may be unapplica...
def markdown_filter(value, typogrify=True, extensions=('extra', 'codehilite')): """ A smart wrapper around the ``markdown`` and ``typogrify`` functions that automatically removes leading whitespace before every line. This is necessary because Markdown is whitespace-sensitive. Consider some Markdown cont...
A smart wrapper around the ``markdown`` and ``typogrify`` functions that automatically removes leading whitespace before every line. This is necessary because Markdown is whitespace-sensitive. Consider some Markdown content in a template that looks like this: .. codeblock:: html+jinja <article> ...
def list_build_configurations_for_product(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all BuildConfigurations associated with the given Product. """ data = list_build_configurations_for_product_raw(id, name, page_size, page_index, sort, q) if data: return utils....
List all BuildConfigurations associated with the given Product.
def get_timestamp(self, **kwargs): """Retrieves the timestamp for a given set of data""" timestamp = kwargs.get('timestamp') if not timestamp: now = datetime.datetime.utcnow() timestamp = now.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (now.microsecond / 1000) + "Z" ...
Retrieves the timestamp for a given set of data
def multiple_optima(gene_number=937, resolution=80, model_restarts=10, seed=10000, max_iters=300, optimize=True, plot=True): """ Show an example of a multimodal error surface for Gaussian process regression. Gene 939 has bimodal behaviour where the noisy mode is higher. """ # Contour over a ran...
Show an example of a multimodal error surface for Gaussian process regression. Gene 939 has bimodal behaviour where the noisy mode is higher.
def _populate_and_save_user_profile(self): """ Populates a User profile object with fields from the LDAP directory. """ try: app_label, class_name = django.conf.settings.AUTH_PROFILE_MODULE.split('.') profile_model = apps.get_model(app_label, class_name) ...
Populates a User profile object with fields from the LDAP directory.
def listen_on_udp_port(): """listen_on_udp_port Run a simple server for processing messages over ``UDP``. ``UDP_LISTEN_ON_HOST`` - listen on this host ip address ``UDP_LISTEN_ON_PORT`` - listen on this ``UDP`` port ``UDP_LISTEN_SIZE`` - listen on to packets of this size ``UDP_LISTEN_SLEEP``...
listen_on_udp_port Run a simple server for processing messages over ``UDP``. ``UDP_LISTEN_ON_HOST`` - listen on this host ip address ``UDP_LISTEN_ON_PORT`` - listen on this ``UDP`` port ``UDP_LISTEN_SIZE`` - listen on to packets of this size ``UDP_LISTEN_SLEEP`` - sleep this number of seconds p...
def set_resource_type(resource, type_id, types={}, **kwargs): """ Set this resource to be a certain type. Type objects (a dictionary keyed on type_id) may be passed in to save on loading. This function does not call save. It must be done afterwards. New resource attributes ar...
Set this resource to be a certain type. Type objects (a dictionary keyed on type_id) may be passed in to save on loading. This function does not call save. It must be done afterwards. New resource attributes are added to the resource if the template requires them. Resource attrib...
def download(self, bucket_name, object_name, filename=None): """ Get a file from Google Cloud Storage. :param bucket_name: The bucket to fetch from. :type bucket_name: str :param object_name: The object to fetch. :type object_name: str :param filename: If set, a ...
Get a file from Google Cloud Storage. :param bucket_name: The bucket to fetch from. :type bucket_name: str :param object_name: The object to fetch. :type object_name: str :param filename: If set, a local file path where the file should be written to. :type filename: str
def _new_stream(self, idx): '''Randomly select and create a new stream. Parameters ---------- idx : int, [0:n_streams - 1] The stream index to replace ''' # Don't activate the stream if the weight is 0 or None if self.stream_weights_[idx]: ...
Randomly select and create a new stream. Parameters ---------- idx : int, [0:n_streams - 1] The stream index to replace
def move_into(self, destination_folder): # type: (Folder) -> None """Move the Folder into a different folder. This makes the Folder provided a child folder of the destination_folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expir...
Move the Folder into a different folder. This makes the Folder provided a child folder of the destination_folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Args: destination_folder: A :class:`Folder <pyO...
def aggcv(rlist, show_stdv=True, show_progress=None, as_pandas=True): # pylint: disable=invalid-name """ Aggregate cross-validation results. """ cvmap = {} idx = rlist[0].split()[0] for line in rlist: arr = line.split() assert idx == arr[0] for it in arr[1:]: ...
Aggregate cross-validation results.
def plot_isotherm(self, T, zs, ws, Pmin=None, Pmax=None, methods=[], pts=50, only_valid=True): # pragma: no cover r'''Method to create a plot of the property vs pressure at a specified temperature and composition according to either a specified list of methods, or the us...
r'''Method to create a plot of the property vs pressure at a specified temperature and composition according to either a specified list of methods, or the user methods (if set), or all methods. User-selectable number of points, and pressure range. If only_valid is set, `test_method_v...
def block_verify( block_data ): """ Given block data (a dict with 'merkleroot' hex string and 'tx' list of hex strings--i.e. a block compatible with bitcoind's getblock JSON RPC method), verify that the transactions are consistent. Return True on success Return False if not. """ # ...
Given block data (a dict with 'merkleroot' hex string and 'tx' list of hex strings--i.e. a block compatible with bitcoind's getblock JSON RPC method), verify that the transactions are consistent. Return True on success Return False if not.
def python(self, cmd): """Execute a python script using the virtual environment python.""" python_bin = self.cmd_path('python') cmd = '{0} {1}'.format(python_bin, cmd) return self._execute(cmd)
Execute a python script using the virtual environment python.
def serializer_for(self, obj): """ Searches for a serializer for the provided object Serializers will be searched in this order; 1-NULL serializer 2-Default serializers, like primitives, arrays, string and some default types 3-Custom registered types...
Searches for a serializer for the provided object Serializers will be searched in this order; 1-NULL serializer 2-Default serializers, like primitives, arrays, string and some default types 3-Custom registered types by user 4-Global serializer if registered ...
def _check_values(self, values): """Check values whenever they come through the values setter.""" assert isinstance(values, Iterable) and not \ isinstance(values, (str, dict, bytes, bytearray)), \ 'values should be a list or tuple. Got {}'.format(type(values)) assert len(...
Check values whenever they come through the values setter.
def removeChild(self, child_id): """Remove a child from current workitem :param child_id: the child workitem id/number (integer or equivalent string) """ self.log.debug("Try to remove a child <Workitem %s> from current " "<Workitem %s>", ...
Remove a child from current workitem :param child_id: the child workitem id/number (integer or equivalent string)
def construct_error_message(driver_id, error_type, message, timestamp): """Construct a serialized ErrorTableData object. Args: driver_id: The ID of the driver that the error should go to. If this is nil, then the error will go to all drivers. error_type: The type of the error. ...
Construct a serialized ErrorTableData object. Args: driver_id: The ID of the driver that the error should go to. If this is nil, then the error will go to all drivers. error_type: The type of the error. message: The error message. timestamp: The time of the error. R...
def find_suitable_encoding(self, char): """The order of our search is a specific one: 1. code pages that we already tried before; there is a good chance they might work again, reducing the search space, and by re-using already used encodings we might also reduce the num...
The order of our search is a specific one: 1. code pages that we already tried before; there is a good chance they might work again, reducing the search space, and by re-using already used encodings we might also reduce the number of codepage change instructiosn we have ...
def write_biom(self, sample_names, read_taxonomies, biom_file_io): '''Write the OTU info to a biom IO output stream Parameters ---------- sample_names: String names of each sample (sample_ids for biom) read_taxonomies: Array of hashes as per _iterate_otu_tabl...
Write the OTU info to a biom IO output stream Parameters ---------- sample_names: String names of each sample (sample_ids for biom) read_taxonomies: Array of hashes as per _iterate_otu_table_rows() biom_file_io: io open writeable stream to write b...
def check_schedule(): """Helper routine to easily test if the schedule is valid""" all_items = prefetch_schedule_items() for validator, _type, _msg in SCHEDULE_ITEM_VALIDATORS: if validator(all_items): return False all_slots = prefetch_slots() for validator, _type, _msg in SLOT_...
Helper routine to easily test if the schedule is valid
def _query_select_options(self, query, select_columns=None): """ Add select load options to query. The goal is to only SQL select what is requested :param query: SQLAlchemy Query obj :param select_columns: (list) of columns :return: SQLAlchemy Query obj "...
Add select load options to query. The goal is to only SQL select what is requested :param query: SQLAlchemy Query obj :param select_columns: (list) of columns :return: SQLAlchemy Query obj
def retry_on_exception(tries=6, delay=1, backoff=2, max_delay=32): ''' Decorator for implementing exponential backoff for retrying on failures. tries: Max number of tries to execute the wrapped function before failing. delay: Delay time in seconds before the FIRST retry. backoff: Multiplier to exte...
Decorator for implementing exponential backoff for retrying on failures. tries: Max number of tries to execute the wrapped function before failing. delay: Delay time in seconds before the FIRST retry. backoff: Multiplier to extend the initial delay by for each retry. max_delay: Max time in seconds to w...
def from_name(cls, name, all_fallback=True): """Gets a vocation filter from a vocation's name. Parameters ---------- name: :class:`str` The name of the vocation. all_fallback: :class:`bool` Whether to return :py:attr:`ALL` if no match is found. Otherwise,...
Gets a vocation filter from a vocation's name. Parameters ---------- name: :class:`str` The name of the vocation. all_fallback: :class:`bool` Whether to return :py:attr:`ALL` if no match is found. Otherwise, ``None`` will be returned. Returns ---...
def path(self, *args: typing.List[str]) -> typing.Union[None, str]: """ Creates an absolute path in the project source directory from the relative path components. :param args: Relative components for creating a path within the project source directory :r...
Creates an absolute path in the project source directory from the relative path components. :param args: Relative components for creating a path within the project source directory :return: An absolute path to the specified file or directory within the ...
def _updateCallSetIds(self, variantFile): """ Updates the call set IDs based on the specified variant file. """ if len(self._callSetIdMap) == 0: for sample in variantFile.header.samples: self.addCallSetFromName(sample)
Updates the call set IDs based on the specified variant file.
def items(self): "Returns a list of (key, value) pairs as 2-tuples." return (list(self._pb.IntMap.items()) + list(self._pb.StringMap.items()) + list(self._pb.FloatMap.items()) + list(self._pb.BoolMap.items()))
Returns a list of (key, value) pairs as 2-tuples.
def get_transitions(self, indexes): """ Get dictionary of transition data """ assert indexes.shape[1] == self.state_buffer.shape[1], \ "Must have the same number of indexes as there are environments" frame_batch_shape = ( [indexes.shape[0], indexes.shape[1]] ...
Get dictionary of transition data
def get_data_csv(file_name, encoding='utf-8', file_contents=None, on_demand=False): ''' Gets good old csv data from a file. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. encoding: Loads the file with the sp...
Gets good old csv data from a file. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. encoding: Loads the file with the specified cell encoding. file_contents: The file-like object holding contents of file_name...
def init_app(self, app): """Initialize the extension. It will create the `index_path_root` directory upon initalization but it will **not** create the index. Please use :meth:`reindex` for this. :param app: The application instance for which the extension should be i...
Initialize the extension. It will create the `index_path_root` directory upon initalization but it will **not** create the index. Please use :meth:`reindex` for this. :param app: The application instance for which the extension should be initialized.
def recover_chain_id(storage: SQLiteStorage) -> ChainID: """We can reasonably assume, that any database has only one value for `chain_id` at this point in time. """ action_init_chain = json.loads(storage.get_state_changes(limit=1, offset=0)[0]) assert action_init_chain['_type'] == 'raiden.transfer....
We can reasonably assume, that any database has only one value for `chain_id` at this point in time.
def get_storage_id_for_state(state): """ Calculates the storage id of a state. This ID can be used for generating the file path for a state. :param rafcon.core.states.state.State state: state the storage_id should is composed for """ if global_config.get_config_value('STORAGE_PATH_WITH_STATE_NAME'): ...
Calculates the storage id of a state. This ID can be used for generating the file path for a state. :param rafcon.core.states.state.State state: state the storage_id should is composed for
def loop(self): """ main game loop. returns the final score. """ pause_key = self.board.PAUSE margins = {'left': 4, 'top': 4, 'bottom': 4} atexit.register(self.showCursor) try: self.hideCursor() while True: self.clearScree...
main game loop. returns the final score.
def parse_query(self, query): """Parse query string using given grammar""" tree = pypeg2.parse(query, Main, whitespace="") return tree.accept(self.converter)
Parse query string using given grammar
def trimLeft(self, amount): """ Trim this fastqSequence in-place by removing <amount> nucleotides from the 5' end (left end). :param amount: the number of nucleotides to trim from the left-side of this sequence. """ if amount == 0: return self.sequenceData =...
Trim this fastqSequence in-place by removing <amount> nucleotides from the 5' end (left end). :param amount: the number of nucleotides to trim from the left-side of this sequence.
def connect(host, default_protocol='telnet', **kwargs): """ Like :class:`prepare()`, but also connects to the host by calling :class:`Protocol.connect()`. If the URL or host contain any login info, this function also logs into the host using :class:`Protocol.login()`. :type host: str or Host :...
Like :class:`prepare()`, but also connects to the host by calling :class:`Protocol.connect()`. If the URL or host contain any login info, this function also logs into the host using :class:`Protocol.login()`. :type host: str or Host :param host: A URL-formatted hostname or a :class:`Exscript.Host` obj...
def main(self, spin, data): """ The function which uses irc rfc regex to extract the basic arguments from the msg. """ data = data.decode(self.encoding) field = re.match(RFC_REG, data) if not field: return prefix = self.extract...
The function which uses irc rfc regex to extract the basic arguments from the msg.
def get_pathway(self, pathway_name=None, pathway_id=None, limit=None, as_df=False): """Get pathway .. note:: Format of pathway_id is KEGG:X* or REACTOME:X* . X* stands for a sequence of digits :param bool as_df: if set to True result returns as `pandas.DataFrame` :param str...
Get pathway .. note:: Format of pathway_id is KEGG:X* or REACTOME:X* . X* stands for a sequence of digits :param bool as_df: if set to True result returns as `pandas.DataFrame` :param str pathway_name: pathway name :param str pathway_id: KEGG or REACTOME identifier ...
def debug(self, debug_commands): """Run a debug command.""" if isinstance(debug_commands, sc_debug.DebugCommand): debug_commands = [debug_commands] return self._client.send(debug=sc_pb.RequestDebug(debug=debug_commands))
Run a debug command.
def get(self, key): """ simple `select` """ if not Log: _late_import() return FlatList(vals=[unwrap(coalesce(_datawrap(v), Null)[key]) for v in _get_list(self)])
simple `select`
def _traverse_command(self, name, *args, **kwargs): """ Add the key to the args and call the Redis command. """ if not name in self.available_commands: raise AttributeError("%s is not an available command for %s" % (name, self.__class__.__name...
Add the key to the args and call the Redis command.
def _translate(teleport_value): """Translate a teleport value in to a val subschema.""" if isinstance(teleport_value, dict): return _translate_composite(teleport_value) if teleport_value in PRIMITIVES: return PRIMITIVES[teleport_value] raise DeserializationError( "Could not int...
Translate a teleport value in to a val subschema.
def registration_id_chunks(self, registration_ids): """ Splits registration ids in several lists of max 1000 registration ids per list Args: registration_ids (list): FCM device registration ID Yields: generator: list including lists with registration ids ...
Splits registration ids in several lists of max 1000 registration ids per list Args: registration_ids (list): FCM device registration ID Yields: generator: list including lists with registration ids
def metalarchives(song): """ Returns the lyrics found in MetalArchives for the specified mp3 file or an empty string if not found. """ artist = normalize(song.artist) title = normalize(song.title) url = 'https://www.metal-archives.com/search/ajax-advanced/searching/songs' url += f'/?son...
Returns the lyrics found in MetalArchives for the specified mp3 file or an empty string if not found.
def warn_message(self, message, fh=None, prefix="[warn]:", suffix="..."): """ print warn type message, if file handle is `sys.stdout`, print color message :param str message: message to print :param file fh: file handle,default is `sys.stdout` :param str prefix: message...
print warn type message, if file handle is `sys.stdout`, print color message :param str message: message to print :param file fh: file handle,default is `sys.stdout` :param str prefix: message prefix,default is `[warn]` :param str suffix: message suffix ,default is `...` ...
def filter_featured_apps(admin_apps, request): """ Given a list of apps return a set of pseudo-apps considered featured. Apps are considered featured if the are defined in the settings property called `DASHBOARD_FEATURED_APPS` which contains a list of the apps that are considered to be featured. ...
Given a list of apps return a set of pseudo-apps considered featured. Apps are considered featured if the are defined in the settings property called `DASHBOARD_FEATURED_APPS` which contains a list of the apps that are considered to be featured. :param admin_apps: A list of apps. :param request: D...
def get_interfaces_ip(self): """ Get interface IP details. Returns a dictionary of dictionaries. Sample output: { "Ethernet2/3": { "ipv4": { "4.4.4.4": { "prefix_length": 16 } }, ...
Get interface IP details. Returns a dictionary of dictionaries. Sample output: { "Ethernet2/3": { "ipv4": { "4.4.4.4": { "prefix_length": 16 } }, "ipv6": { "20...
def build(self, path=None, tag=None, quiet=False, fileobj=None, nocache=False, rm=False, timeout=None, custom_context=False, encoding=None, pull=False, forcerm=False, dockerfile=None, container_limits=None, decode=False, buildargs=None, gzip=False, shmsize=None, ...
Similar to the ``docker build`` command. Either ``path`` or ``fileobj`` needs to be set. ``path`` can be a local path (to a directory containing a Dockerfile) or a remote URL. ``fileobj`` must be a readable file-like object to a Dockerfile. If you have a tar file for the Docker build co...
def ensure_dim(core, dim, dim_): """Ensure that dim is correct.""" if dim is None: dim = dim_ if not dim: return core, 1 if dim_ == dim: return core, int(dim) if dim > dim_: key_convert = lambda vari: vari[:dim_] else: key_convert = lambda vari: vari + (0...
Ensure that dim is correct.
def load(self, callback=None, errback=None, reload=False): """ Load network data from the API. """ if not reload and self.data: raise NetworkException('Network already loaded') def success(result, *args): self.data = result self.id = result['i...
Load network data from the API.
def send_venue(chat_id, latitude, longitude, title, address, foursquare_id=None, reply_to_message_id=None, reply_markup=None, disable_notification=False, **kwargs): """ Use this method to send information about a venue. :param chat_id: Unique identifier for the target chat or ...
Use this method to send information about a venue. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param latitude: Latitude of location. :param longitude: Longitude of location. :param title: Name of the venue. :param address...
def user_open(url_or_command): """Open the specified paramater in the web browser if a URL is detected, othewrise pass the paramater to the shell as a subprocess. This function is inteded to bu used in on_leftclick/on_rightclick callbacks. :param url_or_command: String containing URL or command """...
Open the specified paramater in the web browser if a URL is detected, othewrise pass the paramater to the shell as a subprocess. This function is inteded to bu used in on_leftclick/on_rightclick callbacks. :param url_or_command: String containing URL or command
def mtanh(alpha, z): """Modified hyperbolic tangent function mtanh(z; alpha). Parameters ---------- alpha : float The core slope of the mtanh. z : float or array The coordinate of the mtanh. """ z = scipy.asarray(z) ez = scipy.exp(z) enz = 1.0 / ez return ((1...
Modified hyperbolic tangent function mtanh(z; alpha). Parameters ---------- alpha : float The core slope of the mtanh. z : float or array The coordinate of the mtanh.
def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret
Return a list of all job ids