code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def forward(node, analysis): if not isinstance(analysis, Forward): raise TypeError() for succ in gast.walk(node): if isinstance(succ, gast.FunctionDef): cfg_obj = CFG.build_cfg(succ) analysis.visit(cfg_obj.entry) return node
Perform a given analysis on all functions within an AST.
def _get_sr(name=None, session=None): if session is None: session = _get_session() srs = session.xenapi.SR.get_by_name_label(name) if len(srs) == 1: return srs[0] return None
Get XEN sr (storage repo) object reference
def get_raw_fixed_block(self, unbuffered=False): if unbuffered or not self._fixed_block: self._fixed_block = self._read_fixed_block() return self._fixed_block
Get the raw "fixed block" of settings and min/max data.
def fit(self, x0=None, distribution=, n=None, **kwargs): dist = {: PSDLognormal, : PSDGatesGaudinSchuhman, : PSDRosinRammler}[distribution] if distribution == : if x0 is None: d_characteristic = sum([fi*di for fi, di in zip(...
Incomplete method to fit experimental values to a curve. It is very hard to get good initial guesses, which are really required for this. Differential evolution is promissing. This API is likely to change in the future.
def save_report( self, name, address=True): try: message = None file = open(name + ".comp", "w") report = compare_report_print( self.sorted, self.scores, self.best_name) file.write(report) fi...
Save Compare report in .comp (flat file format). :param name: filename :type name : str :param address: flag for address return :type address : bool :return: saving Status as dict {"Status":bool , "Message":str}
def unset_iscsi_info(self): if(self._is_boot_mode_uefi()): iscsi_info = {: } self._change_iscsi_target_settings(iscsi_info) else: msg = raise exception.IloCommandNotSupportedInBiosError(msg)
Disable iSCSI boot option in UEFI boot mode. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode.
def _to_dict(self): _dict = {} if hasattr(self, ) and self.notice_id is not None: _dict[] = self.notice_id if hasattr(self, ) and self.created is not None: _dict[] = datetime_to_string(self.created) if hasattr(self, ) and self.document_id is not None: ...
Return a json dictionary representing this model.
def predict_proba(self, a, b, **kwargs): estimators = {: lambda x, y: eval_entropy(y) - eval_entropy(x), : integral_approx_estimator} ref_measures = {: lambda x: standard_scale.fit_transform(x.reshape((-1, 1))), : lambda x: min_max_scale.fit_transform(x.reshape((-1, 1)))...
Evaluate a pair using the IGCI model. :param a: Input variable 1D :param b: Input variable 1D :param kwargs: {refMeasure: Scaling method (gaussian, integral or None), estimator: method used to evaluate the pairs (entropy or integral)} :return: Return value of the...
def upload(self, file_path, dataset=None, public=False): upload_status = self.upload_file(file_path) err_msg = if not upload_status.successful: msg = .format(err_msg, upload_status.error) raise ValueError(msg) err_msg = upload_ver_st...
Use this function to upload data to Knoema dataset.
def do_scan_all(self, line): self.application.master.ScanAllObjects(opendnp3.GroupVariationID(2, 1), opendnp3.TaskConfig().Default())
Call ScanAllObjects. Command syntax is: scan_all
def handle_connack(self): self.logger.info("CONNACK reveived") ret, flags = self.in_packet.read_byte() if ret != NC.ERR_SUCCESS: self.logger.error("error read byte") return ret session_present = flags & 0x01 ret, retcode = self....
Handle incoming CONNACK command.
def get_skos(self, id=None, uri=None, match=None): if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not is_http(uri): match = uri uri = None if match: ...
get the saved skos concept with given ID or via other methods... Note: it tries to guess what is being passed as above
def fix(self, value=None): if value is None: self._impl.fix() else: self._impl.fix(value)
Fix all instances of this variable to a value if provided or to their current value otherwise. Args: value: value to be set.
def __diff_dict(self, level, parents_ids=frozenset({}), print_as_attribute=False, override=False, override_t1=None, override_t2=None): if override: ...
Difference of 2 dictionaries
def _init_filename(self, filename=None, ext=None): extension = ext or self.default_extension filename = self.filename(filename, ext=extension, use_my_ext=True, set_default=True) self.real_filename = os.path.realpath(filename)
Initialize the current filename :attr:`FileUtils.real_filename` of the object. Bit of a hack. - The first invocation must have ``filename != None``; this will set a default filename with suffix :attr:`FileUtils.default_extension` unless another one was supplied. - Subseque...
def _create_user_posts_table(self): with self._engine.begin() as conn: user_posts_table_name = self._table_name("user_posts") if not conn.dialect.has_table(conn, user_posts_table_name): post_id_key = self._table_name("post") + ".id" self._user_pos...
Creates the table to store association info between user and blog posts. :return:
def signrawtransaction(self, rawtxhash, parent_tx_outputs=None, private_key=None): if not parent_tx_outputs and not private_key: return self.req("signrawtransaction", [rawtxhash]) else: return self.req( "signrawtransaction", [rawtxhash, parent_tx_outputs...
signrawtransaction returns status and rawtxhash : rawtxhash - serialized transaction (hex) : parent_tx_outputs - outputs being spent by this transaction : private_key - a private key to sign this transaction with
def metadata_matches(self, query={}): result = len(query.keys()) > 0 for key in query.keys(): result = result and query[key] == self.metadata.get(key) return result
Returns key matches to metadata This will check every key in query for a matching key in metadata returning true if every key is in metadata. query without keys return false. Args: query(object): metadata for matching Returns: bool: Tru...
def get_dag_params(self) -> Dict[str, Any]: try: dag_params: Dict[str, Any] = utils.merge_configs(self.dag_config, self.default_config) except Exception as e: raise Exception(f"Failed to merge config with default config, err: {e}") dag_params["dag_id"]: str = sel...
Merges default config with dag config, sets dag_id, and extropolates dag_start_date :returns: dict of dag parameters
def delete_file(self, fname, multiple, yes_to_all): if multiple: buttons = QMessageBox.Yes|QMessageBox.YesToAll| \ QMessageBox.No|QMessageBox.Cancel else: buttons = QMessageBox.Yes|QMessageBox.No if yes_to_all is None: an...
Delete file
def process_line(self, record): "Process a single record. This assumes only a single sample output." cleaned = [] for key in self.vcf_fields: out = self.process_column(key, getattr(record, key)) if isinstance(out, (list, tuple)): cleaned.extend(out) ...
Process a single record. This assumes only a single sample output.
async def available_ssids() -> List[Dict[str, Any]]: fields = [, , , ] cmd = [, , .join(fields), , , ] out, err = await _call(cmd) if err: raise RuntimeError(err) output = _dict_from_terse_tabular( fields, out, trans...
List the visible (broadcasting SSID) wireless networks. Returns a list of the SSIDs. They may contain spaces and should be escaped if later passed to a shell.
def scopes(self, **kwargs): return self._client.scopes(team=self.id, **kwargs)
Scopes associated to the team.
def head(self, n=None, **kwargs): if n is None: n = options.display.max_rows return self._handle_delay_call(, self, head=n, **kwargs)
Return the first n rows. Execute at once. :param n: :return: result frame :rtype: :class:`odps.df.backends.frame.ResultFrame`
def label_accuracy_score(label_trues, label_preds, n_class): hist = np.zeros((n_class, n_class)) for lt, lp in zip(label_trues, label_preds): hist += _fast_hist(lt.flatten(), lp.flatten(), n_class) acc = np.diag(hist).sum() / hist.sum() with np.errstate(divide=, invalid=): acc_cls =...
Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc
def _create_filter_by(self): filter_by = [] for name, values in request.args.copy().lists(): if name not in _SKIPPED_ARGUMENTS: column = _re_column_name.search(name).group(1) if column not in self._model_columns: continue ...
Transform the json-server filter arguments to model-resource ones.
def search(self, ctype, level=None, category=None, assetId=None, defId=None, min_price=None, max_price=None, min_buy=None, max_buy=None, league=None, club=None, position=None, zone=None, nationality=None, rare=False, playStyle=None, start=0, page_size=itemsPerPage[], ...
Prepare search request, send and return parsed data as a dict. :param ctype: [development / ? / ?] Card type. :param level: (optional) [?/?/gold] Card level. :param category: (optional) [fitness/?/?] Card category. :param assetId: (optional) Asset id. :param defId: (optional) De...
def sde(self): variance = float(self.variance.values) lengthscale = float(self.lengthscale) F = np.array(((-1.0/lengthscale,),)) L = np.array(((1.0,),)) Qc = np.array( ((2.0*variance/lengthscale,),) ) H = np.array(((1.0,),)) Pinf = np.array(((variance,...
Return the state space representation of the covariance.
def get_managers(self): if self._single_env: return None if not hasattr(self, ): self._managers = self.env.get_slave_managers() return self._managers
Get managers for the slave environments.
def _add_helpingmaterials(config, helping_file, helping_type): try: project = find_project_by_short_name(config.project[], config.pbclient, config.all) data = _load_data(helping_file, helping_type) ...
Add helping materials to a project.
def decrypt_email(enc_email): aes = SimpleAES(flask.current_app.config["AES_KEY"]) return aes.decrypt(enc_email)
The inverse of :func:`encrypt_email`. :param enc_email: The encrypted email address.
def view_task_hazard(token, dstore): tasks = set(dstore[]) if not in dstore: return if in tasks: data = dstore[].value else: data = dstore[].value data.sort(order=) rec = data[int(token.split()[1])] taskno = rec[] arr = get_array(dstore[].value, taskno=tas...
Display info about a given task. Here are a few examples of usage:: $ oq show task_hazard:0 # the fastest task $ oq show task_hazard:-1 # the slowest task
def optimal_marginal_branch_length(self, node, tol=1e-10): if node.up is None: return self.one_mutation pp, pc = self.marginal_branch_profile(node) return self.gtr.optimal_t_compressed((pp, pc), self.multiplicity, profiles=True, tol=tol)
calculate the marginal distribution of sequence states on both ends of the branch leading to node, Parameters ---------- node : PhyloTree.Clade TreeNode, attached to the branch. Returns ------- branch_length : float branch length of the bra...
def get_trap_definitions(): if auth is None or url is None: set_imc_creds() global r get_trap_def_url = "/imcrs/fault/trapDefine/sync/query?enterpriseId=1.3.6.1.4.1.11&size=10000" f_url = url + get_trap_def_url payload = None r = requests.get(f_url, auth=auth, headers=head...
Takes in no param as input to fetch SNMP TRAP definitions from HP IMC RESTFUL API :param None :return: object of type list containing the device asset details
def long_input(prompt= + \ + \ , maxlines = None, maxlength = None): lines = [] print(prompt) lnum = 1 try: while True: if maxlines: if lnum > maxlines: break ...
Get a multi-line string as input
def delete_notes(self, noteids): if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req(, post_data={ : noteids ...
Delete a note or notes :param noteids: The noteids to delete
def verify_subscription(request, ident): try: unverified = UnverifiedSubscription.objects.get(ident=ident) except UnverifiedSubscription.DoesNotExist: return respond(, {}, request) subscription = Subscription.objects.get_or_create(email=unverified.email, defaults={ : u...
Verifies an unverified subscription and create or appends to an existing subscription.
def hypermedia_in(): ct_in_map = { : urlencoded_processor, : json_processor, : yaml_processor, : yaml_processor, : text_processor, } if (cherrypy.request.method.upper() == and cherrypy.request.headers.get(, ) == ): cherrypy.re...
Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for
def date_from_isoformat(isoformat_date): year, month, day = isoformat_date.split() return datetime.date(int(year), int(month), int(day))
Convert an ISO-8601 date into a `datetime.date` object. Argument: isoformat_date (str): a date in ISO-8601 format (YYYY-MM-DD) Returns: ~datetime.date: the object corresponding to the given ISO date. Raises: ValueError: when the date could not be converted successfully. See A...
def get_user(): return dict( ip_address=request.remote_addr, user_agent=request.user_agent.string, user_id=( current_user.get_id() if current_user.is_authenticated else None ), session_id=session.get() )
User information. .. note:: **Privacy note** A users IP address, user agent string, and user id (if logged in) is sent to a message queue, where it is stored for about 5 minutes. The information is used to: - Detect robot visits from the user agent string. - Generate an anonymi...
def dict_to_dataset(data, *, attrs=None, library=None, coords=None, dims=None): if dims is None: dims = {} data_vars = {} for key, values in data.items(): data_vars[key] = numpy_to_data_array( values, var_name=key, coords=coords, dims=dims.get(key) ) return xr.D...
Convert a dictionary of numpy arrays to an xarray.Dataset. Parameters ---------- data : dict[str] -> ndarray Data to convert. Keys are variable names. attrs : dict Json serializable metadata to attach to the dataset, in addition to defaults. library : module Library used for...
def transform_and_attach(self, image_list, func, show=True): if not callable(func): raise TypeError() if not isinstance(image_list, (tuple, list)) and isinstance(image_list, np.ndarray): ...
Displays the transformed (combined) version of the cross-sections from each image, (same slice and dimension). So if you input n>=1 images, n slices are obtained from each image, which are passed to the func (callable) provided, and the result will be displayed in the corresponding c...
def group_update(auth=None, **kwargs): *new description** cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) if in kwargs: kwargs[] = kwargs.pop() return cloud.update_group(**kwargs)
Update a group CLI Example: .. code-block:: bash salt '*' keystoneng.group_update name=group1 description='new description' salt '*' keystoneng.group_create name=group2 domain_id=b62e76fbeeff4e8fb77073f591cf211e new_name=newgroupname salt '*' keystoneng.group_create name=0e4febc2a5ab4...
def list_actions(cls): actions = [, , , ] for func_name in dir(cls): func = getattr(cls, func_name) if (not hasattr(func, ) or not getattr(func, , False)): continue action = func_...
Get a list of exposed actions that are callable via the ``do_action()`` method.
def _updateMinDutyCycles(self): if self._globalInhibition or self._inhibitionRadius > self._numInputs: self._updateMinDutyCyclesGlobal() else: self._updateMinDutyCyclesLocal()
Updates the minimum duty cycles defining normal activity for a column. A column with activity duty cycle below this minimum threshold is boosted.
def resolve(self, targets, compile_classpath, sources, javadoc, executor): manager = JarDependencyManagement.global_instance() jar_targets = manager.targets_by_artifact_set(targets) executor = executor or SubprocessExecutor(DistributionLocator.cached()) if not isinstance(executor, Executor): ...
This is the core function for coursier resolve. Validation strategy: 1. All targets are going through the `invalidated` to get fingerprinted in the target level. No cache is fetched at this stage because it is disabled. 2. Once each target is fingerprinted, we combine them into a `VersionedTargetSe...
def valid_path(path): if path.endswith(): Log.debug(, path[:-1]) if os.path.isdir(path[:-1]): return True return False Log.debug(, path) if os.path.isdir(path): return True else: Log.debug(, path) if os.path.isfile(path): return True return False
Check if an entry in the class path exists as either a directory or a file
async def fetchone(self): self._check_executed() row = await self._read_next() if row is None: return self._rownumber += 1 return row
Fetch next row
def load_module(self, fullname): if fullname in sys.modules: return sys.modules[fullname] end_name = fullname[len(self._group_with_dot):] for entry_point in iter_entry_points(group=self.group, name=end_name): mod = entry_point.load() sys.modules[fulln...
Load a module if its name starts with :code:`self.group` and is registered.
def circle(radius=None, center=None, **kwargs): from .path import Path2D if center is None: center = [0.0, 0.0] else: center = np.asanyarray(center, dtype=np.float64) if radius is None: radius = 1.0 else: radius = float(radius) three = arc.to_threepoin...
Create a Path2D containing a single or multiple rectangles with the specified bounds. Parameters -------------- bounds : (2, 2) float, or (m, 2, 2) float Minimum XY, Maximum XY Returns ------------- rect : Path2D Path containing specified rectangles
def _get_nailgun_client(self, jvm_options, classpath, stdout, stderr, stdin): classpath = self._nailgun_classpath + classpath new_fingerprint = self._fingerprint(jvm_options, classpath, self._distribution.version) with self._NAILGUN_SPAWN_LOCK: running, updated = self._check_nailgun_state(new_fi...
This (somewhat unfortunately) is the main entrypoint to this class via the Runner. It handles creation of the running nailgun server as well as creation of the client.
def readObject(self): try: _, res = self._read_and_exec_opcode(ident=0) position_bak = self.object_stream.tell() the_rest = self.object_stream.read() if len(the_rest): log_error("Warning!!!!: Stream still has %s bytes left.\ Enable debug mode of logging to see the hexdump." % l...
read object
def _get_environment_details(python_bin: str) -> list: cmd = "{} -m pipdeptree --json".format(python_bin) output = run_command(cmd, is_json=True).stdout return [_create_entry(entry) for entry in output]
Get information about packages in environment where packages get installed.
def save_attrgetter(self, obj): class Dummy(object): def __init__(self, attrs, index=None): self.attrs = attrs self.index = index def __getattribute__(self, item): attrs = object.__getattribute__(self, "attrs") inde...
attrgetter serializer
def send_sci(self, operation, target, payload, reply=None, synchronous=None, sync_timeout=None, cache=None, allow_offline=None, wait_for_reconnect=None): if not isinstance(payload, six.string_types) and not isinstance(payload, six.binary_type): raise TypeError("payload is r...
Send SCI request to 1 or more targets :param str operation: The operation is one of {send_message, update_firmware, disconnect, query_firmware_targets, file_system, data_service, and reboot} :param target: The device(s) to be targeted with this request :type target: :class:`~.Target...
def classificationgroup(self): path = [, , , ] out = [(item[], item[]) for item in listify(chained_get(self._json, path, []))] return out or None
List with (subject group ID, number of documents)-tuples.
def inject_instance(self, classkey=None, allow_override=False, verbose=VERBOSE_CLASS, strict=True): import utool as ut if verbose: print() try: if classkey is None: classkey = self.__class__ if classkey == : ...
Injects an instance (self) of type (classkey) with all functions registered to (classkey) call this in the __init__ class function Args: self: the class instance classkey: key for a class, preferably the class type itself, but it doesnt have to be SeeAlso: make_cla...
def _coords2vec(self, coords): c = coords.transform_to(self._frame).represent_as() vec_norm = np.sqrt(c.x**2 + c.y**2 + c.z**2) vec = np.empty((c.shape[0], 3), dtype=c.x.dtype) vec[:,0] = (c.x / vec_norm).value[:] vec[:,1] ...
Converts from sky coordinates to unit vectors. Before conversion to unit vectors, the coordiantes are transformed to the coordinate system used internally by the :obj:`UnstructuredDustMap`, which can be set during initialization of the class. Args: coords (:obj:`astropy.coor...
def _make_request_to_broker(self, broker, requestId, request, **kwArgs): def _timeout_request(broker, requestId): try: broker.cancelRequest(requestId, reason=RequestTimedOutError( .format(requestId))) ...
Send a request to the specified broker.
def OnRemoveReaders(self, removedreaders): self.mutex.acquire() try: parentnode = self.root for readertoremove in removedreaders: (childReader, cookie) = self.GetFirstChild(parentnode) while childReader.IsOk(): if self....
Called when a reader is removed. Removes the reader from the smartcard readers tree.
def _fusion_to_dsl(tokens) -> FusionBase: func = tokens[FUNCTION] fusion_dsl = FUNC_TO_FUSION_DSL[func] member_dsl = FUNC_TO_DSL[func] partner_5p = member_dsl( namespace=tokens[FUSION][PARTNER_5P][NAMESPACE], name=tokens[FUSION][PARTNER_5P][NAME] ) partner_3p = member_dsl(...
Convert a PyParsing data dictionary to a PyBEL fusion data dictionary. :param tokens: A PyParsing data dictionary representing a fusion :type tokens: ParseResult
def _get_geocoding(self, key, location): url = self._location_query_base % quote_plus(key) if self.api_key: url += "&key=%s" % self.api_key data = self._read_from_url(url) response = json.loads(data) if response["status"] == "OK": formatted_addre...
Lookup the Google geocoding API information for `key`
def kernels_list(self, **kwargs): kwargs[] = True if kwargs.get(): return self.kernels_list_with_http_info(**kwargs) else: (data) = self.kernels_list_with_http_info(**kwargs) return data
List kernels # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernels_list(async_req=True) >>> result = thread.get() :param async_req bool :param int page: Page numbe...
def addslashes(s, escaped_chars=None): if escaped_chars is None: escaped_chars = ["\\", """, "\0", ] for i in escaped_chars: if i in s: s = s.replace(i, + i) return s
Add slashes for given characters. Default is for ``\`` and ``'``. :param s: string :param escaped_chars: list of characters to prefix with a slash ``\`` :return: string with slashed characters :rtype: str :Example: >>> addslashes("'") "\\'"
def submit(recaptcha_response_field, secret_key, remoteip, verify_server=VERIFY_SERVER): if not (recaptcha_response_field and len(recaptcha_response_field)): return RecaptchaResponse( is_valid=False, error_code= ) def encode_if_nece...
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse for the request recaptcha_response_field -- The value from the form secret_key -- your reCAPTCHA secret key remoteip -- the user's ip address
def _connect_docker(spec): return { : , : { : spec.remote_user(), : spec.remote_addr(), : spec.python_path(), : spec.ansible_ssh_timeout() or spec.timeout(), : get_remote_name(spec), } }
Return ContextService arguments for a Docker connection.
def form_invalid(self, form): response = {self.errors_key: {}} response[self.non_field_errors_key] = form.non_field_errors() response.update(self.get_hidden_fields_errors(form)) for field in form.visible_fields(): if field.errors: response[self.error...
Builds the JSON for the errors
def _extract_elements(self, tree, element_type): setattr(self, element_type, []) etree_elements = get_elements(tree, element_type) for i, etree_element in enumerate(etree_elements): salt_element = create_class_instance(etree_element, i, self.do...
extracts all element of type `element_type from the `_ElementTree` representation of a SaltXML document and adds them to the corresponding `SaltDocument` attributes, i.e. `self.nodes`, `self.edges` and `self.layers`. Parameters ---------- tree : lxml.etree._ElementTree ...
def get_gateway_id(self): host, _ = self.server_address try: ip_address = ipaddress.ip_address(host) except ValueError: return None if ip_address.version == 6: mac = get_mac_address(ip6=host) else: mac = get_ma...
Return a unique id for the gateway.
def from_pubkey(cls, pubkey, compressed=False, version=56, prefix=None): pubkey = PublicKey(pubkey) if compressed: pubkey = pubkey.compressed() else: pubkey = pubkey.uncompressed() addressbin = ripemd160(hexlify(hashlib.sha256(unhexlify(pubkey))...
Derive address using ``RIPEMD160(SHA256(x))``
def add(self, variant, arch, image): if arch not in productmd.common.RPM_ARCHES: raise ValueError("Arch not found in RPM_ARCHES: %s" % arch) if arch in ["src", "nosrc"]: raise ValueError("Source arch is not allowed. Map source files under binary arches.") if sel...
Assign an :class:`.Image` object to variant and arch. :param variant: compose variant UID :type variant: str :param arch: compose architecture :type arch: str :param image: image :type image: :class:`.Image`
def pipe_rename(context=None, _INPUT=None, conf=None, **kwargs): splits = get_splits(_INPUT, conf[], **cdicts(opts, kwargs)) _OUTPUT = parse_results(splits, **kwargs) return _OUTPUT
An operator that renames or copies fields in the input source. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : { 'RULE': [ { 'op': {'value': 'rename or copy'}, ...
def dom_lt(graph): def _dfs(v, n): semi[v] = n = n + 1 vertex[n] = label[v] = v ancestor[v] = 0 for w in graph.all_sucs(v): if not semi[w]: parent[w] = v n = _dfs(w, n) pred[w].add(v) return n def _compress(v)...
Dominator algorithm from Lengauer-Tarjan
def describe(name, tags=None, region=None, key=None, keyid=None, profile=None): res = __salt__[](name, tags, region, key, keyid, profile) if not res.get(): return {: bool(res), : .format(name)} try: conn = _get_conn(reg...
Return RDS instance details. CLI example:: salt myminion boto_rds.describe myrds
def inference_q(self, next_action_arr): q_arr = next_action_arr.reshape((next_action_arr.shape[0], -1)) self.__q_arr_list.append(q_arr) while len(self.__q_arr_list) > self.__seq_len: self.__q_arr_list = self.__q_arr_list[1:] while len(self.__q_arr_list) < self.__seq_...
Infernce Q-Value. Args: next_action_arr: `np.ndarray` of action. Returns: `np.ndarray` of Q-Values.
def format(args): from jcvi.formats.base import DictFile p = OptionParser(format.__doc__) p.add_option("--switchcomponent", help="Switch component id based on") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) oldagpfile, newagpfile...
%prog format oldagpfile newagpfile Reformat AGP file. --switch will replace the ids in the AGP file.
def log(args, number=None, oneline=False, quiet=False): options = .join([ number and str( % number) or , oneline and or ]) try: return run( % (options, args), quiet=quiet) except UnknownRevision: return
Run a "git log ..." command, and return stdout args is anything which can be added after a normal "git log ..." it can be blank number, if true-ish, will be added as a "-n" option oneline, if true-ish, will add the "--oneline" option
def y_subset(y, query=None, aux=None, subset=None, dropna=False, outcome=, k=None, p=None, ascending=False, score=, p_of=): if query is not None: if aux is None: y = y.query(query) else: s = aux.ix[y.index] if len(s) != len(y): lo...
Subset a model "y" dataframe Args: query: operates on y, or aux if present subset: takes a dataframe or index thereof and subsets to that dropna: means drop missing outcomes return: top k (count) or p (proportion) if specified p_of: specifies what the proportion is relative t...
def toggle_settings( toolbar=False, nbname=False, hideprompt=False, kernellogo=False): toggle = if toolbar: toggle += toggle += else: toggle += if nbname: toggle += ( ) toggle += ( ) ...
Toggle main notebook toolbar (e.g., buttons), filename, and kernel logo.
def setFontFamily(self, family): self.blockSignals(True) self.editor().setFontFamily(family) self.blockSignals(False)
Sets the current font family to the inputed family. :param family | <str>
def wsgi(self, environ, start_response): try: environ[] = self request.bind(environ) response.bind() out = self._cast(self._handle(environ), request, response) if response._status_code in (100, 101, 204, 304)\ or reque...
The bottle WSGI-interface.
def init_account(self): ghuser = self.api.me() hook_token = ProviderToken.create_personal( , self.user_id, scopes=[], is_internal=True, ) self.account.extra_data = dict( id=ghuser.id, login...
Setup a new GitHub account.
def translate(srcCol, matching, replace): sc = SparkContext._active_spark_context return Column(sc._jvm.functions.translate(_to_java_column(srcCol), matching, replace))
A function translate any character in the `srcCol` by a character in `matching`. The characters in `replace` is corresponding to the characters in `matching`. The translate will happen when any character in the string matching with the character in the `matching`. >>> spark.createDataFrame([('translate...
def set_mesh(self, mesh, shift=None, is_time_reversal=True, is_mesh_symmetry=True, is_eigenvectors=False, is_gamma_center=False, run_immediately=True): warnings.warn("Phonopy.set_mesh...
Phonon calculations on sampling mesh grids Parameters ---------- mesh: array_like Mesh numbers along a, b, c axes. dtype='intc' shape=(3,) shift: array_like, optional, default None (no shift) Mesh shifts along a*, b*, c* axes with respect ...
def table_formatter(self, dataframe, inc_header=1, inc_index=1): return TableFormatter(dataframe, inc_header=inc_header, inc_index=inc_index)
Return a table formatter for the dataframe. Saves the user the need to import this class
def _prep_ssh( self, tgt, fun, arg=(), timeout=None, tgt_type=, kwarg=None, **kwargs): opts = copy.deepcopy(self.opts) opts.update(kwargs) if timeout: opts[] = timeout arg...
Prepare the arguments
def dump(self): from rez.utils.formatting import columnise rows = [] for i, phase in enumerate(self.phase_stack): rows.append((self._depth_label(i), phase.status, str(phase))) print "status: %s (%s)" % (self.status.name, self.status.description) print "init...
Print a formatted summary of the current solve state.
def collation(self, collation): self.__check_okay_to_chain() self.__collation = validate_collation_or_none(collation) return self
Adds a :class:`~pymongo.collation.Collation` to this query. This option is only supported on MongoDB 3.4 and above. Raises :exc:`TypeError` if `collation` is not an instance of :class:`~pymongo.collation.Collation` or a ``dict``. Raises :exc:`~pymongo.errors.InvalidOperation` if this :...
def gsea(data, gene_sets, cls, outdir=, min_size=15, max_size=500, permutation_num=1000, weighted_score_type=1,permutation_type=, method=, ascending=False, processes=1, figsize=(6.5,6), format=, graph_num=20, no_plot=False, seed=None, verbose=False): gs = GSEA(data, gene_sets, cls, o...
Run Gene Set Enrichment Analysis. :param data: Gene expression data table, Pandas DataFrame, gct file. :param gene_sets: Enrichr Library name or .gmt gene sets file or dict of gene sets. Same input with GSEA. :param cls: A list or a .cls file format required for GSEA. :param str outdir: Results output ...
def linear_gradient(start_hex, finish_hex, n=10): s = hex2rgb(start_hex) f = hex2rgb(finish_hex) gradient = [s] for t in range(1, n): curr_vector = [int(s[j] + (float(t)/(n-1))*(f[j]-s[j])) for j in range(3)] gradient.append(curr_vector) return [rgb2hex([c/255. for c in rgb]) fo...
Interpolates the color gradient between to hex colors
def prepare_mergetable_sql(self, precursor=False, isobaric=False, probability=False, fdr=False, pep=False): featcol = self.colmap[self.table_map[self.datatype][]][1] selectmap, count = self.update_selects({}, [, ], 0) joins = [] if self.datatype ==...
Dynamically build SQL query to generate entries for the multi-set merged protein and peptide tables. E.g. SELECT g.gene_acc, pc.channel_name, pc.amount_psms_name, giq.quantvalue giq.amount_psms gfdr.fdr FROM genes AS g JOIN biosets AS bs JOIN gene_tables AS gt ON ...
def allowed_methods(self, path_info=None): try: self.match(path_info, method="--") except MethodNotAllowed as e: return e.valid_methods except HTTPException: pass return []
Returns the valid methods that match for a given path. .. versionadded:: 0.7
def info_community(self,teamid): headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",: +self.domain+,"User-Agent": user_agent} req = self.session.get(+self.domain++teamid,headers=headers).content soup = BeautifulSoup(req) info = [] for i...
Get comunity info using a ID
def import_words_from_file(self, inputfile: str, is_diceware: bool) -> None: if not Aux.isfile_notempty(inputfile): raise FileNotFoundError( .format(inputfile)) self._wordlist_entropy_...
Import words for the wordlist from a given file. The file can have a single column with words or be diceware-like (two columns). Keyword arguments: inputfile -- A string with the path to the wordlist file to load, or the value 'internal' to load the internal one. is_dic...
def warn(self, message, *args, **kwargs): self._log(logging.WARNING, message, *args, **kwargs)
Send email and syslog by default ...
def add_pypiper_args(parser, groups=("pypiper", ), args=None, required=None, all_args=False): args_to_add = _determine_args( argument_groups=groups, arguments=args, use_all_args=all_args) parser = _add_args(parser, args_to_add, required) return parser
Use this to add standardized pypiper arguments to your python pipeline. There are two ways to use `add_pypiper_args`: by specifying argument groups, or by specifying individual arguments. Specifying argument groups will add multiple arguments to your parser; these convenient argument groupings make it ...
def profile_args(_args): if ( _args.get(, {}).get() is not None or _args.get(, {}).get() is not None ): app_args_optional = _args.get(, {}).get(, {}) app_args_required = _args.get(, {}).get(, {}) default_args = _a...
Return args for v1, v2, or v3 structure. Args: _args (dict): The args section from the profile. Returns: dict: A collapsed version of the args dict.
def to_projection(self): roots = self._root_tables() if len(roots) > 1: raise com.RelationError( ) table = TableExpr(roots[0]) return table.projection([self])
Promote this column expression to a table projection
def set_mag_offsets_encode(self, target_system, target_component, mag_ofs_x, mag_ofs_y, mag_ofs_z): return MAVLink_set_mag_offsets_message(target_system, target_component, mag_ofs_x, mag_ofs_y, mag_ofs_z)
Deprecated. Use MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS instead. Set the magnetometer offsets target_system : System ID (uint8_t) target_component : Component ID (uint8_t) mag_ofs_x : magnetometer X offset (int16_t) ...
def pop_min(self): if self.root is NULL: raise KeyError("pop from an empty blackjack") self.root, value = self.root.delete_min() self._len -= 1 return value
Remove the minimum value and return it.