Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
341,600
def msh_to_cielab (msh): cielab = np.empty_like (msh) cielab[...,L] = msh[...,M] * np.cos (msh[...,S]) cielab[...,A] = msh[...,M] * np.sin (msh[...,S]) * np.cos (msh[...,H]) cielab[...,B] = msh[...,M] * np.sin (msh[...,S]) * np.sin (msh[...,H]) return cielab
Convert Moreland's Msh colorspace to CIE L*a*b*. *msh* should be of shape (*, 3). Return value will have same shape.
341,601
def make_file_exist(self, filename=None): if filename is None: path_to_file = FilePath(self) path_to_file.make_file_exist() return path_to_file else: self.make_directory_exist() path_to_file = self.touch_file(filename) retu...
Make the directory exist, then touch the file If the filename is None, then use self.name as filename
341,602
def difference(self, *others): return self.copy(super(NGram, self).difference(*others))
Return the difference of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> list(a.difference(b)) ['eggs']
341,603
def host_stanzas(self, config_access): defn_lines = self.resolve_defn(config_access) for val_dict in self.variable_iter(config_access.get_variables()): subst = list(self.apply_substitutions(defn_lines, val_dict)) host = subst[0] lines = [ConfigOutput.to_line(...
returns a list of host definitions
341,604
def register(self, managed_object): if not isinstance(managed_object, pobjects.ManagedObject): raise TypeError("managed object must be a Pie ManagedObject") object_attributes = list() if hasattr(managed_object, ): if managed_object.cryptograph...
Register a managed object with a KMIP appliance. Args: managed_object (ManagedObject): A managed object to register. An instantiatable subclass of ManagedObject from the Pie API. Returns: string: The uid of the newly registered managed object. Raises: ...
341,605
def open_forwarded_tcpip_channel(self, (src_addr, src_port), (dest_addr, dest_port)): return self.open_channel(, (dest_addr, dest_port), (src_addr, src_port))
Request a new channel back to the client, of type C{"forwarded-tcpip"}. This is used after a client has requested port forwarding, for sending incoming connections back to the client. @param src_addr: originator's address @param src_port: originator's port @param dest_addr: loca...
341,606
def create_polynoms(): fname = pr.resource_filename(, ) res_df = pd.read_csv(fname) polys = {} for resorder, row in zip(.split(), range(4)): p = poly1d([res_df.loc[row, ], res_df.loc[row, ]]) polys[ + .join(resorder)] = p return polys
Create and return poly1d objects. Uses the parameters from Morgan to create poly1d objects for calculations.
341,607
def get_nanopub_urls(ns_root_url: str = None, start_dt: str = None) -> dict: if not ns_root_url: ns_root_url = config["bel_api"]["servers"]["nanopubstore"] url = f"{ns_root_url}/nanopubs/timed" if not start_dt: start_dt = get_nanopubstore_start_dt(ns_root_url) params = {"startTim...
Get modified and deleted nanopub urls Limited by last datetime retrieved (start_dt). Modified includes new and updated nanopubs Returns: dict: {'modified': [], 'deleted': []}
341,608
def list_upgrades(refresh=True, **kwargs): * ret = {} if salt.utils.data.is_true(refresh): refresh_db() cmd = [, ] call = __salt__[](cmd, output_loglevel=, python_shell=False) if call[] != 0: comment = ...
List all available package upgrades. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades
341,609
def _read_import_root_map_file(path): if os.path.exists(path): with open(path, ) as fp: return dict({import_path: root for import_path, root in (x.strip().split() for x in fp.readlines())}) else: return {}
Reads a file mapping import paths to roots (e.g., example.org/pkg/foo -> example.org).
341,610
def newtons_method_scalar(f: fl.Fluxion, x: float, tol: float =1e-8) -> float: max_iters: int = 100 for i in range(max_iters): y, dy_dx = f(x) if abs(y) < tol: break dx = -y / dy_dx x += float(dx) return x, i
Solve the equation f(x) = 0 for a function from R->R using Newton's method
341,611
def viterbi_binary(prob, transition, p_state=None, p_init=None, return_logp=False): prob = np.atleast_2d(prob) n_states, n_steps = prob.shape if transition.shape == (2, 2): transition = np.tile(transition, (n_states, 1, 1)) elif transition.shape != (n_states, 2, 2): raise Paramet...
Viterbi decoding from binary (multi-label), discriminative state predictions. Given a sequence of conditional state predictions `prob[s, t]`, indicating the conditional likelihood of state `s` being active conditional on observation at time `t`, and a 2*2 transition matrix `transition` which encodes th...
341,612
def send(self, endpoint, json_message): _send_event_task.spool(endpoint=endpoint, json_message=json_message)
Queues the message to be sent.
341,613
def esc(self, val): if type(val) in self.type_map: return self.type_map[type(val)](val) else: return Esc(val)
Returns the given object in the appropriate wrapper class from esc_types.py. In most cases, you will not need to call this directly. However, if you are passing a string to the interp method that should be used as an SQL bind value and not raw SQL, you must pass it to this method to avoid a SQ...
341,614
def oortC(self,R,romberg=False,nsigma=None,phi=0.): meanvr= self.meanvR(R,romberg=romberg,nsigma=nsigma,phi=phi, use_physical=False) dmeanvphiRdphi= 0. surfmass= self._vmomentsurfacemass(R,0,0,phi=phi,romberg=romberg,nsigma=nsigma) dmeanvRdR...
NAME: oortC PURPOSE: calculate the Oort function C INPUT: R - radius at which to calculate C (can be Quantity) OPTIONAL INPUT: nsigma - number of sigma to integrate the velocities over KEYWORDS: romberg - if True, use a romb...
341,615
def equals(self, other): if self.is_dtype_equal(other): if self.categories.equals(other.categories): other_codes = other._codes else: other_codes = _recode_for_categories(other.codes, ...
Returns True if categorical arrays are equal. Parameters ---------- other : `Categorical` Returns ------- bool
341,616
def get_conn(client_type): conn_kwargs = {} conn_kwargs[] = salt.utils.stringutils.to_str( config.get_cloud_config_value( , get_configured_provider(), __opts__, search_global=False ) ) cloud_env = config.get_cloud_config_value( , get_configu...
Return a connection object for a client type.
341,617
def update_notes(self): fields = record_get_field_instances(self.record, ) for field in fields: subs = field_get_subfields(field) for sub in subs.get(, []): sub = sub.strip() if sub.startswith("*") and sub.endswith("*"): ...
Remove INSPIRE specific notes.
341,618
def updateMappingsOnDeviceType(self, thingTypeId, logicalInterfaceId, mappingsObject, notificationStrategy = "never"): req = ApiClient.oneThingTypeMappingUrl % (self.host, "/draft", thingTypeId, logicalInterfaceId) try: mappings = json.dumps({ "logicalInterfaceId" : ...
Add mappings for a thing type. Parameters: - thingTypeId (string) - the thing type - logicalInterfaceId (string) - the id of the application interface these mappings are for - notificationStrategy (string) - the notification strategy to use for these mappings - ma...
341,619
def emit(events, stream=None, Dumper=Dumper, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None): getvalue = None if stream is None: from StringIO import StringIO stream = StringIO() getvalue = stream.getvalue dumper = Dumper(stream, can...
Emit YAML parsing events into a stream. If stream is None, return the produced string instead.
341,620
def _create_metadata_cache(cache_location): cache_url = os.getenv() if cache_url: return FusekiMetadataCache(cache_location, cache_url) try: return SleepycatMetadataCache(cache_location) except InvalidCacheException: logging.warning( ...
Creates a new metadata cache instance appropriate for this platform.
341,621
def get_clients_per_page(self, per_page=1000, page=1, params=None): return self._get_resource_per_page(resource=CLIENTS, per_page=per_page, page=page, params=params)
Get clients per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list
341,622
def filter_by_folder(self, include=None, exclude=None): "Only keep filenames in `include` folder or reject the ones in `exclude`." include,exclude = listify(include),listify(exclude) def _inner(o): if isinstance(o, Path): n = o.relative_to(self.path).parts[0] else: n = o....
Only keep filenames in `include` folder or reject the ones in `exclude`.
341,623
def _rm_compute_leading_space(space_s_pres_split): i = 0 c = 0 while (i < len(space_s_pres_split) and (space_s_pres_split[i].isspace() or (space_s_pres_split[i] == ""))): c += len(space_s_pres_split[i]) i += 1 return c
count the number of spaces that precede a non-space token (not including empty string tokens) in a string. :param space_s_pres_split: the string, split into tokens around spaces, but with the spaces conserved as tokens.
341,624
def define_unit( symbol, value, tex_repr=None, offset=None, prefixable=False, registry=None ): from unyt.array import unyt_quantity, _iterable import unyt if registry is None: registry = default_unit_registry if symbol in registry: raise RuntimeError( "Unit symbol ...
Define a new unit and add it to the specified unit registry. Parameters ---------- symbol : string The symbol for the new unit. value : tuple or :class:`unyt.array.unyt_quantity` The definition of the new unit in terms of some other units. For example, one would define a new "mp...
341,625
def tr_iter(text, kword, color): s= for _t in text: if _t in kword: s += colorize(BgColor.Null, Base.Null, color, _t) else: s += _t return s
tr_iter(text, kword, color)
341,626
def getLCDType(self): command = settings = self.sendCommand(command) flags = int(settings[2], 16) if flags & 0x0100: lcdtype = else: lcdtype = return lcdtype
Returns LCD type as a string, either monochrome or rgb
341,627
def tilequeue_rawr_seed_all(cfg, peripherals): rawr_yaml = cfg.yml.get() assert rawr_yaml is not None, group_by_zoom = rawr_yaml.get() assert group_by_zoom is not None, max_coord = 2 ** group_by_zoom coords = [] for x in xrange(0, max_coord): for y in xrange...
command to enqueue all the tiles at the group-by zoom
341,628
def translate_to_dbus_type(typeof, value): if ((isinstance(value, types.UnicodeType) or isinstance(value, str)) and typeof is not dbus.String): return typeof(eval(value)) else: return typeof(value)
Helper function to map values from their native Python types to Dbus types. :param type typeof: Target for type conversion e.g., 'dbus.Dictionary' :param value: Value to assign using type 'typeof' :return: 'value' converted to type 'typeof' :rtype: typeof
341,629
def _wanna_emit_id_changed(self): if self._last_id != self._get_id(): self._last_id = self._get_id() self.id_changed.emit()
Filters intentions to emit the id_changed signal (only does if id really changed)
341,630
def next(self): if self.__g_object is None: self.__g_object = self.__g_function( *self.__v_args, **self.__d_args ) try: return self.__g_object.next() except StopIteration: self.__g_object = None raise
x.next() -> the next value, or raise StopIteration
341,631
def debug(self, msg: str) -> None: if self.debugging: s = "{}: {}".format(self.fullname, msg) log.debug(s)
If we are being verbose, write a debug message to the Python disk log.
341,632
def tty_stream(self): return hasattr(self.options.stream, "isatty") \ and self.options.stream.isatty()
Whether or not our stream is a tty
341,633
def _load_json_module(): first_import_error = None for module_name in [, ]: try: module = __import__(module_name, {}, {}, ) if not hasattr(module, ): message = ( % module_name) l...
Try to load a valid json module. There are more than one json modules that might be installed. They are mostly compatible with one another but some versions may be different. This function attempts to load various json modules in a preferred order. It does a basic check to guess if a loaded version of...
341,634
def focusOutEvent(self, e): self.source_model.update_active_row() super(ShortcutsTable, self).focusOutEvent(e)
Qt Override.
341,635
def exempt(self, obj): name = % (obj.__module__, obj.__name__) @wraps(obj) def __inner(*a, **k): return obj(*a, **k) self._exempt_routes.add(name) return __inner
decorator to mark a view as exempt from htmlmin.
341,636
def geo_line(self, edge): with context(self.fname, edge.LineString.posList) as plist: coords = split_coords_2d(~plist) return geo.Line([geo.Point(*p) for p in coords])
Utility function to convert a node of kind edge into a :class:`openquake.hazardlib.geo.Line` instance. :param edge: a node describing an edge
341,637
def report(self, item_id, report_format="json"): report_format = report_format.lower() response = self._request("/report/{job_id}/summary".format(job_id=item_id)) if response.status_code == 429: raise sandboxapi.SandboxError() if report_format == "json": ...
Retrieves the specified report for the analyzed item, referenced by item_id. Available formats include: json, html. :type item_id: str :param item_id: File ID number :type report_format: str :param report_format: Return format :rtype: dict :return: D...
341,638
def get_resource_from_handle(self, resource_handle, verify_repo=True): if verify_repo: if resource_handle.variables.get("repository_type") != self.name(): raise ResourceError("repository_type mismatch - requested %r, " ...
Get a resource. Args: resource_handle (`ResourceHandle`): Handle of the resource. Returns: `PackageRepositoryResource` instance.
341,639
def gtf_to_fasta(gtf_file, ref_fasta, cds=False, out_file=None): if out_file and file_exists(out_file): return out_file if not out_file: out_file = tempfile.NamedTemporaryFile(delete=False, suffix=".fa").name tmp_file = out_file + ".tmp" if cds: cmd = "gffread -g {ref_fast...
convert a GTF to FASTA format if cds=True, use the start/stop codons to output only the CDS handles malformed FASTA files where a single transcript is repeated multiple times by just using the first one
341,640
async def handle_token_async(self): timeout = False in_progress = False try: await self._connection.lock_async() if self._connection._closing or self._connection._error: return timeout, in_progress auth_status = self._cbs_auth...
This coroutine is called periodically to check the status of the current token if there is one, and request a new one if needed. If the token request fails, it will be retried according to the retry policy. A token refresh will be attempted if the token will expire soon. This function w...
341,641
def create_cloud_user(cfg, args): url = cfg[] + "admin/add-user" params = {: args.user_email, : args.user_name, : args.user_role, : cfg[], : cfg[]} headers = {: } response = requests.post(url, data=json.dumps(params), headers=headers) if ...
Attempt to create the user on the cloud node.
341,642
def delete(self, instance_or_query): sm = self.model(instance_or_query) if is_query(instance_or_query): if instance_or_query.session is not self: raise ValueError() sm._delete_query.append(instance_or_query) else: inst...
Delete an ``instance`` or a ``query``. Adds ``instance_or_query`` to this :class:`Session` list of data to be deleted. If the session is not in a :ref:`transactional state <transactional-state>`, this operation commits changes to the backend server immediately. :paramete...
341,643
def restore_snapshot(self, subid, snapshotid, params=None): params = update_params(params, { : subid, : snapshotid }) return self.request(, params, )
/v1/server/restore_snapshot POST - account Restore the specificed snapshot to the virtual machine. Any data already on the virtual machine will be lost. Link: https://www.vultr.com/api/#server_restore_snapshot
341,644
def run(self): if self.workflow.build_process_failed: self.log.info() return build_id = self.workflow.exit_results.get(KojiImportPlugin.key) if not build_id: build_id = self.workflow.exit_results.get(KojiPromotePlugin.key) if not build_id...
Run the plugin.
341,645
def run_migrations_online(): def process_revision_directives(context, revision, directives): if getattr(config.cmd_opts, , False): script = directives[0] if script.upgrade_ops.is_empty(): directives[:] = [] logger.info() engin...
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
341,646
def prompt_for_existing_session(self, sessions): if not sessions: return None print("Would you like to join a previous session or create a new session?") for index, session in enumerate(sessions): print(("{id} : {creator} started at {timestamp} ({hashid})" ...
Prompt user if they want to resume an old session (or their partners session) or create a new session.
341,647
def _get_x_label(self, i): if not self.x_labels or not self._y_labels or len(self._y_labels) <= i: return return self._y_labels[i][0]
Convenience function to get the x_label of a value index
341,648
def send_audio(self, ws): def run(*args): if not self.audio_source.is_buffer: while True: chunk = self.audio_source.input.read(ONE_KB) if not chunk: break self.ws_client.send(chu...
Stream audio to server :param ws: Websocket client
341,649
def set(self, interval, callback, repeat=False, force=True): if self.timer: if force: self.clear() else: return def callback_wrapper(): if self.timer == timer: ...
添加timer
341,650
def update_lincs_proteins(): url = prot_data = load_lincs_csv(url) prot_dict = {d[]: d.copy() for d in prot_data} assert len(prot_dict) == len(prot_data), "We lost data." fname = os.path.join(path, ) with open(fname, ) as fh: json.dump(prot_dict, fh, indent=1)
Load the csv of LINCS protein metadata into a dict. Produces a dict keyed by HMS LINCS protein ids, with the metadata contained in a dict of row values keyed by the column headers extracted from the csv.
341,651
def get_rng(obj=None): seed = (id(obj) + os.getpid() + int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 4294967295 if _RNG_SEED is not None: seed = _RNG_SEED return np.random.RandomState(seed)
Get a good RNG seeded with time, pid and the object. Args: obj: some object to use to generate random seed. Returns: np.random.RandomState: the RNG.
341,652
def vectorize(json_file, vec, dofit=True): screen_names = [x[0] for x in extract_tweets(json_file)] if dofit: X = vec.fit_transform(x[1] for x in extract_tweets(json_file)) else: X = vec.transform(x[1] for x in extract_tweets(json_file)) return screen_names, X
Return a matrix where each row corresponds to a Twitter account, and each column corresponds to the number of times a term is used by that account.
341,653
def update_user_password(client, userpass): vault_path = user = user_path_bits = userpass.split() if len(user_path_bits) == 1: user = user_path_bits[0] vault_path = "auth/userpass/users/%s/password" % user LOG.debug("Updating password for user %s at the default path", user...
Will update the password for a userpass user
341,654
def borrow_cached_network(klass, network_json, network_weights): assert network_weights is not None key = klass.keras_network_cache_key(network_json) if key not in klass.KERAS_MODELS_CACHE: import keras.models network = keras.models.model_from_json(n...
Return a keras Model with the specified architecture and weights. As an optimization, when possible this will reuse architectures from a process-wide cache. The returned object is "borrowed" in the sense that its weights can change later after subsequent calls to this method from other ...
341,655
def _getMultiFastaOffsets(fasta): f = open(fasta, ) i = 0 j = f.read(1) l = [] while j != : i += 1 if j == : i += 1 while f.read(1) != : i += 1 l.append(i) j = f.read(1) f.close() return l
Reads in columns of multiple alignment and returns them iteratively
341,656
def _execute(self, worker): self._assert_status_is(TaskStatus.RUNNING) operation = worker.look_up(self.operation) operation.invoke(self, [], worker=worker)
This method is ASSIGNED during the evaluation to control how to resume it once it has been paused
341,657
def _MaybeWriteIndex(self, i, ts, mutation_pool): if i > self._max_indexed and i % self.INDEX_SPACING == 0: if ts[0] < (rdfvalue.RDFDatetime.Now() - self.INDEX_WRITE_DELAY).AsMicrosecondsSinceEpoch(): mutation_pool.CollectionAddIndex(self.collection_id, i, ts[0], t...
Write index marker i.
341,658
def block(self): statements = [] self.eat(TokenTypes.LBRACE) if self.cur_token.type == TokenTypes.NEW_LINE: self.eat(TokenTypes.NEW_LINE) while self.cur_token.type != TokenTypes.RBRACE: statements.append(self.statement()) self.eat(TokenTypes.RBRAC...
block : { (newline) statements } (newline)
341,659
def metadata(): with open(os.path.join(charm_dir(), )) as md: return yaml.safe_load(md)
Get the current charm metadata.yaml contents as a python object
341,660
def closest_uniform_tile(s, shift, size, other): region = util.Tile(size, dim=s.dim, dtype=).translate(shift - s.pad) vec = np.round((other.center - region.center) / region.shape) return region.translate(region.shape * vec)
Given a tiling of space (by state, shift, and size), find the closest tile to another external tile
341,661
def pretty_unique_identifier(inst, identifier): values = prefix = metaclass = xtuml.get_metaclass(inst) for name, ty in metaclass.attributes: if name in metaclass.identifying_attributes: value = getattr(inst, name) value = xtuml.serialize_value(value, ty) ...
Create a human-readable representation a unique identifier.
341,662
def collapse_addresses(addresses): addrs = [] ips = [] nets = [] for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip...
Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: ...
341,663
def full_number(self): return .format( .join(str(n) for n in self.numbers), ReceiptBarcodeGenerator.verification_digit(self.numbers), )
Returns the full number including the verification digit. :return: str
341,664
def get_config(self, budget): sample = None info_dict = {} if len(self.kde_models.keys()) == 0 or np.random.rand() < self.random_fraction: sample = self.configspace.sample_configuration() info_dict[] = False if sample is None: try: samples = self.kde_models[budget][].sample(self...
Function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration
341,665
def get_file(self): if self.cdn_file_hashes: cdn_hash = self.cdn_file_hashes.pop(0) cdn_file = self.client(GetCdnFileRequest( self.file_token, cdn_hash.offset, cdn_hash.limit )) cdn_file.bytes = self.cdn_aes.encrypt(cdn_file.bytes) ...
Calls GetCdnFileRequest and decrypts its bytes. Also ensures that the file hasn't been tampered. :return: the CdnFile result.
341,666
def add_vertex(self, vertex): if vertex not in self._vertices: self._vertices.add(vertex) return True return False
Adds a new vertex to the graph if not present. :param vertex: Vertex :return: ``True`` if ``vertex`` added and not yet present. ``False`` otherwise.
341,667
def if_range(self) -> Optional[datetime.datetime]: return self._http_date(self.headers.get(hdrs.IF_RANGE))
The value of If-Range HTTP header, or None. This header is represented as a `datetime` object.
341,668
def __send_request(self, url, params=None): r = self.fetch(url, payload=params) return r.text
Send request
341,669
def catchable_exceptions(exceptions): if isinstance(exceptions, type) and issubclass(exceptions, BaseException): return True if ( isinstance(exceptions, tuple) and exceptions and all(issubclass(it, BaseException) for it in exceptions) ): return True return ...
Returns True if exceptions can be caught in the except clause. The exception can be caught if it is an Exception type or a tuple of exception types.
341,670
def likelihood(self, outcomes, modelparams, expparams): super(MultiQubitStatePauliModel, self).likelihood(outcomes, modelparams, expparams) pr0 = 0.5*(1 + modelparams[:,expparams[]]) return Model.pr0_to_likelihood...
Calculates the likelihood function at the states specified by modelparams and measurement specified by expparams. This is given by the Born rule and is the probability of outcomes given the state and measurement operator.
341,671
def listen(self, reactor, endpoint_description): endpoint = serverFromString(reactor, endpoint_description) return endpoint.listen(Site(self.app.resource()))
Run the server, i.e. start listening for requests on the given host and port. :param reactor: The ``IReactorTCP`` to use. :param endpoint_description: The Twisted description for the endpoint to listen on. :return: A deferred that returns an object that provides ...
341,672
def elcm_session_get_status(irmc_info, session_id): resp = elcm_request(irmc_info, method=, path= % session_id) if resp.status_code == 200: return _parse_elcm_response_body_as_json(resp) elif resp.status_code == 404: raise ELCMSessio...
send an eLCM request to get session status :param irmc_info: node info :param session_id: session id :returns: dict object of session info if succeed { 'Session': { 'Id': id 'Status': status ... } } :raises: ELCMSessionNo...
341,673
async def _has_id(self, *args, **kwds): if len(args) == 1: result = await parse_string( self._query, self.service.object_resolver, self.service.connection_resolver, self.service.mutation_resolver, ...
Equality checks are overwitten to perform the actual check in a semantic way.
341,674
def p_port_invocation_assignment_statement(self, p): p[4].__class__ = PortInvocationNode p[0] = AssignmentNode(variable_access=p[2], expression=p[4])
statement : SEND variable_access EQUAL implicit_invocation
341,675
def expected_value(self, feature=None, pstate=None, hstate=None, pstate_prob=None, hstate_prob=None): if feature is None: feature = self.emission_name[0] pstate_idx = self.e[pstate] if pstate is not None and pstate_prob is not None: raise Exce...
Determine the joint maximum likelihood estimate
341,676
def _set_ignore_delete_all_response(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=ignore_delete_all_response.ignore_delete_all_response, is_container=, presence=False, yang_name="ignore-delete-all-response", rest_name="ignore-delete-all-response", p...
Setter method for ignore_delete_all_response, mapped from YANG variable /vcenter/discovery/ignore_delete_all_response (container) If this variable is read-only (config: false) in the source YANG file, then _set_ignore_delete_all_response is considered as a private method. Backends looking to populate this v...
341,677
def add_axes(self, interactive=None, color=None): if interactive is None: interactive = rcParams[] if hasattr(self, ): self.axes_widget.SetInteractive(interactive) self._update_axes_color(color) return self.axes_actor = vtk.vtkAxesActor() ...
Add an interactive axes widget
341,678
def one_for_all(self, deps): requires, dependencies = [], [] deps.reverse() requires = Utils().dimensional_list(deps) dependencies = Utils().remove_dbs(requires) return dependencies
Because there are dependencies that depend on other dependencies are created lists into other lists. Thus creating this loop create one-dimensional list and remove double packages from dependencies.
341,679
def placeOrder(self, id, contract, order): return _swigibpy.EClientSocketBase_placeOrder(self, id, contract, order)
placeOrder(EClientSocketBase self, OrderId id, Contract contract, Order order)
341,680
def main(): filename = os.path.abspath() + s = music21.converter.parse(filename) c = s.getElementById() m = c.flat.notes note_obj_seq = [x for x in m if type(x) is music21.note.Note] bo = vmo.build_oracle(note_obj_seq,) bo.name = if len(sys.argv) == 1: b, kend, kt...
This example shows how to parse a music mxl file (music21 and musescore/finale required) and create a simple oracle representation. The output is a reshuffled midi stream shown in either musescore or finale based on your installation of music21. OPTIONAL ARGS: seq_len: an integer for the leng...
341,681
def ip(self): r = format_regex = re.compile(r) ip_regex = re.compile(r.format(r.join([ r, r, r, r, r, r, r, r, r, ...
return the public ip address
341,682
def remove_interactions_from(self, interactions): for u, v in interactions: self.remove_interaction(u, v)
Remove all specified interactions from the binary quadratic model. Args: interactions (iterable[[variable, variable]]): A collection of interactions. Each interaction should be a 2-tuple of variables in the binary quadratic model. Notes: Any inte...
341,683
def row_csv_limiter(rows, limits=None): limits = [None, None] if limits is None else limits if len(exclude_empty_values(limits)) == 2: upper_limit = limits[0] lower_limit = limits[1] elif len(exclude_empty_values(limits)) == 1: upper_limit = limits[0] lower_limit = row...
Limit row passing a value or detect limits making the best effort.
341,684
def get_serializer(serializer): if isinstance(serializer, string_types): try: app_label, serializer_name = serializer.split() app_package = get_application(app_label) serializer_module = import_module( % app_package) serializer = getattr(serializer_module...
Load a serializer.
341,685
def cont_discr_kalman_filter(cls, F, L, Qc, p_H, p_R, P_inf, X, Y, index = None, m_init=None, P_init=None, p_kalman_filter_type=, calc_log_likelihood=False, calc_grad_log_likelihood=False,...
This function implements the continuous-discrete Kalman Filter algorithm These notations for the State-Space model are assumed: d/dt x(t) = F * x(t) + L * w(t); w(t) ~ N(0, Qc) y_{k} = H_{k} * x_{k} + r_{k}; r_{k-1} ~ N(0, R_{k}) Returns estimated filter dist...
341,686
def create_instances(configuration): instances = {} for methods in configuration.itervalues(): for element in methods.itervalues(): if not isinstance(element, tuple): continue cls, _ = element if cls not in instances: instances[cls...
Create necessary class instances from a configuration with no argument to the constructor :param dict configuration: configuration dict like in :attr:`~pyextdirect.configuration.Base.configuration` :return: a class-instance mapping :rtype: dict
341,687
def serialize(self, sw): detail = None if self.detail is not None: detail = Detail() detail.any = self.detail pyobj = FaultType(self.code, self.string, self.actor, detail) sw.serialize(pyobj, typed=False)
Serialize the object.
341,688
def record(self, *args, **kwargs): args = [iter(args)] * 2 positionals = zip(*args) for name, value in chain(positionals, kwargs.items()): self._recorded_vars[name] = value
Track and record values each day. Parameters ---------- **kwargs The names and values to record. Notes ----- These values will appear in the performance packets and the performance dataframe passed to ``analyze`` and returned from :func:`~zip...
341,689
def get_mtype_and_number_from_code(si, sensor_code): mtype_and_ory, x, y, z = sensor_code.split("-") if mtype_and_ory[-1] in "XYZ" and "ACCX" not in si: mtype = mtype_and_ory[:-1] else: mtype = mtype_and_ory for m_number in si[mtype]: cc = get_sensor_code_by_number(si, mty...
Given a sensor sensor_code, get motion type and sensor number :param si: dict, sensor index json dictionary :param sensor_code: str, a sensor code (e.g. ACCX-UB1-L2C-M) :return:
341,690
def _setup_edge(self, capabilities): edge_driver = self.config.get(, ) self.logger.debug("Edge driver path given in properties: %s", edge_driver) return webdriver.Edge(edge_driver, capabilities=capabilities)
Setup Edge webdriver :param capabilities: capabilities object :returns: a new local Edge driver
341,691
def multi_bulk(self, args): return null_array if args is None else b.join(self._pack(args))
Multi bulk encoding for list/tuple ``args``
341,692
def _json_body_(cls): json = [] for series_name, data in six.iteritems(cls._datapoints): json.append({: series_name, : cls._fields, : [[getattr(point, k) for k in cls._fields] for point in data] ...
Return JSON body of the datapoints. :return: JSON body of the datapoints.
341,693
def get(self, name=None, provider=, print_output=True): Cluster = getattr(providers, provider) cluster = Cluster(name) self.kubeconf.open() if name is None: clusters = self.kubeconf.get_clusters() print("Running Clusters:") for clust...
List all cluster.
341,694
def djoin (*args): from os.path import join i = 0 alen = len (args) while i < alen and (args[i] == or args[i] == ): i += 1 if i == alen: return return join (*args[i:])
dotless' join, for nicer paths.
341,695
def deleteByOrigIndexList(self, indexList): result = [] result_tracker = [] counter = 0 for row in self.table: if not counter in indexList: result.append(row) result_tracker.append(self.index_track[counter]) counter += 1 ...
Remove entries from the list given the index references. The index, in this instance, is a reference to the *original* list indexing as seen when the list was first inserted into PLOD. An example: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 ...
341,696
def main(): parser = build_parser() Job.Runner.addToilOptions(parser) args = parser.parse_args() inputs = {: args.config, : args.config_fastq, : args.input, : args.unc, : args.fasta, : args.composite_exons, ...
This is a Toil pipeline for the UNC best practice RNA-Seq analysis. RNA-seq fastqs are combined, aligned, sorted, filtered, and quantified. Please read the README.md located in the same directory.
341,697
def angledependentabsorption(twotheta, transmission): cor = np.ones(twotheta.shape) if transmission == 1: return cor mud = -np.log(transmission) cor[twotheta > 0] = transmission * mud * (1 - 1 / np.cos(twotheta[twotheta > 0])) / (np.exp(-mud / np.cos(twotheta[twotheta > 0])) - np.exp(-mud)...
Correction for angle-dependent absorption of the sample Inputs: twotheta: matrix of two-theta values transmission: the transmission of the sample (I_after/I_before, or exp(-mu*d)) The output matrix is of the same shape as twotheta. The scattering intensity matrix should be ...
341,698
def _copy(self, other, copy_func): super(ParsableOctetString, self)._copy(other, copy_func) self._bytes = other._bytes self._parsed = copy_func(other._parsed)
Copies the contents of another ParsableOctetString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
341,699
def pop(self): self.updateQueue() if self.timelen(self) < self.lowwatermark: self.requestFuture() if len(self.ready) != 0: return self.ready.popleft() elif len(self.movable) != 0: return self.movable.popleft() ...
Pop the next future from the queue; in progress futures have priority over those that have not yet started; higher level futures have priority over lower level ones;