Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
11,200
def maybe_gzip_open(path, *args, **kwargs): path = path_to_str(path) if path.endswith() or path.endswith(): _open = gzip.open else: _open = open return _open(path, *args, **kwargs)
Open file with either open or gzip.open, depending on file extension. This function doesn't handle json lines format, just opens a file in a way it is decoded transparently if needed.
11,201
def __get_data_en_intervalo(self, d0=None, df=None): params = {: self.DATE_FMT, : self.USAR_MULTITHREAD, : self.MAX_THREADS_REQUESTS, : self.TIMEOUT, : self.NUM_RETRIES, : self.procesa_data_dia, : self.url_data_dia, : self.MAX_ACT...
Obtiene los datos en bruto de la red realizando múltiples requests al tiempo Procesa los datos en bruto obtenidos de la red convirtiendo a Pandas DataFrame
11,202
def match(self, regex, flags=0): if isinstance(regex, str): regex = re.compile(regex, flags) match = regex.match(self.text, self.index) if not match: return None start, end = match.start(), match.end() lines = self.text.count(, start, end) self.index = end if lines: s...
Matches the specified *regex* from the current character of the *scanner* and returns the result. The Scanners column and line numbers are updated respectively. # Arguments regex (str, Pattern): The regex to match. flags (int): The flags to use when compiling the pattern.
11,203
def _sample_mvn(mean, cov, cov_structure=None, num_samples=None): mean_shape = tf.shape(mean) S = num_samples if num_samples is not None else 1 D = mean_shape[-1] leading_dims = mean_shape[:-2] num_leading_dims = tf.size(leading_dims) if cov_structure == "diag": with tf.co...
Returns a sample from a D-dimensional Multivariate Normal distribution :param mean: [..., N, D] :param cov: [..., N, D] or [..., N, D, D] :param cov_structure: "diag" or "full" - "diag": cov holds the diagonal elements of the covariance matrix - "full": cov holds the full covariance matrix (without ...
11,204
def _process_witness(self, witness, matches): tokens = witness.get_tokens() full_text = witness.get_token_content() fields = [constants.NGRAM_FIELDNAME, constants.SIZE_FIELDNAME] ...
Return the counts of total tokens and matching tokens in `witness`. :param witness: witness text :type witness: `tacl.WitnessText` :param matches: n-gram matches :type matches: `pandas.DataFrame` :rtype: `tuple` of `int`
11,205
def append_this_package_path(depth=1): from .caller import caller logg.debug(, caller.modulename(depth + 1)) c = caller.abspath(depth + 1) logg.debug(, c) p = guess_package_path(dirname(c)) if p: logg.debug(, p) append_sys_path(p) else: logg.debug(, c)
this_package.py 에서 사용 import snipy.this_package
11,206
def getpackagepath(): moduleDirectory = os.path.dirname(__file__) packagePath = os.path.dirname(__file__) + "/../" return packagePath
*Get the root path for this python package - used in unit testing code*
11,207
def subsample_n(X, n=0, seed=0): if n < 0: raise ValueError() np.random.seed(seed) n = X.shape[0] if (n == 0 or n > X.shape[0]) else n rows = np.random.choice(X.shape[0], size=n, replace=False) Xsampled = X[rows] return Xsampled, rows
Subsample n samples from rows of array. Parameters ---------- X : np.ndarray Data array. seed : int Seed for sampling. Returns ------- Xsampled : np.ndarray Subsampled X. rows : np.ndarray Indices of rows that are stored in Xsampled.
11,208
def load_metadata_for_topics(self, *topics, **kwargs): if in kwargs: ignore_leadernotavailable = kwargs[] else: ignore_leadernotavailable = False if topics: self.reset_topic_metadata(*topics) else: self.reset_all_metadata() ...
Fetch broker and topic-partition metadata from the server. Updates internal data: broker list, topic/partition list, and topic/partition -> broker map. This method should be called after receiving any error. Note: Exceptions *will not* be raised in a full refresh (i.e. no topic ...
11,209
def tls_session_update(self, msg_str): super(SSLv2ServerHello, self).tls_session_update(msg_str) s = self.tls_session client_cs = s.sslv2_common_cs css = [cs for cs in client_cs if cs in self.ciphers] s.sslv2_common_cs = css s.sslv2_connection_id = self.connecti...
XXX Something should be done about the session ID here.
11,210
def map_alignment(self, prot_seq, nucl_seq): if prot_seq.id != nucl_seq.id: logging.warning( , prot_seq.id, nucl_seq.id) codons = batch(str(nucl_seq.seq.ungap()), 3) codons = [.join(i) for i in codons] codon_iter = iter(codon...
Use aligned prot_seq to align nucl_seq
11,211
def lessons(self): if hasattr(self, ): return self._lessons else: self.get_lesson() return self._lessons
返回lessons,如果未调用过``get_lesson()``会自动调用 :return: list of lessons :rtype: list
11,212
def mme_matches(case_obj, institute_obj, mme_base_url, mme_token): data = { : institute_obj, : case_obj, : [] } matches = {} if not case_obj.get(): return None for patient in case_obj[][]: patient_id = patient[] matches[patient_id] = None...
Show Matchmaker submission data for a sample and eventual matches. Args: case_obj(dict): a scout case object institute_obj(dict): an institute object mme_base_url(str) base url of the MME server mme_token(str) auth token of the MME server Returns: data(dict): data to di...
11,213
def rug(x, label=None, opacity=None): x = _try_pydatetime(x) x = np.atleast_1d(x) data = [ go.Scatter( x=x, y=np.ones_like(x), name=label, opacity=opacity, mode=, marker=dict(symbol=), ) ] layout = dict( ...
Rug chart. Parameters ---------- x : array-like, optional label : TODO, optional opacity : TODO, optional Returns ------- Chart
11,214
def get_application_access_token(application_id, application_secret_key, api_version=None): graph = GraphAPI(version=api_version) response = graph.get( path=, client_id=application_id, client_secret=application_secret_key, grant_type= ) try: data = parse_qs...
Get an OAuth access token for the given application. :param application_id: An integer describing a Facebook application's ID. :param application_secret_key: A string describing a Facebook application's secret key.
11,215
def other_supplementary_files(self): if self._other_supplementary_files is not None: return self._other_supplementary_files return getattr(self.nb.metadata, , None)
The supplementary files of this notebook
11,216
def transformToRef(self): if in self.pars and self.pars[] == : log.info() self.outxy = np.column_stack([self.all_radec[0][:,np.newaxis],self.all_radec[1][:,np.newaxis]]) skypos = self.wcs.wcs_pix2world(self.all_radec[0],self.all_radec[1],self.origin) sel...
Transform reference catalog sky positions (self.all_radec) to reference tangent plane (self.wcs) to create output X,Y positions.
11,217
def main(): now = datetime.datetime.now try: while True: sys.stdout.write(str(now()) + ) time.sleep(1) except KeyboardInterrupt: pass except IOError as exc: if exc.errno != errno.EPIPE: raise
Slowly writes to stdout, without emitting a newline so any output buffering (or input for next pipeline command) can be detected.
11,218
def tree_build(self): from skbio.tree import TreeNode nodes = {} for tax_id in self.taxonomy.index: node = TreeNode(name=tax_id, length=1) node.tax_name = self.taxonomy["name"][tax_id] node.rank = self.taxonomy["rank"][tax_id] n...
Build a tree from the taxonomy data present in this `ClassificationsDataFrame` or `SampleCollection`. Returns ------- `skbio.tree.TreeNode`, the root node of a tree that contains all the taxa in the current analysis and their parents leading back to the root node.
11,219
def read_full(data, size): default_read_size = 32768 chunk = io.BytesIO() chunk_size = 0 while chunk_size < size: read_size = default_read_size if (size - chunk_size) < default_read_size: read_size = size - chunk_size current_data = data.read(read_size) ...
read_full reads exactly `size` bytes from reader. returns `size` bytes. :param data: Input stream to read from. :param size: Number of bytes to read from `data`. :return: Returns :bytes:`part_data`
11,220
def get_other_props(all_props, reserved_props): if hasattr(all_props, ) and callable(all_props.items): return dict([(k,v) for (k,v) in list(all_props.items()) if k not in reserved_props]) return None
Retrieve the non-reserved properties from a dictionary of properties @args reserved_props: The set of reserved properties to exclude
11,221
def add_model(self, model_type: str, model_uuid: str, meta: dict, template_model: Template, update_default: bool=False): if update_default or model_type not in self.meta: self.meta[model_type] = meta["default"] model_meta = meta["model"] self.models.setdefa...
Add a new model to the registry. Call `upload()` to update the remote side.
11,222
def file_checksum(filepath): checksum = hashlib.md5() with open(filepath, ) as f: for fragment in iter(lambda: f.read(65536), ): checksum.update(fragment) return checksum.hexdigest()
Calculate md5 checksum on file :param filepath: Full path to file (e.g. /home/stack/image.qcow2) :type filepath: string
11,223
def script(script, interpreter=, suffix=, args=, **kwargs): return SoS_ExecuteScript(script, interpreter, suffix, args).run(**kwargs)
Execute specified script using specified interpreter. This action accepts common action arguments such as input, active, workdir, docker_image and args. In particular, content of one or more files specified by option input would be prepended before the specified script.
11,224
def execute(self, sql, args): c = None try: c = self._con.cursor() LOGGER.debug("execute sql: " + sql + " args:" + str(args)) if type(args) is tuple: c.execute(sql, args) elif type(args) is list: if len(args) > 1 an...
Execute sql :param sql string: the sql stamtement like 'select * from %s' :param args list: Wen set None, will use dbi execute(sql), else db execute(sql, args), the args keep the original rules, it shuld be tuple or list of list
11,225
def xmoe_dense_4k(): hparams = mtf_transformer.mtf_transformer_base_lm() hparams.attention_dropout = 0.0 hparams.relu_dropout = 0.0 hparams.layer_prepostprocess_dropout = 0.0 hparams.batch_size = 128 hparams.d_model = 512 hparams.d_kv = 128 hparams.num_heads = 4 hparams.decoder_layers = ["att",...
Series of architectural experiments on cheap language models. For all of these architectures, we run on languagemodel_lm1b8k_packed for 32000 steps. All log-perplexities are per-token - multiply by 1.298 for per-word Results: model params(M) einsum alltoall mxu-util log-ppl xmoe_dense_4k ...
11,226
def local_path(self, url, filename=None, decompress=False, download=False): if download: return self.fetch(url=url, filename=filename, decompress=decompress) else: filename = self.local_filename(url, filename, decompress) return join(self.cache_directory_path...
What will the full local path be if we download the given file?
11,227
def get_resolved_res_configs(self, rid, config=None): resolver = ARSCParser.ResourceResolver(self, config) return resolver.resolve(rid)
Return a list of resolved resource IDs with their corresponding configuration. It has a similar return type as :meth:`get_res_configs` but also handles complex entries and references. Also instead of returning :class:`ARSCResTableEntry` in the tuple, the actual values are resolved. This...
11,228
def save_formset_with_author(formset, user): instances = formset.save(commit=False) for obj in formset.deleted_objects: obj.delete() for instance in instances: if user.is_authenticated() and hasattr(instance, ) and not instance.author: instance.author = user instance...
Проставляет моделям из набора форм автора :param formset: набор форм :param user: автор :return:
11,229
def keep_on_one_line(): class CondensedStream: def __init__(self): self.sys_stdout = sys.stdout def write(self, string): with swap_streams(self.sys_stdout): string = string.replace(, ) string = truncate_to_fit_terminal(string) ...
Keep all the output generated within a with-block on one line. Whenever a new line would be printed, instead reset the cursor to the beginning of the line and print the new line without a line break.
11,230
def create(annot=None, config=None, id=None, ui=None): return Network( annot=annot, config=config, id=id, ui=ui, )
:type annot: dict :type config: NetworkConfig :type id: str :type ui: dict :rtype: Network
11,231
def qft(circ, q, n): for j in range(n): for k in range(j): circ.cu1(math.pi / float(2**(j - k)), q[j], q[k]) circ.h(q[j])
n-qubit QFT on q in circ.
11,232
def _ParseBooleanValue(self, byte_stream): if byte_stream == b: return False if byte_stream == b: return True raise errors.ParseError()
Parses a boolean value. Args: byte_stream (bytes): byte stream. Returns: bool: boolean value. Raises: ParseError: when the boolean value cannot be parsed.
11,233
def delete_profile_extension_members(self, profile_extension, query_column, ids_to_delete): profile_extension = profile_extension.get_soap_object(self.client) result = self.call( , profile_extension, query_column, ids_to_delete) if hasattr(result, ): return [Dele...
Responsys.deleteProfileExtensionRecords call Accepts: InteractObject profile_extension list field_list list ids_to_retrieve string query_column default: 'RIID' Returns list of DeleteResults
11,234
def load(pattern, *args, **kw): cssmypackage:static/style/**.css spec = pattern if not in pattern: raise ValueError() pkgname, pkgpat = pattern.split(, 1) pkgdir, pattern = globre.compile(pkgpat, split_prefix=True, flags=globre.EXACT) if pkgdir: idx = pkgdir.rfind() pkgdir = pkgdir[:idx] if...
Given a package asset-spec glob-pattern `pattern`, returns an :class:`AssetGroup` object, which in turn can act as a generator of :class:`Asset` objects that match the pattern. Example: .. code-block:: python import asset # concatenate all 'css' files into one string: css = asset.load('mypackage...
11,235
def main(arguments=None): su = tools( arguments=arguments, docString=__doc__, logLevel="WARNING", options_first=False, projectName="qubits" ) arguments, settings, log, dbConn = su.setup() for arg, val in arguments.iteritems(): if arg[0...
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
11,236
def str_eta(self): if self.done: return eta_hms(self._eta.elapsed, always_show_hours=True, hours_leading_zero=True) if not self._eta_string: return return .format(self._eta_string)
Returns a formatted ETA value for the progress bar.
11,237
def convert_zero_consonant(pinyin): if pinyin.startswith(): no_y_py = pinyin[1:] first_char = no_y_py[0] if len(no_y_py) > 0 else None if first_char in U_TONES: pinyin = UV_MAP[first_char] + pinyin[2:] elif first_char in I_TONES: ...
零声母转换,还原原始的韵母 i行的韵母,前面没有声母的时候,写成yi(衣),ya(呀),ye(耶),yao(腰), you(忧),yan(烟),yin(因),yang(央),ying(英),yong(雍)。 u行的韵母,前面没有声母的时候,写成wu(乌),wa(蛙),wo(窝),wai(歪), wei(威),wan(弯),wen(温),wang(汪),weng(翁)。 ü行的韵母,前面没有声母的时候,写成yu(迂),yue(约),yuan(冤), yun(晕);ü上两点省略。
11,238
def as_tuple(ireq): if not is_pinned_requirement(ireq): raise TypeError("Expected a pinned InstallRequirement, got {}".format(ireq)) name = key_from_req(ireq.req) version = first(ireq.specifier._specs)._spec[1] extras = tuple(sorted(ireq.extras)) return name, version, extras
Pulls out the (name: str, version:str, extras:(str)) tuple from the pinned InstallRequirement.
11,239
def clusterStatus(self): servers = yield self.getClusterServers() d = { : {}, : {}, : {} } now = time.time() reverse_map = {} for sname in servers: last = yield self.get( % sname) status = yield self...
Returns a dict of cluster nodes and their status information
11,240
def calcKYratioDifference(self): KYratioSim = np.mean(np.array(self.KtoYnow_hist)[self.ignore_periods:]) diff = KYratioSim - self.KYratioTarget return diff
Returns the difference between the simulated capital to income ratio and the target ratio. Can only be run after solving all AgentTypes and running makeHistory. Parameters ---------- None Returns ------- diff : float Difference between simulated and ...
11,241
def SunLongitude(jdn): T = (jdn - 2451545.0) / 36525. T2 = T * T dr = math.pi / 180. M = 357.52910 + 35999.05030 * T \ - 0.0001559 * T2 - 0.00000048 * T * T2 L0 = 280.46645 + 36000.76983 * T + 0.0003032 * T2 DL = (1.914600 - 0.004817 * T - 0.000014 * T2) \ ...
def SunLongitude(jdn): Compute the longitude of the sun at any time. Parameter: floating number jdn, the number of days since 1/1/4713 BC noon.
11,242
def _parse_stsd(self, atom, fileobj): assert atom.name == b"stsd" ok, data = atom.read(fileobj) if not ok: raise MP4StreamInfoError("Invalid stsd") try: version, flags, data = parse_full_atom(data) except ValueError as e: raise MP4S...
Sets channels, bits_per_sample, sample_rate and optionally bitrate. Can raise MP4StreamInfoError.
11,243
def PrintFieldValue(self, field, value): out = self.out if self.pointy_brackets: openb = closeb = else: openb = closeb = if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: if self.as_one_line: out.write( % openb) self.PrintMessage(val...
Print a single field value (not including name). For repeated fields, the value should be a single element. Args: field: The descriptor of the field to be printed. value: The value of the field.
11,244
def restart_on_change(restart_map, stopstart=False, restart_functions=None): def wrap(f): @functools.wraps(f) def wrapped_f(*args, **kwargs): return restart_on_change_helper( (lambda: f(*args, **kwargs)), restart_map, stopstart, restart_functions) ...
Restart services based on configuration files changing This function is used a decorator, for example:: @restart_on_change({ '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] '/etc/apache/sites-enabled/*': [ 'apache2' ] }) def config_changed(): ...
11,245
def run_benchmark(monitor): url = urlparse(monitor.cfg.test_url) name = slugify(url.path) or name = % (name, monitor.cfg.workers) monitor.logger.info(, name) total = REQUESTS//monitor.cfg.workers with open(name, ) as csvfile: writer = csv.DictWriter(csvfile, fieldnames=FIELDNAMES...
Run the benchmarks
11,246
def get_income_in_period(self, start: datetime, end: datetime) -> Decimal: accounts = self.get_income_accounts() income = Decimal(0) for acct in accounts: acc_agg = AccountAggregate(self.book, acct) acc_bal = acc_agg.get_balance_in_period(start, end) ...
Returns all income in the given period
11,247
def FULL_TEXT(val): if isinstance(val, float): val = repr(val) elif val in (None, ): return None elif not isinstance(val, six.string_types): if six.PY3 and isinstance(val, bytes): val = val.decode() else: val = str(val) r = sorted(set([x for x...
This is a basic full-text index keygen function. Words are lowercased, split by whitespace, and stripped of punctuation from both ends before an inverted index is created for term searching.
11,248
def _merge_update_item(self, model_item, data): data_item = self.edit_model_schema.dump(model_item, many=False).data for _col in self.edit_columns: if _col not in data.keys(): data[_col] = data_item[_col] return data
Merge a model with a python data structure This is useful to turn PUT method into a PATCH also :param model_item: SQLA Model :param data: python data structure :return: python data structure
11,249
def retrieve(self, request, project, pk=None): log = JobLog.objects.get(id=pk) return Response(self._log_as_dict(log))
Returns a job_log_url object given its ID
11,250
def get_project_config_file(path, default_config_file_name): _path, _config_file_path = None, None path = os.path.abspath(path) if os.path.isdir(path): _path = path _config_file_path = os.path.join(_path, default_config_file_name) logger.debug("Using default project co...
Attempts to extract the project config file's absolute path from the given path. If the path is a directory, it automatically assumes a "config.yml" file will be in that directory. If the path is to a .yml file, it assumes that that is the root configuration file for the project.
11,251
def language(self): language_item = [subtag for subtag in self.subtags if subtag.type == ] return language_item[0] if len(language_item) > 0 else None
Get the language :class:`language_tags.Subtag.Subtag` of the tag. :return: language :class:`language_tags.Subtag.Subtag` that is part of the tag. The return can be None.
11,252
def extract_meta(self, text): first_line = True metadata = [] content = [] metadata_parsed = False for line in text.split(): if first_line: first_line = False if line.strip() != : raise MetaParseException()...
Takes input as the entire file. Reads the first yaml document as metadata. and the rest of the document as text
11,253
def _job_completed(self, job_name, success, message): job = self._objects[job_name][Interface[]] action = self._action_by_operation.get(job[]) if not action: return object_path, = job[] device = self[object_path] if success: ...
Internal method. Called when a job of a long running task completes.
11,254
async def wait_event(signals: Sequence[], filter: Callable[[T_Event], bool] = None) -> T_Event: if sys.version_info >= (3, 5, 3): assert check_argument_types() async with aclosing(stream_events(signals, filter)) as events: return await events.asend(None)
Wait until any of the given signals dispatches an event that satisfies the filter (if any). If no filter has been given, the first event dispatched from the signal is returned. :param signals: the signals to get events from :param filter: a callable that takes an event object as an argument and returns ``...
11,255
def _adjust_beforenext(self, real_wave_mfcc, algo_parameters): def new_time(nsi): delay = max(algo_parameters[0], TimeValue("0.000")) return max(nsi.end - delay, nsi.begin) self.log(u"Called _adjust_beforenext") self._adjust_on_nonspeech(real_wave_mf...
BEFORENEXT
11,256
def parseprint(code, filename="<string>", mode="exec", **kwargs): node = parse(code, mode=mode) print(dump(node, **kwargs))
Parse some code from a string and pretty-print it.
11,257
def _run(self): up_cnt = 0 down_cnt = 0 check_state = for key, value in self.config.items(): self.log.debug("%s=%s:%s", key, value, type(value)) if self._check_disabled(): return if self.splay_startu...
Discovers the health of a service. Runs until it is being killed from main program and is responsible to put an item into the queue based on the status of the health check. The status of service is consider UP after a number of consecutive successful health checks, in that case it asks ...
11,258
def calc_mean_time(timepoints, weights): timepoints = numpy.array(timepoints) weights = numpy.array(weights) validtools.test_equal_shape(timepoints=timepoints, weights=weights) validtools.test_non_negative(weights=weights) return numpy.dot(timepoints, weights)/numpy.sum(weights)
Return the weighted mean of the given timepoints. With equal given weights, the result is simply the mean of the given time points: >>> from hydpy import calc_mean_time >>> calc_mean_time(timepoints=[3., 7.], ... weights=[2., 2.]) 5.0 With different weights, the resulting m...
11,259
def split(self, file): with open(file, ) as f: for record in sagemaker.amazon.common.read_recordio(f): yield record
Split a file into records using a specific strategy This RecordIOSplitter splits the data into individual RecordIO records. Args: file (str): path to the file to split Returns: generator for the individual records that were split from the file
11,260
def publish(): print("To be ready for release, remember:") print(" 1) Update the version number (and associated test)") print(" 2) Update the ChangeLog.rst (and other documentation)") print( " ChangeLog should have an line (title) consisting of the version number" ) ...
Publishes Formic to PyPi (don't run unless you are the maintainer)
11,261
def lambda_A_calc(classes, table, P, POP): try: result = 0 maxreference = max(list(P.values())) length = POP for i in classes: col = [] for col_item in table.values(): col.append(col_item[i]) result += max(col) result =...
Calculate Goodman and Kruskal's lambda A. :param classes: confusion matrix classes :type classes : list :param table: confusion matrix table :type table : dict :param P: condition positive :type P : dict :param POP: population :type POP : int :return: Goodman and Kruskal's lambda A ...
11,262
def handle_log_data(self, m): if self.download_file is None: return if m.ofs != self.download_ofs: self.download_file.seek(m.ofs) self.download_ofs = m.ofs if m.count != 0: s = bytearray(m.data[...
handling incoming log data
11,263
def set_global_fontsize_from_fig(fig, scale=1.5): fig_size_inch = fig.get_size_inches() fig_size_len_geom_mean = (fig_size_inch[0] * fig_size_inch[1]) ** 0.5 rcParams[] = fig_size_len_geom_mean * scale return rcParams[]
Set matplotlib.rcParams['font.size'] value so that all texts on a plot would look nice in terms of fontsize. [NOTE] The formula for the font size is: fontsize = sqrt(fig_area) * 'scale' where fig_area = fig_height * fig_width (in inch)
11,264
def pre_render(self): self.add_styles() self.add_scripts() self.root.set( , % (self.graph.width, self.graph.height) ) if self.graph.explicit_size: self.root.set(, str(self.graph.width)) self.root.set(, str(self.graph.height))
Last things to do before rendering
11,265
def set_cpuid_leaf(self, idx, idx_sub, val_eax, val_ebx, val_ecx, val_edx): if not isinstance(idx, baseinteger): raise TypeError("idx can only be an instance of type baseinteger") if not isinstance(idx_sub, baseinteger): raise TypeError("idx_sub can only be an instance o...
Sets the virtual CPU cpuid information for the specified leaf. Note that these values are not passed unmodified. VirtualBox clears features that it doesn't support. Currently supported index values for cpuid: Standard CPUID leaves: 0 - 0x1f Extended CPUID leaves: 0x80000000 - 0x...
11,266
def get_monitor(self, topics): for monitor in self.get_monitors(MON_TOPIC_ATTR == ",".join(topics)): return monitor return None
Attempts to find a Monitor in device cloud that matches the provided topics :param topics: a string list of topics (e.g. ``['DeviceCore[U]', 'FileDataCore'])``) Returns a :class:`DeviceCloudMonitor` if found, otherwise None.
11,267
def beholder_ng(func): @functools.wraps(func) def behold(file, length, *args, **kwargs): seek_cur = file.tell() try: return func(file, length, *args, **kwargs) except Exception: from pcapkit.protocols.raw import Raw error = traceback....
Behold analysis procedure.
11,268
def _transpose_chars(text, pos): if len(text) < 2 or pos == 0: return text, pos if pos == len(text): return text[:pos - 2] + text[pos - 1] + text[pos - 2], pos return text[:pos - 1] + text[pos] + text[pos - 1] + text[pos + 1:], pos + 1
Drag the character before pos forward over the character at pos, moving pos forward as well. If pos is at the end of text, then this transposes the two characters before pos.
11,269
def _getLayer(self, name, **kwargs): for layer in self.layers: if layer.name == name: return layer
This is the environment implementation of :meth:`BaseFont.getLayer`. **name** will be a :ref:`type-string`. It will have been normalized with :func:`normalizers.normalizeLayerName` and it will have been verified as an existing layer. This must return an instance of :class:`BaseLa...
11,270
def next(self): try: child = self.children[self.pos] self.pos += 1 return child except: raise StopIteration()
Get the next child. @return: The next child. @rtype: L{Element} @raise StopIterator: At the end.
11,271
def sync(self, command, arguments, tags=None, id=None): response = self.raw(command, arguments, tags=tags, id=id) result = response.get() if result.state != : raise ResultError(msg= % result.data, code=result.code) return result
Same as self.raw except it do a response.get() waiting for the command execution to finish and reads the result :param command: Command name to execute supported by the node (ex: core.system, info.cpu, etc...) check documentation for list of built in commands :param arguments: A ...
11,272
def get_paying_proxy_contract(w3: Web3, address=None): return w3.eth.contract(address, abi=PAYING_PROXY_INTERFACE[], bytecode=PAYING_PROXY_INTERFACE[])
Get Paying Proxy Contract. This should be used just for contract creation/changing master_copy If you want to call Safe methods you should use `get_safe_contract` with the Proxy address, so you can access every method of the Safe :param w3: Web3 instance :param address: address of the proxy contract ...
11,273
def remove_metadata_key(self, container, key): meta_dict = {key: ""} return self.set_metadata(container, meta_dict)
Removes the specified key from the container's metadata. If the key does not exist in the metadata, nothing is done.
11,274
def _kvmatrix2d(km,vm): ab d = {} kmwfs = get_kmwfs(km) vmwfs = elel.get_wfs(vm) lngth = vmwfs.__len__() for i in range(0,lngth): value = elel.getitem_via_pathlist(vm,vmwfs[i]) cond = elel.is_leaf(value) if(cond): _setitem_via_pathlist(d,kmwfs[i],value) ...
km = [[[1], [3]], [[1, 2], [3, 'a']], [[1, 2, 22]]] show_kmatrix(km) vm = [[[222]], ['b']] show_vmatrix(vm) d = _kvmatrix2d(km,vm)
11,275
def background_knowledge(self): modeslist, getters = [self.mode(self.__target_predicate(), [(, self.db.target_table)], head=True)], [] determinations, types = [], [] for (table, ref_table) in self.db.connected.keys(): if ref_table == self.db.target_table: con...
Emits the background knowledge in prolog form for Aleph.
11,276
def _get_migrate_funcs(cls, orig_version, target_version): direction = 1 if target_version > orig_version else -1 versions = range(orig_version, target_version + direction, direction) transitions = recipes.pairwise(versions) return itertools.starmap(cls._get_func, transitions)
>>> @Manager.register ... def v1_to_2(manager, doc): ... doc['foo'] = 'bar' >>> @Manager.register ... def v2_to_1(manager, doc): ... del doc['foo'] >>> @Manager.register ... def v2_to_3(manager, doc): ... doc['foo'] = doc['foo'] + ' baz' >>> funcs = list(Manager._get_migrate_funcs(1, 3)) ...
11,277
def read_multiple( self, points_list, *, points_per_request=1, discover_request=(None, 6) ): if isinstance(points_list, list): for each in points_list: self.read_single( each, points_per_request=1, discover_request=discover_req...
Functions to read points from a device using the ReadPropertyMultiple request. Using readProperty request can be very slow to read a lot of data. :param points_list: (list) a list of all point_name as str :param points_per_request: (int) number of points in the request Using too ...
11,278
def mgf1(mgf_seed, mask_len, hash_class=hashlib.sha1): h_len = hash_class().digest_size if mask_len > 0x10000: raise ValueError() T = b for i in range(0, integer_ceil(mask_len, h_len)): C = i2osp(i, 4) T = T + hash_class(mgf_seed + C).digest() return T[:mask_len]
Mask Generation Function v1 from the PKCS#1 v2.0 standard. mgs_seed - the seed, a byte string mask_len - the length of the mask to generate hash_class - the digest algorithm to use, default is SHA1 Return value: a pseudo-random mask, as a byte string
11,279
def get_url_kwargs(self, request_kwargs=None, **kwargs): if not request_kwargs: request_kwargs = getattr(self, , {}) for k in self.bundle.url_params: if k in request_kwargs and not k in kwargs: kwargs[k] = request_kwargs[k] return kwargs
Get the kwargs needed to reverse this url. :param request_kwargs: The kwargs from the current request. \ These keyword arguments are only retained if they are present \ in this bundle's known url_parameters. :param kwargs: Keyword arguments that will always be kept.
11,280
def addFromTex(self,name,img,category): texreg = self.categoriesTexBin[category].add(img) self.categories[category][name]=texreg target = texreg.target texid = texreg.id texcoords = texreg.tex_coords glTexParameteri(GL...
Adds a new texture from the given image. ``img`` may be any object that supports Pyglet-style copying in form of the ``blit_to_texture()`` method. This can be used to add textures that come from non-file sources, e.g. Render-to-texture.
11,281
def regroup(self, group): if util.config.future_deprecations: self.param.warning( % type(self).__name__) new_items = [el.relabel(group=group) for el in self.data.values()] return reduce(lambda x,y: x+y, new_items...
Deprecated method to apply new group to items. Equivalent functionality possible using: ViewableTree(tree.relabel(group='Group').values())
11,282
def engagement_context(self): if self._engagement_context is None: self._engagement_context = EngagementContextList( self._version, flow_sid=self._solution[], engagement_sid=self._solution[], ) return self._engagement_conte...
Access the engagement_context :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextList
11,283
def drawing_end(self): from MAVProxy.modules.mavproxy_map import mp_slipmap if self.draw_callback is None: return self.draw_callback(self.draw_line) self.draw_callback = None self.map.add_object(mp_slipmap.SlipDefaultPopup(self.default_popup, combine=True)) ...
end line drawing
11,284
def altitudes_encode(self, time_boot_ms, alt_gps, alt_imu, alt_barometric, alt_optical_flow, alt_range_finder, alt_extra): return MAVLink_altitudes_message(time_boot_ms, alt_gps, alt_imu, alt_barometric, alt_optical_flow, alt_range_finder, alt_extra)
The altitude measured by sensors and IMU time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) alt_gps : GPS altitude in meters, expressed as * 1000 (millimeters), above MSL (int32_t) alt_imu : IMU altitude ...
11,285
def apply_filter(self, expr, value): if self.skip(value): return expr if not self._valid_value(value): msg = "Invalid value {value} passed to filter {name} - ".format( value=repr(value), name=self.name) if self.default is no...
Returns the given expression filtered by the given value. Args: expr (xpath.expression.AbstractExpression): The expression to filter. value (object): The desired value with which the expression should be filtered. Returns: xpath.expression.AbstractExpression: The fi...
11,286
def GetFile(message=None, title=None, directory=None, fileName=None, allowsMultipleSelection=False, fileTypes=None): return dispatcher["GetFile"](message=message, title=title, directory=directory, fileName=fileName, allowsMultipleSel...
An get file dialog. Optionally a `message`, `title`, `directory`, `fileName` and `allowsMultipleSelection` can be provided. :: from fontParts.ui import GetFile print(GetFile())
11,287
def calculate(self, film, substrate, elasticity_tensor=None, film_millers=None, substrate_millers=None, ground_state_energy=0, lowest=False): self.film = film self.substrate = substrate if film_millers is None: film_millers = sor...
Finds all topological matches for the substrate and calculates elastic strain energy and total energy for the film if elasticity tensor and ground state energy are provided: Args: film(Structure): conventional standard structure for the film substrate(Structure): convent...
11,288
def unicode_symbol(self, *, invert_color: bool = False) -> str: symbol = self.symbol().swapcase() if invert_color else self.symbol() return UNICODE_PIECE_SYMBOLS[symbol]
Gets the Unicode character for the piece.
11,289
def authenticate_application(self, api_token, admin_token, override=False, fetch=True): if (self.context.has_auth_params() and not override): raise OverrideError() if (not api_token or not admin_token or not self.context.authorize(, ...
Set credentials for Application authentication. Important Note: Do not use Application auth on any end-user device. Application auth provides read-access to all Users who have authorized an Application. Use on a secure application server only. Args: api_token (str): Token issu...
11,290
def create_server(self, loop=None, as_coroutine=False, protocol_factory=None, **server_config): if loop is None: import asyncio loop = asyncio.get_event_loop() if protocol_factory is...
Helper function which constructs a listening server, using the default growler.http.protocol.Protocol which responds to this app. This function exists only to remove boilerplate code for starting up a growler app when using asyncio. Args: as_coroutine (bool): If Tru...
11,291
def properties(obj, type=None, set=None): **ro=false,label="My Storage" if type and type not in [, , , , , , , ]: raise CommandExecutionError("Unknown property type: \"{0}\" specified".format(type)) cmd = [] cmd.append() cmd.append(set and or ) if type: cmd.append(.format(type)...
List properties for given btrfs object. The object can be path of BTRFS device, mount point, or any directories/files inside the BTRFS filesystem. General options: * **type**: Possible types are s[ubvol], f[ilesystem], i[node] and d[evice]. * **force**: Force overwrite existing filesystem on the disk ...
11,292
def create(self, name, img_format=None, data=None, container=None, obj=None, metadata=None): return self._manager.create(name, img_format, data=data, container=container, obj=obj)
Creates a new image with the specified name. The image data can either be supplied directly in the 'data' parameter, or it can be an image stored in the object storage service. In the case of the latter, you can either supply the container and object names, or simply a StorageObject refe...
11,293
def default_instance(): if ConfigManager._instance is None: with threading.Lock(): if ConfigManager._instance is None: ConfigManager._instance = ConfigManager() return ConfigManager._instance
For use like a singleton, return the existing instance of the object or a new instance
11,294
def remote_log_data_block_encode(self, target_system, target_component, seqno, data): return MAVLink_remote_log_data_block_message(target_system, target_component, seqno, data)
Send a block of log data to remote location target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seqno : log data block sequence number (uint32_t) data : log data block...
11,295
def dict_to_object(self, obj): if not isinstance(obj, dict): return obj if in obj: sensor = Sensor(obj[]) for key, val in obj.items(): setattr(sensor, key, val) return sensor if all(k in obj for k in [, , ]): ...
Return object from dict.
11,296
def _get_generators(self): generators = [ep.name for ep in pkg_resources.iter_entry_points(self.group)] return generators
Get installed banana plugins. :return: dictionary of installed generators name: distribution
11,297
def kill(self): self.process.kill() self.set_status(self.S_ERROR, "status set to Error by task.kill") self._returncode = self.process.returncode
Kill the child.
11,298
def _manage_args(parser, args): for item in data.CONFIGURABLE_OPTIONS: action = parser._option_string_actions[item] choices = default = input_value = getattr(args, action.dest) new_val = None if not args.noinput: if action.choices: ...
Checks and validate provided input
11,299
def patterson_f3(acc, aca, acb): aca = AlleleCountsArray(aca, copy=False) assert aca.shape[1] == 2, acb = AlleleCountsArray(acb, copy=False) assert acb.shape[1] == 2, acc = AlleleCountsArray(acc, copy=False) assert acc.shape[1] == 2, check_dim0_aligned(aca, acb, acc) ...
Unbiased estimator for F3(C; A, B), the three-population test for admixture in population C. Parameters ---------- acc : array_like, int, shape (n_variants, 2) Allele counts for the test population (C). aca : array_like, int, shape (n_variants, 2) Allele counts for the first source ...