Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
387,200
def get_reports(self): url = .format(self.url) return Report._get_list_from_url(url, append_base_url=False)
Retrieve all reports submitted for this Sample. :return: A list of :class:`.Report`
387,201
def norm(self, valu): func = self._type_norms.get(type(valu)) if func is None: raise s_exc.NoSuchFunc(name=self.name, mesg= % (type(valu),)) return func(valu)
Normalize the value for a given type. Args: valu (obj): The value to normalize. Returns: ((obj,dict)): The normalized valu, info tuple. Notes: The info dictionary uses the following key conventions: subs (dict): The normalized sub-fields as ...
387,202
def getFloat(self, name, default=0.0, parent_search=False, multikeys_search=False): try: value = self.get(name, default, parent_search, multikeys_search) return float(value) except: return default
récupération d'un élément float
387,203
def circleconvert(amount, currentformat, newformat): if currentformat.lower() == newformat.lower(): return amount if currentformat.lower() == : if newformat.lower() == : return amount * 2 elif newformat.lower() == : ...
Convert a circle measurement. :type amount: number :param amount: The number to convert. :type currentformat: string :param currentformat: The format of the provided value. :type newformat: string :param newformat: The intended format of the value. >>> circleconvert(45, "radius", "diamet...
387,204
def _ftp_pwd(self): try: return self.ftp.pwd() except UnicodeEncodeError: if compat.PY2 or self.ftp.encoding != "utf-8": raise prev_encoding = self.ftp.encoding try: write("ftp.pwd() failed wi...
Variant of `self.ftp.pwd()` that supports encoding-fallback. Returns: Current working directory as native string.
387,205
def name(self): if not self._name: self._name = self._alternatives[self._choice][0] return self._name
:return: A unicode string of the field name of the chosen alternative
387,206
def dir2fn(ofn, ifn, suffix) -> Union[None, Path]: if not ofn: return None ofn = Path(ofn).expanduser() ifn = Path(ifn).expanduser() assert ifn.is_file() if ofn.suffix == suffix: pass else: assert ofn.is_dir(), f ofn = ofn / ifn.with_suffix(suffix).na...
ofn = filename or output directory, to create filename based on ifn ifn = input filename (don't overwrite!) suffix = desired file extension e.g. .h5
387,207
def get_static(root=None): * ret = set() out = __salt__[]( _systemctl_cmd(, root=root), python_shell=False, ignore_retcode=True) for line in salt.utils.itertools.split(out, ): try: fullname, unit_state = line.strip().split(None...
.. versionadded:: 2015.8.5 Return a list of all static services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_static
387,208
def write_vtu(Verts, Cells, pdata=None, pvdata=None, cdata=None, cvdata=None, fname=): vtk_cell_info = [-1, 1, None, 2, None, 3, None, None, 4, 4, 4, 8, 8, 6, 5] if isinstance(fname, str): try: fname = open(fname, ) except IOError as e: print...
Write a .vtu file in xml format. Parameters ---------- fname : {string} file to be written, e.g. 'mymesh.vtu' Verts : {array} Ndof x 3 (if 2, then expanded by 0) list of (x,y,z) point coordinates Cells : {dictionary} Dictionary of with the keys pdata : {array} ...
387,209
def get_object(self, url, month_format=, day_format=): params = self.get_params(url) try: year = params[self._meta.year_part] month = params[self._meta.month_part] day = params[self._meta.day_part] except KeyError: try: ...
Parses the date from a url and uses it in the query. For objects which are unique for date.
387,210
def server_inspect_exception(self, req_event, rep_event, task_ctx, exc_info): if self._hide_zerorpc_frames: traceback = exc_info[2] while traceback: zerorpc_frame = traceback.tb_frame ...
Called when an exception has been raised in the code run by ZeroRPC
387,211
def close(self): if self.delegate: return self._close() future = self._framework.get_future(self.get_io_loop()) future.set_result(None) return future
Close this change stream. Stops any "async for" loops using this change stream.
387,212
def get_location(dom, location): node = dom.documentElement for i in location: node = get_child(node, i) if not node: raise ValueError( % location) return node
Get the node at the specified location in the dom. Location is a sequence of child indices, starting at the children of the root element. If there is no node at this location, raise a ValueError.
387,213
def allele_reads_from_locus_reads(locus_reads, n_ref): for locus_read in locus_reads: allele_read = AlleleRead.from_locus_read(locus_read, n_ref) if allele_read is None: continue else: yield allele_read
Given a collection of LocusRead objects, returns a list of AlleleRead objects (which are split into prefix/allele/suffix nucleotide strings). Parameters ---------- locus_reads : sequence of LocusRead records n_ref : int Number of reference nucleotides affected by variant. Generate...
387,214
def _compensate_pressure(self, adc_p): var_1 = (self._temp_fine / 2.0) - 64000.0 var_2 = ((var_1 / 4.0) * (var_1 / 4.0)) / 2048 var_2 *= self._calibration_p[5] var_2 += ((var_1 * self._calibration_p[4]) * 2.0) var_2 = (var_2 / 4.0) + (self._calibration_p[3] * 65536.0) ...
Compensate pressure. Formula from datasheet Bosch BME280 Environmental sensor. 8.1 Compensation formulas in double precision floating point Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015.
387,215
def split_sentences(tokens): begin = 0 for i, token in enumerate(tokens): if is_end_of_sentence(tokens, i): yield tokens[begin:i+1] begin = i+1 if begin <= len(tokens)-1: yield tokens[begin:]
Split sentences (based on tokenised data), returns sentences as a list of lists of tokens, each sentence is a list of tokens
387,216
def editors(self): lay = self.layout() return [lay.itemAt(i).widget() for i in range(lay.count())]
Returns the editors that are associated with this edit. :return [<XLineEdit>, ..]
387,217
def action_spatial(self, action): if self.surf.surf_type & SurfType.FEATURE: return action.action_feature_layer elif self.surf.surf_type & SurfType.RGB: return action.action_render else: assert self.surf.surf_type & (SurfType.RGB | SurfType.FEATURE)
Given an Action, return the right spatial action.
387,218
def connect(self): if not self.connected(): self._ws = create_connection(self.WS_URI) message = { :self.WS_TYPE, :self.WS_PRODUCT_ID } self._ws.send(dumps(message)) with self._lock: if not self._thread: thread = Thread(target=self._keep_al...
Connects and subscribes to the WebSocket Feed.
387,219
def add_value(self, value, index_point): if index_point not in self.index: self.values.append(value) self.index.append(index_point)
The function is addeing new value to provied index. If index does not exist
387,220
def ensure(assertion, message=None): message = message or assertion if not assertion: raise AssertionError(message) return True
Checks an assertion argument for truth-ness. Will return ``True`` or explicitly raise ``AssertionError``. This is to deal with environments using ``python -O` or ``PYTHONOPTIMIZE=``. :param assertion: some value to evaluate for truth-ness :param message: optional message used for raising AssertionError
387,221
def bulk_overwrite(self, entities_and_kinds): EntityGroupMembership.objects.filter(entity_group=self).delete() return self.bulk_add_entities(entities_and_kinds)
Update the group to the given entities and sub-entity groups. After this operation, the only members of this EntityGroup will be the given entities, and sub-entity groups. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-...
387,222
def setCodecPreferences(self, codecs): if not codecs: self._preferred_codecs = [] capabilities = get_capabilities(self.kind).codecs unique = [] for codec in reversed(codecs): if codec not in capabilities: raise ValueError() if...
Override the default codec preferences. See :meth:`RTCRtpSender.getCapabilities` and :meth:`RTCRtpReceiver.getCapabilities` for the supported codecs. :param: codecs: A list of :class:`RTCRtpCodecCapability`, in decreasing order of preference. If empty, restores the defa...
387,223
def compute_acf(cls, filename, start_index=None, end_index=None, per_walker=False, walkers=None, parameters=None, temps=None): acfs = {} with cls._io(filename, ) as fp: if parameters is None: parameters = fp.variable_params ...
Computes the autocorrleation function of the model params in the given file. By default, parameter values are averaged over all walkers at each iteration. The ACF is then calculated over the averaged chain for each temperature. An ACF per-walker will be returned instead if ``per...
387,224
def _perturbation(self): if self.P>1: scales = [] for term_i in range(self.n_randEffs): _scales = sp.randn(self.diag[term_i].shape[0]) if self.jitter[term_i]>0: _scales = sp.concatenate((_scales,sp.zeros(1))) s...
Internal function for parameter initialization Returns Gaussian perturbation
387,225
def _get_webapi_requests(self): headers = { : , : , : , : , : , : , : } NCloudBot.req.headers.update(headers) ...
Update headers of webapi for Requests.
387,226
def sim( self, src, tar, qval=1, mode=, long_strings=False, boost_threshold=0.7, scaling_factor=0.1, ): if mode == : if boost_threshold > 1 or boost_threshold < 0: raise ValueError( ...
Return the Jaro or Jaro-Winkler similarity of two strings. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison qval : int The length of each q-gram (defaults to 1: character-wise matching) ...
387,227
def make_filter(self, fieldname, query_func, expct_value): s property based on query_func eqneltltegtgtestartswithendswith{} {} {}val', query_func, expct_value) return actual_filter
makes a filter that will be appliead to an object's property based on query_func
387,228
def translate(s, table, deletions=""): if deletions or table is None: return s.translate(table, deletions) else: return s.translate(table + s[:0])
translate(s,table [,deletions]) -> string Return a copy of the string s, where all characters occurring in the optional argument deletions are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. The deletions argument is...
387,229
def get(aadb: str): if (aadb): cfg = Config() value = cfg.get(ConfigKeys.asset_allocation_database_path) click.echo(value) if not aadb: click.echo("Use --help for more information.")
Retrieves a value from config
387,230
def tpu_estimator_model_fn(model_type, transformer_model, model_dir, use_tpu, mesh_shape, layout_rules, batch_size, sequence_length...
Create a TPUEstimator model function. Args: model_type: a string transformer_model: a transformer.Unitransformer or transformer.Bitransformer model_dir: a string use_tpu: a boolean mesh_shape: a mtf.Shape layout_rules: a mtf.LayoutRules batch_size: an integer sequence_length: an integ...
387,231
def _get_logical_raid_levels(self): logical_drive_details = self._get_logical_drive_resource() raid_level = {} if logical_drive_details: for item in logical_drive_details: if in item: raid_level_var = "logical_raid_level_" + item[] ...
Gets the different raid levels configured on a server. :returns a dictionary of logical_raid_levels set to true. Example if raid level 1+0 and 6 are configured, it returns {'logical_raid_level_10': 'true', 'logical_raid_level_6': 'true'}
387,232
def clickmap(parser, token): bits = token.split_contents() if len(bits) > 1: raise TemplateSyntaxError(" takes no arguments" % bits[0]) return ClickmapNode()
Clickmap tracker template tag. Renders Javascript code to track page visits. You must supply your clickmap tracker ID (as a string) in the ``CLICKMAP_TRACKER_ID`` setting.
387,233
def _send(self): if not statsd: return for metric in self.metrics: self.connection.send() self.metrics = []
Send data to statsd. Fire and forget. Cross fingers and it'll arrive.
387,234
def jit_load(self): try: model = importlib.import_module( + self.model, ) device = getattr(model, self.device) self.system.__dict__[self.name] = device(self.system, self.name) g = self.system.__dict__[self.name]._group self.system.group_add(g...
Import and instantiate this JIT object Returns -------
387,235
def get_attrs(self): return FrozenOrderedDict((a, getattr(self.ds, a)) for a in self.ds.ncattrs())
Get the global attributes from underlying data set.
387,236
def delete_all(config=None): storm_ = get_storm_instance(config) try: storm_.delete_all_entries() print(get_formatted_message(, )) except Exception as error: print(get_formatted_message(str(error), ), file=sys.stderr) sys.exit(1)
Deletes all hosts from ssh config.
387,237
def open_db(db, zipped=None, encoding=None, fieldnames_lower=True, case_sensitive=True): kwargs = dict( encoding=encoding, fieldnames_lower=fieldnames_lower, case_sensitive=case_sensitive, ) if zipped: with Dbf.open_zip(db, zipped, **kwargs) as dbf: yield db...
Context manager. Allows reading DBF file (maybe even from zip). :param str|unicode|file db: .dbf file name or a file-like object. :param str|unicode zipped: .zip file path or a file-like object. :param str|unicode encoding: Encoding used by DB. This will be used if there's no encoding information...
387,238
def distributions(self, _args): ctx = self.ctx dists = Distribution.get_distributions(ctx) if dists: print( .format(Style=Out_Style, Fore=Out_Fore)) pretty_log_dists(dists, print) else: print( .format(Style...
Lists all distributions currently available (i.e. that have already been built).
387,239
def append_manage_data_op(self, data_name, data_value, source=None): op = operation.ManageData(data_name, data_value, source) return self.append_op(op)
Append a :class:`ManageData <stellar_base.operation.ManageData>` operation to the list of operations. :param str data_name: String up to 64 bytes long. If this is a new Name it will add the given name/value pair to the account. If this Name is already present then the associated...
387,240
def dumps(self, script): "Return a compressed representation of script as a binary string." string = BytesIO() self._dump(script, string, self._protocol, self._version) return string.getvalue()
Return a compressed representation of script as a binary string.
387,241
def set_entries(self, entries: List[Tuple[str, str]], titles, resources): self.entries = [] for flag, pagename in entries: title = titles[pagename].children[0] resource = resources.get(pagename, None) if resource and hasattr(resource, ...
Provide the template the data for the toc entries
387,242
def get_support_variables(polynomial): support = [] if is_number_type(polynomial): return support for monomial in polynomial.expand().as_coefficients_dict(): mon, _ = __separate_scalar_factor(monomial) symbolic_support = flatten(split_commutative_parts(mon)) for s in sym...
Gets the support of a polynomial.
387,243
def create_ver_browser(self, layout): brws = ComboBoxBrowser(1, headers=[]) layout.insertWidget(1, brws) return brws
Create a version browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` :raises: None
387,244
def integers(start, count): if count < 0: raise ValueError("integers() count cannot be negative") return query(irange(start, start + count))
Generates in sequence the integral numbers within a range. Note: This method uses deferred execution. Args: start: The first integer in the sequence. count: The number of sequential integers to generate. Returns: A Queryable over the specified range of integers. Ra...
387,245
def get_published(self, layer_id, expand=[]): target_url = self.client.get_url(, , , {: layer_id}) return self._get(target_url, expand=expand)
Get the latest published version of this layer. :raises NotFound: if there is no published version.
387,246
def get_extra_functions(self) -> Dict[str, Callable]: if self.channel_type == ChannelType.Master: raise NameError("get_extra_function is not available on master channels.") methods = {} for mName in dir(self): m = getattr(self, mName) if callable(m) a...
Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``.
387,247
def is_de_listed(self): env = Environment.get_instance() instrument = env.get_instrument(self._order_book_id) current_date = env.trading_dt if instrument.de_listed_date is not None: if instrument.de_listed_date.date() > env.config.base.end_date: retu...
判断合约是否过期
387,248
def _write_cache(self, lines, append=False): mode = if append else with open(self.filepath, mode, encoding=) as fh: fh.writelines(line + for line in lines)
Write virtualenv metadata to cache.
387,249
def fit(self, train_x, train_y): if self.first_fitted: self.incremental_fit(train_x, train_y) else: self.first_fit(train_x, train_y)
Fit the regressor with more data. Args: train_x: A list of NetworkDescriptor. train_y: A list of metric values.
387,250
def _process_results(self, raw_results, *args, **kwargs): if in raw_results: for agg_fieldname, agg_info in raw_results[].items(): agg_info[] = for bucket_item in agg_info[]: if in bucket_item: bucket_item[] = bu...
Naively translate between the 'aggregations' search result data structure returned by ElasticSearch 2+ in response to 'aggs' queries into a structure with 'facets'-like content that Haystack (2.6.1) can understand and process, then pass it on to Haystack's default result processing code....
387,251
def read_raw(data_path): with open(data_path, ) as f: data = pickle.load(f) return data
Parameters ---------- data_path : str
387,252
def get_trees(self, data, showerrors = False): if showerrors: raise NotImplementedError("This parser doesn't implement errors") self.data = data self.index = 0 try: return [self.__aux_parser(self._productionset.initialsymbol)] except (IndexError,...
returns a list of trees with valid guesses
387,253
def direct_messages(self, delegate, params={}, extra_args=None): return self.__get(, delegate, params, txml.Direct, extra_args=extra_args)
Get direct messages for the authenticating user. Search results are returned one message at a time a DirectMessage objects
387,254
def _on_group_stream_changed(self, data): self._groups.get(data.get()).update_stream(data)
Handle group stream change.
387,255
def _run_apt_command(cmd, fatal=False): cmd_env = { : os.environ.get(, )} if fatal: _run_with_retries( cmd, cmd_env=cmd_env, retry_exitcodes=(1, APT_NO_LOCK,), retry_message="Couldn't acquire DPKG lock") else: env = os.environ.copy() env.upd...
Run an apt command with optional retries. :param: cmd: str: The apt command to run. :param: fatal: bool: Whether the command's output should be checked and retried.
387,256
async def _on_trace_notification(self, trace_event): conn_string = trace_event.get() payload = trace_event.get() await self.notify_event(conn_string, , payload)
Callback function called when a trace chunk is received. Args: trace_chunk (dict): The received trace chunk information
387,257
def on_quote_changed(self, tiny_quote): data = tiny_quote str_log = "on_quote_changed symbol=%s open=%s high=%s close=%s low=%s" % (data.symbol, data.openPrice, data.highPrice, data.lastPrice, data.lowPrice) self.log(str_log)
报价、摆盘实时数据变化时,会触发该回调
387,258
def create(self, data): if data is None: return None prototype = {} errors = {} for field_name, field_spec in self.spec.fields.items(): try: value = self._create_value(data, field_name, self.spec) except V...
Create object from the given data. The given data may or may not have been validated prior to calling this function. This function will try its best in creating the object. If the resulting object cannot be produced, raises ``ValidationError``. The spec can affect how individual fields...
387,259
def calculated_intervals(self, value): if not value: self._calculated_intervals = TimeIntervals() return if isinstance(value, TimeInterval): value = TimeIntervals([value]) elif isinstance(value, TimeIntervals): pass elif isinstanc...
Set the calculated intervals This will be written to the stream_status collection if it's in the database channel :param value: The calculated intervals :type value: TimeIntervals, TimeInterval, list[TimeInterval]
387,260
def addExpectedFailure(self, test: unittest.case.TestCase, err: tuple) -> None: self.add_result(TestState.expected_failure, test, err)
Transforms the test in a serializable version of it and sends it to a queue for further analysis :param test: the test to save :param err: tuple of the form (Exception class, Exception instance, traceback)
387,261
def poll_event(self): curses.flushinp() ch = self.screen.getch() if ch == 27: return EVENT_ESC elif ch == -1 or ch == curses.KEY_RESIZE: return EVENT_RESIZE elif ch == 10 or ch == curses.KEY_ENTER: return EVENT_ENTER ...
Waits for an event to happen and returns a string related to the event. If the event is a normal (letter) key press, the letter is returned (case sensitive) :return: Event type
387,262
def eigenvectors_nrev(T, right=True): r if right: val, R = eig(T, left=False, right=True) perm = np.argsort(np.abs(val))[::-1] eigvec = R[:, perm] else: val, L = eig(T, left=True, right=False) perm = np.argsort(np.abs(val))[::-1] ...
r"""Compute eigenvectors of transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) k : int or tuple of ints, optional Compute the first k eigenvalues of T right : bool, optional If right=True compute right eigenvectors, left eigenve...
387,263
def consume_network_packet_messages_from_redis(): sub = KombuSubscriber( name, FORWARD_BROKER_URL, FORWARD_SSL_OPTIONS) seconds_to_consume = 10.0 heartbeat = 60 serializer = "application/json" queue = FORWARD_QUEUE sub.consume( callback=recv_...
consume_network_packet_messages_from_redis Setup a ``celery_connectors.KombuSubscriber`` to consume meessages from the ``FORWARD_BROKER_URL`` broker in the ``FORWARD_QUEUE`` queue.
387,264
def get_imports(filename): with open(filename, "rb") as f: src = f.read() finder = ImportFinder() finder.visit(ast.parse(src, filename=filename)) imports = [] for i in finder.imports: name, _, is_from, is_star = i imports.append(i + (resolve_import(name, is_from, is_star...
Get all the imports in a file. Each import is a tuple of: (name, alias, is_from, is_star, source_file)
387,265
def get(self, file_id: str) -> [typing.BinaryIO, str, datetime.datetime]: raise NotImplementedError("Downloading files for downloading files in FileStore has not been implemented yet.")
Return the file identified by a file_id string, its file name and upload date.
387,266
def fit(self, X, y=None, groups=None, **fit_params): return self._fit(X, y=y, groups=groups, **fit_params)
Run fit on the estimator with parameters chosen sequentially by SigOpt. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vector, where n_samples in the number of samples and n_features is the number of features. y : array-like, shape ...
387,267
def entrypoint(cls): if not isinstance(cls, type) or not issubclass(cls, Command): raise TypeError(f"inappropriate entrypoint instance of type {cls.__class__}") cls._argcmdr_entrypoint_ = True return cls
Mark the decorated command as the intended entrypoint of the command module.
387,268
def url_(client_id: str, redirect_uri: str, *, scope: str = None, state: str = None, secure: bool = True) -> str: attrs = { : client_id, : quote(redirect_uri) } if scope is not None: attrs[] = quote(scope) if state is not None: a...
Construct a OAuth2 URL instead of an OAuth2 object.
387,269
def crosslisting_feature(catalog, soup): listing = {} for elem in soup.coursedb.findAll(): seats = int(elem[]) crns = [safeInt(crn.string) for crn in elem.findAll()] cl = CrossListing(crns, seats) for crn in crns: listing[crn] = cl catalog.crosslist...
Parses all the crosslistings. These refer to the similar CRNs, such as a grad & undergrad level course.
387,270
def _get_value(data_structure, key): if len(key) == 0: raise KeyError() value = data_structure[key[0]] if len(key) > 1: return _get_value(value, key[1:]) return value
Return the value of a data_structure given a path. :param data_structure: Dictionary, list or subscriptable object. :param key: Array with the defined path ordered.
387,271
def getSparseTensor(numNonzeros, inputSize, outputSize, onlyPositive=False, fixedRange=1.0/24): w = torch.Tensor(outputSize, inputSize, ) if onlyPositive: w.data.uniform_(0, fixedRange) else: w.data.uniform_(-fixedRange, fixedRange) if numNonzeros < inp...
Return a random tensor that is initialized like a weight matrix Size is outputSize X inputSize, where weightSparsity% of each row is non-zero
387,272
def step( self, local_inv=None, peer_table=None, peer_queue=None, con=None, path=None ): if path is None: path = self.atlasdb_path if self.max_neighbors is None: self.max_neighbors = atlas_max_neighbors() log.debug("%s: max neighbors is %s" % (self.my_hostp...
Execute one round of the peer discovery algorithm: * Add at most 10 new peers from the pending peer queue (but ping them first, and drop hosts if the pending queue gets to be too long). * Execute one step of the MHRWDA algorithm. Add any new peers from the neighbor sets discover...
387,273
def namespace(self): if self.m_name == -1 or (self.m_event != const.START_TAG and self.m_event != const.END_TAG): return u if self.m_namespaceUri == 0xFFFFFFFF: return u return self.sb[self.m_namespaceUri]
Return the Namespace URI (if any) as a String for the current tag
387,274
def get_repo(self, auth, username, repo_name): path = "/repos/{u}/{r}".format(u=username, r=repo_name) response = self.get(path, auth=auth) return GogsRepo.from_json(response.json())
Returns a the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: a representation of the re...
387,275
def eval(self, construct): data = clips.data.DataObject(self._env) if lib.EnvEval(self._env, construct.encode(), data.byref) != 1: raise CLIPSError(self._env) return data.value
Evaluate an expression returning its value. The Python equivalent of the CLIPS eval command.
387,276
def config_merge_text(source=, merge_config=None, merge_path=None, saltenv=): * config_txt = __salt__[](source=source)[][source] return __salt__[](initial_config=config_txt, merge_config=merge_confi...
.. versionadded:: 2019.2.0 Return the merge result of the configuration from ``source`` with the merge configuration, as plain text (without loading the config on the device). source: ``running`` The configuration type to retrieve from the network device. Default: ``running``. Availabl...
387,277
def delete_file(self, path, prefixed_path, source_storage): if self.faster: return True else: return super(Command, self).delete_file(path, prefixed_path, source_storage)
We don't need all the file_exists stuff because we have to override all files anyways.
387,278
def map(source = , z = 0, x = 0, y = 0, format = , srs=, bin=None, hexPerTile=None, style=, taxonKey=None, country=None, publishingCountry=None, publisher=None, datasetKey=None, year=None, basisOfRecord=None, **kwargs): t work) :param publishingCountry: [str] The 2-letter country code (as per ...
GBIF maps API :param source: [str] Either ``density`` for fast, precalculated tiles, or ``adhoc`` for any search :param z: [str] zoom level :param x: [str] longitude :param y: [str] latitude :param format: [str] format of returned data. One of: - ``.mvt`` - vector tile - ``@Hx....
387,279
def cli(*args, **kwargs): log.debug(.format(args, kwargs)) env.update(kwargs)
通用自动化处理工具 详情参考 `GitHub <https://github.com/littlemo/mohand>`_
387,280
def database(self, database_id, ddl_statements=(), pool=None): return Database(database_id, self, ddl_statements=ddl_statements, pool=pool)
Factory to create a database within this instance. :type database_id: str :param database_id: The ID of the instance. :type ddl_statements: list of string :param ddl_statements: (Optional) DDL statements, excluding the 'CREATE DATABSE' statement. ...
387,281
def numeric_function_clean_dataframe(self, axis): result = None query_compiler = self if not axis and len(self.index) == 0: result = pandas.Series(dtype=np.int64) nonnumeric = [ col for col, dtype in zip(self.columns, self.dtypes) ...
Preprocesses numeric functions to clean dataframe and pick numeric indices. Args: axis: '0' if columns and '1' if rows. Returns: Tuple with return value(if any), indices to apply func to & cleaned Manager.
387,282
def javascript_escape(s, quote_double_quotes=True): ustring_re = re.compile(u"([\u0080-\uffff])") def fix(match): return r"\u%04x" % ord(match.group(1)) if type(s) == str: s = s.decode() elif type(s) != six.text_type: raise TypeError(s) s = s.replace(, ) s = s.repl...
Escape characters for javascript strings.
387,283
def is_eligible(self, timestamp, status, notif_number, in_notif_time, interval, escal_period): short_states = { u: , u: , u: , u: , u: , u: , u: , u: , u: , u: } if not self.time_based: if notif_number < se...
Check if the escalation is eligible (notification is escalated or not) Escalation is NOT eligible in ONE of the following condition is fulfilled:: * escalation is not time based and notification number not in range [first_notification;last_notification] (if last_notif == 0, it's infinity) ...
387,284
def virtualenv_no_global(): site_mod_dir = os.path.dirname(os.path.abspath(site.__file__)) no_global_file = os.path.join(site_mod_dir, ) if running_under_virtualenv() and os.path.isfile(no_global_file): return True
Return True if in a venv and no system site packages.
387,285
def set_passport_data_errors(self, user_id, errors): from pytgbot.api_types.sendable.passport import PassportElementError assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(errors, list, parameter_name="errors") result = ...
Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. Use this if the data submitted by t...
387,286
def add_neighbor(self, edge: "Edge") -> None: if edge is None or (edge.source != self and edge.target != self): return if edge.source == self: other: Node = edge.target elif edge.target == self: other: Node = edge.source else: ...
Adds a new neighbor to the node. Arguments: edge (Edge): The edge that would connect this node with its neighbor.
387,287
def header(self, array): self._check_row_size(array) self._header = list(map(obj2unicode, array)) return self
Specify the header of the table
387,288
def relations_used(self): g = self.get_graph() types = set() for (x,y,d) in g.edges(data=True): types.add(d[]) return list(types)
Return list of all relations used to connect edges
387,289
def _build_environ(self) -> Dict[str, Optional[str]]: d: Dict[str, Optional[str]] = {} if self.__config__.case_insensitive: env_vars = {k.lower(): v for k, v in os.environ.items()} else: env_vars = cast(Dict[str, str], os.environ) for field in self.__fi...
Build environment variables suitable for passing to the Model.
387,290
def transfer_size(self): ts = self.attributes[] if isinstance(ts, six.string_types): ts = shlex.split(ts) ts = [str(e) for e in ts] return ts
Size of transfer in bytes (e.g.: 8, 4k, 2m, 1g)
387,291
def ask(question): while True: ans = input(question) al = ans.lower() if match(, al): return True elif match(, al): return False elif match(, al): stdout.write(CYAN) print("\nGoodbye.\n") stdout.write(RESET) ...
Infinite loop to get yes or no answer or quit the script.
387,292
def find_all_files(glob): for finder in finders.get_finders(): for path, storage in finder.list([]): if fnmatch.fnmatchcase(os.path.join(getattr(storage, , ) or , path), glob): yield path, sto...
Finds all files in the django finders for a given glob, returns the file path, if available, and the django storage object. storage objects must implement the File storage API: https://docs.djangoproject.com/en/dev/ref/files/storage/
387,293
def get(self, path, content=True, type=None, format=None, load_alternative_format=True): path = path.strip() ext = os.path.splitext(path)[1] if not self.exists(path) or (type != if type else ext not in self.all_nb_extensions()): return super(TextFileContentsManage...
Takes a path for an entity and returns its model
387,294
def write_file(content, *path): with open(os.path.join(*path), "w") as file: return file.write(content)
Simply write some content to a file, overriding the file if necessary.
387,295
def clean_whitespace(statement): import re statement.text = statement.text.replace(, ).replace(, ).replace(, ) statement.text = statement.text.strip() statement.text = re.sub(, , statement.text) return statement
Remove any consecutive whitespace characters from the statement text.
387,296
def post(self, res_path, data=None, files=None, timeout=10.): resp = requests.post( self.__res_uri(res_path), data=data, files=files, headers=self.__headers(), verify=False, auth=self.__auth(), timeout=timeout ) return ( resp.status_code, json.loads(resp.text) )
Post operation. :param str res_path: Resource path. :param list data: Request parameters for data. :param list files: Request parameters for files. :param float timeout: Timeout in seconds. :rtype: tuple :return: Tuple with status code and response body.
387,297
def handle_get_token(self, req): try: pathsegs = split_path(req.path_info, minsegs=1, maxsegs=3, rest_with_last=True) except ValueError: return HTTPNotFound(request=req) if pathsegs[0] == and pathsegs[2] == : ...
Handles the various `request for token and service end point(s)` calls. There are various formats to support the various auth servers in the past. Examples:: GET <auth-prefix>/v1/<act>/auth X-Auth-User: <act>:<usr> or X-Storage-User: <usr> X-Auth-Key: <key>...
387,298
def browse(self, ml_item=None, start=0, max_items=100, full_album_art_uri=False, search_term=None, subcategories=None): if ml_item is None: search = else: search = ml_item.item_id if subcategories is not None: for category in...
Browse (get sub-elements from) a music library item. Args: ml_item (`DidlItem`): the item to browse, if left out or `None`, items at the root level will be searched. start (int): the starting index of the results. max_items (int): the maximum number of items ...
387,299
def _run_paired(paired): from bcbio.structural import titancna work_dir = _sv_workdir(paired.tumor_data) seg_files = model_segments(tz.get_in(["depth", "bins", "normalized"], paired.tumor_data), work_dir, paired) call_file = call_copy_numbers(seg_files["seg"], work_di...
Run somatic variant calling pipeline.