code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def _merge_lib_dict(d1, d2): for required, requirings in d2.items(): if required in d1: d1[required].update(requirings) else: d1[required] = requirings return None
Merges lib_dict `d2` into lib_dict `d1`
def add(self, dist): new_path = ( dist.location not in self.paths and ( dist.location not in self.sitedirs or dist.location == os.getcwd() ) ) if new_path: self.paths.append(dist.location) self.dirty = True E...
Add `dist` to the distribution map
def delete_downloads(): shutil.rmtree(vtki.EXAMPLES_PATH) os.makedirs(vtki.EXAMPLES_PATH) return True
Delete all downloaded examples to free space or update the files
def data_size(metadata): info = metadata['info'] if 'length' in info: total_size = info['length'] else: total_size = sum([f['length'] for f in info['files']]) return total_size
Calculate the size of a torrent based on parsed metadata.
def snils(self) -> str: numbers = [] control_codes = [] for i in range(0, 9): numbers.append(self.random.randint(0, 9)) for i in range(9, 0, -1): control_codes.append(numbers[9 - i] * i) control_code = sum(control_codes) code = ''.join(str(number) ...
Generate snils with special algorithm. :return: SNILS. :Example: 41917492600.
def guess_encoding(request): ctype = request.headers.get('content-type') if not ctype: LOGGER.warning("%s: no content-type; headers are %s", request.url, request.headers) return 'utf-8' match = re.search(r'charset=([^ ;]*)(;| |$)', ctype) if match: return m...
Try to guess the encoding of a request without going through the slow chardet process
def walk(self, root="~/"): root = validate_type(root, *six.string_types) directories = [] files = [] query_fd_path = root if not query_fd_path.endswith("/"): query_fd_path += "/" for fd_object in self.get_filedata(fd_path == query_fd_path): if fd_o...
Emulation of os.walk behavior against Device Cloud filedata store This method will yield tuples in the form ``(dirpath, FileDataDirectory's, FileData's)`` recursively in pre-order (depth first from top down). :param str root: The root path from which the search should commence. By default, th...
def step(self, action): if self.done: raise ValueError('cannot step in a done environment! call `reset`') self.controllers[0][:] = action _LIB.Step(self._env) reward = self._get_reward() self.done = self._get_done() info = self._get_info() self._did_st...
Run one frame of the NES and return the relevant observation data. Args: action (byte): the bitmap determining which buttons to press Returns: a tuple of: - state (np.ndarray): next frame as a result of the given action - reward (float) : amount of rewar...
def validate(self, require_all=True, scale='colors'): super(self.__class__, self).validate() required_attribs = ('data', 'scales', 'axes', 'marks') for elem in required_attribs: attr = getattr(self, elem) if attr: for entry in attr: ent...
Validate the visualization contents. Parameters ---------- require_all : boolean, default True If True (default), then all fields ``data``, ``scales``, ``axes``, and ``marks`` must be defined. The user is allowed to disable this if the intent is to define the...
def get_qapp(): global app app = QtGui.QApplication.instance() if app is None: app = QtGui.QApplication([], QtGui.QApplication.GuiClient) return app
Return an instance of QApplication. Creates one if neccessary. :returns: a QApplication instance :rtype: QApplication :raises: None
def get_handle(): global __handle__ if not __handle__: __handle__ = FT_Library() error = FT_Init_FreeType(byref(__handle__)) if error: raise RuntimeError(hex(error)) return __handle__
Get unique FT_Library handle
def runner_argspec(module=''): run_ = salt.runner.Runner(__opts__) return salt.utils.args.argspec_report(run_.functions, module)
Return the argument specification of functions in Salt runner modules. .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' sys.runner_argspec state salt '*' sys.runner_argspec http salt '*' sys.runner_argspec Runner names can be specified as globs. ...
def train_step(self, Xi, yi, **fit_params): step_accumulator = self.get_train_step_accumulator() def step_fn(): step = self.train_step_single(Xi, yi, **fit_params) step_accumulator.store_step(step) return step['loss'] self.optimizer_.step(step_fn) retu...
Prepares a loss function callable and pass it to the optimizer, hence performing one optimization step. Loss function callable as required by some optimizers (and accepted by all of them): https://pytorch.org/docs/master/optim.html#optimizer-step-closure The module is set to be...
def partition_pair(bif_point): n = float(sum(1 for _ in bif_point.children[0].ipreorder())) m = float(sum(1 for _ in bif_point.children[1].ipreorder())) return (n, m)
Calculate the partition pairs at a bifurcation point The number of nodes in each child tree is counted. The partition pairs is the number of bifurcations in the two daughter subtrees at each branch point.
def _gather_beams(nested, beam_indices, batch_size, new_beam_size): batch_pos = tf.range(batch_size * new_beam_size) // new_beam_size batch_pos = tf.reshape(batch_pos, [batch_size, new_beam_size]) coordinates = tf.stack([batch_pos, beam_indices], axis=2) return nest.map_structure( lambda state: tf.gather_...
Gather beams from nested structure of tensors. Each tensor in nested represents a batch of beams, where beam refers to a single search state (beam search involves searching through multiple states in parallel). This function is used to gather the top beams, specified by beam_indices, from the nested tensors...
def set_waypoint_quota(self, waypoint_quota): if self.get_waypoint_quota_metadata().is_read_only(): raise NoAccess() if not self.my_osid_object_form._is_valid_cardinal(waypoint_quota, self.get_waypoint_quota_metadata()): ...
how many waypoint questions need to be answered correctly
def _decode_value(self, value): if isinstance(value, (int, float, str, bool, datetime)): return value elif isinstance(value, list): return [self._decode_value(item) for item in value] elif isinstance(value, dict): result = {} for key, item in value...
Decodes the value by turning any binary data back into Python objects. The method searches for ObjectId values, loads the associated binary data from GridFS and returns the decoded Python object. Args: value (object): The value that should be decoded. Raises: D...
def _find_pivot_addr(self, index): if not self.addresses or index.start == 0: return CharAddress('', self.tree, 'text', -1) if index.start > len(self.addresses): return self.addresses[-1] return self.addresses[index.start]
Inserting by slicing can lead into situation where no addresses are selected. In that case a pivot address has to be chosen so we know where to add characters.
def calc_qbgz_v1(self): con = self.parameters.control.fastaccess flu = self.sequences.fluxes.fastaccess sta = self.sequences.states.fastaccess sta.qbgz = 0. for k in range(con.nhru): if con.lnk[k] == SEE: sta.qbgz += con.fhru[k]*(flu.nkor[k]-flu.evi[k]) elif con.lnk[k] no...
Aggregate the amount of base flow released by all "soil type" HRUs and the "net precipitation" above water areas of type |SEE|. Water areas of type |SEE| are assumed to be directly connected with groundwater, but not with the stream network. This is modelled by adding their (positive or negative) "net...
def apply(self, axes="gca"): if axes == "gca": axes = _pylab.gca() self.reset() lines = axes.get_lines() for l in lines: l.set_color(self.get_line_color(1)) l.set_mfc(self.get_face_color(1)) l.set_marker(self.get_marker(1)) l.set_mec(self.g...
Applies the style cycle to the lines in the axes specified
def victims(self, filters=None, params=None): victim = self._tcex.ti.victim(None) for v in self.tc_requests.victims_from_tag( victim, self.name, filters=filters, params=params ): yield v
Gets all victims from a tag.
def stage(self, name): for stage in self.stages(): if stage.data.name == name: return stage
Method for searching specific stage by it's name. :param name: name of the stage to search. :return: found stage or None. :rtype: yagocd.resources.stage.StageInstance
def get_value(self, attribute, section, default=""): if not self.attribute_exists(attribute, section): return default if attribute in self.__sections[section]: value = self.__sections[section][attribute] elif foundations.namespace.set_namespace(section, attribute) in self...
Returns requested attribute value. Usage:: >>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \ "[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"] >>> sections_file_parser = SectionsFileParser() >>> sections_file_parser.content = con...
def export_survey_participant_list(self, instrument, event=None, format='json'): pl = self.__basepl(content='participantList', format=format) pl['instrument'] = instrument if event: pl['event'] = event return self._call_api(pl, 'exp_survey_participant_list')
Export the Survey Participant List Notes ----- The passed instrument must be set up as a survey instrument. Parameters ---------- instrument: str Name of instrument as seen in second column of Data Dictionary. event: str Unique event name...
def create_schema(self, schema): if schema not in self.schemas: sql = "CREATE SCHEMA " + schema self.execute(sql)
Create specified schema if it does not already exist
def _add_id_or_name(flat_path, element_pb, empty_allowed): id_ = element_pb.id name = element_pb.name if id_ == 0: if name == u"": if not empty_allowed: raise ValueError(_EMPTY_ELEMENT) else: flat_path.append(name) else: if name == u"": ...
Add the ID or name from an element to a list. :type flat_path: list :param flat_path: List of accumulated path parts. :type element_pb: :class:`._app_engine_key_pb2.Path.Element` :param element_pb: The element containing ID or name. :type empty_allowed: bool :param empty_allowed: Indicates if...
def shutdown(self): with self._lock: for cid in list(self.connections.keys()): if self.connections[cid].executing: raise ConnectionBusyError(cid) if self.connections[cid].locked: self.connections[cid].free() self...
Forcefully shutdown the entire pool, closing all non-executing connections. :raises: ConnectionBusyError
def normalize(self, body): resource = body['data'] data = {'rtype': resource['type']} if 'attributes' in resource: attributes = resource['attributes'] attributes = self._normalize_attributes(attributes) data.update(attributes) if 'relationships' in res...
Invoke the JSON API normalizer Perform the following: * add the type as a rtype property * flatten the payload * add the id as a rid property ONLY if present We don't need to vet the inputs much because the Parser has already done all the work. :pa...
def find_deck_spawns(provider: Provider, prod: bool=True) -> Iterable[str]: pa_params = param_query(provider.network) if isinstance(provider, RpcNode): if prod: decks = (i["txid"] for i in provider.listtransactions("PAPROD")) else: decks = (i["txid"] for i in provider.lis...
find deck spawn transactions via Provider, it requires that Deck spawn P2TH were imported in local node or that remote API knows about P2TH address.
def labels(self, hs_dims=None, prune=False): if self.ca_as_0th: labels = self._cube.labels(include_transforms_for_dims=hs_dims)[1:] else: labels = self._cube.labels(include_transforms_for_dims=hs_dims)[-2:] if not prune: return labels def prune_dimensi...
Get labels for the cube slice, and perform pruning by slice.
def rollforward(self, date): if self.onOffset(date): return date else: return date + QuarterEnd(month=self.month)
Roll date forward to nearest end of quarter
def _expression_to_sql(expression, node, context): _expression_transformers = { expressions.LocalField: _transform_local_field_to_expression, expressions.Variable: _transform_variable_to_expression, expressions.Literal: _transform_literal_to_expression, expressions.BinaryComposition:...
Recursively transform a Filter block predicate to its SQLAlchemy expression representation. Args: expression: expression, the compiler expression to transform. node: SqlNode, the SqlNode the expression applies to. context: CompilationContext, global compilation state and metadata. Retu...
def convert_to_xml(cls, degrees): if degrees < 0.0: degrees %= -360 degrees += 360 elif degrees > 0.0: degrees %= 360 return str(int(round(degrees * cls.DEGREE_INCREMENTS)))
Convert signed angle float like -427.42 to int 60000 per degree. Value is normalized to a positive value less than 360 degrees.
def count_delayed_jobs(cls, names): return sum([queue.delayed.zcard() for queue in cls.get_all(names)])
Return the number of all delayed jobs in queues with the given names
def log_likelihood(self): if self._log_likelihood is None: self._log_likelihood = logpdf(x=self.y, cov=self.S) return self._log_likelihood
log-likelihood of the last measurement.
def list(): kbs = [] ret = _pshell_json('Get-HotFix | Select HotFixID') for item in ret: kbs.append(item['HotFixID']) return kbs
Get a list of updates installed on the machine Returns: list: A list of installed updates CLI Example: .. code-block:: bash salt '*' wusa.list
def _get_match(self, prefix): if _cpr_response_re.match(prefix): return Keys.CPRResponse elif _mouse_event_re.match(prefix): return Keys.Vt100MouseEvent try: return ANSI_SEQUENCES[prefix] except KeyError: return None
Return the key that maps to this prefix.
def subclass_exception(name, parents, module, attached_to=None): class_dict = {'__module__': module} if attached_to is not None: def __reduce__(self): return (unpickle_inner_exception, (attached_to, name), self.args) def __setstate__(self, args): self.args = args ...
Create exception subclass. If 'attached_to' is supplied, the exception will be created in a way that allows it to be pickled, assuming the returned exception class will be added as an attribute to the 'attached_to' class.
def parse_model_group(path, group): context = FilePathContext(path) for reaction_id in group.get('reactions', []): yield reaction_id for reaction_id in parse_model_group_list( context, group.get('groups', [])): yield reaction_id
Parse a structured model group as obtained from a YAML file Path can be given as a string or a context.
def on_selection_changed(self, sel): m, self.editing_iter = sel.get_selected() if self.editing_iter: self.editing_model = m[self.editing_iter][0] self.show_curr_model_view(self.editing_model, False) else: self.view.remove_currency_view() return
The user changed selection
def delay(self, params, now=None): if now is None: now = time.time() if not self.last: self.last = now elif now < self.last: now = self.last leaked = now - self.last self.last = now self.level = max(self.level - leaked, 0) diffe...
Determine delay until next request.
def NormalizePath(path, sep="/"): if not path: return sep path = SmartUnicode(path) path_list = path.split(sep) if path_list[0] in [".", "..", ""]: path_list.pop(0) i = 0 while True: list_len = len(path_list) for i in range(i, len(path_list)): if path_list[i] == "." or not path_list[i]...
A sane implementation of os.path.normpath. The standard implementation treats leading / and // as different leading to incorrect normal forms. NOTE: Its ok to use a relative path here (without leading /) but any /../ will still be removed anchoring the path at the top level (e.g. foo/../../../../bar => bar)...
def get_child_ids(self): if self.has_magic_children(): if self._child_parts is None: self.generate_children() child_ids = list() for part in self._child_parts: child_ids.append(part.get_id()) return IdList(child_ids, ...
gets the ids for the child parts
def tox_configure(config): if 'TRAVIS' not in os.environ: return ini = config._cfg if 'TOXENV' not in os.environ and not config.option.env: envlist = detect_envlist(ini) undeclared = set(envlist) - set(config.envconfigs) if undeclared: print('Matching undeclared e...
Check for the presence of the added options.
def remove(self, row): self._rows.remove(row) self._deleted_rows.add(row)
Removes the row from the list.
def process(self, job): sandbox = self.sandboxes.pop(0) try: with Worker.sandbox(sandbox): job.sandbox = sandbox job.process() finally: self.greenlets.pop(job.jid, None) self.sandboxes.append(sandbox)
Process a job
def cat_data(data_kw): if len(data_kw) == 0: return pd.DataFrame() return pd.DataFrame(pd.concat([ data.assign(ticker=ticker).set_index('ticker', append=True) .unstack('ticker').swaplevel(0, 1, axis=1) for ticker, data in data_kw.items() ], axis=1))
Concatenate data with ticker as sub column index Args: data_kw: key = ticker, value = pd.DataFrame Returns: pd.DataFrame Examples: >>> start = '2018-09-10T10:10:00' >>> tz = 'Australia/Sydney' >>> idx = pd.date_range(start=start, periods=6, freq='min').tz_localize(...
def lemmatize(self): _lemmatizer = PatternParserLemmatizer(tokenizer=NLTKPunktTokenizer()) _raw = " ".join(self) + "." _lemmas = _lemmatizer.lemmatize(_raw) return self.__class__([Word(l, t) for l, t in _lemmas])
Return the lemma of each word in this WordList. Currently using NLTKPunktTokenizer() for all lemmatization tasks. This might cause slightly different tokenization results compared to the TextBlob.words property.
def get_create_batch_env_fun(batch_env_fn, time_limit): def create_env_fun(game_name=None, sticky_actions=None): del game_name, sticky_actions batch_env = batch_env_fn(in_graph=False) batch_env = ResizeBatchObservation(batch_env) batch_env = DopamineBatchEnv(batch_env, max_episode_steps=time_limit) ...
Factory for dopamine environment initialization function. Args: batch_env_fn: function(in_graph: bool) -> batch environment. time_limit: time steps limit for environment. Returns: function (with optional, unused parameters) initializing environment.
def name(self): python = self._python if self._python.startswith('pypy'): python = python[2:] return environment.get_env_name(self.tool_name, python, self._requirements)
Get a name to uniquely identify this environment.
def context(self, id): if id not in self.circuits: self.circuits[id] = self.factory(self.clock, self.log.getChild(id), self.error_types, self.maxfail, self.reset_timeout, ...
Return a circuit breaker for the given ID.
def id(opts): r = salt.utils.http.query(opts['proxy']['url']+'id', decode_type='json', decode=True) return r['dict']['id'].encode('ascii', 'ignore')
Return a unique ID for this proxy minion. This ID MUST NOT CHANGE. If it changes while the proxy is running the salt-master will get really confused and may stop talking to this minion
def down(self, migration_id): if not self.check_directory(): return for migration in self.get_migrations_to_down(migration_id): logger.info('Rollback migration %s' % migration.filename) migration_module = self.load_migration_file(migration.filename) if has...
Rollback to migration.
def nt_yielder(self, graph, size): for grp in self.make_batch(size, graph): tmpg = Graph() tmpg += grp yield (len(tmpg), tmpg.serialize(format='nt'))
Yield n sized ntriples for a given graph. Used in sending chunks of data to the VIVO SPARQL API.
def interpolate(self): self.latitude = self._interp(self.lat_tiepoint) self.longitude = self._interp(self.lon_tiepoint) return self.latitude, self.longitude
Do the interpolation and return resulting longitudes and latitudes.
def encodeSequence(seq_vec, vocab, neutral_vocab, maxlen=None, seq_align="start", pad_value="N", encode_type="one_hot"): if isinstance(neutral_vocab, str): neutral_vocab = [neutral_vocab] if isinstance(seq_vec, str): raise ValueError("seq_vec should be an iterable returning " ...
Convert a list of genetic sequences into one-hot-encoded array. # Arguments seq_vec: list of strings (genetic sequences) vocab: list of chars: List of "words" to use as the vocabulary. Can be strings of length>0, but all need to have the same length. For DNA, this is: ["A", "C", "G", "T"]...
def __on_message(self, msg): msgtype = msg['type'] msgfrom = msg['from'] if msgtype == 'groupchat': if self._nick == msgfrom.resource: return elif msgtype not in ('normal', 'chat'): return self.__callback(msg)
XMPP message received
def make_token(cls, ephemeral_token: 'RedisEphemeralTokens') -> str: value = ephemeral_token.key if ephemeral_token.scope: value += ''.join(ephemeral_token.scope) return get_hmac(cls.KEY_SALT + ephemeral_token.salt, value)[::2]
Returns a token to be used x number of times to allow a user account to access certain resource.
def _get_marker_output(self, asset_quantities, metadata): payload = openassets.protocol.MarkerOutput(asset_quantities, metadata).serialize_payload() script = openassets.protocol.MarkerOutput.build_script(payload) return bitcoin.core.CTxOut(0, script)
Creates a marker output. :param list[int] asset_quantities: The asset quantity list. :param bytes metadata: The metadata contained in the output. :return: An object representing the marker output. :rtype: TransactionOutput
def return_single_real_id_base(dbpath, set_object, object_id): engine = create_engine('sqlite:////' + dbpath) session_cl = sessionmaker(bind=engine) session = session_cl() tmp_object = session.query(set_object).get(object_id) session.close() return tmp_object.real_id
Generic function which returns a real_id string of an object specified by the object_id Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database object_id : int, id of object in database Returns ---...
def log_url (self, url_data, priority=None): self.xml_starttag(u'url') self.xml_tag(u'loc', url_data.url) if url_data.modified: self.xml_tag(u'lastmod', self.format_modified(url_data.modified, sep="T")) self.xml_tag(u'changefreq', self.frequency) self.xml_tag(u'priori...
Log URL data in sitemap format.
def _get_bufsize_linux(iface): ret = {'result': False} cmd = '/sbin/ethtool -g {0}'.format(iface) out = __salt__['cmd.run'](cmd) pat = re.compile(r'^(.+):\s+(\d+)$') suffix = 'max-' for line in out.splitlines(): res = pat.match(line) if res: ret[res.group(1).lower().r...
Return network interface buffer information using ethtool
def monthly_build_list_regex(self): return r'nightly/%(YEAR)s/%(MONTH)s/' % { 'YEAR': self.date.year, 'MONTH': str(self.date.month).zfill(2)}
Return the regex for the folder containing builds of a month.
def precondition(precond): def decorator(f): def decorated(*args): if len(args) > 2: raise TypeError('%s takes only 1 argument (or 2 for instance methods)' % f.__name__) try: instance, data = args if not isinstance(instance, Pipe): ...
Runs the callable responsible for making some assertions about the data structure expected for the transformation. If the precondition is not achieved, a UnmetPrecondition exception must be raised, and then the transformation pipe is bypassed.
def get_directory_as_zip(self, remote_path, local_file): remote_path = self._normalize_path(remote_path) url = self.url + 'index.php/apps/files/ajax/download.php?dir=' \ + parse.quote(remote_path) res = self._session.get(url, stream=True) if res.status_code == 200: ...
Downloads a remote directory as zip :param remote_path: path to the remote directory to download :param local_file: path and name of the target local file :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
def get_max_id(self, object_type, role): if object_type == 'user': objectclass = 'posixAccount' ldap_attr = 'uidNumber' elif object_type == 'group': objectclass = 'posixGroup' ldap_attr = 'gidNumber' else: raise ldap_tools.exceptions.In...
Get the highest used ID.
def _pick_unused_port_without_server(): rng = random.Random() for _ in range(10): port = int(rng.randrange(15000, 25000)) if is_port_free(port): _random_ports.add(port) return port for _ in range(10): port = bind(0, _PROTOS[0][0], _PROTOS[0][1]) if por...
Pick an available network port without the help of a port server. This code ensures that the port is available on both TCP and UDP. This function is an implementation detail of PickUnusedPort(), and should not be called by code outside of this module. Returns: A port number that is unused on bo...
def readTableFromCSV(f, dialect="excel"): rowNames = [] columnNames = [] matrix = [] first = True for row in csv.reader(f, dialect): if first: columnNames = row[1:] first = False else: rowNames.append(row[0]) matrix.append([float(c) for...
Reads a table object from given CSV file.
def get_encoding(input_string, guesses=None, is_html=False): converted = UnicodeDammit(input_string, override_encodings=[guesses] if guesses else [], is_html=is_html) return converted.original_encoding
Return the encoding of a byte string. Uses bs4 UnicodeDammit. :param string input_string: Encoded byte string. :param list[string] guesses: (Optional) List of encoding guesses to prioritize. :param bool is_html: Whether the input is HTML.
def delete_account_metadata(self, prefix=None): if prefix is None: prefix = ACCOUNT_META_PREFIX curr_meta = self.get_account_metadata(prefix=prefix) for ckey in curr_meta: curr_meta[ckey] = "" new_meta = _massage_metakeys(curr_meta, prefix) uri = "/" ...
Removes all metadata matching the specified prefix from the account. By default, the standard account metadata prefix ('X-Account-Meta-') is prepended to the header name if it isn't present. For non-standard headers, you must include a non-None prefix, such as an empty string.
def __read_chunk(self, start, size): for _retries in range(3): command = 1504 command_string = pack('<ii', start, size) if self.tcp: response_size = size + 32 else: response_size = 1024 + 8 cmd_response = self.__send_com...
read a chunk from buffer
def stop(self): if self.server.eio.async_mode == 'threading': func = flask.request.environ.get('werkzeug.server.shutdown') if func: func() else: raise RuntimeError('Cannot stop unknown web server') elif self.server.eio.async_mode == 'ev...
Stop a running SocketIO web server. This method must be called from a HTTP or SocketIO handler function.
def get_protocol(handle: Handle, want_v2: bool) -> Protocol: force_v1 = int(os.environ.get("TREZOR_PROTOCOL_V1", 1)) if want_v2 and not force_v1: return ProtocolV2(handle) else: return ProtocolV1(handle)
Make a Protocol instance for the given handle. Each transport can have a preference for using a particular protocol version. This preference is overridable through `TREZOR_PROTOCOL_V1` environment variable, which forces the library to use V1 anyways. As of 11/2018, no devices support V2, so we enforce...
def _post_build(self, module, encoding): module.file_encoding = encoding self._manager.cache_module(module) for from_node in module._import_from_nodes: if from_node.modname == "__future__": for symbol, _ in from_node.names: module.future_imports.ad...
Handles encoding and delayed nodes after a module has been built
def get_template(self, path): if self.options['debug'] and self.options['cache_size']: return self.cache.get(path, self.cache_template(path)) return self.load_template(path)
Load and compile template.
def get_feature_report(self, report_id, length): self._check_device_status() bufp = ffi.new("unsigned char[]", length+1) buf = ffi.buffer(bufp, length+1) buf[0] = report_id rv = hidapi.hid_get_feature_report(self._device, bufp, length+1) if rv == -1: raise IOE...
Get a feature report from the device. :param report_id: The Report ID of the report to be read :type report_id: int :return: The report data :rtype: str/bytes
def GetGRRVersionString(self): client_info = self.startup_info.client_info client_name = client_info.client_description or client_info.client_name if client_info.client_version > 0: client_version = str(client_info.client_version) else: client_version = _UNKNOWN_GRR_VERSION return " ".jo...
Returns the client installation-name and GRR version as a string.
def parse_item(self, location: str, item_type: Type[T], item_name_for_log: str = None, file_mapping_conf: FileMappingConfiguration = None, options: Dict[str, Dict[str, Any]] = None) -> T: item_name_for_log = item_name_for_log or '' check_var(item_name_for_log, var_types=str, var_name=...
Main method to parse an item of type item_type :param location: :param item_type: :param item_name_for_log: :param file_mapping_conf: :param options: :return:
def create_token(self, request, refresh_token=False, **kwargs): if "save_token" in kwargs: warnings.warn("`save_token` has been deprecated, it was not called internally." "If you do, call `request_validator.save_token()` instead.", DeprecationWarni...
Create a BearerToken, by default without refresh token. :param request: OAuthlib request. :type request: oauthlib.common.Request :param refresh_token:
def stop(self): if self.container_id is None: raise Exception('No Docker Selenium container was running') check_call(['docker', 'stop', self.container_id]) self.container_id = None
Stop the Docker container
def log_time(func): @functools.wraps(func) def _execute(*args, **kwargs): func_name = get_method_name(func) timer = Timer() log_message(func_name, "has started") with timer: result = func(*args, **kwargs) seconds = "{:.3f}".format(timer.elapsed_time()) ...
Executes function and logs time :param func: function to call :return: function result
def srun_nodes(self): count = self.execution.get('srun_nodes', 0) if isinstance(count, six.string_types): tag = count count = 0 elif isinstance(count, SEQUENCES): return count else: assert isinstance(count, int) tag = self.tag ...
Get list of nodes where to execute the command
def processor(ctx, processor_cls, process_time_limit, enable_stdout_capture=True, get_object=False): g = ctx.obj Processor = load_cls(None, None, processor_cls) processor = Processor(projectdb=g.projectdb, inqueue=g.fetcher2processor, status_queue=g.status_queue, ...
Run Processor.
def unregister(self, label: str) -> None: self.unregister_encoder(label) self.unregister_decoder(label)
Unregisters the entries in the encoder and decoder registries which have the label ``label``.
def eval(thunk, env): key = Activation.key(thunk, env) if Activation.activated(key): raise exceptions.RecursionError('Reference cycle') with Activation(key): return eval_cache.get(key, thunk.eval, env)
Evaluate a thunk in an environment. Will defer the actual evaluation to the thunk itself, but adds two things: caching and recursion detection. Since we have to use a global evaluation stack (because there is a variety of functions that may be invoked, not just eval() but also __getitem__, and not all of them...
def _process_event(self, event, tagged_data): event_type = event.WhichOneof('what') if event_type == 'summary': for value in event.summary.value: value = data_compat.migrate_value(value) tag, metadata, values = tagged_data.get(value.tag, (None, None, [])) values.append((event.step,...
Processes a single tf.Event and records it in tagged_data.
def _get_reader(self, network_reader): with (yield from self._lock): if self._reader_process is None: self._reader_process = network_reader if self._reader: if self._reader_process == network_reader: self._current_read = asyncio.async(s...
Get a reader or None if another reader is already reading.
def cleanup(self, cluster): if self._storage_path and os.path.exists(self._storage_path): fname = '%s.%s' % (AnsibleSetupProvider.inventory_file_ending, cluster.name) inventory_path = os.path.join(self._storage_path, fname) if os.path.exists(inv...
Deletes the inventory file used last recently used. :param cluster: cluster to clear up inventory file for :type cluster: :py:class:`elasticluster.cluster.Cluster`
def pil2tensor(image:Union[NPImage,NPArray],dtype:np.dtype)->TensorImage: "Convert PIL style `image` array to torch style image tensor." a = np.asarray(image) if a.ndim==2 : a = np.expand_dims(a,2) a = np.transpose(a, (1, 0, 2)) a = np.transpose(a, (2, 1, 0)) return torch.from_numpy(a.astype(dty...
Convert PIL style `image` array to torch style image tensor.
def get_explicit_resnorms(self, indices=None): res = self.get_explicit_residual(indices) linear_system = self._deflated_solver.linear_system Mres = linear_system.M * res resnorms = numpy.zeros(res.shape[1]) for i in range(resnorms.shape[0]): resnorms[i] = utils.norm(r...
Explicitly computes the Ritz residual norms.
def metadata_get(self, path, cached=True): try: value = graceful_chain_get(self.inspect(cached=cached).response, *path) except docker.errors.NotFound: logger.warning("object %s is not available anymore", self) raise NotAvailableAnymore() return value
get metadata from inspect, specified by path :param path: list of str :param cached: bool, use cached version of inspect if available
def _GetHeader(self): header = [] for value in self.values: try: header.append(value.Header()) except SkipValue: continue return header
Returns header.
def to_serializable_value(self): return { name: field.to_serializable_value() for name, field in self.value.__dict__.items() if isinstance(field, Field) and self.value }
Run through all fields of the object and parse the values :return: :rtype: dict
def new_document(self): doc = Document(self, None) doc.create() super(CouchDatabase, self).__setitem__(doc['_id'], doc) return doc
Creates a new, empty document in the remote and locally cached database, auto-generating the _id. :returns: Document instance corresponding to the new document in the database
def get_methodnames(self, node): nodekey = self.get_nodekey(node) prefix = self._method_prefix if isinstance(nodekey, self.GeneratorType): for nodekey in nodekey: yield self._method_prefix + nodekey else: yield self._method_prefix + nodekey
Given a node, generate all names for matching visitor methods.
def button_with_label(self, description, assistants=None): btn = self.create_button() label = self.create_label(description) if assistants is not None: h_box = self.create_box(orientation=Gtk.Orientation.VERTICAL) h_box.pack_start(label, False, False, 0) label...
Function creates a button with lave. If assistant is specified then text is aligned
def get_field(self, page, language, initial=None): if self.parsed: help_text = _('Note: This field is evaluated as template code.') else: help_text = '' widget = self.get_widget(page, language) return self.field( widget=widget, initial=initial, ...
The field that will be shown within the admin.
def add_listener(self, event_name: str, listener: Callable): self.listeners[event_name].append(listener) return self
Add a listener.
def downloads_per_week(self): if len(self.cache_dates) < 7: logger.error("Only have %d days of data; cannot calculate " "downloads per week", len(self.cache_dates)) return None count, _ = self._downloads_for_num_days(7) logger.debug("Downloads per...
Return the number of downloads in the last 7 days. :return: number of downloads in the last 7 days; if we have less than 7 days of data, returns None. :rtype: int
def delete_user_avatar(self, username, avatar): params = {'username': username} url = self._get_url('user/avatar/' + avatar) return self._session.delete(url, params=params)
Delete a user's avatar. :param username: the user to delete the avatar from :param avatar: ID of the avatar to remove