code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def sample(args): from random import random p = OptionParser(sample.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) vcffile, ratio = args ratio = float(ratio) fp = open(vcffile) pf = vcffile.rsplit(".", 1)[0] kept = pf + ".kept...
%prog sample vcffile 0.9 Sample subset of vcf file.
def _integrate_mpwrap(ts_and_pks, integrate, fopts): ts, tpks = ts_and_pks pks = integrate(ts, tpks, **fopts) return pks
Take a zipped timeseries and peaks found in it and integrate it to return peaks. Used to allow multiprocessing support.
def get_key(self, key): return self.__mapping.get(self.type(key), self.__getitem__)(key)
Return a rich object for the given key. For instance, if a hash key is requested, then a :py:class:`Hash` will be returned. :param str key: Key to retrieve. :returns: A hash, set, list, zset or array.
def send_handle_get_request(self, handle, indices=None): s response. GET Request to GETGET', handle=handle, url=url, headers=head, verify=veri, resp=resp ) self.__first_request = False return resp
Send a HTTP GET request to the handle server to read either an entire handle or to some specified values from a handle record, using the requests module. :param handle: The handle. :param indices: Optional. A list of indices to delete. Defaults to None (i.e. the enti...
def init(cls, *args, **kwargs): instance = cls() instance._values.update(dict(*args, **kwargs)) return instance
Initialize the config like as you would a regular dict.
def is_installed(pkg_name): with settings(hide(, , , ), warn_only=True): res = run("dpkg -s %(pkg_name)s" % locals()) for line in res.splitlines(): if line.startswith("Status: "): status = line[8:] if "installed" in status.split(): ...
Check if a package is installed.
async def terminateInstance(self, *args, **kwargs): return await self._makeApiCall(self.funcinfo["terminateInstance"], *args, **kwargs)
Terminate an instance Terminate an instance in a specified region This method is ``experimental``
def event_trigger(self, event_type): def callback(**kwargs): self.queued_events.append(event_type(**kwargs)) return callback
Returns a callback that creates events. Returned callback function will add an event of type event_type to a queue which will be checked the next time an event is requested.
def clear(self, asset_manager_id, book_ids=None): self.logger.info(, asset_manager_id) url = % (self.endpoint, asset_manager_id) params = {: .join(book_ids)} if book_ids else {} response = self.session.delete(url, params=params) if response.ok: tran_count = ...
This method deletes all the data for an asset_manager_id and option book_ids. It should be used with extreme caution. In production it is almost always better to Inactivate rather than delete.
def fmt_latex_output(hyps: Sequence[Sequence[str]], refs: Sequence[Sequence[str]], prefixes: Sequence[str], out_fn: Path, ) -> None: alignments_ = [min_edit_distance_align(ref, hyp) for hyp, ref in zip(hyps, r...
Output the hypotheses and references to a LaTeX source file for pretty printing.
def fetch_by_url(self, url): service = self.collection.find_one({: url}) if not service: raise ServiceNotFound return Service(service)
Gets service for given ``url`` from mongodb storage.
def cumulative_value(self, slip, mmax, mag_value, bbar, dbar, beta): delta_m = mmax - mag_value a_3 = self._get_a3_value(bbar, dbar, slip / 10., beta, mmax) central_term = np.exp(bbar * delta_m) - 1.0 - (bbar * delta_m) return a_3 * central_term * (delta_m > 0.0)
Returns the rate of events with M > mag_value :param float slip: Slip rate in mm/yr :param float mmax: Maximum magnitude :param float mag_value: Magnitude value :param float bbar: \bar{b} parameter (effectively = b * log(10.)) :par...
def compute_precession(jd_tdb): eps0 = 84381.406 t = (jd_tdb - T0) / 36525.0 psia = ((((- 0.0000000951 * t + 0.000132851 ) * t - 0.00114045 ) * t - 1.0790069 ) * t + 5038.481507 ) * t o...
Return the rotation matrices for precessing to an array of epochs. `jd_tdb` - array of TDB Julian dates The array returned has the shape `(3, 3, n)` where `n` is the number of dates that have been provided as input.
def rhol(self): ro-xylene Vml = self.Vml if Vml: return Vm_to_rho(Vml, self.MW) return None
r'''Liquid-phase mass density of the chemical at its current temperature and pressure, in units of [kg/m^3]. For calculation of this property at other temperatures and pressures, or specifying manually the method used to calculate it, and more - see the object oriented interface :obj:`th...
def _filter(self, criteria: Q, db): negated = criteria.negated input_db = None if criteria.connector == criteria.AND: input_db = db for child in criteria.children: if isinstance(child, Q): in...
Recursive function to filter items from dictionary
def to_dict(self): return { : , : self.name, : self.segmentation_col, : self.fit_filters, : self.predict_filters, : self.min_segment_size, : { : self.default_model_expr, : YTRANSFORM_MAPP...
Returns a dict representation of this instance suitable for conversion to YAML.
def company_prefix(self): offset = self.EXTRA_DIGITS return self._id[offset:self._ref_idx]
Return the identifier's company prefix part.
def str_dict(some_dict): return {str(k): str(v) for k, v in some_dict.items()}
Convert dict of ascii str/unicode to dict of str, if necessary
def get_kwargs(self): return {k: v for k, v in vars(self).items() if k not in self._ignored}
Return kwargs from attached attributes.
def wm_preferences(name, user=None, action_double_click_titlebar=None, action_middle_click_titlebar=None, action_right_click_titlebar=None, application_based=None, audible_bell=None, auto...
wm_preferences: sets values in the org.gnome.desktop.wm.preferences schema
def _adaptive(self, gamma=1.0, relative_tolerance=1.0e-8, maximum_iterations=1000, verbose=True, print_warning=True): if verbose: print("Determining dimensionless free energies by Newton-Raphson iteration.") nr_iter = 0 sci_iter = 0 N_k = self.N_k[self.st...
Determine dimensionless free energies by a combination of Newton-Raphson iteration and self-consistent iteration. Picks whichever method gives the lowest gradient. Is slower than NR (approximated, not calculated) since it calculates the log norms twice each iteration. OPTIONAL ARGUMENTS ...
def _to_dict(self): _dict = {} if hasattr(self, ) and self.types is not None: _dict[] = [x._to_dict() for x in self.types] if hasattr(self, ) and self.categories is not None: _dict[] = [x._to_dict() for x in self.categories] return _dict
Return a json dictionary representing this model.
def from_file(cls, filename, **kwargs): if not in kwargs: kwargs[] = cls._internal_flux_unit if ((filename.endswith() or filename.endswith()) and not in kwargs): kwargs[] = header, wavelengths, rvs = specio.read_spec(filename, **kwargs) ...
Create a reddening law from file. If filename has 'fits' or 'fit' suffix, it is read as FITS. Otherwise, it is read as ASCII. Parameters ---------- filename : str Reddening law filename. kwargs : dict Keywords acceptable by :func:`~s...
def task_done(self): self._parent._check_closing() with self._parent._all_tasks_done: unfinished = self._parent._unfinished_tasks - 1 if unfinished <= 0: if unfinished < 0: raise ValueError() self._parent._all_tasks_don...
Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items ...
def _extract_path_parameters_from_paths(paths): params = set() for path in paths: parts = PART_REGEX.split(path) for p in parts: match = PARAM_REGEX.match(p) if match: params.add(match.group("name")) return params
from a list of paths, return back a list of the arguments present in those paths. the arguments available in all of the paths must match: if not, an exception will be raised.
def moveSpeed(self, location, seconds=0.3): self._lock.acquire() original_location = mouse.get_position() mouse.move(location.x, location.y, duration=seconds) if mouse.get_position() == original_location and original_location != location.getTuple(): raise IOError() ...
Moves cursor to specified ``Location`` over ``seconds``. If ``seconds`` is 0, moves the cursor immediately. Used for smooth somewhat-human-like motion.
def _put_cluster(self, dic, params=None): cluster = self._put(, ApiCluster, data=dic, params=params) self._update(cluster) return self
Change cluster attributes
def __mgmt(name, _type, action): cmd = .format(action, _type, name) return __firewall_cmd(cmd)
Perform zone management
def __getitem_slice(self, slce): scaled_indices = (self._step * n for n in slce.indices(self._len)) start_offset, stop_offset, new_step = scaled_indices return newrange(self._start + start_offset, self._start + stop_offset, new_step)
Return a range which represents the requested slce of the sequence represented by this range.
def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.reject() super(XOverlayWidget, self).keyPressEvent(event)
Exits the modal window on an escape press. :param event | <QtCore.QKeyPressEvent>
def find_cycle(self): for node in self.nodes: cyc = self._follow_children(node) if len(cyc) > 0: return [self._nodes[x] for x in cyc] return None
greedy search for a cycle
def is_mouse_over(self, event): return event.x == self._x and self._y <= event.y < self._y + self._height
Check whether a MouseEvent is over thus scroll bar. :param event: The MouseEvent to check. :returns: True if the mouse event is over the scroll bar.
def margin_to_exchange(self, symbol, currency, amount): params = {: symbol, : currency, : amount} path = def _wrapper(_func): @wraps(_func) def handle(): _func(api_key_post(params, path)) return handle return _wrapper
借贷账户划出至现货账户 :param amount: :param currency: :param symbol: :return:
def as_sql(self, qn, connection): from versions.fields import VersionedExtraWhere for child in self.children: if isinstance(child, VersionedExtraWhere) and not child.params: _query = qn.query query_time = _query.querytime.time ...
This method identifies joined table aliases in order for VersionedExtraWhere.as_sql() to be able to add time restrictions for those tables based on the VersionedQuery's querytime value. :param qn: In Django 1.7 & 1.8 this is a compiler :param connection: A DB connection :return:...
def blend(self, clr, factor=0.5): r = self.r * (1 - factor) + clr.r * factor g = self.g * (1 - factor) + clr.g * factor b = self.b * (1 - factor) + clr.b * factor a = self.a * (1 - factor) + clr.a * factor return Color(r, g, b, a, mode="rgb")
Returns a mix of two colors.
def expand_with_style(template, style, data, body_subtree=): if template.has_defines: return template.expand(data, style=style) else: tokens = [] execute_with_style_LEGACY(template, style, data, tokens.append, body_subtree=body_subtree) retu...
Expand a data dictionary with a template AND a style. DEPRECATED -- Remove this entire function in favor of expand(d, style=style) A style is a Template instance that factors out the common strings in several "body" templates. Args: template: Template instance for the inner "page content" style: Temp...
def t_t_eopen(self, t): r"escapequotes\: t.lexer.push_state() return t
r'~"|~\
def _all_possible_indices(self, column_names): candidate_column_groups = [ [, , ], [], [], [], [], [], [], [], ] indices = [] column_set = set(column_names) ...
Create list of tuples containing all possible index groups we might want to create over tables in this database. If a set of genome annotations is missing some column we want to index on, we have to drop any indices which use that column. A specific table may later drop some of these i...
def statements(self): if len(self.rows) == 0: return [] current_statement = Statement(self.rows[0]) current_statement.startline = self.rows[0].linenumber current_statement.endline = self.rows[0].linenumber statements = [] for row in...
Return a list of statements This is done by joining together any rows that have continuations
def cross_signal(s1, s2, continuous=0): def _convert(src, other): if isinstance(src, pd.DataFrame): return src.min(axis=1, skipna=0), src.max(axis=1, skipna=0) elif isinstance(src, pd.Series): return src, src elif isinstance(src, (int, float)): s = p...
return a signal with the following 1 : when all values of s1 cross all values of s2 -1 : when all values of s2 cross below all values of s2 0 : if s1 < max(s2) and s1 > min(s2) np.nan : if s1 or s2 contains np.nan at position s1: Series, DataFrame, float, int, or tuple(float|int) s2: Series, D...
def wrap_star_digger(item, type_str, data_name=): ret = [] if type(item) == dict: if in item and item[] == type_str and data_name in item: if len(item[data_name]) > 1: pass return item[data_name] else: for k in item: ...
code used to extract data from Bing's wrap star :param item: wrap star obj :param type_str: target type string :param data_name: target data label, might be "Entities", "Properties", 'Value' :return: list of all matched target, arranged in occurance
def list_(saltenv=, test=None): sevent = salt.utils.event.get_event( , __opts__[], __opts__[], opts=__opts__, listen=True) master_key = salt.utils.master.get_master_key(, __opts__) __jid_event__.fire_event({: master_key}, ) results = se...
List currently configured reactors CLI Example: .. code-block:: bash salt-run reactor.list
def create_privkey(self): if self.group in _tls_named_ffdh_groups: params = _ffdh_groups[_tls_named_ffdh_groups[self.group]][0] privkey = params.generate_private_key() self.privkey = privkey pubkey = privkey.public_key() self.key_exchange = pu...
This is called by post_build() for key creation.
def prepare_feature(best_processed_path, option=): n_pad = 21 n_pad_2 = int((n_pad - 1)/2) pad = [{: , : , : True}] df_pad = pd.DataFrame(pad * n_pad_2) df = [] for article_type in article_types: df.append(pd.read_csv(os.path.join(best_processed_path, option, .format(article_t...
Transform processed path into feature matrix and output array Input ===== best_processed_path: str, path to processed BEST dataset option: str, 'train' or 'test'
def __bind(self): if self.log_queue is not None: salt.log.setup.set_multiprocessing_logging_queue(self.log_queue) if self.log_queue_level is not None: salt.log.setup.set_multiprocessing_logging_level(self.log_queue_level) salt.log.setup.setup_multiprocessing_logg...
Binds the reply server
def generateL2Sequences(nL1Patterns=10, l1Hubs=[2,6], l1SeqLength=[5,6,7], nL1SimpleSequences=50, nL1HubSequences=50, l1Pooling=4, perfectStability=False, spHysteresisFactor=1.0, patternLen=500, patternActivity=50): l1SeqList = generateSimpleSequences(nCoi...
Generate the simulated output from a spatial pooler that's sitting on top of another spatial pooler / temporal memory pair. The average on-time of the outputs from the simulated TM is given by the l1Pooling argument. In this routine, L1 refers to the first spatial and temporal memory and L2 refers to the spat...
def RegisterDefinition(self, data_type_definition): name_lower = data_type_definition.name.lower() if name_lower in self._definitions: raise KeyError(.format( data_type_definition.name)) if data_type_definition.name in self._aliases: raise KeyError(.format( data_type_de...
Registers a data type definition. The data type definitions are identified based on their lower case name. Args: data_type_definition (DataTypeDefinition): data type definitions. Raises: KeyError: if data type definition is already set for the corresponding name.
def launch_shell(username, hostname, password, port=22): if not username or not hostname or not password: return False with tempfile.NamedTemporaryFile() as tmpFile: os.system(sshCmdLine.format(password, tmpFile.name, username, hostname, port)) retur...
Launches an ssh shell
def start(self, start_offset): if self._start_d is not None: raise RestartError("Start called on already-started consumer") self._state = start_d = self._start_d = Deferred() self._fetch_offset = start_offset self._do_f...
Starts fetching messages from Kafka and delivering them to the :attr:`.processor` function. :param int start_offset: The offset within the partition from which to start fetching. Special values include: :const:`OFFSET_EARLIEST`, :const:`OFFSET_LATEST`, and :const:`OF...
def _pindel_options(items, config, out_file, region, tmp_path): variant_regions = utils.get_in(config, ("algorithm", "variant_regions")) target = subset_variant_regions(variant_regions, region, out_file, items) opts = "" if target: if isinstance(target, six.string_types) and os.path.isfile(...
parse pindel options. Add region to cmd. :param items: (dict) information from yaml :param config: (dict) information from yaml (items[0]['config']) :param region: (str or tupple) region to analyze :param tmp_path: (str) temporal folder :returns: (list) options for pindel
def decode_schedule(string): splits = string.split() steps = [int(x[1:]) for x in splits[1:] if x[0] == ] pmfs = np.reshape( [float(x) for x in splits[1:] if x[0] != ], [len(steps), -1]) return splits[0], tuplize(steps), tuplize(pmfs)
Decodes a string into a schedule tuple. Args: string: The string encoding of a schedule tuple. Returns: A schedule tuple, see encode_schedule for details.
def _submit_task_with_template(self, task_ids): runtime = self.config runtime.update({ : os.getcwd(), : os.getcwd(), : env.verbosity, : env.config.get(, ), : env.config.get(, ), : os.path.expanduser() }) i...
Submit tasks by interpolating a shell script defined in job_template
def _generate_file_set(self, var=None, start_date=None, end_date=None, domain=None, intvl_in=None, dtype_in_vert=None, dtype_in_time=None, intvl_out=None): try: return self.file_map[intvl_in] except KeyError: raise Ke...
Returns the file_set for the given interval in.
def cut(sentence, HMM=True): global dt if jieba.pool is None: for w in dt.cut(sentence, HMM=HMM): yield w else: parts = strdecode(sentence).splitlines(True) if HMM: result = jieba.pool.map(_lcut_internal, parts) else: result = jieba.po...
Global `cut` function that supports parallel processing. Note that this only works using dt, custom POSTokenizer instances are not supported.
def algorithm(self): if self._algorithm is None: self._algorithm = self[][].native return self._algorithm
:return: A unicode string of "rsa", "dsa" or "ec"
def call_script(self, script_dict, keys=None, args=None): if keys is None: keys = [] if args is None: args = [] if not in script_dict: script_dict[] = self.connection.register_script(script_dict[]) return script_dict[](keys=keys, args=args, c...
Call a redis script with keys and args The first time we call a script, we register it to speed up later calls. We expect a dict with a ``lua`` key having the script, and the dict will be updated with a ``script_object`` key, with the content returned by the the redis-py ``register_scri...
def int_option(string, options): i = int(string) if i in options: return i raise ValueError()
Requires values (int) to be in `args` :param string: Value to validate :type string: str
async def jsk_hide(self, ctx: commands.Context): if self.jsk.hidden: return await ctx.send("Jishaku is already hidden.") self.jsk.hidden = True await ctx.send("Jishaku is now hidden.")
Hides Jishaku from the help command.
def to_CAG(self): G = nx.DiGraph() for (name, attrs) in self.nodes(data=True): if attrs["type"] == "variable": for pred_fn in self.predecessors(name): if not any( fn_type in pred_fn for fn_type in (...
Export to a Causal Analysis Graph (CAG) PyGraphviz AGraph object. The CAG shows the influence relationships between the variables and elides the function nodes.
def is_package(self, fullname): filename = os.path.split(self.get_filename(fullname))[1] filename_base = filename.rsplit(, 1)[0] tail_name = fullname.rpartition()[2] return filename_base == and tail_name !=
Concrete implementation of InspectLoader.is_package by checking if the path returned by get_filename has a filename of '__init__.py'.
def list_images(self, tag_values=None): title = % self.__class__.__name__ input_fields = { : tag_values } for key, value in input_fields.items(): if value: object_title = % (title, key, str(value)) self.fields.val...
a method to retrieve the list of images of account on AWS EC2 :param tag_values: [optional] list of tag values :return: list of image AWS ids
def setCenter(self, loc): offset = self.getCenter().getOffset(loc) return self.setLocation(self.getTopLeft().offset(offset))
Move this region so it is centered on ``loc``
def _try_instantiate(self, ipopo, factory, component): try: with self.__lock: properties = self.__queue[factory][component] except KeyError: return else: try: ipopo.in...
Tries to instantiate a component from the queue. Hides all exceptions. :param ipopo: The iPOPO service :param factory: Component factory :param component: Component name
def make_order_and_cancel(api_svr_ip, api_svr_port, unlock_password, test_code, trade_env, acc_id): if unlock_password == "": raise Exception("请先配置交易解锁密码!") quote_ctx = ft.OpenQuoteContext(host=api_svr_ip, port=api_svr_port) quote_ctx.subscribe(test_code, ft.SubType.ORDER_BOOK) is...
使用请先配置正确参数: :param api_svr_ip: (string) ip :param api_svr_port: (string) ip :param unlock_password: (string) 交易解锁密码, 必需修改! :param test_code: (string) 股票 :param trade_env: 参见 ft.TrdEnv的定义 :param acc_id: 交易子账号id
def _print_help(self): msg = if platform.system() != "Windows": msg += d1_cli.impl.util.print_info(msg)
Custom help message to group commands by functionality.
def check_error(self): if not self.is_done: raise CloudUnhandledError("Need to check if request is done, before checking for error") response = self.db[self.async_id] error_msg = response["error"] status_code = int(response["status_code"]) payload = response[...
Check if the async response is an error. Take care to call `is_done` before calling `error`. Note that the error messages are always encoded as strings. :raises CloudUnhandledError: When not checking `is_done` first :return: status_code, error_msg, payload :rtype: tuple
def band_names(self): if self._band_names is None: self._populate_from_rasterio_object(read_image=False) return self._band_names
Raster affine.
def visualize_explanation(explanation, label=None): if not sys.version_info[:2] >= (3, 5): raise IndicoError("Python >= 3.5+ is required for explanation visualization") try: from colr import Colr as C except ImportError: raise IndicoError("Package colr >= 0.8.1 is required for explan...
Given the output of the explain() endpoint, produces a terminal visual that plots response strength over a sequence
def description(self): result = "" if isinstance(self._element, ValueElement): if self._element.kind is not None: result = "{}({}) | {}".format(self._element.dtype, self._element.kind, self._element.summary) else:...
Returns the full docstring information for the element suggested as a completion.
def process_dimensions(kdims, vdims): dimensions = {} for group, dims in [(, kdims), (, vdims)]: if dims is None: continue elif isinstance(dims, (tuple, basestring, Dimension, dict)): dims = [dims] elif not isinstance(dims, list): raise ValueError...
Converts kdims and vdims to Dimension objects. Args: kdims: List or single key dimension(s) specified as strings, tuples dicts or Dimension objects. vdims: List or single value dimension(s) specified as strings, tuples dicts or Dimension objects. Returns: Dictio...
def get_root(self): if self.is_root_node(): return self return self.get_ancestors().order_by( "-%s__depth" % self._closure_parentref() )[0]
Return the furthest ancestor of this node.
def merge(self, imgs): if not imgs: raise ValueError() if len(imgs) == 1: return imgs[0] return Image.merge(self.mode, imgs)
Merge image channels. Parameters ---------- imgs : `list` of `PIL.Image.Image` Returns ------- `PIL.Image.Image` Raises ------ ValueError If image channel list is empty.
def density_profile(self,ixaxis=,ifig=None,colour=None,label=None,fname=None): massradiusmass pT=self._classTest() if pT is : x = self.get(ixaxis) if ixaxis is : x = x*ast.rsun_cm y = self.get() elif pT is : if fn...
Plot density as a function of either mass coordiate or radius. Parameters ---------- ixaxis : string 'mass' or 'radius' The default value is 'mass' ifig : integer or string The figure label The default value is None colour : string...
def circle_radii(params, xedge, yedge): cx = params["cx"].value cy = params["cy"].value radii = np.sqrt((cx - xedge)**2 + (cy - yedge)**2) return radii
Compute the distance to the center from cartesian coordinates This method is used for fitting a circle to a set of contour points. Parameters ---------- params: lmfit.Parameters Must contain the keys: - "cx": origin of x coordinate [px] - "cy": origin of y coordinate [px] ...
def convert_all(self): for url_record in self._url_table.get_all(): if url_record.status != Status.done: continue self.convert_by_record(url_record)
Convert all links in URL table.
def missing_pids(self): missing = [] for p in self.pids: try: PersistentIdentifier.get(p.pid_type, p.pid_value) except PIDDoesNotExistError: missing.append(p) return missing
Filter persistent identifiers.
def which(software, strip_newline=True): if software is None: software = "singularity" cmd = [, software ] try: result = run_command(cmd) if strip_newline is True: result[] = result[].strip() return result except: return None
get_install will return the path to where an executable is installed.
def migrate_keys(self, host, port, keys, dest_db, timeout, *, copy=False, replace=False): if not isinstance(host, str): raise TypeError("host argument must be str") if not isinstance(timeout, int): raise TypeError("timeout argument must be int") ...
Atomically transfer keys from one Redis instance to another one. Keys argument must be list/tuple of keys to migrate.
def is_admin(controller, client, actor): config = controller.config if not config.has_section("admins"): logging.debug("Ignoring is_admin check - no [admins] config found.") return False for key,val in config.items("admins"): if actor == User(key): logging.debug("is_...
Used to determine whether someone issuing a command is an admin. By default, checks to see if there's a line of the type nick=host that matches the command's actor in the [admins] section of the config file, or a key that matches the entire mask (e.g. "foo@bar" or "foo@bar=1").
def get(self, username): if not self.remember: raise NotSaving if username not in self.token_storage: raise UserNotFound if self.token_storage[username][] < time.time(): new_token = self.refresh(self.token_storage[username][]) self.token...
If using the remember option and KitsuAuth is storing your tokens, this function will retrieve one. :param username: The username whose token we are retrieving :return: A token, NotFound or NotSaving error
def new(cls, pn, comment="", email=""): uid = PGPUID() if isinstance(pn, bytearray): uid._uid = UserAttribute() uid._uid.image.image = pn uid._uid.image.iencoding = ImageEncoding.encodingof(pn) uid._uid.update_hlen() else: uid...
Create a new User ID or photo. :param pn: User ID name, or photo. If this is a ``bytearray``, it will be loaded as a photo. Otherwise, it will be used as the name field for a User ID. :type pn: ``bytearray``, ``str``, ``unicode`` :param comment: The comment field for a User I...
def ExpandPath(path, opts=None): precondition.AssertType(path, Text) for grouped_path in ExpandGroups(path): for globbed_path in ExpandGlobs(grouped_path, opts): yield globbed_path
Applies all expansion mechanisms to the given path. Args: path: A path to expand. opts: A `PathOpts` object. Yields: All paths possible to obtain from a given path by performing expansions.
def _set_ca(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("trustpoint",ca.ca, yang_name="ca", rest_name="ca", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, extensions={u: {u: u, u: None, u: u...
Setter method for ca, mapped from YANG variable /rbridge_id/crypto/ca (list) If this variable is read-only (config: false) in the source YANG file, then _set_ca is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ca() directly.
def generate(variables, templates_path, main_template): env = jinja2.Environment( loader=jinja2.FileSystemLoader(templates_path), lstrip_blocks=True, trim_blocks=True ) def norm_alg_filename(alg_name): if alg_name in variables[][]: return variables[][][alg_...
:Parameters: variables : dict Template parameters, passed through. templates_path : str Root directory for transclusions. main_template : str Contents of the main template. Returns the rendered output.
def parameters_from_model(parameters_model): parameters = {} for p in parameters_model: if p.is_function: code, defaults, closure = pickle.loads(p.value) parameters[p.key] = func_load(code, defaults, closure, globs=globals()) elif p.is_set...
Get the tool parameters model from dictionaries :param parameters_model: The parameters as a mongoengine model :return: The tool parameters as a dictionary
def add_scope(self, scope_type, scope_name, scope_start, is_method=False): if self._curr is not None: self._curr[] = scope_start - 1 self._curr = { : scope_type, : scope_name, : scope_start, : scope_start } if is_method and self._positions:...
we identified a scope and add it to positions.
def iter_variants_by_names(self, names): for name in names: for result in self.get_variant_by_name(name): yield result
Iterates over the genotypes for variants using a list of names. Args: names (list): The list of names for variant extraction.
def get_all_results_from_jobs(user, j_id): job = v1_utils.verify_existence_and_get(j_id, _TABLE) if not user.is_in_team(job[]) and not user.is_read_only_user(): raise dci_exc.Unauthorized() query = sql.select([models.TESTS_RESULTS]). \ where(models.TESTS_RESULTS.c.job_id == job[...
Get all results from job.
def get_version(filename, pattern=None): if pattern is None: cre = DEFAULT_VERSION_RE else: cre = re.compile(pattern) with open(filename) as fp: for line in fp: if line.startswith(): mo = cre.search(line) assert mo, re...
Extract the __version__ from a file without importing it. While you could get the __version__ by importing the module, the very act of importing can cause unintended consequences. For example, Distribute's automatic 2to3 support will break. Instead, this searches the file for a line that starts with ...
def info (logname, msg, *args, **kwargs): log = logging.getLogger(logname) if log.isEnabledFor(logging.INFO): _log(log.info, msg, args, **kwargs)
Log an informational message. return: None
def cuboid(space, min_pt=None, max_pt=None): dom_min_pt = np.asarray(space.domain.min()) dom_max_pt = np.asarray(space.domain.max()) if min_pt is None: min_pt = dom_min_pt * 0.75 + dom_max_pt * 0.25 if max_pt is None: max_pt = dom_min_pt * 0.25 + dom_max_pt * 0.75 min_pt = np....
Rectangular cuboid. Parameters ---------- space : `DiscreteLp` Space in which the phantom should be created. min_pt : array-like of shape ``(space.ndim,)``, optional Lower left corner of the cuboid. If ``None`` is given, a quarter of the extent from ``space.min_pt`` towards the ...
def _get_spaces(self): guid = self.api.config.get_organization_guid() uri = % (guid) return self.api.get(uri)
Get the marketplace services.
def jackknife_connectivity(measures, data, var, nfft=512, leaveout=1, n_jobs=1, verbose=0): data = atleast_3d(data) t, m, n = data.shape assert(t > 1) if leaveout < 1: leaveout = int(leaveout * t) num_blocks = t // leaveout mask = lambda block: [i for ...
Calculate jackknife estimates of connectivity. For each jackknife estimate a block of trials is left out. This is repeated until each trial was left out exactly once. The number of estimates depends on the number of trials and the value of `leaveout`. It is calculated by repeats = `n_trials` // `leaveo...
def get_directly_accessible_stops_within_distance(self, stop, distance): query = % (stop, distance) return pd.read_sql_query(query, self.conn)
Returns stops that are accessible without transfer from the stops that are within a specific walking distance :param stop: int :param distance: int :return:
def get_rec_dtype(self, **keys): colnums = keys.get(, None) vstorage = keys.get(, self._vstorage) if colnums is None: colnums = self._extract_colnums() descr = [] isvararray = numpy.zeros(len(colnums), dtype=numpy.bool) for i, colnum in enumerate(co...
Get the dtype for the specified columns parameters ---------- colnums: integer array The column numbers, 0 offset vstorage: string, optional See docs in read_columns
def do_GET_body(self): iiif = self.iiif if (len(self.path) > 1024): raise IIIFError(code=414, text="URI Too Long: Max 1024 chars, got %d\n" % len(self.path)) try: self.path = self.path.lstrip() sys.stderr.write...
Create body of GET.
def translate_char(source_char, carrier, reverse=False, encoding=False): u if not isinstance(source_char, unicode) and encoding: source_char = source_char.decode(encoding, ) elif not isinstance(source_char, unicode): raise AttributeError(u"`source_char` must be decoded to `unicode` or set `e...
u"""translate unicode emoji character to unicode carrier emoji character (or reverse) Attributes: source_char - emoji character. it must be unicode instance or have to set `encoding` attribute to decode carrier - the target carrier reverse - if you want to translate CARRIE...
def snow(im, voxel_size=1, boundary_faces=[, , , , , ], marching_cubes_area=False): r regions = snow_partitioning(im=im, return_all=True) im = regions.im dt = regions.dt regions = regions.regions b_num = sp.amax(regions) regions = add_boundary_regions(r...
r""" Analyzes an image that has been partitioned into void and solid regions and extracts the void and solid phase geometry as well as network connectivity. Parameters ---------- im : ND-array Binary image in the Boolean form with True’s as void phase and False’s as solid phase....
def add_policy(self, name, policy_type, cooldown, change=None, is_percent=False, desired_capacity=None, args=None): return self.manager.add_policy(self, name, policy_type, cooldown, change=change, is_percent=is_percent, desired_capacity=desired_capacity, args...
Adds a policy with the given values to this scaling group. The 'change' parameter is treated as an absolute amount, unless 'is_percent' is True, in which case it is treated as a percentage.
def i2osp(x, x_len): if x > 256**x_len: raise exceptions.IntegerTooLarge h = hex(x)[2:] if h[-1] == : h = h[:-1] if len(h) & 1 == 1: h = % h x = binascii.unhexlify(h) return b * int(x_len-len(x)) + x
Converts the integer x to its big-endian representation of length x_len.