Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
345,500
def _extract_work(self, filename): basename = os.path.splitext(os.path.basename(filename))[0] match = self.work_pattern.search(basename) if match is None: self._logger.warning(.format( filename)) return None, None work = .format(match.grou...
Returns the name of the work in `filename`. Some works are divided into multiple parts that need to be joined together. :param filename: filename of TEI :type filename: `str` :rtype: `tuple` of `str`
345,501
def tmp_file(suffix=u"", root=None): if root is None: root = custom_tmp_dir() return tempfile.mkstemp(suffix=suffix, dir=root)
Return a (handler, path) tuple for a temporary file with given suffix created by ``tempfile``. :param string suffix: the suffix (e.g., the extension) of the file :param string root: path to the root temporary directory; if ``None``, the default temporary directory ...
345,502
def parse_datetime(self, text): return parse_datetime(text, date_format=self.date_format, is_day_period=self.is_day_period)
Parse datetime from line of text.
345,503
def lookup(self, nick): query = dict(nick=nick) order = [(, pymongo.DESCENDING)] recs = self.db.pastes.find(query).sort(order).limit(1) try: return next(recs)[] except StopIteration: pass
Looks for the most recent paste by a given nick. Returns the uid or None
345,504
def get_max_age(self): default_ttl = self.context.config.RESULT_STORAGE_EXPIRATION_SECONDS if self.context.request.max_age == 0: return self.context.request.max_age return default_ttl
Return the TTL of the current request. :returns: The TTL value for the current request. :rtype: int
345,505
def build(self, stmts=None, set_check_var=True, invert=False): out = "" if set_check_var: out += self.check_var + " = False\n" out += self.out() if stmts is not None: out += "if " + ("not " if invert else "") + self.check_var + ":" + "\n" + openindent + "...
Construct code for performing the match then executing stmts.
345,506
def _preparse(source, f=_compose(_replace_locals, _replace_booleans, _rewrite_assign, _clean_spaces_backtick_quoted_names)): assert callable(f), return tokenize.untokenize(lmap(f, tokenize_string(source)))
Compose a collection of tokenization functions Parameters ---------- source : str A Python source code string f : callable This takes a tuple of (toknum, tokval) as its argument and returns a tuple with the same structure but possibly different elements. Defaults to the ...
345,507
def lookup(self, inc_raw=False, retry_count=3, asn_data=None, depth=0, excluded_entities=None, response=None, bootstrap=False, rate_limit_timeout=120): if not excluded_entities: excluded_entities = [] results = { : self._net.addr...
The function for retrieving and parsing information for an IP address via RDAP (HTTP). Args: inc_raw (:obj:`bool`, optional): Whether to include the raw results in the returned dictionary. Defaults to False. retry_count (:obj:`int`): The number of times to retry ...
345,508
def _submit_gauge(self, metric_name, val, metric, custom_tags=None, hostname=None): _tags = self._metric_tags(metric_name, val, metric, custom_tags, hostname) self.check.gauge(.format(self.NAMESPACE, metric_name), val, _tags, hostname=hostname)
Submit a metric as a gauge, additional tags provided will be added to the ones from the label provided via the metrics object. `custom_tags` is an array of 'tag:value' that will be added to the metric when sending the gauge to Datadog.
345,509
def create(model_config, model, vec_env, storage, takes, parallel_envs, action_noise=None, sample_args=None): return EvaluateEnvCommand( model_config=model_config, model_factory=model, env_factory=vec_env, parallel_envs=parallel_envs, action_noise=action_noise, s...
Vel factory function
345,510
def resolve_path(file_path, calling_function): if not file_path: resolved = os.path.join(os.getcwd(), calling_function) elif file_path.count(os.sep) == 0: resolved = os.path.join(os.getcwd(), file_path) else: resolved = file_path if not resolved.endswi...
Conditionally set a path to a CSV file. Option 1 - Join working directory and calling function name (file_name) Option 2 - Join working directory and provided file_path string Option 3 - Return provided file_path :param file_path: None, filename string or Full file path :param calling_function: Na...
345,511
def hash_algo(self): if self.algorithm != : raise ValueError(unwrap( , self.algorithm.upper() )) parameters = self[][] if parameters.native is None: return None byte_len = math.log(parameters[].native, 2) / 8...
Returns the name of the family of hash algorithms used to generate a DSA key :raises: ValueError - when the key is not a DSA key :return: A unicode string of "sha1" or "sha2" or None if no parameters are present
345,512
def guess_phred_format(self): self.intervals = { : (33, 74), : (59, 105), : (64, 105), : (67, 105), } glob_min = 9999 glob_max = 0 take_next = False ...
Guess the PHRED score format. The gold standard is the first one, aka the one called "Sanger". Sanger encoding is exactly equivalent to Illumina-1.8 encoding. In other words, they finally gave up with their bullshit.
345,513
def print_capabilities_by_ext(self, strict_type_matching: bool = False): print() l = self.get_capabilities_by_ext(strict_type_matching=strict_type_matching) pprint({ext: get_pretty_type_keys_dict(parsers) for ext, parsers in l.items()}) print()
Used to print the list of all file extensions that can be parsed by this parser registry. :return:
345,514
def check_garden_requirements(self): garden_requirements = self.config.getlist(, , ) if exists(self.gardenlibs_dir) and \ self.state.get(, ) == garden_requirements: self.debug() return
Ensure required garden packages are available to be included.
345,515
def cylindrical(cls, mag, theta, z=0): return cls( mag * math.cos(theta), mag * math.sin(theta), z )
Returns a Vector instance from cylindircal coordinates
345,516
def start(self): try: state = yield from self._get_container_state() except DockerHttp404Error: raise DockerError("Docker container with ID {cid} does not exist or is not ready yet. Please try again in a few seconds.".format(name=self.name, ...
Starts this Docker container.
345,517
def download_artist_by_id(self, artist_id, artist_name): try: songs = self.crawler.get_artists_hot_songs(artist_id) except RequestException as exception: click.echo(exception) else: folder = os.path.join(self.folder, artist_name) ...
Download a artist's top50 songs by his/her id. :params artist_id: artist id. :params artist_name: artist name.
345,518
def load_config(self): for key in self.settings: value = self.config(key) if value == or value is None: continue if value.lower() == : value = True elif value.lower() == : value = Fal...
Load the configuration from git config.
345,519
def create_SpikeGeneratorGroup(self,time_label=0,index_label=1,reorder_indices=False,index_offset=True): import brian2 spike_times = self.spike_times.convert(time_label,)[time_label]*brian2.second indices = [0] * len(spike_times) if len(self.spike_times.find_labels(index_label))...
Creates a brian 2 create_SpikeGeneratorGroup object that contains the spikes in this container. time_label: Name or number of the label that contains the spike times (default: 0 / first column) index_label: Name or number of the label that contains the cell indices (default: 1 / ...
345,520
def _merge(self, a, b): for k, v in a.items(): if isinstance(v, dict): item = b.setdefault(k, {}) self._merge(v, item) elif isinstance(v, list): item = b.setdefault(k, [{}]) if len(v) == 1 and isinstance(v[0], dict)...
Merges a into b.
345,521
def distinct_column_values_at_locus( self, column, feature, contig, position, end=None, strand=None): return self.column_values_at_locus( column, feature, contig, position...
Gather all the distinct values for a property/column at some specified locus. Parameters ---------- column : str Which property are we getting the values of. feature : str Which type of entry (e.g. transcript, exon, gene) is the property asso...
345,522
def RestoreSnapshot(self,name=None): if not len(self.data[][]): raise(clc.CLCException("No snapshots exist")) if name is None: name = self.GetSnapshots()[0] name_links = [obj[] for obj in self.data[][] if obj[]==name][0] return(clc.v2.Requests(clc.v2.API.Call(, [obj[] for obj in name_links ...
Restores an existing Hypervisor level snapshot. Supply snapshot name to restore If no snapshot name is supplied will restore the first snapshot found >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').RestoreSnapshot().WaitUntilComplete() 0
345,523
def abstract_relational_comparison(self, other, self_first=True): px = self.to_primitive() py = other.to_primitive() if not self_first: px, py = py, px if not (px.Class == and py.Class == ): px, py = px.to_number(), py.to_number() if px.is_...
self<other if self_first else other<self. Returns the result of the question: is self smaller than other? in case self_first is false it returns the answer of: is other smaller than self. result is PyJs type: bool or undefined
345,524
def _compute(self, approx): i = 0 while i < len(approx): to_test = approx[:i] + approx[(i + 1):] sel, clid = approx[i], self.vmap[approx[i]] if self.verbose > 1: print(.format(clid), end=) if self.oracle.solve(assumptions=to_te...
Deletion-based MUS extraction. Given an over-approximation of an MUS, i.e. an unsatisfiable core previously returned by a SAT oracle, the method represents a loop, which at each iteration removes a clause from the core and checks whether the remaining clauses of the appro...
345,525
def _check_object_list_is_ordered(self): if hasattr(self.object_list, ) and not self.object_list.ordered: warnings.warn( .format(self.object_list), UnorderedObjectListWarning )
Warn if self.object_list is unordered (typically a QuerySet).
345,526
def _pull_schema_definition(self, fname): std_url = urlopen(self._ontology_file) cached_std = open(fname, "w+") cached_std.write(std_url.read()) cached_std.close()
download an ontology definition from the web
345,527
def wait_for_startup(self, timeout=None): if not self.is_starting(): logger.warning("wait_for_startup() called when not in starting state") while not self.check_startup_state_changed(): with self._cancellable_lock: if self._is_cancelled: ...
Waits for PostgreSQL startup to complete or fail. :returns: True if start was successful, False otherwise
345,528
def build_maya_environment(config, env=None, arg_paths=None): maya_env = MayaEnvironment() maya_env.exclude_pattern = config.get_list(Config.PATTERNS, ) maya_env.icon_extensions = config.get_list(Config.PATTERNS, ) env = get_environment_paths(config, env) if not env and arg_paths is Non...
Construct maya environment.
345,529
def _normalize_merge_diff_incr(diff): new_diff = [] changes_found = False for line in diff.splitlines(): if re.search(r"order-dependent line.*re-ordered", line): changes_found = True elif "No changes were found" in line: ...
Make the compare config output look better. Cisco IOS incremental-diff output No changes: !List of Commands: end !No changes were found
345,530
def diff_texts(a, b, filename): a = a.splitlines() b = b.splitlines() return difflib.unified_diff(a, b, filename, filename, "(original)", "(refactored)", lineterm="")
Return a unified diff of two strings.
345,531
def get_site_dict(self, ads_pos): C = self.B[-self.ntop - 1:-1] SC = C * (3, 3, 1) D = {} cell = C.get_cell() top_dist = 1 for i, atom in \ enumerate([atom for atom in SC if np.linalg.norm(atom.position[:2] ...
Get dictionary with high symmetry sites close to adsorbate position. Top sites: Optained from the atomic positions of the top layer of the slab. Bridge sites: The average position of atomic pairs Hollow sites: Optained as the Voronoi vertices 4-fold sites: As...
345,532
def main(argv=None): if float(sys.version[0:3]) < 2.6: print("This script requires Python version 2.6 or better.") print("This is Python version %s" % sys.version) return 0 if argv is None: argv = sys.argv import re import optparse search_doc = lambda r, d: re....
Command line usage main function.
345,533
def mem_ds(res, extent, srs=None, dtype=gdal.GDT_Float32): dst_ns = int((extent[2] - extent[0])/res + 0.99) dst_nl = int((extent[3] - extent[1])/res + 0.99) m_ds = gdal.GetDriverByName().Create(, dst_ns, dst_nl, 1, dtype) m_gt = [extent[0], res, 0, extent[3], 0, -res] m_ds.S...
Create a new GDAL Dataset in memory Useful for various applications that require a Dataset
345,534
def get_extended_metadata(self, item_id): response = self.soap_client.call( , [(, item_id)]) return response.get(, None)
Get extended metadata for a media item, such as related items. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's extended metadata or None. See also: The Sonos `getExtendedMetadata API <h...
345,535
def endGroup(self): if self._customFormat: self._customFormat.endGroup() else: super(XSettings, self).endGroup()
Ends the current group of xml data.
345,536
def calculate_timeout(http_date): try: return int(http_date) except ValueError: date_after = parse(http_date) utc_now = datetime.now(tz=timezone.utc) return int((date_after - utc_now).total_seconds())
Extract request timeout from e.g. ``Retry-After`` header. Notes: Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can be either an integer number of seconds or an HTTP date. This function can handle either. Arguments: http_date (:py:class:`str`): The da...
345,537
def split_filename(name): parts = hashed_filename_re.match(name).groupdict() return (parts[] or , parts[] or , parts[] or )
Splits the filename into three parts: the name part, the hash part, and the extension. Like with the extension, the hash part starts with a dot.
345,538
def match_RCSB_pdb_chains(pdb_id1, pdb_id2, cut_off = 60.0, allow_multiple_matches = False, multiple_match_error_margin = 3.0, use_seqres_sequences_if_possible = True, strict = True): try: stage = pdb_id1 pdb_1 = PDB(retrieve_pdb(pdb_id1), strict = strict) stage = pdb_id2 pdb_2 ...
A convenience function for match_pdb_chains. The required arguments are two PDB IDs from the RCSB.
345,539
def _kip_vline(self, modstart, modstop, sparse, outfile, xlims=[0.,0.], ylims=[0.,0.], ixaxis=, mix_zones=5, burn_zones=50): xxyy=[self.get()[modstart:modstop],self.get()[modstart:modstop]] mup = max(float(self.get()[0])*1.02,1.0) nmodels=len(self.g...
*** DEPRECIATED and hence UNSUPPORTED *** This function creates a Kippenhahn plot with energy flux using vertical lines, better thermal pulse resolution. For a more comprehensive plot, your history.data or star.log file should contain columns called "mix_type_n", "mix_qtop_n", "...
345,540
async def fetch(self, query, *args, timeout=None) -> list: async with self.acquire() as con: return await con.fetch(query, *args, timeout=timeout)
Run a query and return the results as a list of :class:`Record`. Pool performs this operation using one of its connections. Other than that, it behaves identically to :meth:`Connection.fetch() <connection.Connection.fetch>`. .. versionadded:: 0.10.0
345,541
def make_make_email_data(to, cc=None, bcc=None, subject=None, body=None): def multi(val): if not val: return () if isinstance(val, str_type): return (val,) return tuple(val) delim = data = [] if not to: raise ValueError() data.append(.jo...
\ Creates either a simple "mailto:" URL or complete e-mail message with (blind) carbon copies and a subject and a body. :param str|iterable to: The email address (recipient). Multiple values are allowed. :param str|iterable|None cc: The carbon copy recipient. Multiple values are...
345,542
def begin(self): for plugin in self.nose_config.plugins.plugins: if getattr(plugin, , False): self.django_plugins.append(plugin) os.environ[] = self.settings_module if self.conf.addPaths: map(add_path, self.conf.where) try: ...
Create the test database and schema, if needed, and switch the connection over to that database. Then call install() to install all apps listed in the loaded settings module.
345,543
def create(genome, config): genome_config = config.genome_config required = required_for_output(genome_config.input_keys, genome_config.output_keys, genome.connections) node_inputs = {} for cg in itervalues(genome.connections): if not cg.enabled: ...
Receives a genome and returns its phenotype (a neural network).
345,544
def parse(self, config_file=None, specs=None, default_file=None): self._config_exists(config_file) self._specs_exists(specs) self.loaded_config = anyconfig.load(self.config_file, ac_parser=) if default_file is not None: self._merge_default(default_file) i...
Read a config_file, check the validity with a JSON Schema as specs and get default values from default_file if asked. All parameters are optionnal. If there is no config_file defined, read the venv base dir and try to get config/app.yml. If no specs, don't validate anything. ...
345,545
def get_module_paths(): module_paths = [] cpenv_modules_path = os.environ.get(, None) if cpenv_modules_path: module_paths.extend(cpenv_modules_path.split(os.pathsep)) module_paths.append(unipath(get_home_path(), )) return module_paths
:returns: paths in CPENV_MODULES env var and CPENV_HOME/modules
345,546
def build_hardware_simulator( cls, attached_instruments: Dict[top_types.Mount, Dict[str, Optional[str]]] = None, attached_modules: List[str] = None, config: robot_configs.robot_config = None, loop: asyncio.AbstractEventLoop = None, strict_attache...
Build a simulating hardware controller. This method may be used both on a real robot and on dev machines. Multiple simulating hardware controllers may be active at one time.
345,547
def set_loss(self, *args, **kwargs): self.losses = [] self.add_loss(*args, **kwargs)
Clear the current loss functions from the network and add a new one. All parameters and keyword arguments are passed to :func:`add_loss` after clearing the current losses.
345,548
def prepare_context(pipeline, context_in_string, context): logger.debug("starting") parsed_context = get_parsed_context( pipeline=pipeline, context_in_string=context_in_string) context.update(parsed_context) logger.debug("done")
Prepare context for pipeline run. Args: pipeline: dict. Dictionary representing the pipeline. context_in_string: string. Argument string used to initialize context. context: pypyr.context.Context. Merge any new context generated from context_in_string into this context inst...
345,549
def fail_request(self, orig_request, message, start_response): cors_handler = self._create_cors_handler(orig_request) return util.send_wsgi_error_response( message, start_response, cors_handler=cors_handler)
Write an immediate failure response to outfile, no redirect. This calls start_response and returns the error body. Args: orig_request: An ApiRequest, the original request from the user. message: A string containing the error message to be displayed to user. start_response: A function with se...
345,550
def _decorate_block(self, start, end): color = self._get_scope_highlight_color() draw_order = DRAW_ORDERS.get() d = TextDecoration(self.editor.document(), start_line=start, end_line=end+1, draw_order=draw_order) d.set_background(color) d.set_fu...
Create a decoration and add it to the editor. Args: start (int) start line of the decoration end (int) end line of the decoration
345,551
def process_origin( headers: Headers, origins: Optional[Sequence[Optional[Origin]]] = None ) -> Optional[Origin]: try: origin = cast(Origin, headers.get("Origin")) except MultipleValuesError: raise InvalidHeader("Origin", "more than one Orig...
Handle the Origin HTTP request header. Raise :exc:`~websockets.exceptions.InvalidOrigin` if the origin isn't acceptable.
345,552
def _sequence_handler(self, cfg, irsb, irsb_addr, stmt_idx, data_addr, max_size): if not self._is_sequence(cfg, data_addr, 5): return None, None sequence_max_size = min(256, max_size) for i in range(5, min(256, max_size)): if not self._is_sequen...
Find sequences in binary data. :param angr.analyses.CFG cfg: The control flow graph. :param pyvex.IRSB irsb: The IRSB object. :param int irsb_addr: Address of the block. :param int stmt_idx: Statement ID. :param int data_addr: Address of the data in memory. :param int ma...
345,553
def read_bytes(fo, writer_schema=None, reader_schema=None): size = read_long(fo) return fo.read(size)
Bytes are encoded as a long followed by that many bytes of data.
345,554
def robust_rule(self, method=): A, B, C, Q, R = self.A, self.B, self.C, self.Q, self.R beta, theta = self.beta, self.theta k, j = self.k, self.j I = identity(j) Z = np.zeros((k, j)) if self.pure_forecasting: lq = LQ(-beta*I*theta, R...
This method solves the robust control problem by tricking it into a stacked LQ problem, as described in chapter 2 of Hansen- Sargent's text "Robustness." The optimal control with observed state is .. math:: u_t = - F x_t And the value function is :math:`-x'Px` ...
345,555
def set_bookmark(self, slot_num): if self.data: editor = self.get_current_editor() editor.add_bookmark(slot_num)
Bookmark current position to given slot.
345,556
def update_user_login(self, login, account_id=None): if account_id is None: account_id = self._canvas_account_id if account_id is None: raise MissingAccountID login_id = login.login_id url = ACCOUNTS_API.format(account_id) + "/logins/{}".format(l...
Update an existing login for a user in the given account. https://canvas.instructure.com/doc/api/logins.html#method.pseudonyms.update
345,557
def explain_weights_xgboost(xgb, vec=None, top=20, target_names=None, targets=None, feature_names=None, feature_re=None, ...
Return an explanation of an XGBoost estimator (via scikit-learn wrapper XGBClassifier or XGBRegressor, or via xgboost.Booster) as feature importances. See :func:`eli5.explain_weights` for description of ``top``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``target_name...
345,558
def mention_to_tokens(mention, token_type="words", lowercase=False): tokens = mention.context.sentence.__dict__[token_type] return [w.lower() if lowercase else w for w in tokens]
Extract tokens from the mention :param mention: mention object. :param token_type: token type that wants to extract. :type token_type: str :param lowercase: use lowercase or not. :type lowercase: bool :return: The token list. :rtype: list
345,559
def load_meta_data(self, path=None): if not path: path = self.state.file_system_path if path is None: self.meta = Vividict({}) return False path_meta_data = os.path.join(path, storage.FILE_NAME_META_DATA) i...
Load meta data of state model from the file system The meta data of the state model is loaded from the file system and stored in the meta property of the model. Existing meta data is removed. Also the meta data of all state elements (data ports, outcomes, etc) are loaded, as those stored in the...
345,560
def update_values(self): self.method = self.idx_method.currentText() spin_det = DetectSpindle(method=self.method) self.index[].set_value(spin_det.frequency[0]) self.index[].set_value(spin_det.frequency[1]) self.index[].set_value(spin_det.tolerance) self....
Update form values when detection method is selected.
345,561
def schema_helper(self, name, _, schema=None, **kwargs): if schema is None: return None schema_instance = resolve_schema_instance(schema) schema_key = make_schema_key(schema_instance) self.warn_if_schema_already_in_spec(schema_key) self.openapi.refs[schema_...
Definition helper that allows using a marshmallow :class:`Schema <marshmallow.Schema>` to provide OpenAPI metadata. :param type|Schema schema: A marshmallow Schema class or instance.
345,562
def _strip_auth(self, proc_params): params = proc_params.copy() params.pop("auth", None) params.pop("clusterAuthMode", None) return params
Remove options from parameters that cause auth to be enabled.
345,563
def load_preset(self): if in self.settings.preview: with open(os.path.join(os.path.dirname(__file__), )) as f: presets = yaml.load(f.read()) if self.settings.preview[] in presets: self.preset = presets[self.settings.preview[]] return...
Loads preset if it is specified in the .frigg.yml
345,564
def start_circle_left(self, radius_m, velocity=VELOCITY): circumference = 2 * radius_m * math.pi rate = 360.0 * velocity / circumference self._set_vel_setpoint(velocity, 0.0, 0.0, -rate)
Start a circular motion to the left. This function returns immediately. :param radius_m: The radius of the circle (meters) :param velocity: The velocity of the motion (meters/second) :return:
345,565
def render(self, template_name: str, **kwargs: Any) -> "Future[None]": if self._finished: raise RuntimeError("Cannot render() after finish()") html = self.render_string(template_name, **kwargs) js_embed = [] js_files = [] css_embed = [] css_...
Renders the template with the given arguments as the response. ``render()`` calls ``finish()``, so no other output methods can be called after it. Returns a `.Future` with the same semantics as the one returned by `finish`. Awaiting this `.Future` is optional. .. versionchange...
345,566
def zip_cluster(data, k, init=None, max_iters=100): genes, cells = data.shape init, new_assignments = kmeans_pp(data+eps, k, centers=init) centers = np.copy(init) M = np.zeros(centers.shape) assignments = new_assignments for c in range(k): centers[:,c], M[:,c] = zip_fit_params_mle(d...
Performs hard EM clustering using the zero-inflated Poisson distribution. Args: data (array): A 2d array- genes x cells k (int): Number of clusters init (array, optional): Initial centers - genes x k array. Default: None, use kmeans++ max_iters (int, optional): Maximum number of ite...
345,567
def crypto_kx_keypair(): public_key = ffi.new("unsigned char[]", crypto_kx_PUBLIC_KEY_BYTES) secret_key = ffi.new("unsigned char[]", crypto_kx_SECRET_KEY_BYTES) res = lib.crypto_kx_keypair(public_key, secret_key) ensure(res == 0, "Key generation failed.", raising=exc.CryptoError) return (ffi.b...
Generate a keypair. This is a duplicate crypto_box_keypair, but is included for api consistency. :return: (public_key, secret_key) :rtype: (bytes, bytes)
345,568
def quick_hyst(dir_path=".", meas_file="measurements.txt", save_plots=True, interactive=False, fmt="png", specimen="", verbose=True, n_plots=10, contribution=None): if contribution is None: con = cb.Contribution(dir_path, read_tables=[], cust...
makes specimen plots of hysteresis data Parameters ---------- dir_path : str, default "." input directory meas_file : str, default "measurements.txt" name of MagIC measurement file save_plots : bool, default True save figures interactive : bool, default False if ...
345,569
def simple_separated_format(separator): return TableFormat(None, None, None, None, headerrow=DataRow(, separator, ), datarow=DataRow(, separator, ), padding=0, with_header_hide=None)
Construct a simple TableFormat with columns separated by a separator. >>> tsv = simple_separated_format("\\t") ; \ tabulate([["foo", 1], ["spam", 23]], tablefmt=tsv) == 'foo \\t 1\\nspam\\t23' True
345,570
def add_schema_attributes(container, nexson_version): if _is_by_id_hbf(nexson_version): _add_by_id_nexson_schema_attributes(container) elif _is_badgerfish_version(nexson_version): _add_badgerfish_nexson_schema_attributes(container) elif _is_direct_hbf(nexson_version): _add_direc...
Adds several attributes to `container`: _using_hbf_meta - boolean. True for HoneyBadgerFish v1-style meta elements ('^prop': value rather than 'meta': {'$':value}) and the following _SchemaFragment instances: _NexmlEl_Schema
345,571
def normalize(self): if self.tz is None or timezones.is_utc(self.tz): not_null = ~self.isna() DAY_NS = ccalendar.DAY_SECONDS * 1000000000 new_values = self.asi8.copy() adjustment = (new_values[not_null] % DAY_NS) new_values[not_null] = new_val...
Convert times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected. This method is available on Series with datetime values under the ``...
345,572
def initialize_shade(self, shade_name, shade_color, alpha): self.shades[shade_name] = [0, pygame.Surface(self.image.get_size())] if type(shade_color) == str: background = pygame.image.load(shade_color).convert() background = pygame.transform.scale(bac...
This method will create semi-transparent surfaces with a specified color. The surface can be toggled on and off. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: Shade_name - String of the name that you want to associate with the surfac...
345,573
def set_file_to_upload(self, file_to_upload): if in self.data: del self.data[] self.file_to_upload = file_to_upload
Delete any existing url and set the file uploaded to the local path provided Args: file_to_upload (str): Local path to file to upload Returns: None
345,574
def request_transfer(subject, recipient, comment): TransferPermission(subject).test() if recipient == (subject.organization or subject.owner): raise ValueError( ) transfer = Transfer.objects.create( owner=subject.organization or subject.owner, recipient=recipient, ...
Initiate a transfer request
345,575
def on_train_end(self, **kwargs): "Load the best model." if self.every=="improvement" and (self.learn.path/f).is_file(): self.learn.load(f, purge=False)
Load the best model.
345,576
def execute(self, try_limit=5, try_interval=0.5, timeout=30): return Promise( no_error(self._execute), u"Executing {!r}".format(self), try_limit=try_limit, try_interval=try_interval, timeout=timeout, ).fulfill()
Execute this query, retrying based on the supplied parameters. Keyword Args: try_limit (int): The number of times to retry the query. try_interval (float): The number of seconds to wait between each try (float). timeout (float): The maximum number of seconds to spend retryin...
345,577
def kde(self, name, npoints=_npoints, **kwargs): data = self.get(name,**kwargs) return kde(data,npoints)
Calculate kernel density estimator for parameter
345,578
def make_syllables(self, sentences_words): all_syllables = [] for sentence in sentences_words: syll_per_sent = [] for word in sentence: syll_start = 0 syll_per_word = [] cur_letter_in = 0 while cur_lette...
Divide the word tokens into a list of syllables. Note that a syllable in this instance is defined as a vocalic group (i.e., a vowel or a diphthong). This means that all syllables which are not the last syllable in the word will end with a vowel or diphthong. TODO: Determine whether Luke...
345,579
def local_settings(settings, prefix): prefix = "{}.".format(prefix) new_settings = {k[len(prefix):]: v for k, v in settings.items() if k.startswith(prefix)} return new_settings
Localizes the settings for the dotted prefix. For example, if the prefix where 'xyz':: {'xyz.foo': 'bar', 'other': 'something'} Would become:: {'foo': 'bar'} Note, that non-prefixed items are left out and the prefix is dropped.
345,580
def list_projects(self, tags=None, pattern=None, username=None, owner=None, namespace=None, fork=None, short=None, page=None, per_page=None): request_url = "{}/api/0/projects".format(self.instance) payload = {} if tags is not None: ...
Lisk all projects on this Pagure instance. :param tags: filters the tags of the project :param pattern: filters the projects by the pattern string :param username: filters the username of the project administrators :param owner: filters the projects by ownership :param namespace:...
345,581
def get_ports(proto=, direction=): *tcpin proto = proto.upper() direction = direction.upper() results = {} _validate_direction_and_proto(direction, proto) directions = build_directions(direction) for direction in directions: option = .format(proto, direction) results[directi...
Lists ports from csf.conf based on direction and protocol. e.g. - TCP_IN, TCP_OUT, UDP_IN, UDP_OUT, etc.. CLI Example: .. code-block:: bash salt '*' csf.allow_port 22 proto='tcp' direction='in'
345,582
def page_data_frame (df, pager_argv=[], **kwargs): import codecs, subprocess, sys pager = subprocess.Popen (pager_argv, shell=False, stdin=subprocess.PIPE, close_fds=True) try: enc = codecs.getwriter (sys.stdout.encoding or ) (pager....
Render a DataFrame as text and send it to a terminal pager program (e.g. `less`), so that one can browse a full table conveniently. df The DataFrame to view pager_argv: default ``['less']`` A list of strings passed to :class:`subprocess.Popen` that launches the pager program kwargs ...
345,583
def _wrap_set_op(self, fun, arg): result = fun(self, arg) result._autostep = self._autostep result.padding = self.padding return result
Wrap built-in set operations for RangeSet to workaround built-in set base class issues (RangeSet.__new/init__ not called)
345,584
def research(root, query=lambda p, k, v: True, reraise=False): ret = [] if not callable(query): raise TypeError( % query) def enter(path, key, value): try: if query(path, key, value): ret.append((path + (key,), value)) except Exception: ...
The :func:`research` function uses :func:`remap` to recurse over any data nested in *root*, and find values which match a given criterion, specified by the *query* callable. Results are returned as a list of ``(path, value)`` pairs. The paths are tuples in the same format accepted by :func:`get_pat...
345,585
def define_xml_str(xml, **kwargs): * conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret
Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 20...
345,586
def scan_url(url, line, project, split_path, apikey): logger.info(, split_path, line.strip()) logger.info(, url) with open(reports_dir + "urls-" + project + ".log", "a") as gate_report: gate_report.write(.format(split_path, url)) v_api = virus_total.VirusTotal() while True: url...
If URL is found, scan it
345,587
def reset(self, method=None): self.logger.info( % self.name) self.__send_break()
Resets the serial device. Internally calls __send_break(). :param method: Not used for DutSerial :return: Nothing
345,588
async def query(self, path, method=, **params): if method in (, , , , ): full_path = self.host + path if method == : resp = await self.aio_sess.get(full_path, params=params) elif method == : resp = await self.aio_sess.post(full_path, d...
Do a query to the System API :param path: url to the API :param method: the kind of query to do :param params: a dict with all the necessary things to query the API :return json data
345,589
def kde(self, term, bandwidth=2000, samples=1000, kernel=): terms = np.array(self.terms[term])[:, np.newaxis] kde = KernelDensity(kernel=kernel, bandwidth=bandwidth).fit(terms) x_axis = np.linspace(0, len(self.tokens), samples)[:, np.newaxis] score...
Estimate the kernel density of the instances of term in the text. Args: term (str): A stemmed term. bandwidth (int): The kernel bandwidth. samples (int): The number of evenly-spaced sample points. kernel (str): The kernel function. Returns: n...
345,590
def ParseOptions(cls, options, output_module): elastic_output_modules = ( elastic.ElasticsearchOutputModule, elastic.ElasticsearchOutputModule) if not isinstance(output_module, elastic_output_modules): raise errors.BadConfigObject( ) index_name = cls._ParseStringOption( ...
Parses and validates options. Args: options (argparse.Namespace): parser options. output_module (OutputModule): output module to configure. Raises: BadConfigObject: when the output module object is of the wrong type. BadConfigOption: when a configuration parameter fails validation.
345,591
def after_invoke(self, coro): if not asyncio.iscoroutinefunction(coro): raise TypeError() self._after_invoke = coro return coro
A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a :class:`.C...
345,592
def create_job(self, phases, name=None, input=None): log.debug() path = % self.account body = {"phases": phases} if name: body["name"] = name if input: body["input"] = input headers = {"Content-Type": "application/json"} res, cont...
CreateJob https://apidocs.joyent.com/manta/api.html#CreateJob
345,593
def create_temp_file(file_name=None, string_or_another_file=""): temp_file_path = temp_path(file_name) if isinstance(string_or_another_file, file): temp_file = open(temp_file_path, "wb") temp_file.write(string_or_another_file.read()) else: temp_file = codecs.op...
Creates a temp file using a given name. Temp files are placed in the Project/temp/ directory. Any temp files being created with an existing temp file, will be overridden. This is useful for testing uploads, where you would want to create a temporary file with a desired name, upload it, then delete the...
345,594
def leq3(levels): n = float(len(levels)) sums = 0.0 if sum(levels) == 0.0: return 0.0 for l in levels: if l == 0: continue sums += pow(10.0, float(l) / 10.0) leq3 = 10.0 * math.log10((1.0 / n) * sums) leq3 = max(0.0, leq3) return leq3
Calculates the energy-equivalent (Leq3) value given a regular measurement interval.
345,595
def iter_genotypes(self): self._impute2_file.seek(0) for i, line in enumerate(self._impute2_file): genotypes = self._parse_impute2_line(line) variant_info = None if self.has_index: variant_info = self._impute2_index.iloc[i,...
Iterates on available markers. Returns: Genotypes instances.
345,596
def _ReadElementSequenceDataTypeDefinition( self, definitions_registry, definition_values, data_type_definition_class, definition_name, supported_definition_values): unsupported_definition_values = set(definition_values.keys()).difference( supported_definition_values) if unsupported_def...
Reads an element sequence data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. data_type_definition_class (str): data type definition class. definition_name (str): ...
345,597
def on_status(self, status): self.out.write(json.dumps(status)) self.out.write(os.linesep) self.received += 1 return not self.terminate
Print out some tweets
345,598
def split(self, point=None): if point is None: point = len(self) / 2 if point < 0: raise NGSReadError("Cannot split read at index less than 0 " + "(index provided: " + str(point) + ")") if point > len(self): raise NGSReadError("Cannot split read at index great...
Split this read into two halves. Original sequence is left unaltered. The name of the resultant reads will have '.1' and '.2' appended to the name from the original read. :param point: the point (index, starting from 0) at which to split this read -- everything before this index will be ...
345,599
def rpc(commands, method=, **kwargs): conn_args = nxos_device[] conn_args.update(kwargs) return __utils__[](commands, method=method, **conn_args)
Executes an RPC request over the NX-API.