code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def stop_step(self, step_name): """ Stop a step. """ if self.finished is not None: raise AlreadyFinished() steps = copy.deepcopy(self.steps) step_data = self._get_step(step_name, steps=steps) if step_data is None: raise StepNotStarted() elif 'sto...
Stop a step.
def get_html(self, url, params=None, cache_cb=None, decoder_encoding=None, decoder_errors=url_specified_decoder.ErrorsHandle.strict, **kwargs): """ Get html of an url. """ response = sel...
Get html of an url.
def create_binary_descriptor(streamer): """Create a packed binary descriptor of a DataStreamer object. Args: streamer (DataStreamer): The streamer to create a packed descriptor for Returns: bytes: A packed 14-byte streamer descriptor. """ trigger = 0 if streamer.automatic: ...
Create a packed binary descriptor of a DataStreamer object. Args: streamer (DataStreamer): The streamer to create a packed descriptor for Returns: bytes: A packed 14-byte streamer descriptor.
def common_wire_version(self): """Minimum of all servers' max wire versions, or None.""" servers = self.known_servers if servers: return min(s.max_wire_version for s in self.known_servers) return None
Minimum of all servers' max wire versions, or None.
def _read_composites(self, compositor_nodes): """Read (generate) composites.""" keepables = set() for item in compositor_nodes: self._generate_composite(item, keepables) return keepables
Read (generate) composites.
def _calculateBasalLearning(self, activeColumns, burstingColumns, correctPredictedCells, activeBasalSegments, matchingBasalSegments, basalPo...
Basic Temporal Memory learning. Correctly predicted cells always have active basal segments, and we learn on these segments. In bursting columns, we either learn on an existing basal segment, or we grow a new one. The only influence apical dendrites have on basal learning is: the apical dendrites influ...
def fmt_routes(bottle_app): """Return a pretty formatted string of the list of routes.""" routes = [(r.method, r.rule) for r in bottle_app.routes] if not routes: return string = 'Routes:\n' string += fmt_pairs(routes, sort_key=operator.itemgetter(1)) return string
Return a pretty formatted string of the list of routes.
async def start_component_in_thread(executor, workload: CoroutineFunction[T], *args: Any, loop=None, **kwargs: Any) -> Component[T]: """\ Starts the passed `workload` with additional `commands` and `events` pipes. The workload will be executed on an event loop in a new thread; the thread is provided by `exe...
\ Starts the passed `workload` with additional `commands` and `events` pipes. The workload will be executed on an event loop in a new thread; the thread is provided by `executor`. This function is not compatible with `ProcessPoolExecutor`, as references between the workload and component are necessary....
def match_uriinfo(cls, info): """ :param info: an :py:class:`~httpretty.core.URIInfo` :returns: a 2-item tuple: (:py:class:`~httpretty.core.URLMatcher`, :py:class:`~httpretty.core.URIInfo`) or ``(None, [])`` """ items = sorted( cls._entries.items(), key=la...
:param info: an :py:class:`~httpretty.core.URIInfo` :returns: a 2-item tuple: (:py:class:`~httpretty.core.URLMatcher`, :py:class:`~httpretty.core.URIInfo`) or ``(None, [])``
def blend(self, clr, factor=0.5): """ Returns a mix of two colors. """ r = self.r * (1 - factor) + clr.r * factor g = self.g * (1 - factor) + clr.g * factor b = self.b * (1 - factor) + clr.b * factor a = self.a * (1 - factor) + clr.a * factor return Color(...
Returns a mix of two colors.
def make_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000): """Makes a texture consisting of a spiral from the origin. Args: spirals (float): the number of rotations to make ccw (bool): make spirals counter-clockwise (default is clockwise) offset (float): if non-zero, ...
Makes a texture consisting of a spiral from the origin. Args: spirals (float): the number of rotations to make ccw (bool): make spirals counter-clockwise (default is clockwise) offset (float): if non-zero, spirals start offset by this amount resolution (int): number of midpoints alo...
def get(self, oid): """ Get a single OID value. """ snmpsecurity = self._get_snmp_security() try: engine_error, pdu_error, pdu_error_index, objects = self._cmdgen.getCmd( snmpsecurity, cmdgen.UdpTransportTarget((self.host, self.port), ...
Get a single OID value.
def validate(self, _portfolio, account, algo_datetime, _algo_current_data): """ Make validation checks if we are after the deadline. Fail if the leverage is less than the min leverage. """ if (algo_datetime > sel...
Make validation checks if we are after the deadline. Fail if the leverage is less than the min leverage.
def get_race_card(self, market_ids, data_entries=None, session=None, lightweight=None): """ Returns a list of race cards based on market ids provided. :param list market_ids: The filter to select desired markets :param str data_entries: Data to be returned :param requests.sessio...
Returns a list of race cards based on market ids provided. :param list market_ids: The filter to select desired markets :param str data_entries: Data to be returned :param requests.session session: Requests session object :param bool lightweight: If True will return dict not a resource ...
def native(s): """ Convert :py:class:`bytes` or :py:class:`unicode` to the native :py:class:`str` type, using UTF-8 encoding if conversion is necessary. :raise UnicodeError: The input string is not UTF-8 decodeable. :raise TypeError: The input is neither :py:class:`bytes` nor :py:class:`un...
Convert :py:class:`bytes` or :py:class:`unicode` to the native :py:class:`str` type, using UTF-8 encoding if conversion is necessary. :raise UnicodeError: The input string is not UTF-8 decodeable. :raise TypeError: The input is neither :py:class:`bytes` nor :py:class:`unicode`.
def register(self, key, value, type_info): """ Registers a callable with the specified key and type info. `key` String key to identify a callable. `value` Callable object. `type_info` Dictionary with type information about the ...
Registers a callable with the specified key and type info. `key` String key to identify a callable. `value` Callable object. `type_info` Dictionary with type information about the value provided.
def _get_chart(self, chart_type, x=None, y=None, style=None, opts=None, label=None, options={}, **kwargs): """ Get a full chart object """ sbcharts = ["density", "distribution", "dlinear"] acharts = ["tick", "circle", "text", "line_num", "bar_num"] if chart_type in sbcharts: self._set_seaborn_engi...
Get a full chart object
def entry_at(cls, filepath, index): """:return: RefLogEntry at the given index :param filepath: full path to the index file from which to read the entry :param index: python list compatible index, i.e. it may be negative to specify an entry counted from the end of the list :...
:return: RefLogEntry at the given index :param filepath: full path to the index file from which to read the entry :param index: python list compatible index, i.e. it may be negative to specify an entry counted from the end of the list :raise IndexError: If the entry didn't exist ...
def set_max_attempts(self, value): """stub""" if value is None: raise InvalidArgument('value must be an integer') if value is not None and not isinstance(value, int): raise InvalidArgument('value is not an integer') if not self.my_osid_object_form._is_valid_intege...
stub
def set_vibration(self, left_motor, right_motor, duration): """Control the speed of both motors seperately or together. left_motor and right_motor arguments require a number between 0 (off) and 1 (full). duration is miliseconds, e.g. 1000 for a second.""" if WIN: self...
Control the speed of both motors seperately or together. left_motor and right_motor arguments require a number between 0 (off) and 1 (full). duration is miliseconds, e.g. 1000 for a second.
def is_in_schedule_mode(self): """Returns True if base_station is currently on a scheduled mode.""" resource = "schedule" mode_event = self.publish_and_get_event(resource) if mode_event and mode_event.get("resource", None) == "schedule": properties = mode_event.get('propertie...
Returns True if base_station is currently on a scheduled mode.
def _changes(name, uid=None, gid=None, groups=None, optional_groups=None, remove_groups=True, home=None, createhome=True, password=None, enforce_password=True, empty_password=False, ...
Return a dict of the changes required for a user if the user is present, otherwise return False. Updated in 2015.8.0 to include support for windows homedrive, profile, logonscript, and description fields. Updated in 2014.7.0 to include support for shadow attributes, all attributes supported as int...
def backward_committor(T, A, B, mu=None): r"""Backward committor between given sets. The backward committor u(x) between sets A and B is the probability for the chain starting in x to have come from A last rather than from B. Parameters ---------- T : (M, M) ndarray Transition matr...
r"""Backward committor between given sets. The backward committor u(x) between sets A and B is the probability for the chain starting in x to have come from A last rather than from B. Parameters ---------- T : (M, M) ndarray Transition matrix A : array_like List of integer ...
def cache(self, checkvalidity=True, staleonly=False, allowraise=True): """ Re-caches the Symbol's datatable by querying each Feed. Parameters ---------- checkvalidity : bool, optional Optionally, check validity post-cache. Improve speed by turnin...
Re-caches the Symbol's datatable by querying each Feed. Parameters ---------- checkvalidity : bool, optional Optionally, check validity post-cache. Improve speed by turning to False. staleonly : bool, default False Set to True, for s...
def create(self, key, value): """ Create a new VariableInstance :param unicode key: The key :param unicode value: The value :returns: Newly created VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance """ data ...
Create a new VariableInstance :param unicode key: The key :param unicode value: The value :returns: Newly created VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
def _get_team_results(self, team_result_html): """ Extract the winning or losing team's name and abbreviation. Depending on which team's data field is passed (either the winner or loser), return the name and abbreviation of that team to denote which team won and which lost the g...
Extract the winning or losing team's name and abbreviation. Depending on which team's data field is passed (either the winner or loser), return the name and abbreviation of that team to denote which team won and which lost the game. Parameters ---------- team_result_htm...
def _check_label_or_level_ambiguity(self, key, axis=0): """ Check whether `key` is ambiguous. By ambiguous, we mean that it matches both a level of the input `axis` and a label of the other axis. Parameters ---------- key: str or object label or leve...
Check whether `key` is ambiguous. By ambiguous, we mean that it matches both a level of the input `axis` and a label of the other axis. Parameters ---------- key: str or object label or level name axis: int, default 0 Axis that levels are associa...
def rename_columns(self, col): """ Rename columns of dataframe. Parameters ---------- col : list(str) List of columns to rename. """ try: self.cleaned_data.columns = col except Exception as e: raise e
Rename columns of dataframe. Parameters ---------- col : list(str) List of columns to rename.
def get_account_from_name(self, name): """ Returns the account with the given name. :type name: string :param name: The name of the account. """ for account in self.accounts: if account.get_name() == name: return account return None
Returns the account with the given name. :type name: string :param name: The name of the account.
def add_default_initial_conditions(self, value=None): """Set default initial conditions in the PySB model. Parameters ---------- value : Optional[float] Optionally a value can be supplied which will be the initial amount applied. Otherwise a built-in default is u...
Set default initial conditions in the PySB model. Parameters ---------- value : Optional[float] Optionally a value can be supplied which will be the initial amount applied. Otherwise a built-in default is used.
def do_fuzzyindex(self, word): """Compute fuzzy extensions of word that exist in index. FUZZYINDEX lilas""" word = list(preprocess_query(word))[0] token = Token(word) neighbors = make_fuzzy(token) neighbors = [(n, DB.zcard(dbkeys.token_key(n))) for n in neighbors] neighbors.sort(key=lambda n...
Compute fuzzy extensions of word that exist in index. FUZZYINDEX lilas
def random_word(tokens, tokenizer): """ Masking some random tokens for Language Model task with probabilities as in the original BERT paper. :param tokens: list of str, tokenized sentence. :param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here) :return: (list of str, list...
Masking some random tokens for Language Model task with probabilities as in the original BERT paper. :param tokens: list of str, tokenized sentence. :param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here) :return: (list of str, list of int), masked tokens and related labels for L...
def makephy(data, samples, longname): """ builds phy output. If large files writes 50000 loci at a time to tmp files and rebuilds at the end""" ## order names names = [i.name for i in samples] names.sort() ## read in loci file locifile = os.path.join(data.dirs.outfiles, data.name+".loc...
builds phy output. If large files writes 50000 loci at a time to tmp files and rebuilds at the end
def get(self): """ *do the frankenstein magic!* """ self.log.info('starting the ``get`` method') self._copy_folder_and_get_directory_listings() self._join_all_filenames_and_text() self._collect_placeholders_required() self._populate_dynamic_placeholders()...
*do the frankenstein magic!*
def hexstr(x, onlyasc=0, onlyhex=0, color=False): """Build a fancy tcpdump like hex from bytes.""" x = bytes_encode(x) _sane_func = sane_color if color else sane s = [] if not onlyasc: s.append(" ".join("%02X" % orb(b) for b in x)) if not onlyhex: s.append(_sane_func(x)) retu...
Build a fancy tcpdump like hex from bytes.
def _get_stream(filename, openfunction=open, mode='r'): """Return open stream if *filename* can be opened with *openfunction* or else ``None``.""" try: stream = openfunction(filename, mode=mode) except (IOError, OSError) as err: # An exception might be raised due to two reasons, first the op...
Return open stream if *filename* can be opened with *openfunction* or else ``None``.
def get_canonical_key_id(self, key_id): """ get_canonical_key_id is used by get_canonical_key, see the comment for that method for more explanation. Keyword arguments: key_id -- the key id (e.g. '12345') returns the canonical key id (e.g. '12') """ shard...
get_canonical_key_id is used by get_canonical_key, see the comment for that method for more explanation. Keyword arguments: key_id -- the key id (e.g. '12345') returns the canonical key id (e.g. '12')
def x(self): """Block the main thead until future finish, return the future.result().""" with self._condition: result = None if not self.done(): self._condition.wait(self._timeout) if not self.done(): # timeout self.set_...
Block the main thead until future finish, return the future.result().
def next_frame_basic_stochastic_discrete(): """Basic 2-frame conv model with stochastic discrete latent.""" hparams = basic_deterministic_params.next_frame_sampling() hparams.batch_size = 4 hparams.video_num_target_frames = 6 hparams.scheduled_sampling_mode = "prob_inverse_lin" hparams.scheduled_sampling_de...
Basic 2-frame conv model with stochastic discrete latent.
def unregister(self, svc_ref): # type: (ServiceReference) -> Any """ Unregisters a service :param svc_ref: A service reference :return: The unregistered service instance :raise BundleException: Unknown service reference """ with self.__svc_lock: ...
Unregisters a service :param svc_ref: A service reference :return: The unregistered service instance :raise BundleException: Unknown service reference
def date_range_builder(self, start='2013-02-11', end=None): """ Builds date range query. :param start: Date string. format: YYYY-MM-DD :type start: String :param end: date string. format: YYYY-MM-DD :type end: String ...
Builds date range query. :param start: Date string. format: YYYY-MM-DD :type start: String :param end: date string. format: YYYY-MM-DD :type end: String :returns: String
def remove_node(self, p_id, remove_unconnected_nodes=True): """ Removes a node from the graph. """ if self.has_node(p_id): for neighbor in self.incoming_neighbors(p_id): self._edges[neighbor].remove(p_id) neighbors = set() if remove_unconnected_nodes:...
Removes a node from the graph.
def _get_lineage(self, tax_id, merge_obsolete=True): """Return a list of [(rank, tax_id)] describing the lineage of tax_id. If ``merge_obsolete`` is True and ``tax_id`` has been replaced, use the corresponding value in table merged. """ # Be sure we aren't working with an obsol...
Return a list of [(rank, tax_id)] describing the lineage of tax_id. If ``merge_obsolete`` is True and ``tax_id`` has been replaced, use the corresponding value in table merged.
def do_ls(self, nothing = ''): """list files in current remote directory""" for d in self.dirs: self.stdout.write("\033[0;34m" + ('%s\n' % d) + "\033[0m") for f in self.files: self.stdout.write('%s\n' % f)
list files in current remote directory
def run_benchmarks(dir, models, wav, alphabet, lm_binary=None, trie=None, iters=-1): r''' Core of the running of the benchmarks. We will run on all of models, against the WAV file provided as wav, and the provided alphabet. ''' assert_valid_dir(dir) inference_times = [ ] for model in mode...
r''' Core of the running of the benchmarks. We will run on all of models, against the WAV file provided as wav, and the provided alphabet.
def http2time(text): """Returns time in seconds since epoch of time represented by a string. Return value is an integer. None is returned if the format of str is unrecognized, the time is outside the representable range, or the timezone string is not recognized. If the string contains no timezone...
Returns time in seconds since epoch of time represented by a string. Return value is an integer. None is returned if the format of str is unrecognized, the time is outside the representable range, or the timezone string is not recognized. If the string contains no timezone, UTC is assumed. The t...
def compare_config(self): """ Netmiko is being used to obtain config diffs because pan-python doesn't support the needed command. """ if self.ssh_connection is False: self._open_ssh() self.ssh_device.exit_config_mode() diff = self.ssh_device.send_comm...
Netmiko is being used to obtain config diffs because pan-python doesn't support the needed command.
def snippetWithLink(self, url): """ This method will try to return the first <p> or <div> that contains an <a> tag linking to the given URL. """ link = self.soup.find("a", attrs={'href': url}) if link: for p in link.parents: if p.name in ('p', ...
This method will try to return the first <p> or <div> that contains an <a> tag linking to the given URL.
def log_info(self, data): ''' Logs successful responses ''' info = 'label={label}, id={id}, ilx={ilx}, superclass_tid={super_id}' info_filled = info.format(label = data['label'], id = data['id'], ilx = data['ilx'],...
Logs successful responses
def _is_intrinsic_dict(self, input): """ Can the input represent an intrinsic function in it? :param input: Object to be checked :return: True, if the input contains a supported intrinsic function. False otherwise """ # All intrinsic functions are dictionaries with just...
Can the input represent an intrinsic function in it? :param input: Object to be checked :return: True, if the input contains a supported intrinsic function. False otherwise
def compress_dir(path, compression="gz"): """ Recursively compresses all files in a directory. Note that this compresses all files singly, i.e., it does not create a tar archive. For that, just use Python tarfile class. Args: path (str): Path to parent directory. compression (str): ...
Recursively compresses all files in a directory. Note that this compresses all files singly, i.e., it does not create a tar archive. For that, just use Python tarfile class. Args: path (str): Path to parent directory. compression (str): A compression mode. Valid options are "gz" or ...
def make_filename(s, space=None, language='msdos', strict=False, max_len=None, repeats=1024): r"""Process string to remove any characters not allowed by the language specified (default: MSDOS) In addition, optionally replace spaces with the indicated "space" character (to make the path useful in a copy-pas...
r"""Process string to remove any characters not allowed by the language specified (default: MSDOS) In addition, optionally replace spaces with the indicated "space" character (to make the path useful in a copy-paste without quoting). Uses the following regular expression to substitute spaces for invalid c...
def melt(self, plot=False): """ Find and merge groups of polygons in the surface that meet the following criteria: * Are coplanars. * Are contiguous. * The result is convex. This method is very useful at reducing the num...
Find and merge groups of polygons in the surface that meet the following criteria: * Are coplanars. * Are contiguous. * The result is convex. This method is very useful at reducing the number the items and, therefore, the shadowi...
def list(self, pattern='*'): """Returns a list of resource descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"aws*"``, ``"*cluster*"``. Returns: A list of ResourceDescriptor ob...
Returns a list of resource descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"aws*"``, ``"*cluster*"``. Returns: A list of ResourceDescriptor objects that match the filters.
def run_action(self, unit_sentry, action, _check_output=subprocess.check_output, params=None): """Translate to amulet's built in run_action(). Deprecated. Run the named action on a given unit sentry. params a dict of parameters to use _check_output...
Translate to amulet's built in run_action(). Deprecated. Run the named action on a given unit sentry. params a dict of parameters to use _check_output parameter is no longer used @return action_id.
def _GetGsScopes(self): """Return all Google Storage scopes available on this VM.""" service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key) try: scopes = service_accounts[self.service_account]['scopes'] return list(GS_SCOPES.intersection(set(scopes))) if scopes else None ...
Return all Google Storage scopes available on this VM.
def precompute_optimzation_Y(laplacian_matrix, n_samples, relaxation_kwds): """compute Lk, neighbors and subset to index map for projected == False""" relaxation_kwds.setdefault('presave',False) relaxation_kwds.setdefault('presave_name','pre_comp_current.npy') relaxation_kwds.setdefault('verbose',False)...
compute Lk, neighbors and subset to index map for projected == False
def op(scalars_layout, collections=None): """Creates a summary that contains a layout. When users navigate to the custom scalars dashboard, they will see a layout based on the proto provided to this function. Args: scalars_layout: The scalars_layout_pb2.Layout proto that specifies the layout. ...
Creates a summary that contains a layout. When users navigate to the custom scalars dashboard, they will see a layout based on the proto provided to this function. Args: scalars_layout: The scalars_layout_pb2.Layout proto that specifies the layout. collections: Optional list of graph collections...
def set_idle_params(self, timeout=None, exit=None): """Activate idle mode - put uWSGI in cheap mode after inactivity timeout. :param int timeout: Inactivity timeout in seconds. :param bool exit: Shutdown uWSGI when idle. """ self._set('idle', timeout) self._set('die-on...
Activate idle mode - put uWSGI in cheap mode after inactivity timeout. :param int timeout: Inactivity timeout in seconds. :param bool exit: Shutdown uWSGI when idle.
def upload_sequence_fileobj(file_obj, file_name, fields, retry_fields, session, samples_resource): """Uploads a single file-like object to the One Codex server via either fastx-proxy or directly to S3. Parameters ---------- file_obj : `FASTXInterleave`, `FilePassthru`, or a file-like object ...
Uploads a single file-like object to the One Codex server via either fastx-proxy or directly to S3. Parameters ---------- file_obj : `FASTXInterleave`, `FilePassthru`, or a file-like object A wrapper around a pair of fastx files (`FASTXInterleave`) or a single fastx file. In the case of...
def __create_author_investigator_str(self): """ When investigators is empty, try to get authors from the first publication instead. :return str author: Author names """ _author = "" try: for pub in self.noaa_data_sorted["Publication"]: if "auth...
When investigators is empty, try to get authors from the first publication instead. :return str author: Author names
def get_results_msg(self, results, study): """Return summary for GOEA results.""" # To convert msg list to string: "\n".join(msg) msg = [] if results: fmt = "{M:6,} GO terms are associated with {N:6,} of {NT:6,}" stu_items, num_gos_stu = self.get_item_cnt(results,...
Return summary for GOEA results.
def decrement_display_ref_count(self, amount: int=1): """Decrement display reference count to indicate this library item is no longer displayed.""" assert not self._closed self.__display_ref_count -= amount if self.__display_ref_count == 0: self.__is_master = False if...
Decrement display reference count to indicate this library item is no longer displayed.
def render_targets_weighted_spans( targets, # type: List[TargetExplanation] preserve_density, # type: Optional[bool] ): # type: (...) -> List[Optional[str]] """ Return a list of rendered weighted spans for targets. Function must accept a list in order to select consistent weight ra...
Return a list of rendered weighted spans for targets. Function must accept a list in order to select consistent weight ranges across all targets.
def copyMakeBorder(src, top, bot, left, right, *args, **kwargs): """Pad image border with OpenCV. Parameters ---------- src : NDArray source image top : int, required Top margin. bot : int, required Bottom margin. left : int, required Left margin. right :...
Pad image border with OpenCV. Parameters ---------- src : NDArray source image top : int, required Top margin. bot : int, required Bottom margin. left : int, required Left margin. right : int, required Right margin. type : int, optional, default='...
def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: ...
Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input.
def set_default_names(data): """Sets index names to 'index' for regular, or 'level_x' for Multi""" if all(name is not None for name in data.index.names): return data data = data.copy() if data.index.nlevels > 1: names = [name if name is not None else 'level_{}'.format(i) ...
Sets index names to 'index' for regular, or 'level_x' for Multi
def _tag_net_direction(data): """Create a tag based on the direction of the traffic""" # IP or IPv6 src = data['packet']['src_domain'] dst = data['packet']['dst_domain'] if src == 'internal': if dst == 'internal' or 'multicast' in dst or 'broadcast' in dst: ...
Create a tag based on the direction of the traffic
def extend(self, clauses, weights=None): """ Add several clauses to WCNF formula. The clauses should be given in the form of list. For every clause in the list, method :meth:`append` is invoked. The clauses can be hard or soft depending on the ``weights`` ...
Add several clauses to WCNF formula. The clauses should be given in the form of list. For every clause in the list, method :meth:`append` is invoked. The clauses can be hard or soft depending on the ``weights`` argument. If no weights are set, the clauses are considered ...
def ssn(self): """ Returns a 11 digits Belgian SSN called "rijksregisternummer" as a string The first 6 digits represent the birthdate with (in order) year, month and day. The second group of 3 digits is represents a sequence number (order of birth). It is even for women and odd...
Returns a 11 digits Belgian SSN called "rijksregisternummer" as a string The first 6 digits represent the birthdate with (in order) year, month and day. The second group of 3 digits is represents a sequence number (order of birth). It is even for women and odd for men. For men the range...
def parse_config(file_name='/usr/local/etc/pkg.conf'): ''' Return dict of uncommented global variables. CLI Example: .. code-block:: bash salt '*' pkg.parse_config ``NOTE:`` not working properly right now ''' ret = {} if not os.path.isfile(file_name): return 'Unable t...
Return dict of uncommented global variables. CLI Example: .. code-block:: bash salt '*' pkg.parse_config ``NOTE:`` not working properly right now
def bisect(func, a, b, xtol=1e-12, maxiter=100): """ Finds the root of `func` using the bisection method. Requirements ------------ - func must be continuous function that accepts a single number input and returns a single number - `func(a)` and `func(b)` must have opposite sign Para...
Finds the root of `func` using the bisection method. Requirements ------------ - func must be continuous function that accepts a single number input and returns a single number - `func(a)` and `func(b)` must have opposite sign Parameters ---------- func : function the functio...
def from_text(text): """Convert text into an rcode. @param text: the texual rcode @type text: string @raises UnknownRcode: the rcode is unknown @rtype: int """ if text.isdigit(): v = int(text) if v >= 0 and v <= 4095: return v v = _by_text.get(text.upper()) ...
Convert text into an rcode. @param text: the texual rcode @type text: string @raises UnknownRcode: the rcode is unknown @rtype: int
def _draw(self, color): """Draw the gradient and the selection cross on the canvas.""" width = self.winfo_width() height = self.winfo_height() self.delete("bg") self.delete("cross_h") self.delete("cross_v") del self.bg self.bg = tk.PhotoImage(width=width, ...
Draw the gradient and the selection cross on the canvas.
def revoke(self, paths: Union[str, Iterable[str]], users: Union[str, Iterable[str], User, Iterable[User]], recursive: bool=False): """ See `AccessControlMapper.revoke`. :param paths: see `AccessControlMapper.revoke` :param users: see `AccessControlMapper.revoke` :p...
See `AccessControlMapper.revoke`. :param paths: see `AccessControlMapper.revoke` :param users: see `AccessControlMapper.revoke` :param recursive: whether the access control list should be changed recursively for all nested collections
def main(): '''main routine''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = config_data['tenantI...
main routine
def bundle_dir(): """Handle resource management within an executable file.""" if frozen(): directory = sys._MEIPASS else: directory = os.path.dirname(os.path.abspath(stack()[1][1])) if os.path.exists(directory): return directory
Handle resource management within an executable file.
def tenant_token(self): """The cached token of the current tenant.""" rv = getattr(self, '_tenant_token', None) if rv is None: rv = self._tenant_token = self.tenant.get_token() return rv
The cached token of the current tenant.
def resolve(self, file_path, follow_symlinks=True, allow_fd=False): """Search for the specified filesystem object, resolving all links. Args: file_path: Specifies the target FakeFile object to retrieve. follow_symlinks: If `False`, the link itself is resolved, ot...
Search for the specified filesystem object, resolving all links. Args: file_path: Specifies the target FakeFile object to retrieve. follow_symlinks: If `False`, the link itself is resolved, otherwise the object linked to. allow_fd: If `True`, `file_path` may ...
def ping(self): """ Ping the LDBD Server and return any message received back as a string. @return: message received (may be empty) from LDBD Server as a string """ msg = "PING\0" self.sfile.write(msg) ret, output = self.__response__() reply = str(output[0]) if ret: msg = "...
Ping the LDBD Server and return any message received back as a string. @return: message received (may be empty) from LDBD Server as a string
def catalog(self, categories=None): """ Return information about documents in corpora: a list of tuples (doc_id, doc_title). """ ids = self._filter_ids(None, categories) doc_meta = self._get_meta() return [(doc_id, doc_meta[doc_id].title) for doc_id in ids]
Return information about documents in corpora: a list of tuples (doc_id, doc_title).
def _tls_pad(self, s): """ Provided with the concatenation of the TLSCompressed.fragment and the HMAC, append the right padding and return it as a whole. This is the TLS-style padding: while SSL allowed for random padding, TLS (misguidedly) specifies the repetition of the same by...
Provided with the concatenation of the TLSCompressed.fragment and the HMAC, append the right padding and return it as a whole. This is the TLS-style padding: while SSL allowed for random padding, TLS (misguidedly) specifies the repetition of the same byte all over, and this byte must be ...
def raise_sigint(): """ Raising the SIGINT signal in the current process and all sub-processes. os.kill() only issues a signal in the current process (without subprocesses). CTRL+C on the console sends the signal to the process group (which we need). """ if hasattr(signal, 'CTRL_C_EVENT'): ...
Raising the SIGINT signal in the current process and all sub-processes. os.kill() only issues a signal in the current process (without subprocesses). CTRL+C on the console sends the signal to the process group (which we need).
def touch(self, connection=None): """ Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created. """ self.create_marker_table() i...
Mark this update as complete. IMPORTANT, If the marker table doesn't exist, the connection transaction will be aborted and the connection reset. Then the marker table will be created.
def generatemouseevent(self, x, y, eventType="b1c", drag_button_override='drag_default_button'): """ Generate mouse event on x, y co-ordinates. @param x: X co-ordinate @type x: int @param y: Y co-ordinate @type y: int @param eve...
Generate mouse event on x, y co-ordinates. @param x: X co-ordinate @type x: int @param y: Y co-ordinate @type y: int @param eventType: Mouse click type @type eventType: str @param drag_button_override: Any drag_xxx value Only relevant for ...
def sc_to_fc(spvec, nmax, mmax, nrows, ncols): """assume Ncols is even""" fdata = np.zeros([int(nrows), ncols], dtype=np.complex128) for k in xrange(0, int(ncols / 2)): if k < mmax: kk = k ind = mindx(kk, nmax, mmax) vec = spvec[ind:ind + nmax - np.abs(...
assume Ncols is even
def from_nds2(cls, nds2channel): """Generate a new channel using an existing nds2.channel object """ # extract metadata name = nds2channel.name sample_rate = nds2channel.sample_rate unit = nds2channel.signal_units if not unit: unit = None ctype...
Generate a new channel using an existing nds2.channel object
def delegate_method(other, method, name=None): """Add a method to the current class that delegates to another method. The *other* argument must be a property that returns the instance to delegate to. Due to an implementation detail, the property must be defined in the current class. The *method* argume...
Add a method to the current class that delegates to another method. The *other* argument must be a property that returns the instance to delegate to. Due to an implementation detail, the property must be defined in the current class. The *method* argument specifies a method to delegate to. It can be an...
def delete_user(self, user_descriptor): """DeleteUser. [Preview API] Disables a user. :param str user_descriptor: The descriptor of the user to delete. """ route_values = {} if user_descriptor is not None: route_values['userDescriptor'] = self._serialize.url('...
DeleteUser. [Preview API] Disables a user. :param str user_descriptor: The descriptor of the user to delete.
def read_state_file(self, state_file): """Read the state file, if it exists. If this script has been run previously, resource IDs will have been written to a state file. On starting a run, a state file will be looked for before creating new infrastructure. Information on VPCs, security ...
Read the state file, if it exists. If this script has been run previously, resource IDs will have been written to a state file. On starting a run, a state file will be looked for before creating new infrastructure. Information on VPCs, security groups, and subnets are saved, as well as ...
def endline_repl(self, inputstring, reformatting=False, **kwargs): """Add end of line comments.""" out = [] ln = 1 # line number for line in inputstring.splitlines(): add_one_to_ln = False try: if line.endswith(lnwrapper): line...
Add end of line comments.
def visit_Tuple(self, node): ''' A tuple is abstracted as an ordered container of its values >>> from pythran import passmanager >>> pm = passmanager.PassManager('demo') >>> module = ast.parse('def foo(a, b): return a, b') >>> result = pm.gather(Aliases, module) ...
A tuple is abstracted as an ordered container of its values >>> from pythran import passmanager >>> pm = passmanager.PassManager('demo') >>> module = ast.parse('def foo(a, b): return a, b') >>> result = pm.gather(Aliases, module) >>> Aliases.dump(result, filter=ast.Tuple) ...
def update_user_trackers(sender, topic, user, request, response, **kwargs): """ Receiver to mark a topic being viewed as read. This can result in marking the related forum tracker as read. """ TrackingHandler = get_class('forum_tracking.handler', 'TrackingHandler') # noqa track_handler = Tracking...
Receiver to mark a topic being viewed as read. This can result in marking the related forum tracker as read.
def committer(self) -> Developer: """ Return the committer of the commit as a Developer object. :return: committer """ return Developer(self._c_object.committer.name, self._c_object.committer.email)
Return the committer of the commit as a Developer object. :return: committer
def modules(self): """Iterates over the defined Modules.""" defmodule = lib.EnvGetNextDefmodule(self._env, ffi.NULL) while defmodule != ffi.NULL: yield Module(self._env, defmodule) defmodule = lib.EnvGetNextDefmodule(self._env, defmodule)
Iterates over the defined Modules.
def _add_config_regions(nblock_regions, ref_regions, data): """Add additional nblock regions based on configured regions to call. Identifies user defined regions which we should not be analyzing. """ input_regions_bed = dd.get_variant_regions(data) if input_regions_bed: input_regions = pybed...
Add additional nblock regions based on configured regions to call. Identifies user defined regions which we should not be analyzing.
def set_transform_interface_params(spec, input_features, output_features, are_optional = False): """ Common utilities to set transform interface params. """ input_features = _fm.process_or_validate_features(input_features) output_features = _fm.process_or_validate_features(output_features) # Add in...
Common utilities to set transform interface params.
def request_slot(client, service: JID, filename: str, size: int, content_type: str): """ Request an HTTP upload slot. :param client: The client to request the slot with. :type client: :class:`aioxmpp.Client` :param service: Address...
Request an HTTP upload slot. :param client: The client to request the slot with. :type client: :class:`aioxmpp.Client` :param service: Address of the HTTP upload service. :type service: :class:`~aioxmpp.JID` :param filename: Name of the file (without path), may be used by the server to gene...
def seek(self, offset, whence=0): """Change the file position. The new position is specified by offset, relative to the position indicated by whence. Possible values for whence are: 0: start of stream (default): offset must not be negative 1: current stream position ...
Change the file position. The new position is specified by offset, relative to the position indicated by whence. Possible values for whence are: 0: start of stream (default): offset must not be negative 1: current stream position 2: end of stream; offset must not be...
def prj_show_path(self, ): """Show the dir in the a filebrowser of the project :returns: None :rtype: None :raises: None """ f = self.prj_path_le.text() osinter = ostool.get_interface() osinter.open_path(f)
Show the dir in the a filebrowser of the project :returns: None :rtype: None :raises: None