Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
365,500
def import_fasst(self, checked=False, test_fasst=None, test_annot=None): if self.parent.info.filename is not None: fasst_file = splitext(self.parent.info.filename)[0] + annot_file = splitext(self.parent.info.filename)[0] + else: fasst_file = annot_file = ...
Action: import from FASST .mat file
365,501
def assert_title(self, title, **kwargs): query = TitleQuery(title, **kwargs) @self.synchronize(wait=query.wait) def assert_title(): if not query.resolves_for(self): raise ExpectationNotMet(query.failure_message) return True return asse...
Asserts that the page has the given title. Args: title (str | RegexObject): The string or regex that the title should match. **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`. Returns: True Raises: ExpectationNotMet: If the assertion...
365,502
def create_module_page(mod, dest_path, force=False): "Create the documentation notebook for module `mod_name` in path `dest_path`" nb = get_empty_notebook() mod_name = mod.__name__ strip_name = strip_fastai(mod_name) init_cell = [get_md_cell(f), get_md_cell()] cells = [get_code_cell(f, True)] ...
Create the documentation notebook for module `mod_name` in path `dest_path`
365,503
def save(self): id = self.id or self.objects.id(self.name) self.objects[id] = self.prepare_save(dict(self)) self.id = id self.post_save() return id
Save this entry. If the entry does not have an :attr:`id`, a new id will be assigned, and the :attr:`id` attribute set accordingly. Pre-save processing of the fields saved can be done by overriding the :meth:`prepare_save` method. Additional actions to be done after the save o...
365,504
def hgnc_genes(self, hgnc_symbol, build=, search=False): LOG.debug("Fetching genes with symbol %s" % hgnc_symbol) if search: full_query = self.hgnc_collection.find({ : [ {: hgnc_symbol}, {: int(hgnc_symbol) if hgnc...
Fetch all hgnc genes that match a hgnc symbol Check both hgnc_symbol and aliases Args: hgnc_symbol(str) build(str): The build in which to search search(bool): if partial searching should be used Returns: result()
365,505
def stop(self, container, instances=None, map_name=None, **kwargs): return self.run_actions(, container, instances=instances, map_name=map_name, **kwargs)
Stops instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance names to stop. If not specified, will stop all instances as specified in the configuration (or just one default instance). :type instances:...
365,506
def standardizeMapName(mapName): newName = os.path.basename(mapName) newName = newName.split(".")[0] newName = newName.split("(")[0] newName = re.sub("[LT]E+$", "", newName) newName = re.sub("-", "", newName) newName = re.sub(, , newName, flags=re.UNICODE) foreignName = n...
pretty-fy the name for pysc2 map lookup
365,507
def _convert_from_thrift_binary_annotations(self, thrift_binary_annotations): tags = {} local_endpoint = None remote_endpoint = None for binary_annotation in thrift_binary_annotations: if binary_annotation.key == : remote_endpoint = self._convert_fro...
Accepts a thrift decoded binary annotation and converts it to a v1 binary annotation.
365,508
def network_interfaces_list_all(**kwargs): result = {} netconn = __utils__[](, **kwargs) try: nics = __utils__[](netconn.network_interfaces.list_all()) for nic in nics: result[nic[]] = nic except CloudError as exc: __utils__[](, str(exc), **kwargs) resul...
.. versionadded:: 2019.2.0 List all network interfaces within a subscription. CLI Example: .. code-block:: bash salt-call azurearm_network.network_interfaces_list_all
365,509
def dispatch_request(self, *args, **kwargs): if request.method in (, ): return_url, context = self.post(*args, **kwargs) if return_url is not None: return redirect(return_url) elif request.method in (, ): context = self.get(*args, **kwargs) ...
Dispatch the request. Its the actual ``view`` flask will use.
365,510
def write_into(self, block, level=0): for line, l in self._lines: block.write_line(line, level + l) for name, obj in _compat.iteritems(self._deps): block.add_dependency(name, obj)
Append this block to another one, passing all dependencies
365,511
def create(self, template=None, flags=0, args=()): if isinstance(args, dict): template_args = [] for item in args.items(): template_args.append("--%s" % item[0]) template_args.append("%s" % item[1]) else: template_args = args ...
Create a new rootfs for the container. "template" if passed must be a valid template name. "flags" (optional) is an integer representing the optional create flags to be passed. "args" (optional) is a tuple of arguments to pass to the template. It can also b...
365,512
def get_hla_truthset(data): val_csv = tz.get_in(["config", "algorithm", "hlavalidate"], data) out = {} if val_csv and utils.file_exists(val_csv): with open(val_csv) as in_handle: reader = csv.reader(in_handle) next(reader) for sample, locus, alleles in (l fo...
Retrieve expected truth calls for annotating HLA called output.
365,513
def lookup_tf(self, h): for ((_, k1, k2), v) in self.client.scan(HASH_TF_INDEX_TABLE, ((h,), (h,))): yield (kvlayer_key_to_stream_id((k1, k2)), v)
Get stream IDs and term frequencies for a single hash. This yields pairs of strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item` and the corresponding term frequency. ..see:: :meth:`lookup`
365,514
def find_profile_dir_by_name(cls, ipython_dir, name=u, config=None): dirname = u + name paths = [os.getcwdu(), ipython_dir] for p in paths: profile_dir = os.path.join(p, dirname) if os.path.isdir(profile_dir): return cls(location=profile_dir, conf...
Find an existing profile dir by profile name, return its ProfileDir. This searches through a sequence of paths for a profile dir. If it is not found, a :class:`ProfileDirError` exception will be raised. The search path algorithm is: 1. ``os.getcwdu()`` 2. ``ipython_dir`` ...
365,515
def is_same_address(addr1, addr2): hostport1 = addr1.split(":") hostport2 = addr2.split(":") return (is_same_host(hostport1[0], hostport2[0]) and hostport1[1] == hostport2[1])
Where the two addresses are in the host:port Returns true if ports are equals and hosts are the same using is_same_host
365,516
def search_regexp(self): if ((self.season == "") and (self.episode == "")): regexp = % self.title.lower() elif (self.episode == ""): regexp = % (self.title.lower(), self.season, self.season) else: regexp = % (self.title.lower(), self.season, self.e...
Define the regexp used for the search
365,517
def clear_attributes(self): for sample in self.metadata: try: delattr(sample[self.analysistype], ) delattr(sample[self.analysistype], ) delattr(sample[self.analysistype], ) except AttributeError: pass
Remove the record_dict attribute from the object, as SeqRecords are not JSON-serializable. Also remove the contig_lengths and longest_contig attributes, as they are large lists that make the .json file ugly
365,518
def setup_sensors(self): self._add_result = Sensor.float("add.result", "Last ?add result.", "", [-10000, 10000]) self._add_result.set_value(0, Sensor.UNREACHABLE) self._time_result = Sensor.timestamp("time.result", "Last ?time result.", "") self._time_re...
Setup some server sensors.
365,519
def filter_entries(self, request_type=None, content_type=None, status_code=None, http_version=None, regex=True): results = [] for entry in self.entries: valid_entry = True p = self.parser if request_type is not None and no...
Returns a ``list`` of entry objects based on the filter criteria. :param request_type: ``str`` of request type (i.e. - GET or POST) :param content_type: ``str`` of regex to use for finding content type :param status_code: ``int`` of the desired status code :param http_version: ``str`` o...
365,520
def do(self, changes, task_handle=taskhandle.NullTaskHandle()): self.history.do(changes, task_handle=task_handle)
Apply the changes in a `ChangeSet` Most of the time you call this function for committing the changes for a refactoring.
365,521
def spher2cart(rho, theta, phi): st = np.sin(theta) sp = np.sin(phi) ct = np.cos(theta) cp = np.cos(phi) rhost = rho * st x = rhost * cp y = rhost * sp z = rho * ct return np.array([x, y, z])
Spherical to Cartesian coordinate conversion.
365,522
def _set_intf_type(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 1}, u: {: 2}, u: {: 3...
Setter method for intf_type, mapped from YANG variable /logical_interface_state/main_interface_physical/intf_type (intf-type) If this variable is read-only (config: false) in the source YANG file, then _set_intf_type is considered as a private method. Backends looking to populate this variable should do...
365,523
def collection(name=None): if name is None: collection = Collection.query.get_or_404(1) else: collection = Collection.query.filter( Collection.name == name).first_or_404() return render_template([ .format(collection.id), .format(slugify(name, )), ...
Render the collection page. It renders it either with a collection specific template (aka collection_{collection_name}.html) or with the default collection template (collection.html).
365,524
def _to_dict(self): _dict = {} if hasattr(self, ) and self.name is not None: _dict[] = self.name if hasattr(self, ) and self.role is not None: _dict[] = self.role return _dict
Return a json dictionary representing this model.
365,525
def selfSignCert(self, cert, pkey): cert.set_issuer(cert.get_subject()) cert.sign(pkey, self.signing_digest)
Self-sign a certificate. Args: cert (OpenSSL.crypto.X509): The certificate to sign. pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate. Examples: Sign a given certificate with a given private key: cdir.selfSignCert(mycert, myoth...
365,526
def get_repository(self, repository_id=None): if not self._can(): raise PermissionDenied() else: return self._provider_session.get_repository(repository_id)
Gets the ``Repository`` specified by its ``Id``. In plenary mode, the exact ``Id`` is found or a ``NotFound`` results. Otherwise, the returned ``Repository`` may have a different ``Id`` than requested, such as the case where a duplicate ``Id`` was assigned to a ``Repository`` and retain...
365,527
def to_special_value(self, value): if isinstance(value, utils.NoAssert): return self.spdx_namespace.noassertion elif isinstance(value, utils.SPDXNone): return self.spdx_namespace.none else: return Literal(value)
Return proper spdx term or Literal
365,528
def save_project(self, project, filename=): r if filename == : filename = project.name filename = self._parse_filename(filename=filename, ext=) d = {project.name: project} with open(filename, ) as f: pickle.dump(d, f)
r""" Saves given Project to a 'pnm' file This will include all of associated objects, including algorithms. Parameters ---------- project : OpenPNM Project The project to save. filename : string, optional If no filename is given, the given proje...
365,529
def calculate_limits(array_dict, method=, percentiles=None, limit=()): if percentiles is not None: for percentile in percentiles: if not 0 <= percentile <= 100: raise ValueError("percentile (%s) not between [0, 100]") if method == : all_arrays = np.concatenate( ...
Calculate limits for a group of arrays in a flexible manner. Returns a dictionary of calculated (vmin, vmax), with the same keys as `array_dict`. Useful for plotting heatmaps of multiple datasets, and the vmin/vmax values of the colormaps need to be matched across all (or a subset) of heatmaps. P...
365,530
def create(cls, tx_signers, recipients, metadata=None, asset=None): (inputs, outputs) = cls.validate_create(tx_signers, recipients, asset, metadata) return cls(cls.CREATE, {: asset}, inputs, outputs, metadata)
A simple way to generate a `CREATE` transaction. Note: This method currently supports the following Cryptoconditions use cases: - Ed25519 - ThresholdSha256 Additionally, it provides support for the following BigchainDB...
365,531
def read_igpar(self): self.er_ev = {} self.er_bp = {} self.er_ev_tot = None self.er_bp_tot = None self.p_elec = None self.p_ion = None try: search = [] def er_ev(results, match): resu...
Renders accessible: er_ev = e<r>_ev (dictionary with Spin.up/Spin.down as keys) er_bp = e<r>_bp (dictionary with Spin.up/Spin.down as keys) er_ev_tot = spin up + spin down summed er_bp_tot = spin up + spin down summed p_elc = spin up + spin down summed ...
365,532
def num_pending(self, work_spec_name): return self.registry.len(WORK_UNITS_ + work_spec_name, priority_min=time.time())
Get the number of pending work units for some work spec. These are work units that some worker is currently working on (hopefully; it could include work units assigned to workers that died and that have not yet expired).
365,533
def _set_bfd_session_setup_delay(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=bfd_session_setup_delay.bfd_session_setup_delay, is_container=, presence=False, yang_name="bfd-session-setup-delay", rest_name="bfd-session-setup-delay", parent=self, pat...
Setter method for bfd_session_setup_delay, mapped from YANG variable /rbridge_id/bfd_session_setup_delay (container) If this variable is read-only (config: false) in the source YANG file, then _set_bfd_session_setup_delay is considered as a private method. Backends looking to populate this variable should ...
365,534
def create(self): self.create_virtualenv() self.create_project() self.create_uwsgi_script() self.create_nginx_config() self.create_manage_scripts() logging.info()
Creates the full project
365,535
def _set_isis_state(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=isis_state.isis_state, is_container=, presence=False, yang_name="isis-state", rest_name="isis-state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register...
Setter method for isis_state, mapped from YANG variable /isis_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_isis_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_isis_state() dir...
365,536
def _GetStat(self): stat_object = super(LVMFileEntry, self)._GetStat() if self._vslvm_logical_volume is not None: stat_object.size = self._vslvm_logical_volume.size return stat_object
Retrieves information about the file entry. Returns: VFSStat: a stat object.
365,537
def _increment(self, what, host): self.processed[host] = 1 prev = (getattr(self, what)).get(host, 0) getattr(self, what)[host] = prev+1
helper function to bump a statistic
365,538
def Boolean(): @wraps(Boolean) def built(value): if isinstance(value, bool): return value if value == None: return False if isinstance(value, int): return not value == 0 if isinstance(value, str): ...
Creates a validator that attempts to convert the given value to a boolean or raises an error. The following rules are used: ``None`` is converted to ``False``. ``int`` values are ``True`` except for ``0``. ``str`` values converted in lower- and uppercase: * ``y, yes, t, true`` * ``n, no, f, ...
365,539
def asyncPipeFetch(context=None, _INPUT=None, conf=None, **kwargs): splits = yield asyncGetSplits(_INPUT, conf[], **cdicts(opts, kwargs)) items = yield asyncStarMap(asyncParseResult, splits) _OUTPUT = utils.multiplex(items) returnValue(_OUTPUT)
A source that asynchronously fetches and parses one or more feeds to return the feed entries. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : asyncPipe like object (twisted Deferred iterable of items) conf : { 'URL': [ {'type': 'url', 'value': <url1...
365,540
def sample_from_proposal(self, A: pd.DataFrame) -> None: self.source, self.target, self.edge_dict = random.choice( list(self.edges(data=True)) ) self.original_value = A[f"∂({self.source})/∂t"][self.target] A[f"∂({self.source})/∂t"][self.target] += np.random...
Sample a new transition matrix from the proposal distribution, given a current candidate transition matrix. In practice, this amounts to the in-place perturbation of an element of the transition matrix currently being used by the sampler. Args
365,541
def _apply_correction_on_genes(genes, pathway_column_names, pathway_definitions): gene_row_names = index_element_map(genes) membership_matrix = initialize_membership_matrix( genes, pathway_definitions) crosstalk_corrected_index_map =...
Helper function to create the gene-to-pathway membership matrix and apply crosstalk correction on that matrix. Returns the crosstalk-corrected pathway definitions for the input `genes.`
365,542
def unhook_all(): _listener.start_if_necessary() _listener.blocking_keys.clear() _listener.nonblocking_keys.clear() del _listener.blocking_hooks[:] del _listener.handlers[:] unhook_all_hotkeys()
Removes all keyboard hooks in use, including hotkeys, abbreviations, word listeners, `record`ers and `wait`s.
365,543
def delete_copy_field(self, collection, copy_dict): sourcesource_field_namedestdestination_field_name if self.devel: self.logger.debug("Deleting {}".format(str(copy_dict))) copyfields = self.get_schema_copyfields(collection) if copy_dict not in copyfields: ...
Deletes a copy field. copy_dict should look like :: {'source':'source_field_name','dest':'destination_field_name'} :param string collection: Name of the collection for the action :param dict copy_field: Dictionary of field info
365,544
def _next_page(self, response): for link in response.getheader("link", "").split(","): try: (url, rel) = link.split(";") if "next" in rel: return url.lstrip("<").rstrip(">") except Exception: return
return url path to next page of paginated data
365,545
def as_uni_form(form): if isinstance(form, BaseFormSet): if settings.DEBUG: template = get_template() else: template = uni_formset_template c = Context({: form}) else: if settings.DEBUG: template = get_template() else: ...
The original and still very useful way to generate a uni-form form/formset:: {% load uni_form_tags %} <form class="uniForm" action="post"> {% csrf_token %} {{ myform|as_uni_form }} </form>
365,546
def export_original_data(self): def export_field(value): try: return value.export_original_data() except AttributeError: return value return [export_field(val) for val in self.__original_data__]
Retrieves the original_data
365,547
def visit_Call(self, node): if logging_level is None: super(LoggingVisitor, self).generic_visit(node) return self.current_logging_call = node if logging_level == "warn": self.violations.append((node, WARN_VIOLATION)) self....
Visit a function call. We expect every logging statement and string format to be a function call.
365,548
def get_provider_id(self): if ( not in self.my_osid_object._my_map or not self.my_osid_object._my_map[]): raise IllegalState() return Id(self.my_osid_object._my_map[])
Gets the ``Id`` of the provider. return: (osid.id.Id) - the provider ``Id`` *compliance: mandatory -- This method must be implemented.*
365,549
def send_contributor_email(self, contributor): ContributorReport( contributor, month=self.month, year=self.year, deadline=self._deadline, start=self._start, end=self._end ).send()
Send an EmailMessage object for a given contributor.
365,550
def process(in_path, boundaries_id=msaf.config.default_bound_id, labels_id=msaf.config.default_label_id, annot_beats=False, framesync=False, feature="pcp", hier=False, save=False, out_file=None, n_jobs=4, annotator_id=0, config=None): if config is None: config ...
Main process to evaluate algorithms' results. Parameters ---------- in_path : str Path to the dataset root folder. boundaries_id : str Boundaries algorithm identifier (e.g. siplca, cnmf) labels_id : str Labels algorithm identifier (e.g. siplca, cnmf) ds_name : str ...
365,551
def getAllFeatureSets(self): for dataset in self.getAllDatasets(): iterator = self._client.search_feature_sets( dataset_id=dataset.id) for featureSet in iterator: yield featureSet
Returns all feature sets on the server.
365,552
def get_exptime(self, img): header = self.get_header(img) if in header.keys(): etime = header[] elif in header.keys(): etime = header[] else: etime = 1.0 return etime
Obtain EXPTIME
365,553
def combat(adata: AnnData, key: str = , covariates: Optional[Collection[str]] = None, inplace: bool = True): if key not in adata.obs_keys(): raise ValueError(.format(key)) if covariates is not None: cov_exist = np.isin(covariates, adata.obs_keys()) if np.any(~cov_exist): ...
ComBat function for batch effect correction [Johnson07]_ [Leek12]_ [Pedersen12]_. Corrects for batch effects by fitting linear models, gains statistical power via an EB framework where information is borrowed across genes. This uses the implementation of `ComBat <https://github.com/brentp/combat.py>`__ [Pe...
365,554
def _fit(self, Z, parameter_iterable): self.scorer_ = check_scoring(self.estimator, scoring=self.scoring) cv = self.cv cv = _check_cv(cv, Z) if self.verbose > 0: if isinstance(parameter_iterable, Sized): n_candidates = len(parameter_iterable) ...
Actual fitting, performing the search over parameters.
365,555
def stdout_to_results(s): results = s.strip().split() return [BenchmarkResult(*r.split()) for r in results]
Turns the multi-line output of a benchmark process into a sequence of BenchmarkResult instances.
365,556
def output_randomized_kronecker_to_pickle( left_matrix, right_matrix, train_indices_out_path, test_indices_out_path, train_metadata_out_path=None, test_metadata_out_path=None, remove_empty_rows=True): logging.info("Writing item sequences to pickle files %s and %s.", train_indices_out...
Compute randomized Kronecker product and dump it on the fly. A standard Kronecker product between matrices A and B produces [[a_11 B, ..., a_1n B], ... [a_m1 B, ..., a_mn B]] (if A's size is (m, n) and B's size is (p, q) then A Kr...
365,557
def yield_event(self, act): if act in self.tokens: coro = act.coro op = self.try_run_act(act, self.tokens[act]) if op: del self.tokens[act] return op, coro
Hande completion for a request and return an (op, coro) to be passed to the scheduler on the last completion loop of a proactor.
365,558
def gen_headers() -> Dict[str, str]: ua_list: List[str] = [] headers: Dict[str, str] = {: ua_list[random.randint(0, len(ua_list) - 1)]} return headers
Generate a header pairing.
365,559
def _delete_nxos_db(self, unused, vlan_id, device_id, host_id, vni, is_provider_vlan): try: rows = nxos_db.get_nexusvm_bindings(vlan_id, device_id) for row in rows: nxos_db.remove_nexusport_binding(row.port_id, row.vlan_id, ...
Delete the nexus database entry. Called during delete precommit port event.
365,560
def daily_bounds(network, snapshots): sus = network.storage_units network.model.period_starts = network.snapshot_weightings.index[0::24] network.model.storages = sus.index def day_rule(m, s, p): return ( m.state_of_charge[s, p] == m.state_of_cha...
This will bound the storage level to 0.5 max_level every 24th hour.
365,561
def get_image_tags(self): current_images = self.images() tags = {tag: i[] for i in current_images for tag in i[]} return tags
Fetches image labels (repository / tags) from Docker. :return: A dictionary, with image name and tags as the key and the image id as value. :rtype: dict
365,562
def connect(self, fn): self.conn = sqlite3.connect(fn) cur = self.get_cursor() cur.execute() cur.execute() cur.execute() cur.execute()
SQLite connect method initialize db
365,563
def update_settings(self, service_id, version_number, settings={}): body = urllib.urlencode(settings) content = self._fetch("/service/%s/version/%d/settings" % (service_id, version_number), method="PUT", body=body) return FastlySettings(self, content)
Update the settings for a particular service and version.
365,564
def event_log_filter_between_date(start, end, utc): return { : , : [ {: , : [format_event_log_date(start, utc)]}, {: , : [format_event_log_date(end, utc)]} ] }
betweenDate Query filter that SoftLayer_EventLog likes :param string start: lower bound date in mm/dd/yyyy format :param string end: upper bound date in mm/dd/yyyy format :param string utc: utc offset. Defaults to '+0000'
365,565
def init_rotate(cls, radians): result = cls() cairo.cairo_matrix_init_rotate(result._pointer, radians) return result
Return a new :class:`Matrix` for a transformation that rotates by :obj:`radians`. :type radians: float :param radians: Angle of rotation, in radians. The direction of rotation is defined such that positive angles rotate in the direction from the p...
365,566
def get_request_body_chunk(self, content: bytes, closed: bool, more_content: bool) -> Dict[str, Any]: return { : content, : closed, : more_content }
http://channels.readthedocs.io/en/stable/asgi/www.html#request-body-chunk
365,567
def get_specific_subnodes(self, node, name, recursive=0): children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE] ret = [x for x in children if x.tagName == name] if recursive > 0: for x in children: ret.extend(self.get_specific_subnodes(x, na...
Given a node and a name, return a list of child `ELEMENT_NODEs`, that have a `tagName` matching the `name`. Search recursively for `recursive` levels.
365,568
def public_url(self): return "{storage_base_url}/{bucket_name}/{quoted_name}".format( storage_base_url=_API_ACCESS_ENDPOINT, bucket_name=self.bucket.name, quoted_name=quote(self.name.encode("utf-8")), )
The public URL for this blob. Use :meth:`make_public` to enable anonymous access via the returned URL. :rtype: `string` :returns: The public URL for this blob.
365,569
def from_callback(cls, cb, nx=None, nparams=None, **kwargs): if kwargs.get(, False): if not in kwargs: raise ValueError("Need ``names`` in kwargs.") if nx is None: nx = len(kwargs[]) elif nx != len(kwargs[]): raise Val...
Generate a SymbolicSys instance from a callback. Parameters ---------- cb : callable Should have the signature ``cb(x, p, backend) -> list of exprs``. nx : int Number of unknowns, when not given it is deduced from ``kwargs['names']``. nparams : int ...
365,570
def _playsoundOSX(sound, block = True): s Stack Overflow answer here: http://stackoverflow.com/a/34568298/901641 I never would have tried using AppKit.NSSound without seeing his code. :////file://Unable to load sound named: ' + sound) nssound.play() if block: sleep(nssound.duration())
Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not copied from) Aaron's Stack Overflow answer here: ...
365,571
def _euristic_h_function(self, suffix, index): if self.euristics > 0: suffix = suffix[:self.euristics] index_temporary_euristics = self._temporary_euristics[index] cost = index_temporary_euristics.get(suffix, None) if cost is not None: return cos...
Вычисление h-эвристики из работы Hulden,2009 для текущей вершины словаря Аргументы: ---------- suffix : string непрочитанный суффикс входного слова index : int индекс текущего узла в словаре Возвращает: ----------- cost : float ...
365,572
def create_api_pool(self): return ApiPool( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of Api Pool services facade.
365,573
def send_template_email(recipients, title_template, body_template, context, language): send_emails = getattr(settings, , True) if not send_emails: return site_name = getattr(settings, , ) domain = getattr(settings, , None) if domain is None: try: Site = apps.get_m...
Sends e-mail using templating system
365,574
def add_record(self, record): record.setdefault(, {}).setdefault(, []) assert not self.has_record(record) record[][].append(self.spec)
Add a record to the OAISet. :param record: Record to be added. :type record: `invenio_records.api.Record` or derivative.
365,575
def _executor_script(self): fd, path = tempfile.mkstemp(suffix=, dir=os.getcwd()) os.close(fd) with open(path, ) as ostr: self._write_executor_script(ostr) mode = os.stat(path).st_mode os.chmod(path, mode | stat.S_IEXEC | stat.S_IRGRP | stat.S_IRUSR) ...
Create shell-script in charge of executing the benchmark and return its path.
365,576
def best_four_point_to_buy(self): result = [] if self.check_mins_bias_ratio() and \ (self.best_buy_1() or self.best_buy_2() or self.best_buy_3() or \ self.best_buy_4()): if self.best_buy_1(): result.append(self.best_buy_1.__doc__.strip().deco...
判斷是否為四大買點 :rtype: str or False
365,577
def project_stored_info_type_path(cls, project, stored_info_type): return google.api_core.path_template.expand( "projects/{project}/storedInfoTypes/{stored_info_type}", project=project, stored_info_type=stored_info_type, )
Return a fully-qualified project_stored_info_type string.
365,578
def send_email(self, source, subject, body, to_addresses, cc_addresses=None, bcc_addresses=None, format=, reply_addresses=None, return_path=None, text_body=None, html_body=None): format = format.lower().strip() if body is not None: if format == ...
Composes an email message based on input data, and then immediately queues the message for sending. :type source: string :param source: The sender's email address. :type subject: string :param subject: The subject of the message: A short summary of the c...
365,579
def _set_font(self, font): font_metrics = QtGui.QFontMetrics(font) self._control.setTabStopWidth(self.tab_width * font_metrics.width()) self._completion_widget.setFont(font) self._control.document().setDefaultFont(font) if self._page_control: self._page_cont...
Sets the base font for the ConsoleWidget to the specified QFont.
365,580
def _decdeg_distance(pt1, pt2): lat1, lon1 = pt1 lat2, lon2 = pt2 lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2 c = 2 * np.arcsin(np.sqrt(a)) ...
Earth surface distance (in km) between decimal latlong points using Haversine approximation. http://stackoverflow.com/questions/15736995/ how-can-i-quickly-estimate-the-distance-between-two-latitude-longitude- points
365,581
def check_valid_rx_can_msg(result): return (result.value == ReturnCode.SUCCESSFUL) or (result.value > ReturnCode.WARNING)
Checks if function :meth:`UcanServer.read_can_msg` returns a valid CAN message. :param ReturnCode result: Error code of the function. :return: True if a valid CAN messages was received, otherwise False. :rtype: bool
365,582
def wallet_destroy(self, wallet): wallet = self._process_value(wallet, ) payload = {"wallet": wallet} resp = self.call(, payload) return resp == {}
Destroys **wallet** and all contained accounts .. enable_control required :param wallet: Wallet to destroy :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_destroy( ... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F...
365,583
def is_flapping(self, alert, window=1800, count=2): select = .format(window=window, customer= if alert.customer else ) return self._fetchone(select, vars(alert)).count > count
Return true if alert severity has changed more than X times in Y seconds
365,584
def delete_member(self, user): if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") return requests.delete( f"{self.api_url}/{self.address}/members/{user.email}", auth=("api", self.api_key), )
Returns a response after attempting to remove a member from the list.
365,585
def vflip(img): if not _is_pil_image(img): raise TypeError(.format(type(img))) return img.transpose(Image.FLIP_TOP_BOTTOM)
Vertically flip the given PIL Image. Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Vertically flipped image.
365,586
def insert_rows(self, row, no_rows=1): post_command_event(self.main_window, self.ContentChangedMsg) tab = self.grid.current_table self.code_array.insert(row, no_rows, axis=0, tab=tab)
Adds no_rows rows before row, appends if row > maxrows and marks grid as changed
365,587
def handle(self, cycle_delay=0.1): if self._server is not None: self._server.process(cycle_delay) self._driver.process_pv_updates()
Call this method to spend about ``cycle_delay`` seconds processing requests in the pcaspy server. Under load, for example when running ``caget`` at a high frequency, the actual time spent in the method may be much shorter. This effect is not corrected for. :param cycle_delay: Approximat...
365,588
async def send_file( self, entity, file, *, caption=None, force_document=False, progress_callback=None, reply_to=None, attributes=None, thumb=None, allow_cache=True, parse_mode=(), voice_note=False, video_note=False, buttons=None, silent=None, supports_streami...
Sends a file to the specified entity. Args: entity (`entity`): Who will receive the file. file (`str` | `bytes` | `file` | `media`): The file to send, which can be one of: * A local file path to an in-disk file. The file name ...
365,589
def from_path_by_ext(dir_path, ext): if isinstance(ext, (list, set, dict)): def filter(winfile): if winfile.ext in ext: return True else: return False else: def filter(winfile): if ...
Create a new FileCollection, and select all files that extension matching ``ext``:: dir_path = "your/path" fc = FileCollection.from_path_by_ext(dir_path, ext=[".jpg", ".png"])
365,590
def _make_valid_bounds(self, test_bounds): if len(test_bounds) != 2 or not isinstance(test_bounds, tuple): raise ValueError( "test_bounds must be a tuple of (lower bound, upper bound)" ) if test_bounds[0] is not None: if test_bounds[0] * self....
Private method: process input bounds into a form acceptable by scipy.optimize, and check the validity of said bounds. :param test_bounds: minimum and maximum weight of an asset :type test_bounds: tuple :raises ValueError: if ``test_bounds`` is not a tuple of length two. :raises ...
365,591
def history_report(history, config=None, html=True): if config is None: config = ReportConfiguration.load() report = HistoryReport(history=history, configuration=config) if html: return report.render_html() else: return report.render_json()
Test a model and save a history report. Parameters ---------- history : memote.HistoryManager The manager grants access to previous results. config : dict, optional The final test report configuration. html : bool, optional Whether to render the report as full HTML or JSON (...
365,592
def bound_pseudo(arnoldifyer, Wt, g_norm=0., G_norm=0., GW_norm=0., WGW_norm=0., tol=1e-6, pseudo_type=, pseudo_kwargs=None, delta_n=20, terminate_factor=1. ...
r'''Bound residual norms of next deflated system. :param arnoldifyer: an instance of :py:class:`~krypy.deflation.Arnoldifyer`. :param Wt: coefficients :math:`\tilde{W}\in\mathbb{C}^{n+d,k}` of the considered deflation vectors :math:`W` for the basis :math:`[V,U]` where ``V=last_solver.V`` and...
365,593
def push_data(self, data): if not _validate_data(data): return False jdata = json.loads(data[]) if int(self.proto[0:1]) == 1 else _list2map(data[]) if jdata is None: return False sid = data[] for func in self.callbacks[sid]: func(jdata...
Push data broadcasted from gateway to device
365,594
def max(self, key=None): if key is None: return self.reduce(max) return self.reduce(lambda a, b: max(a, b, key=key))
Find the maximum item in this RDD. :param key: A function used to generate key for comparing >>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0]) >>> rdd.max() 43.0 >>> rdd.max(key=str) 5.0
365,595
def ports(self): if self._ports is None: self._ports = {} if self.net_settings["Ports"]: for key, value in self.net_settings["Ports"].items(): cleaned_port = key.split("/")[0] self._ports[cleaned_port] = graceful_chain_get...
:return: dict { # container -> host "1234": "2345" }
365,596
def stage_import_from_file(self, fd, filename=): schema = ImportSchema() resp = self.service.post(self.base, files={: (filename, fd)}) return self.service.decode(schema, resp)
Stage an import from a file upload. :param fd: File-like object to upload. :param filename: (optional) Filename to use for import as string. :return: :class:`imports.Import <imports.Import>` object
365,597
def reading_dates(reading): full_format = .format() month_year_format = .format() year_format = .format() day_format = .format() day_month_format = .format() month_format = .format() period_format_short = period_format_long = start_date =...
Given a Reading, with start and end dates and granularities[1] it returns an HTML string representing that period. eg: * '1–6 Feb 2017' * '1 Feb to 3 Mar 2017' * 'Feb 2017 to Mar 2018' * '2017–2018' etc. [1] https://www.flickr.com/services/api/misc.dates.html
365,598
def register_laser_hooks(self, hook_type: str, hook: Callable): if hook_type == "add_world_state": self._add_world_state_hooks.append(hook) elif hook_type == "execute_state": self._execute_state_hooks.append(hook) elif hook_type == "start_sym_exec": s...
registers the hook with this Laser VM
365,599
def pre_release(version): announce(version) regen() changelog(version, write_out=True) fix_formatting() msg = "Preparing release version {}".format(version) check_call(["git", "commit", "-a", "-m", msg]) print() print(f"{Fore.CYAN}[generate.pre_release] {Fore.GREEN}All done!") ...
Generates new docs, release announcements and creates a local tag.