code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def y_tic_points(self, interval): "Return the list of Y values for which tick marks and grid lines are drawn." if type(interval) == FunctionType: return interval(*self.y_range) return self.y_coord.get_tics(self.y_range[0], self.y_range[1], interval)
Return the list of Y values for which tick marks and grid lines are drawn.
def _replace_wildcards(self, name, run_idx=None): """Replaces the $ wildcards and returns True/False in case it was replaced""" if self._root_instance.f_is_wildcard(name): return True, self._root_instance.f_wildcard(name, run_idx) else: return False, name
Replaces the $ wildcards and returns True/False in case it was replaced
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` clas...
Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to t...
def _parse_title(self): """Parse the title from TeX source. Sets these attributes: - ``_title`` - ``_short_title`` """ command = LatexCommand( 'title', {'name': 'short_title', 'required': False, 'bracket': '['}, {'name': 'long_title',...
Parse the title from TeX source. Sets these attributes: - ``_title`` - ``_short_title``
def _diff_cache_subnet_group(current, desired): ''' If you need to enhance what modify_cache_subnet_group() considers when deciding what is to be (or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used in modify_cache_subnet_group() to that in describe_cache_subnet_grou...
If you need to enhance what modify_cache_subnet_group() considers when deciding what is to be (or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used in modify_cache_subnet_group() to that in describe_cache_subnet_group(). Any data fiddlery that needs to be done to make th...
def hashimage(hashvalue): """generate image by hash, usese tempfile :-/""" tmpf = tempfile.mkstemp(".png")[1] image = pagan.Avatar("") image.img = pagan.generator.generate_by_hash(hashvalue) image.save("/", tmpf) return static_file(tmpf, root="/")
generate image by hash, usese tempfile :-/
def to_sql(self, app=None, last_known_value_date: Optional[date] = None): """ Inserts the model into the SQLite3 database associated with Delphi, for use with the ICM REST API. """ from delphi.apps.rest_api import create_app, db self.assign_uuids_to_nodes_and_edges() icm_metada...
Inserts the model into the SQLite3 database associated with Delphi, for use with the ICM REST API.
def selectisinstance(table, field, value, complement=False): """Select rows where the given field is an instance of the given type.""" return selectop(table, field, value, isinstance, complement=complement)
Select rows where the given field is an instance of the given type.
def ingest(self, text, log_message=None): """ Ingest a new object into Fedora. Returns the pid of the new object on success. Calls :meth:`ApiFacade.ingest`. :param text: full text content of the object to be ingested :param log_message: optional log message :rtype: stri...
Ingest a new object into Fedora. Returns the pid of the new object on success. Calls :meth:`ApiFacade.ingest`. :param text: full text content of the object to be ingested :param log_message: optional log message :rtype: string
def print_permutations(self): """Print all valid permutations.""" index = 0 permutations = [] for p in self._input_permutations: permutations.append({'index': index, 'args': p}) index += 1 with open('permutations.json', 'w') as fh: json.dump(pe...
Print all valid permutations.
def done(self): """ done """ self.elapsed = time.time() - self.start elapsed_disp = self.format_time(self.elapsed) stream = sys.stderr bar_template = '%s|%s%s| \033[32m%s/%s - %s\033[0m\r' self.last_progress = "%.1f" % float(self.last_progress) sel...
done
def disk_free(path): """Return free bytes on partition holding `path`.""" stats = os.statvfs(path) return stats.f_bavail * stats.f_frsize
Return free bytes on partition holding `path`.
def on_open(self, websocket): '''When a new websocket connection is established it creates a new :class:`ChatClient` and adds it to the set of clients of the :attr:`pubsub` handler.''' LOGGER.info('New websocket opened. Add client to %s on "%s" channel', self.pubsub, ...
When a new websocket connection is established it creates a new :class:`ChatClient` and adds it to the set of clients of the :attr:`pubsub` handler.
def finish(self): """Declare this section finished""" self._my_map['over'] = True # finished == over? self._my_map['completionTime'] = DateTime.utcnow() self._save()
Declare this section finished
def validate(self, _portfolio, _account, _algo_datetime, _algo_current_data): """ Fail if the leverage is greater than the allowed leverage. """ if _account.leverage > self.max_leverage: self.fail()
Fail if the leverage is greater than the allowed leverage.
def _is_a_url(input_element): """ ----- Brief ----- Auxiliary function responsible for checking if the input is a string that contains an url. ----------- Description ----------- Some biosignalsnotebooks functions support a remote access to files. In this situation it is importa...
----- Brief ----- Auxiliary function responsible for checking if the input is a string that contains an url. ----------- Description ----------- Some biosignalsnotebooks functions support a remote access to files. In this situation it is important to understand if the input is an url, w...
def spawn_program(self, name, arguments=[], timeout=30, exclusive=False): """Spawns a program in the working directory. This method allows the interaction with the running program, based on the returned RunningProgram object. Args: name (str): The name of the program...
Spawns a program in the working directory. This method allows the interaction with the running program, based on the returned RunningProgram object. Args: name (str): The name of the program to be executed. arguments (tuple): Command-line arguments for the progra...
def _cont_to_discrete_object(cls, X, F, L, Qc, compute_derivatives=False, grad_params_no=None, P_inf=None, dP_inf=None, dF = None, dQc=None, dt0=None): """ Function return the object which is used in Kalma...
Function return the object which is used in Kalman filter and/or smoother to obtain matrices A, Q and their derivatives for discrete model from the continuous model. There are 2 objects AQcompute_once and AQcompute_batch and the function returs the appropriate one based on the number of...
def wait_for_elements( self, using, value, timeout=10000, interval=1000, asserter=is_displayed): """Wait for elements till satisfy the given condition Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(st...
Wait for elements till satisfy the given condition Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. timeout(int): How long we should be retrying stuff. interval...
def access_time(self): """dfdatetime.DateTimeValues: access time or None if not available.""" timestamp = self._fsapfs_file_entry.get_access_time_as_integer() return dfdatetime_apfs_time.APFSTime(timestamp=timestamp)
dfdatetime.DateTimeValues: access time or None if not available.
def _inferPhase1(self, activeColumns, useStartCells): """ Update the inference active state from the last set of predictions and the current bottom-up. This looks at: - ``infPredictedState['t-1']`` This modifies: - ``infActiveState['t']`` :param activeColumns: (list) active bot...
Update the inference active state from the last set of predictions and the current bottom-up. This looks at: - ``infPredictedState['t-1']`` This modifies: - ``infActiveState['t']`` :param activeColumns: (list) active bottom-ups :param useStartCells: (bool) If true, ignore previous ...
def paginate(self, request): """Paginate collection.""" return self.collection.offset(self.offset).limit(self.limit)
Paginate collection.
def member_del(self, repl_id, member_id): """remove member from replica set (reconfig replica) Args: repl_id - replica set identity member_id - member index """ repl = self[repl_id] result = repl.member_del(member_id) self[repl_id] = repl r...
remove member from replica set (reconfig replica) Args: repl_id - replica set identity member_id - member index
def get_components_for_species( alignment, species ): """Return the component for each species in the list `species` or None""" # If the number of components in the alignment is less that the requested number # of species we can immediately fail if len( alignment.components ) < len( species ): return No...
Return the component for each species in the list `species` or None
def request(self, path, method=None, data={}): """sends a request and gets a response from the Plivo REST API path: the URL (relative to the endpoint URL, after the /v1 method: the HTTP method to use, defaults to POST data: for POST or PUT, a dict of data to send returns Plivo ...
sends a request and gets a response from the Plivo REST API path: the URL (relative to the endpoint URL, after the /v1 method: the HTTP method to use, defaults to POST data: for POST or PUT, a dict of data to send returns Plivo response in XML or raises an exception on error
def create_lxc(name, template='ubuntu', service=None): """Factory method for the generic LXC""" service = service or LXCService service.create(name, template=template) meta = LXCMeta(initial=dict(type='LXC')) lxc = LXC.with_meta(name, service, meta, save=True) return lxc
Factory method for the generic LXC
def sameAddr(self, ha, ha2) -> bool: """ Check whether the two arguments correspond to the same address """ if ha == ha2: return True if ha[1] != ha2[1]: return False return ha[0] in self.localips and ha2[0] in self.localips
Check whether the two arguments correspond to the same address
def configurations(self): """Configurations from uwsgiconf module.""" if self._confs is not None: return self._confs with output_capturing(): module = self.load(self.fpath) confs = getattr(module, CONFIGS_MODULE_ATTR) confs = listify(confs) ...
Configurations from uwsgiconf module.
def _do_wait(self, timeout): """Wait for the deferred to be completed for a period of time Raises TimeoutError if the wait times out before the future is done. Raises CancelledError if the future is cancelled before the timeout is done. """ if self._cancelled: ...
Wait for the deferred to be completed for a period of time Raises TimeoutError if the wait times out before the future is done. Raises CancelledError if the future is cancelled before the timeout is done.
def init(self, only_mount=None, skip_mount=None, swallow_exceptions=True): """Generator that mounts this volume and either yields itself or recursively generates its subvolumes. More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by :func:`mou...
Generator that mounts this volume and either yields itself or recursively generates its subvolumes. More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by :func:`mount`, followed by a call to :func:`detect_mountpoint`, after which ``self`` is yielded,...
def _compute_csum(data): # type: (bytes) -> int ''' A method to compute a simple checksum over the given data. Parameters: data - The data to compute the checksum over. Returns: The checksum. ''' def identity(x): # type: (int) -> int ''' The identity functi...
A method to compute a simple checksum over the given data. Parameters: data - The data to compute the checksum over. Returns: The checksum.
def from_codes(cls, codes, categories=None, ordered=None, dtype=None): """ Make a Categorical type from codes and categories or dtype. This constructor is useful if you already have codes and categories/dtype and so do not need the (computation intensive) factorization step, whi...
Make a Categorical type from codes and categories or dtype. This constructor is useful if you already have codes and categories/dtype and so do not need the (computation intensive) factorization step, which is usually done on the constructor. If your data does not follow this conventio...
def command(*commands, visible = True, internal = False, nargs = '*'): """Decorate a function to be the entry function of commands. Arguments: commands: Names of command that should trigger this function object. visible: This command is visible in tab completions. internal: The lexing r...
Decorate a function to be the entry function of commands. Arguments: commands: Names of command that should trigger this function object. visible: This command is visible in tab completions. internal: The lexing rule is unchanged even if the parse_line() method is overloaded in ...
def name_variants(self): """List of named tuples containing variants of the author name with number of documents published with that variant. """ fields = 'indexed_name initials surname given_name doc_count' variant = namedtuple('Variant', fields) path = ['author-profile'...
List of named tuples containing variants of the author name with number of documents published with that variant.
def _parse_key_val(stream): """Parse key, value combination return (tuple): Parsed key (string) Parsed value (either a string, array, or dict) """ logger.debug("parsing key/val") key = _parse_key(stream) val = _parse_val(stream) logger.debug("parsed key/val") logger.deb...
Parse key, value combination return (tuple): Parsed key (string) Parsed value (either a string, array, or dict)
def execute_notebook(nb_path, pkg_dir, dataframes, write_notebook=False, env=None): """ Execute a notebook after adding the prolog and epilog. Can also add %mt_materialize magics to write dataframes to files :param nb_path: path to a notebook. :param pkg_dir: Directory to which dataframes are mater...
Execute a notebook after adding the prolog and epilog. Can also add %mt_materialize magics to write dataframes to files :param nb_path: path to a notebook. :param pkg_dir: Directory to which dataframes are materialized :param dataframes: List of names of dataframes to materialize :return: a Noteboo...
def is_namedtuple_like(x): """Helper which returns `True` if input is `collections.namedtuple`-like.""" try: for fn in x._fields: _ = getattr(x, fn) return True except AttributeError: return False
Helper which returns `True` if input is `collections.namedtuple`-like.
def find(self, location): """ Find the specified location in the store. @param location: The I{location} part of a URL. @type location: str @return: An input stream to the document. @rtype: StringIO """ try: content = self.store[location] ...
Find the specified location in the store. @param location: The I{location} part of a URL. @type location: str @return: An input stream to the document. @rtype: StringIO
def validate_type_registry(option, value): """Validate the type_registry option.""" if value is not None and not isinstance(value, TypeRegistry): raise TypeError("%s must be an instance of %s" % ( option, TypeRegistry)) return value
Validate the type_registry option.
def res(arg): ''' Convert the argument into an IRI ref ''' def _res(ctx): _arg = arg(ctx) if callable(arg) else arg return I(arg) return _res
Convert the argument into an IRI ref
def rc_stats(stats): """ reverse completement stats """ rc_nucs = {'A':'T', 'T':'A', 'G':'C', 'C':'G', 'N':'N'} rcs = [] for pos in reversed(stats): rc = {} rc['reference frequencey'] = pos['reference frequency'] rc['consensus frequencey'] = pos['consensus frequency'] ...
reverse completement stats
def get_plugin_actions(self): """Return a list of actions related to plugin""" return [self.rich_text_action, self.plain_text_action, self.show_source_action, MENU_SEPARATOR, self.auto_import_action]
Return a list of actions related to plugin
def log_status(plugin, filename, status): '''Properly display a migration status line''' display = ':'.join((plugin, filename)) + ' ' log.info('%s [%s]', '{:.<70}'.format(display), status)
Properly display a migration status line
def magic_memory(self, line): """ Print out the current value of memory Usage: Pass in the byte of memory to read, separated by spaced A list of memory contents can be entered by separating them by a hyphen `%mem 4 5` or `%mem 8-12` """ #...
Print out the current value of memory Usage: Pass in the byte of memory to read, separated by spaced A list of memory contents can be entered by separating them by a hyphen `%mem 4 5` or `%mem 8-12`
async def _check_subscriptions(self): """ Checks that all subscriptions are subscribed """ subscribed, url = await self._get_subscriptions() expect = set(settings.FACEBOOK_SUBSCRIPTIONS) if (expect - subscribed) or url != self.webhook_url: await self._set_su...
Checks that all subscriptions are subscribed
def get(self, name, default=None): """Fetch an option from the dictionary. Args: name (str): The name of the option. default: The value to return if the name is missing. Returns: any: The value stored by the option. This method resolves th...
Fetch an option from the dictionary. Args: name (str): The name of the option. default: The value to return if the name is missing. Returns: any: The value stored by the option. This method resolves the option to its value rather than returning ...
def als(X, rank, **kwargs): """ RESCAL-ALS algorithm to compute the RESCAL tensor factorization. Parameters ---------- X : list List of frontal slices X_k of the tensor X. The shape of each X_k is ('N', 'N'). X_k's are expected to be instances of scipy.sparse.csr_matrix ...
RESCAL-ALS algorithm to compute the RESCAL tensor factorization. Parameters ---------- X : list List of frontal slices X_k of the tensor X. The shape of each X_k is ('N', 'N'). X_k's are expected to be instances of scipy.sparse.csr_matrix rank : int Rank of the factoriz...
def set_style(style=None, rc=None): """ Set the aesthetic style of the plots. This affects things like the color of the axes, whether a grid is enabled by default, and other aesthetic elements. Parameters ---------- style : dict, None, or one of {darkgrid, whitegrid, dark, white, ticks} ...
Set the aesthetic style of the plots. This affects things like the color of the axes, whether a grid is enabled by default, and other aesthetic elements. Parameters ---------- style : dict, None, or one of {darkgrid, whitegrid, dark, white, ticks} A dictionary of parameters or the name of ...
def send_message_from_thread(self, stream, msg): """Thread-safe version of send_message() returning a Future instance. Returns ------- A Future that will resolve without raising an exception as soon as the call to send_message() completes. This does not guarantee that the ...
Thread-safe version of send_message() returning a Future instance. Returns ------- A Future that will resolve without raising an exception as soon as the call to send_message() completes. This does not guarantee that the message has been delivered yet. If the call to send_messag...
def play_note(self, note, duration, volume=100, play_type=PLAY_WAIT_FOR_COMPLETE): """ Plays a note, given by its name as defined in ``_NOTE_FREQUENCIES``. :param string note: The note symbol with its octave number :param float duration: Tone duration, in seconds :param int volume: The ...
Plays a note, given by its name as defined in ``_NOTE_FREQUENCIES``. :param string note: The note symbol with its octave number :param float duration: Tone duration, in seconds :param int volume: The play volume, in percent of maximum volume :param play_type: The behavior of ``play_not...
def halt(self): """Switch state to HALT""" buf = [] buf.append(self.act_end) buf.append(0) crc = self.calculate_crc(buf) self.clear_bitmask(0x08, 0x80) self.card_write(self.mode_transrec, buf) self.clear_bitmask(0x08, 0x08) self.authed = False
Switch state to HALT
def file_search(self, query, offset=None, timeout=None): """ Search for samples. In addition to retrieving all information on a particular file, VirusTotal allows you to perform what we call "advanced reverse searches". Reverse searches take you from a file property to a list of files that ...
Search for samples. In addition to retrieving all information on a particular file, VirusTotal allows you to perform what we call "advanced reverse searches". Reverse searches take you from a file property to a list of files that match that property. For example, this functionality enables you ...
def convert_effsize(ef, input_type, output_type, nx=None, ny=None): """Conversion between effect sizes. Parameters ---------- ef : float Original effect size input_type : string Effect size type of ef. Must be 'r' or 'd'. output_type : string Desired effect size type. ...
Conversion between effect sizes. Parameters ---------- ef : float Original effect size input_type : string Effect size type of ef. Must be 'r' or 'd'. output_type : string Desired effect size type. Available methods are :: 'none' : no effect size 'co...
def _iterate(self, delay=None, fromqt=False): """See twisted.internet.interfaces.IReactorCore.iterate. """ self.runUntilCurrent() self.doIteration(delay, fromqt)
See twisted.internet.interfaces.IReactorCore.iterate.
def register(self): """ Register via the method configured :return: """ if self.register_method == "twine": self.register_by_twine() if self.register_method == "setup": self.register_by_setup() if self.register_method == "upload": ...
Register via the method configured :return:
def update(self): "Adjust facade with the dimensions of the original object (and repaint)" x, y = self.obj.wx_obj.GetPosition() w, h = self.obj.wx_obj.GetSize() self.Hide() self.Move((x, y)) self.SetSize((w, h)) # allow original control to repaint before taking th...
Adjust facade with the dimensions of the original object (and repaint)
def enumeration(values, converter=str, default=''): """Return an enumeration string based on the given values. The following four examples show the standard output of function |enumeration|: >>> from hydpy.core.objecttools import enumeration >>> enumeration(('text', 3, [])) 'text, 3, and []' ...
Return an enumeration string based on the given values. The following four examples show the standard output of function |enumeration|: >>> from hydpy.core.objecttools import enumeration >>> enumeration(('text', 3, [])) 'text, 3, and []' >>> enumeration(('text', 3)) 'text and 3' >>> en...
def will_print(level=1): """Returns True if the current global status of messaging would print a message using any of the printing functions in this module. """ if level == 1: #We only affect printability using the quiet setting. return quiet is None or quiet == False else: r...
Returns True if the current global status of messaging would print a message using any of the printing functions in this module.
def betweenness_centrality(self, normalized=True): """ Calculates betweenness centrality and returns an node id -> weight dictionary. Node betweenness weights are updated in the process. """ bc = proximity.brandes_betweenness_centrality(self, normalized) for id, w in bc.iteritems...
Calculates betweenness centrality and returns an node id -> weight dictionary. Node betweenness weights are updated in the process.
def output(self, _filename): """ _filename is not used Args: _filename(string) """ for contract in self.slither.contracts_derived: txt = "\nContract %s"%contract.name table = PrettyTable(["Function", ...
_filename is not used Args: _filename(string)
def calc_db(peak, refval, mphonecaldb=0): u""" Converts voltage difference into decibels : 20*log10(peak/refval) :param peak: amplitude :type peak: float or np.array :param refval: This can be either a another sound peak(or RMS val), to get the dB difference, or the microphone mphone_sensitivi...
u""" Converts voltage difference into decibels : 20*log10(peak/refval) :param peak: amplitude :type peak: float or np.array :param refval: This can be either a another sound peak(or RMS val), to get the dB difference, or the microphone mphone_sensitivity :type refval: float :param mphoneca...
def check_metric(self, metric): """Check that the metric is supported by the KNNIndex instance.""" if metric not in self.VALID_METRICS: raise ValueError( f"`{self.__class__.__name__}` does not support the `{metric}` " f"metric. Please choose one of the support...
Check that the metric is supported by the KNNIndex instance.
def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ with open(os.path.expanduser("~/config/.note.conf")) as fd: config = json.loads(fd.read()) try: u = config['server']['login']['username'] p = config['s...
This function is called to check if a username / password combination is valid.
def binarize(df, category_classes, all_classes=True, drop=True, astype=None, inplace=True, min_freq=None): """ Binarize specified categoricals. Works inplace! Args: - df: the DataFrame whose columns to binarize - category_classes: either a dict of (column : [class1, class2, ......
Binarize specified categoricals. Works inplace! Args: - df: the DataFrame whose columns to binarize - category_classes: either a dict of (column : [class1, class2, ...]) pairs or a collection of column names, in which case classes are given using df[column].unique() ...
def message(self, message: types.Message): """ Select target message :param message: :return: """ setattr(self, 'from_chat_id', message.chat.id) setattr(self, 'message_id', message.message_id) return self
Select target message :param message: :return:
def partial_declaration_path(decl): """ Returns a list of parent declarations names without template arguments that have default value. Args: decl (declaration_t): declaration for which the partial declaration path should be calculated. Returns: list[(...
Returns a list of parent declarations names without template arguments that have default value. Args: decl (declaration_t): declaration for which the partial declaration path should be calculated. Returns: list[(str | basestring)]: list of names, where first i...
def nearestPoint(self, pos): """ Returns the nearest graphing point for this item based on the inputed graph position. :param pos | <QPoint> :return (<variant> x, <variant> y) """ # lookup subpaths for x, y, path in sel...
Returns the nearest graphing point for this item based on the inputed graph position. :param pos | <QPoint> :return (<variant> x, <variant> y)
def slicenet_params1_tiny(): """Version for fast local runs.""" hparams = slicenet_params1() hparams.attention_type = "simple" hparams.separability = 0 hparams.hidden_size = 128 hparams.num_hidden_layers = 2 hparams.batch_size = 512 hparams.learning_rate_warmup_steps = 200 return hparams
Version for fast local runs.
def checkout(repository, target): """ Check out target into the current directory. Target can be a branch, review Id, or commit. :param repository: Current git repository. :param target: Review ID, commit, branch. :return: Return the most recent commit ID (top of the git log). """ # git...
Check out target into the current directory. Target can be a branch, review Id, or commit. :param repository: Current git repository. :param target: Review ID, commit, branch. :return: Return the most recent commit ID (top of the git log).
def _construct_result(left, result, index, name, dtype=None): """ If the raw op result has a non-None name (e.g. it is an Index object) and the name argument is None, then passing name to the constructor will not be enough; we still need to override the name attribute. """ out = left._constructo...
If the raw op result has a non-None name (e.g. it is an Index object) and the name argument is None, then passing name to the constructor will not be enough; we still need to override the name attribute.
def __validation_property_range(self, p): """ if p.sub_property_of(q) then for every y in included_ranges(p) we have y is subclass of some r in included_ranges(q) -- for object properties """ for y in p.included_ranges(): superclasses = y.super_classes_closure...
if p.sub_property_of(q) then for every y in included_ranges(p) we have y is subclass of some r in included_ranges(q) -- for object properties
def _build_model(self): """ Build the model. """ # Set up LSTM modules self.lstms = nn.ModuleList( [ RNN( num_classes=0, num_tokens=self.word_dict.s, emb_size=self.settings["emb_dim"], ...
Build the model.
def client_list(self): """Get the list of client connections. Returns list of ClientInfo named tuples. """ fut = self.execute(b'CLIENT', b'LIST', encoding='utf-8') return wait_convert(fut, to_tuples)
Get the list of client connections. Returns list of ClientInfo named tuples.
def start(instance_id, call=None): ''' Start an instance. CLI Examples: .. code-block:: bash salt-cloud -a start i-2f733r5n ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) log.info('Starting i...
Start an instance. CLI Examples: .. code-block:: bash salt-cloud -a start i-2f733r5n
def check_error(code, context="client"): """ check if the error code is set. If so, a Python log message is generated and an error is raised. """ if code: error = error_text(code, context) logger.error(error) raise Snap7Exception(error)
check if the error code is set. If so, a Python log message is generated and an error is raised.
def reset(resources, *args, **kwargs): """ Remove dispensers and indicators for idle resources. """ test = kwargs.pop('test', False) client = redis.Redis(decode_responses=True, **kwargs) resources = resources if resources else find_resources(client) for resource in resources: # investigate ...
Remove dispensers and indicators for idle resources.
def json_export(self, dest, fieldnames=None, encoding="UTF-8"): """Exports the contents of the table to a JSON-formatted file. @param dest: output file - if a string is given, the file with that name will be opened, written, and closed; if a file object is given, then that object ...
Exports the contents of the table to a JSON-formatted file. @param dest: output file - if a string is given, the file with that name will be opened, written, and closed; if a file object is given, then that object will be written as-is, and left for the caller to be closed. ...
def search(self, pattern="*", mode="both"): """Perform a pattern-based search on keyword names and documentation The pattern matching is insensitive to case. The function returns a list of tuples of the form library_id, library_name, keyword_name, keyword_synopsis, sorted by library id,...
Perform a pattern-based search on keyword names and documentation The pattern matching is insensitive to case. The function returns a list of tuples of the form library_id, library_name, keyword_name, keyword_synopsis, sorted by library id, library name, and then keyword name I...
def _check_compatibility(self): """Make sure the next objects to be tallied are compatible with the stored trace.""" stored_descr = self._file_trace_description() try: for k, v in self._model_trace_description(): assert(stored_descr[k][0] == v[0]) exce...
Make sure the next objects to be tallied are compatible with the stored trace.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict
Return a json dictionary representing this model.
def get_ref_favorites(self, project, repository_id=None, identity_id=None): """GetRefFavorites. [Preview API] Gets the refs favorites for a repo and an identity. :param str project: Project ID or project name :param str repository_id: The id of the repository. :param str identity...
GetRefFavorites. [Preview API] Gets the refs favorites for a repo and an identity. :param str project: Project ID or project name :param str repository_id: The id of the repository. :param str identity_id: The id of the identity whose favorites are to be retrieved. If null, the requestin...
def setting_str_to_bool(s): """ Converts 'true' to True and 'false' to False if s is a string """ if isinstance(s, six.string_types): s = s.lower() if s == 'true': return True elif s == 'false': return False else: return ValueError('Invalid...
Converts 'true' to True and 'false' to False if s is a string
def add_tag_to_derived_metric(self, id, tag_value, **kwargs): # noqa: E501 """Add a tag to a specific Derived Metric # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread...
Add a tag to a specific Derived Metric # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.add_tag_to_derived_metric(id, tag_value, async_req=True) >>> result = th...
def _remove_action_from_type(valid_actions: Dict[str, List[str]], type_: str, filter_function: Callable[[str], bool]) -> None: """ Finds the production rule matching the filter function in the given type's valid action list, and r...
Finds the production rule matching the filter function in the given type's valid action list, and removes it. If there is more than one matching function, we crash.
def _get_debug_context(debug_port, debug_args, debugger_path): """ Creates a DebugContext if the InvokeContext is in a debugging mode Parameters ---------- debug_port int Port to bind the debugger to debug_args str Additional arguments passed to ...
Creates a DebugContext if the InvokeContext is in a debugging mode Parameters ---------- debug_port int Port to bind the debugger to debug_args str Additional arguments passed to the debugger debugger_path str Path to the directory of the deb...
def bedrooms(self): """ This method gets the number of bedrooms. :return: """ try: if self._data_from_search: info = self._data_from_search.find( 'ul', {"class": "info"}).text s = info.split('|') nb =...
This method gets the number of bedrooms. :return:
def build_substr_idx(umis, umi_length, min_edit): ''' Build a dictionary of nearest neighbours using substrings, can be used to reduce the number of pairwise comparisons. ''' substr_idx = collections.defaultdict( lambda: collections.defaultdict(set)) slices = get_substr_slices(umi_length...
Build a dictionary of nearest neighbours using substrings, can be used to reduce the number of pairwise comparisons.
def get_groups(self, username): """Returns list of groups in which user is. :param username: name of Linux user """ groups = [] for group in grp.getgrall(): if username in group.gr_mem: groups.append(group.gr_name) return groups
Returns list of groups in which user is. :param username: name of Linux user
def user_quantity_remaining(self, user, filtered=True): ''' returns 0 if the date range is violated, otherwise, it will return the quantity remaining under the stock limit. The filter for this condition must add an annotation called "remainder" in order for this to work. ''' ...
returns 0 if the date range is violated, otherwise, it will return the quantity remaining under the stock limit. The filter for this condition must add an annotation called "remainder" in order for this to work.
def urls(self, version=None): """Returns all URLS that are mapped to this interface""" urls = [] for base_url, routes in self.api.http.routes.items(): for url, methods in routes.items(): for method, versions in methods.items(): for interface_versio...
Returns all URLS that are mapped to this interface
def cdx_limit(cdx_iter, limit): """ limit cdx to at most `limit`. """ # for cdx, _ in itertools.izip(cdx_iter, xrange(limit)): # yield cdx return (cdx for cdx, _ in zip(cdx_iter, range(limit)))
limit cdx to at most `limit`.
def from_name(cls, name): """ Retrieve a disk id associated to a name. """ disks = cls.list({'name': name}) if len(disks) == 1: return disks[0]['id'] elif not disks: return raise DuplicateResults('disk name %s is ambiguous.' % name)
Retrieve a disk id associated to a name.
def oauth_token_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/oauth_tokens#create-token" api_path = "/api/v2/oauth/tokens.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/oauth_tokens#create-token
def find_index(segmentation, stroke_id): """ >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 0) 0 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 1) 0 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 5) 2 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 6) 2 """ for i, symbol in en...
>>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 0) 0 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 1) 0 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 5) 2 >>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 6) 2
def get_raw_access_token(self, request_token, request_token_secret, method='GET', **kwargs): ''' Returns a Requests' response over the :attr:`rauth.OAuth1Service.access_token_url`....
Returns a Requests' response over the :attr:`rauth.OAuth1Service.access_token_url`. Use this if your endpoint if you need the full `Response` object. :param request_token: The request token as returned by :meth:`get_request_token`. :type request_token: str :param re...
def append(self, element): """See list.append.""" super(ObservableList, self).append(element) self._notify_add_at(len(self) - 1)
See list.append.
def translate_colorname_to_ansi_code(colorname, offset, colormode, colorpalette): """ Translate the given color name to a valid ANSI escape code. :parma str colorname: the name of the color to resolve :parma str offset: the offset for the color code :param int colormode: the color mode to use. ...
Translate the given color name to a valid ANSI escape code. :parma str colorname: the name of the color to resolve :parma str offset: the offset for the color code :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code`` :parma dict colorpalette: the color palette to use for ...
def msg_warn(message): """ Log a warning message :param message: the message to be logged """ to_stdout(" (!) {message}".format(message=message), colorf=yellow, bold=True) if _logger: _logger.warn(message)
Log a warning message :param message: the message to be logged
def _train_and_eval_single(train, valid, model, batch_size=32, epochs=300, use_weight=False, callbacks=[], eval_best=False, add_eval_metrics={}): """Fit and evaluate a keras model eval_best: if True, load the checkpointed model for evaluation """ de...
Fit and evaluate a keras model eval_best: if True, load the checkpointed model for evaluation
def _writeCloseFrame(self, reason=DISCONNECT.GO_AWAY): '''Write a close frame with the given reason and schedule this connection close. ''' self.transport.writeClose(reason) self.transport.loseConnection() self.transport = None
Write a close frame with the given reason and schedule this connection close.