code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _maybe_pandas_data(data, feature_names, feature_types): """ Extract internal data from pd.DataFrame for DMatrix data """ if not isinstance(data, DataFrame): return data, feature_names, feature_types data_dtypes = data.dtypes if not all(dtype.name in PANDAS_DTYPE_MAPPER for dtype in data_dt...
Extract internal data from pd.DataFrame for DMatrix data
def _next_token(self, skipws=True): """Increment _token to the next token and return it.""" self._token = next(self._tokens).group(0) return self._next_token() if skipws and self._token.isspace() else self._token
Increment _token to the next token and return it.
def list(cls, state=None, page=None, per_page=None): """ List existing clusters present in your account. Kwargs: `state`: list only those clusters which are in this state Returns: List of clusters satisfying the given criteria """ conn = Qubole.a...
List existing clusters present in your account. Kwargs: `state`: list only those clusters which are in this state Returns: List of clusters satisfying the given criteria
def _import(func): """Return the namespace path to the function""" func_name = func.__name__ # from foo.bar import func // func() # WARNING: May be broken in IPython, in which case the widget will use a fallback if func_name in globals(): return func_name # ...
Return the namespace path to the function
def search(self, index, query, **params): """ Performs a search query. """ if index is None: index = 'search' options = {} if 'op' in params: op = params.pop('op') options['q.op'] = op options.update(params) url = self...
Performs a search query.
def event_types(self): """ Raises ------ IndexError When there is no selected rater """ try: events = self.rater.find('events') except AttributeError: raise IndexError('You need to have at least one rater') return [x.ge...
Raises ------ IndexError When there is no selected rater
def insert_paraphrase_information(germanet_db, wiktionary_files): ''' Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `wiktionary_files`: ''' num_paraphrases = 0 # ca...
Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `wiktionary_files`:
def feed(self, can): """Attempt to feed an incoming CAN frame into the state machine""" if not isinstance(can, CAN): raise Scapy_Exception("argument is not a CAN frame") identifier = can.identifier data = bytes(can.data) if len(data) > 1 and self.use_ext_addr is not ...
Attempt to feed an incoming CAN frame into the state machine
def create(self): """Create this cluster. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_cluster] :end-before: [END bigtable_create_cluster] .. note:: Uses the ``project``, ``instance`` and ``cluster_id`` on the ...
Create this cluster. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_cluster] :end-before: [END bigtable_create_cluster] .. note:: Uses the ``project``, ``instance`` and ``cluster_id`` on the current :class:`Cl...
def delete(self, kwargs): """ Delete an item Parameters ---------- kwargs : dict The primary key of the item to delete """ self._to_delete.append(kwargs) if self.should_flush(): self.flush()
Delete an item Parameters ---------- kwargs : dict The primary key of the item to delete
def confidence(self): """ Returns a tuple (chi squared, confident) of the experiment. Confident is simply a boolean specifying whether we're > 95%% sure that the results are statistically significant. """ choices = self.choices # Get the chi-squared between the ...
Returns a tuple (chi squared, confident) of the experiment. Confident is simply a boolean specifying whether we're > 95%% sure that the results are statistically significant.
def add_triple(self, subj, pred, obj): ''' Adds an entity property to an existing entity ''' subj_data, pred_data, obj_data = self.are_ilx([subj, pred, obj]) # RELATIONSHIP PROPERTY if subj_data.get('id') and pred_data.get('id') and obj_data.get('id'): if pred_data['type'] !=...
Adds an entity property to an existing entity
def set(self, key, val): """Set value stored for current running task. """ data = self.get_data(True) if data is not None: data[key] = val else: raise RuntimeError("No task is currently running")
Set value stored for current running task.
def retrieve_layers(self, *args, **options): """ Retrieve specified layers or all external layers if no layer specified. """ # init empty Q object queryset = Q() # if no layer specified if len(args) < 1: # cache queryset all_layers = Layer...
Retrieve specified layers or all external layers if no layer specified.
def _initialize_tableaux_ig(X, Y, tableaux, bases): """ Given sequences `X` and `Y` of ndarrays, initialize the tableau and basis arrays in place for the "geometric" imitation game as defined in McLennan and Tourky (2006), to be passed to `_lemke_howson_tbl`. Parameters ---------- X, Y : nd...
Given sequences `X` and `Y` of ndarrays, initialize the tableau and basis arrays in place for the "geometric" imitation game as defined in McLennan and Tourky (2006), to be passed to `_lemke_howson_tbl`. Parameters ---------- X, Y : ndarray(float) Arrays of the same shape (m, n). table...
def get_statements(self): """Return a list of all Statements in a single list. Returns ------- stmts : list[indra.statements.Statement] A list of all the INDRA Statements in the model. """ stmt_lists = [v for k, v in self.stmts.items()] stmts = [] ...
Return a list of all Statements in a single list. Returns ------- stmts : list[indra.statements.Statement] A list of all the INDRA Statements in the model.
def build(self, build_dir, **kwargs): """This function builds the cmake build command.""" # pylint: disable=no-self-use del kwargs args = ["cmake", "--build", build_dir] args.extend(self._get_build_flags()) return [{"args": args}]
This function builds the cmake build command.
def write_to_file(self, output_file_path, intervals, template): """ Write intervals to file. :param output_file_path: path of the output file to be written; if ``None``, print to stdout :type output_file_path: string (path) :param intervals: a l...
Write intervals to file. :param output_file_path: path of the output file to be written; if ``None``, print to stdout :type output_file_path: string (path) :param intervals: a list of tuples, each representing an interval :type intervals: list of tuple...
def from_api_repr(cls, resource): """Factory: construct a job configuration given its API representation :type resource: dict :param resource: An extract job configuration in the same representation as is returned from the API. :rtype: :class:`google.cloud.bigqu...
Factory: construct a job configuration given its API representation :type resource: dict :param resource: An extract job configuration in the same representation as is returned from the API. :rtype: :class:`google.cloud.bigquery.job._JobConfig` :returns: Configu...
def _find_intervals(bundles, duration, step): """Divide bundles into segments of a certain duration and a certain step, discarding any remainder.""" segments = [] for bund in bundles: beg, end = bund['times'][0][0], bund['times'][-1][1] if end - beg >= duration: new_begs = a...
Divide bundles into segments of a certain duration and a certain step, discarding any remainder.
def set_default_moe_hparams(hparams): """Add necessary hyperparameters for mixture-of-experts.""" hparams.moe_num_experts = 16 hparams.moe_loss_coef = 1e-2 hparams.add_hparam("moe_gating", "top_2") # Experts have fixed capacity per batch. We need some extra capacity # in case gating is not perfectly balanc...
Add necessary hyperparameters for mixture-of-experts.
def _get_forecast(api_result: dict) -> List[SmhiForecast]: """Converts results fråm API to SmhiForeCast list""" forecasts = [] # Need the ordered dict to get # the days in order in next stage forecasts_ordered = OrderedDict() forecasts_ordered = _get_all_forecast_from_api(api_result) ...
Converts results fråm API to SmhiForeCast list
def find_gromacs_command(commands): """Return *driver* and *name* of the first command that can be found on :envvar:`PATH`""" # We could try executing 'name' or 'driver name' but to keep things lean we # just check if the executables can be found and then hope for the best. commands = utilities.asiter...
Return *driver* and *name* of the first command that can be found on :envvar:`PATH`
def manhattan(src, tar, qval=2, normalized=False, alphabet=None): """Return the Manhattan distance between two strings. This is a wrapper for :py:meth:`Manhattan.dist_abs`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target...
Return the Manhattan distance between two strings. This is a wrapper for :py:meth:`Manhattan.dist_abs`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison qval : int ...
def find_files(data_path, brokers, minutes, start_time, end_time): """Find all the Kafka log files on the broker that have been modified in the speficied time range. start_time and end_time should be in the format specified by TIME_FORMAT_REGEX. :param data_path: the path to the lof files on the b...
Find all the Kafka log files on the broker that have been modified in the speficied time range. start_time and end_time should be in the format specified by TIME_FORMAT_REGEX. :param data_path: the path to the lof files on the broker :type data_path: str :param brokers: the brokers :type b...
def _errmsg(self, error: "Err", tb: bool=False, i: int=None, msgformat: str="terminal") -> str: """ Get the error message """ if msgformat == "terminal": msg = self._headline(error, i) if error.ex is not None: msg += "\n" + "line " ...
Get the error message
def _merge_two_dicts(x, y): """ Given two dicts, merge them into a new dict as a shallow copy. Once Python 3.6+ only is supported, replace method with ``z = {**x, **y}`` """ z = x.copy() z.update(y) return z
Given two dicts, merge them into a new dict as a shallow copy. Once Python 3.6+ only is supported, replace method with ``z = {**x, **y}``
def addAggregators(cols, aggrnames): 'add aggregator for each aggrname to each of cols' for aggrname in aggrnames: aggrs = aggregators.get(aggrname) aggrs = aggrs if isinstance(aggrs, list) else [aggrs] for aggr in aggrs: for c in cols: if not hasattr(c, 'aggr...
add aggregator for each aggrname to each of cols
def pack_into(self, buf, offset, *args, **kwargs): """See :func:`~bitstruct.pack_into()`. """ # Sanity check of the number of arguments. if len(args) < self._number_of_arguments: raise Error( "pack expected {} item(s) for packing (got {})".format( ...
See :func:`~bitstruct.pack_into()`.
def _generate_examples(self, archive, validation_labels=None): """Yields examples.""" if validation_labels: # Validation split for example in self._generate_examples_validation(archive, validation_labels): yield example # Training split....
Yields examples.
def change_directory(self, path, *args, **kwargs): """ :meth:`.WNetworkClientProto.change_directory` method implementation """ previous_path = self.session_path() self.session_path(path) if os.path.isdir(self.full_path()) is False: self.session_path(previous_path) raise ValueError('Unable to change dire...
:meth:`.WNetworkClientProto.change_directory` method implementation
def get_all_lines(self): """Return all lines of the SourceString as a list of SourceLine's.""" output = [] line = [] lineno = 1 for char in self.string: line.append(char) if char == '\n': output.append(SourceLine(''.join(line), lineno)) ...
Return all lines of the SourceString as a list of SourceLine's.
def on_key_pressed(self, event): """ likely to take in a set of parameters to treat as up, down, left, right, likely to actually be based on a joystick event... not sure yet """ return # TODO if event.keysym == "Up": self.manager...
likely to take in a set of parameters to treat as up, down, left, right, likely to actually be based on a joystick event... not sure yet
def setVisible( self, state ): """ Overloads the setVisible method for the dialog to resize the contents \ of the splitter properly. :param state | <bool> """ super(XWizardBrowserDialog, self).setVisible(state) if ( state ): mwid...
Overloads the setVisible method for the dialog to resize the contents \ of the splitter properly. :param state | <bool>
def check(cls, status): """Checks if a status enum matches the trigger originally set, and if so, raises the appropriate error. Args: status (int, enum): A protobuf enum response status to check. Raises: AssertionError: If trigger or error were not set. ...
Checks if a status enum matches the trigger originally set, and if so, raises the appropriate error. Args: status (int, enum): A protobuf enum response status to check. Raises: AssertionError: If trigger or error were not set. _ApiError: If the statuses don'...
def _list_files(path, suffix=""): """ Returns a list of all files ending in `suffix` contained within `path`. Parameters ---------- path : str a filepath suffix : str Returns ------- l : list A list of all files ending in `suffix` contained within `path`. (If `path` is a file rathe...
Returns a list of all files ending in `suffix` contained within `path`. Parameters ---------- path : str a filepath suffix : str Returns ------- l : list A list of all files ending in `suffix` contained within `path`. (If `path` is a file rather than a directory, it is considered ...
def send_keys(self, keyserver, *keyids): """Send keys to a keyserver.""" result = self._result_map['list'](self) log.debug('send_keys: %r', keyids) data = _util._make_binary_stream("", self._encoding) args = ['--keyserver', keyserver, '--send-keys'] args.extend(keyids) ...
Send keys to a keyserver.
def generate(self): """ Generate all output types and write to disk. """ logger.info('Generating graphs') self._generate_graph( 'by-version', 'Downloads by Version', self._stats.per_version_data, 'Version' ) self._ge...
Generate all output types and write to disk.
def reset_network(roles, extra_vars=None): """Reset the network constraints (latency, bandwidth ...) Remove any filter that have been applied to shape the traffic. Args: roles (dict): role->hosts mapping as returned by :py:meth:`enoslib.infra.provider.Provider.init` inventory (...
Reset the network constraints (latency, bandwidth ...) Remove any filter that have been applied to shape the traffic. Args: roles (dict): role->hosts mapping as returned by :py:meth:`enoslib.infra.provider.Provider.init` inventory (str): path to the inventory
def psturng(q, r, v): """Evaluates the probability from 0 to q for a studentized range having v degrees of freedom and r samples. Parameters ---------- q : (scalar, array_like) quantile value of Studentized Range q >= 0. r : (scalar, array_like) The number of samples ...
Evaluates the probability from 0 to q for a studentized range having v degrees of freedom and r samples. Parameters ---------- q : (scalar, array_like) quantile value of Studentized Range q >= 0. r : (scalar, array_like) The number of samples r >= 2 and r <= 200 ...
def _match(self, query): """Tries to match in dialogues, getters and setters and subcomponents :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ response = self._match_dialog(query) if...
Tries to match in dialogues, getters and setters and subcomponents :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None
def set_rf_samples(n): """ Changes Scikit learn's random forests to give each tree a random sample of n random rows. """ forest._generate_sample_indices = (lambda rs, n_samples: forest.check_random_state(rs).randint(0, n_samples, n))
Changes Scikit learn's random forests to give each tree a random sample of n random rows.
def get_labels(cls, path=None): """Get all server configuration labels. :param path: A string. The configuration file to be manipulated. Defaults to what is returned by :func:`nailgun.config._get_config_file_path`. :returns: Server configuration labels, where each label ...
Get all server configuration labels. :param path: A string. The configuration file to be manipulated. Defaults to what is returned by :func:`nailgun.config._get_config_file_path`. :returns: Server configuration labels, where each label is a string.
def transform_non_affine(self, values): """Transform an array of GPS times. This method is designed to filter out transformations that will generate text elements that require exact precision, and use `Decimal` objects to do the transformation, and simple `float` otherwise. ...
Transform an array of GPS times. This method is designed to filter out transformations that will generate text elements that require exact precision, and use `Decimal` objects to do the transformation, and simple `float` otherwise.
def djfrontend_twbs_css(version=None): """ Returns Twitter Bootstrap CSS file. TEMPLATE_DEBUG returns full file, otherwise returns minified file. """ if version is None: if not getattr(settings, 'DJFRONTEND_TWBS_CSS', False): version = getattr(settings, 'DJFRONTEND_TWBS_VERSION',...
Returns Twitter Bootstrap CSS file. TEMPLATE_DEBUG returns full file, otherwise returns minified file.
def profile_prior_model_dict(self): """ Returns ------- profile_prior_model_dict: {str: PriorModel} A dictionary mapping_matrix instance variable names to variable profiles. """ return {key: value for key, value in filter(lambda t: isinstance(t...
Returns ------- profile_prior_model_dict: {str: PriorModel} A dictionary mapping_matrix instance variable names to variable profiles.
def reduce_sum(x, disable_positional_args=None, output_shape=None, reduced_dim=None, name=None): """Reduction on 1 or more axes. If reduced_dim is present, then only that dimension is reduced out. Alternatively, specify output_shape. Do not specify bo...
Reduction on 1 or more axes. If reduced_dim is present, then only that dimension is reduced out. Alternatively, specify output_shape. Do not specify both reduced_dim and output_shape. If neither is specified, then all dimensions are reduced out. Args: x: a Tensor disable_positional_args: None ou...
def prefix_all(self, prefix='#', *lines): """ Same as :func:`~prefix`, for multiple lines. :param prefix: Dockerfile command to use, e.g. ``ENV`` or ``RUN``. :type prefix: unicode | str :param lines: Lines with arguments to be prefixed. :type lines: collections.Iterable[...
Same as :func:`~prefix`, for multiple lines. :param prefix: Dockerfile command to use, e.g. ``ENV`` or ``RUN``. :type prefix: unicode | str :param lines: Lines with arguments to be prefixed. :type lines: collections.Iterable[unicode | str]
def get_last_date(self, field, filters_=[]): ''' :field: field with the data :filters_: additional filters to find the date ''' last_date = self.get_last_item_field(field, filters_=filters_) return last_date
:field: field with the data :filters_: additional filters to find the date
def _items_to_es(self, json_items): """ Append items JSON to ES (data source state) """ if len(json_items) == 0: return logger.info("Adding items to Ocean for %s (%i items)" % (self, len(json_items))) field_id = self.get_field_unique_id() inser...
Append items JSON to ES (data source state)
def get_fullname(module): """ Reconstruct a Module's canonical path by recursing through its parents. """ bits = [str(module.name)] while module.parent: bits.append(str(module.parent.name)) module = module.parent return '.'.join(reversed(bits))
Reconstruct a Module's canonical path by recursing through its parents.
def new_file(self, vd, length, isoname, parent, seqnum, rock_ridge, rr_name, xa, file_mode): # type: (headervd.PrimaryOrSupplementaryVD, int, bytes, DirectoryRecord, int, str, bytes, bool, int) -> None ''' Create a new file Directory Record. Parameters: vd - Th...
Create a new file Directory Record. Parameters: vd - The Volume Descriptor this record is part of. length - The length of the data. isoname - The name for this directory record. parent - The parent of this directory record. seqnum - The sequence number for this dire...
def _select_broker_pair(self, rg_destination, victim_partition): """Select best-fit source and destination brokers based on partition count and presence of partition over the broker. * Get overloaded and underloaded brokers Best-fit Selection Criteria: Source broker: Select brok...
Select best-fit source and destination brokers based on partition count and presence of partition over the broker. * Get overloaded and underloaded brokers Best-fit Selection Criteria: Source broker: Select broker containing the victim-partition with maximum partitions. ...
def preserve_attr_data(A, B): '''Preserve attr data for combining B into A. ''' for attr, B_data in B.items(): # defined object attrs if getattr(B_data, 'override_parent', True): continue if attr in A: A_data = A[attr] for _attr in getattr(A_data, '_attrs'...
Preserve attr data for combining B into A.
def xml(self, attribs = None,elements = None, skipchildren = False): """See :meth:`AbstractElement.xml`""" if not attribs: attribs = {} if self.idref: attribs['id'] = self.idref return super(AbstractTextMarkup,self).xml(attribs,elements, skipchildren)
See :meth:`AbstractElement.xml`
def _trimSegmentsInCell(self, colIdx, cellIdx, segList, minPermanence, minNumSyns): """ This method goes through a list of segments for a given cell and deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns syna...
This method goes through a list of segments for a given cell and deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining. :param colIdx Column index :param cellIdx Cell index within the column :param se...
def make_temp_path(path, new_ext=None): """ Arguments: new_ext: the new file extension, including the leading dot. Defaults to preserving the existing file extension. """ root, ext = os.path.splitext(path) if new_ext is None: new_ext = ext temp_path = root + TEMP_EXTENSIO...
Arguments: new_ext: the new file extension, including the leading dot. Defaults to preserving the existing file extension.
def determine_output_name(self, sources): """Determine the name of the produced target from the names of the sources.""" assert is_iterable_typed(sources, virtual_target.VirtualTarget) # The simple case if when a name # of source has single dot. Then, we take the part before ...
Determine the name of the produced target from the names of the sources.
def device_info(self): """ Pull basic device information. Purpose: This function grabs the hostname, model, running version, and | serial number of the device. @returns: The output that should be shown to the user. @rtype: str """ # get hostname, model, a...
Pull basic device information. Purpose: This function grabs the hostname, model, running version, and | serial number of the device. @returns: The output that should be shown to the user. @rtype: str
def tarball_files(tar_name, file_paths, output_dir='.', prefix=''): """ Creates a tarball from a group of files :param str tar_name: Name of tarball :param list[str] file_paths: Absolute file paths to include in the tarball :param str output_dir: Output destination for tarball :param str prefix...
Creates a tarball from a group of files :param str tar_name: Name of tarball :param list[str] file_paths: Absolute file paths to include in the tarball :param str output_dir: Output destination for tarball :param str prefix: Optional prefix for files in tarball
def stochrsi(data, period): """ StochRSI. Formula: SRSI = ((RSIt - RSI LOW) / (RSI HIGH - LOW RSI)) * 100 """ rsi = relative_strength_index(data, period)[period:] stochrsi = [100 * ((rsi[idx] - np.min(rsi[idx+1-period:idx+1])) / (np.max(rsi[idx+1-period:idx+1]) - np.min(rsi[idx+1-period:idx...
StochRSI. Formula: SRSI = ((RSIt - RSI LOW) / (RSI HIGH - LOW RSI)) * 100
def basen_to_integer(self, X, cols, base): """ Convert basen code as integers. Parameters ---------- X : DataFrame encoded data cols : list-like Column names in the DataFrame that be encoded base : int The base of transform ...
Convert basen code as integers. Parameters ---------- X : DataFrame encoded data cols : list-like Column names in the DataFrame that be encoded base : int The base of transform Returns ------- numerical: DataFrame
def field_dict_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), strip=True, blank_none=True, ignore_related=True, ignore_values=(None,), ignore_errors=Tr...
Construct a Mapping (dict) from field names to values from a row of data Args: row (list or dict): Data (values) to be assigned to field_names in the dict. If `row` is a list, then the column names (header row) can be provided in `field_names`. If `row` is a list and no field_names are provid...
async def del_aldb(self, addr, mem_addr: int): """Write a device All-Link record.""" dev_addr = Address(addr) device = self.plm.devices[dev_addr.id] if device: _LOGGING.debug('calling device del_aldb') device.del_aldb(mem_addr) await asyncio.sleep(1, l...
Write a device All-Link record.
def reencrypt_single_user(engine, user_id, old_crypto, new_crypto, logger): """ Re-encrypt all files and checkpoints for a single user. """ # Use FallbackCrypto so that we're re-entrant if we halt partway through. crypto = FallbackCrypto([new_crypto, old_crypto]) reencrypt_user_content( ...
Re-encrypt all files and checkpoints for a single user.
def _parse_response(self, result_page): """ Takes a result page of sending the sms, returns an extracted tuple: ('numeric_err_code', '<sent_queued_message_id>', '<smsglobalmsgid>') Returns None if unable to extract info from result_page, it should be safe to assume that it wa...
Takes a result page of sending the sms, returns an extracted tuple: ('numeric_err_code', '<sent_queued_message_id>', '<smsglobalmsgid>') Returns None if unable to extract info from result_page, it should be safe to assume that it was either a failed result or worse, the interface con...
def _lookup(cls: str) -> LdapObjectClass: """ Lookup module.class. """ if isinstance(cls, str): module_name, _, name = cls.rpartition(".") module = importlib.import_module(module_name) try: cls = getattr(module, name) except AttributeError: raise Attribute...
Lookup module.class.
def parse_date(value): """Parse an RFC 1123 or asctime-like format date string to produce a Python datetime object (without a timezone). """ # Do the regex magic; also enforces 2 or 4 digit years match = Definitions.DATE_RE.match(value) if value else None if not match: return None # ...
Parse an RFC 1123 or asctime-like format date string to produce a Python datetime object (without a timezone).
def reset_all_metadata(self): """Clear all cached metadata Metadata will be re-fetched as required to satisfy requests. """ self.topics_to_brokers.clear() self.topic_partitions.clear() self.topic_errors.clear() self.consumer_group_to_brokers.clear()
Clear all cached metadata Metadata will be re-fetched as required to satisfy requests.
def get_rr_queue(self): """Returns a :class: `kombu.Queue` instance for receiving round-robin commands for this actor type.""" return Queue(self.inbox_rr.name + '.rr', self.inbox_rr, auto_delete=True)
Returns a :class: `kombu.Queue` instance for receiving round-robin commands for this actor type.
def parse_and_normalize_url_date(date_str): """Parse a ISO 8601 date-time with optional timezone. - Return as datetime with timezone adjusted to UTC. - Return naive date-time set to UTC. """ if date_str is None: return None try: return d1_common.date_time.dt_from_iso8601_str(da...
Parse a ISO 8601 date-time with optional timezone. - Return as datetime with timezone adjusted to UTC. - Return naive date-time set to UTC.
def _get_schema(self): """ Returns a dictionary with the schema for a QuantFigure """ d={} layout_kwargs=dict((_,'') for _ in get_layout_kwargs()) for _ in ('data','layout','theme','panels'): d[_]={} for __ in eval('__QUANT_FIGURE_{0}'.format(_.upper())): layout_kwargs.pop(__,None) d[_][__]=N...
Returns a dictionary with the schema for a QuantFigure
def attach_subdivision(times): """ Manual assignment of a (stopped) times object as a subdivision of running timer. Use cases are expected to be very limited (mainly provided as a one-Times variant of attach_par_subdivision). Notes: As with any subdivision, the interval in the receiving ti...
Manual assignment of a (stopped) times object as a subdivision of running timer. Use cases are expected to be very limited (mainly provided as a one-Times variant of attach_par_subdivision). Notes: As with any subdivision, the interval in the receiving timer is assumed to totally subsume t...
def open_mask(fn:PathOrStr, div=False, convert_mode='L', after_open:Callable=None)->ImageSegment: "Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255." return open_image(fn, div=div, convert_mode=convert_mode, cls=ImageSegment, after_open=after_open)
Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255.
def user_view_events(self) -> List[str]: """Return event types where use viewed a main object.""" return [event_type for event_type, event in self.items if event.get_event_action() == event_actions.VIEWED]
Return event types where use viewed a main object.
def ancestors(self, full_table_name): """ :param full_table_name: In form `schema`.`table_name` :return: all dependent tables sorted in topological order. Self is included. """ nodes = self.subgraph( nx.algorithms.dag.ancestors(self, full_table_name)) return...
:param full_table_name: In form `schema`.`table_name` :return: all dependent tables sorted in topological order. Self is included.
def restore(self): """ Copy files from the backup folder to the sym-linked optimizer folder. """ if os.path.exists(self.backup_path): for file in glob.glob(self.backup_path + "/*"): shutil.copy(file, self.path)
Copy files from the backup folder to the sym-linked optimizer folder.
def resolve(hostname, family=AF_UNSPEC): """ Resolve hostname to one or more IP addresses through the operating system. Resolution is carried out for the given address family. If no address family is specified, only IPv4 and IPv6 addresses are returned. If multiple IP addresses are found, all are r...
Resolve hostname to one or more IP addresses through the operating system. Resolution is carried out for the given address family. If no address family is specified, only IPv4 and IPv6 addresses are returned. If multiple IP addresses are found, all are returned. :param family: AF_INET or AF_INET6 or A...
def compile(code: list, consts: list, names: list, varnames: list, func_name: str = "<unknown, compiled>", arg_count: int = 0, kwarg_defaults: Tuple[Any] = (), use_safety_wrapper: bool = True): """ Compiles a set of bytecode instructions into a working function, using Python's bytecode ...
Compiles a set of bytecode instructions into a working function, using Python's bytecode compiler. :param code: A list of bytecode instructions. :param consts: A list of constants to compile into the function. :param names: A list of names to compile into the function. :param varnames: A list of ``...
def gen_challenge(self, state): """returns the next challenge and increments the seed and index in the state. :param state: the state to use for generating the challenge. will verify the integrity of the state object before using it to generate a challenge. it will then modify...
returns the next challenge and increments the seed and index in the state. :param state: the state to use for generating the challenge. will verify the integrity of the state object before using it to generate a challenge. it will then modify the state by incrementing the seed ...
async def CharmArchiveSha256(self, urls): ''' urls : typing.Sequence[~CharmURL] Returns -> typing.Sequence[~StringResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Uniter', request='CharmArchiveSha256', ...
urls : typing.Sequence[~CharmURL] Returns -> typing.Sequence[~StringResult]
def split_unescaped(char, string, include_empty_strings=False): ''' :param char: The character on which to split the string :type char: string :param string: The string to split :type string: string :returns: List of substrings of *string* :rtype: list of strings Splits *string* wheneve...
:param char: The character on which to split the string :type char: string :param string: The string to split :type string: string :returns: List of substrings of *string* :rtype: list of strings Splits *string* whenever *char* appears without an odd number of backslashes ('\\') preceding i...
def do_rotation(self, mirror, rot): """Null implementation of rotate and/or mirror.""" if (mirror): raise IIIFError(code=501, parameter="rotation", text="Null manipulator does not support mirroring.") if (rot != 0.0): raise IIIFError(code=501, ...
Null implementation of rotate and/or mirror.
def list_distributions(region=None, key=None, keyid=None, profile=None): ''' List, with moderate information, all CloudFront distributions in the bound account. region Region to connect to. key Secret key to use. keyid Access key to use. profile Dict, or pilla...
List, with moderate information, all CloudFront distributions in the bound account. region Region to connect to. key Secret key to use. keyid Access key to use. profile Dict, or pillar key pointing to a dict, containing AWS region/key/keyid. CLI Example: .. ...
def start_time(self): """Retrieves the start time of the incident/incidents from the output response Returns: start_time(namedtuple): List of named tuples of start time of the incident/incidents """ resource_list = self.traffic_incident() start_ti...
Retrieves the start time of the incident/incidents from the output response Returns: start_time(namedtuple): List of named tuples of start time of the incident/incidents
def nl_error_handler_verbose(_, err, arg): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L78.""" ofd = arg or _LOGGER.debug ofd('-- Error received: ' + strerror(-err.error)) ofd('-- Original message: ' + print_header_content(err.msg)) return -nl_syserr2nlerr(err.error)
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L78.
def _curvature_range(self): """Curvature range. Returns: h_max_t, h_min_t ops """ self._curv_win = tf.get_variable("curv_win", dtype=tf.float32, trainable=False, shape=[self.curvature_wi...
Curvature range. Returns: h_max_t, h_min_t ops
def airborne_position_with_ref(msg, lat_ref, lon_ref): """Decode airborne position with only one message, knowing reference nearby location, such as previously calculated location, ground station, or airport location, etc. The reference position shall be with in 180NM of the true position. Args: ...
Decode airborne position with only one message, knowing reference nearby location, such as previously calculated location, ground station, or airport location, etc. The reference position shall be with in 180NM of the true position. Args: msg (string): even message (28 bytes hexadecimal string)...
def HandleVersion(self, payload): """Process the response of `self.RequestVersion`.""" self.Version = IOHelper.AsSerializableWithType(payload, "neo.Network.Payloads.VersionPayload.VersionPayload") if not self.Version: return if self.incoming_client: if self.Vers...
Process the response of `self.RequestVersion`.
def metric(self): """ The metric of the parameter space. This is a Dictionary of numpy.matrix Each entry in the dictionary is as described under evals. Each numpy.matrix contains the metric of the parameter space in the Lambda_i coordinate system. """ if s...
The metric of the parameter space. This is a Dictionary of numpy.matrix Each entry in the dictionary is as described under evals. Each numpy.matrix contains the metric of the parameter space in the Lambda_i coordinate system.
def _convert_odict_to_classes(self, data, clean=False, merge=True, pop_schema=True, compare_to_existing=True, filter...
Convert `OrderedDict` into `Entry` or its derivative classes.
def rmdir(path): """ Recursively deletes a directory. Includes an error handler to retry with different permissions on Windows. Otherwise, removing directories (eg. cloned via git) can cause rmtree to throw a PermissionError exception """ logger.debug("DEBUG** Window rmdir sys.platform: {}".form...
Recursively deletes a directory. Includes an error handler to retry with different permissions on Windows. Otherwise, removing directories (eg. cloned via git) can cause rmtree to throw a PermissionError exception
def add_column_healpix(self, name="healpix", longitude="ra", latitude="dec", degrees=True, healpix_order=12, nest=True): """Add a healpix (in memory) column based on a longitude and latitude :param name: Name of column :param longitude: longitude expression :param latitude: latitude exp...
Add a healpix (in memory) column based on a longitude and latitude :param name: Name of column :param longitude: longitude expression :param latitude: latitude expression (astronomical convenction latitude=90 is north pole) :param degrees: If lon/lat are in degrees (default) or radians...
def restrict_to_version(self, version): """Restricts the generated SVG file to :obj:`version`. See :meth:`get_versions` for a list of available version values that can be used here. This method should only be called before any drawing operations have been performed on the given...
Restricts the generated SVG file to :obj:`version`. See :meth:`get_versions` for a list of available version values that can be used here. This method should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to...
def generate_grid_coords(gx, gy): r"""Calculate x,y coordinates of each grid cell. Parameters ---------- gx: numeric x coordinates in meshgrid gy: numeric y coordinates in meshgrid Returns ------- (X, Y) ndarray List of coordinates in meshgrid """ retur...
r"""Calculate x,y coordinates of each grid cell. Parameters ---------- gx: numeric x coordinates in meshgrid gy: numeric y coordinates in meshgrid Returns ------- (X, Y) ndarray List of coordinates in meshgrid
def nl_list_entry(ptr, type_, member): """https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L64.""" if ptr.container_of: return ptr.container_of null_data = type_() setattr(null_data, member, ptr) return null_data
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L64.
def get_qout_index(self, river_index_array=None, date_search_start=None, date_search_end=None, time_index_start=None, time_index_end=None, time_index=None, tim...
This method extracts streamflow data by river index. It allows for extracting single or multiple river streamflow arrays It has options to extract by date or by date index. See: :meth:`RAPIDpy.RAPIDDataset.get_qout`
def from_csv(self, csv_source, delimiter=","): """ Set tabular attributes to the writer from a character-separated values (CSV) data source. Following attributes are set to the writer by the method: - :py:attr:`~.headers`. - :py:attr:`~.value_matrix`. :py:attr:`~.table_...
Set tabular attributes to the writer from a character-separated values (CSV) data source. Following attributes are set to the writer by the method: - :py:attr:`~.headers`. - :py:attr:`~.value_matrix`. :py:attr:`~.table_name` also be set if the CSV data source is a file. In that...
def form(**kwargs: Question): """Create a form with multiple questions. The parameter name of a question will be the key for the answer in the returned dict.""" return Form(*(FormField(k, q) for k, q in kwargs.items()))
Create a form with multiple questions. The parameter name of a question will be the key for the answer in the returned dict.
def subscribe_sqs_queue(self, topic, queue): """ Subscribe an SQS queue to a topic. This is convenience method that handles most of the complexity involved in using ans SQS queue as an endpoint for an SNS topic. To achieve this the following operations are performed: ...
Subscribe an SQS queue to a topic. This is convenience method that handles most of the complexity involved in using ans SQS queue as an endpoint for an SNS topic. To achieve this the following operations are performed: * The correct ARN is constructed for the SQS queue and tha...