content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def get_key(): """ Gets the private key used to access Transcriptic's services. Returns ------- str """ if TRANSCRIPTIC_KEY is not None: return TRANSCRIPTIC_KEY return os.environ['TRANSCRIPTIC_KEY']
76213bc4b2a07d24b2f183eaa0fca18dcfec508b
2,700
from typing import Any def linear_search_while(lst: list, value: Any) -> int: """Return the index of the first occurrence of value in lst, or return -1 if value is not in lst. >>> linear_search([2, 5, 1, -3], 5) 1 >>> linear_search([2, 4, 2], 2) 0 >>> linear_search([2, 5, 1, -3], 4) -1...
c90c39148b5c30fbb4f6732e322d03632ad63b39
2,701
def get_pagerduty_secret_name(): """ Get name of the PagerDuty secret for currently used addon. Returns: string: name of the secret """ return config.DEPLOYMENT["addon_name"] + constants.MANAGED_PAGERDUTY_SECRET_SUFFIX
be731e1dcebc3f8a225e249def332abd0d8ea71b
2,702
from typing import Dict def check_docs( doc_path: str, recurse: bool = True, max_threads: int = 10, delay: float = 0 ) -> Dict[str, Dict[str, UrlResult]]: """ Check multiple HTML files in `doc_path`. Parameters ---------- doc_path : str Path recurse: bool If True, recurse ...
c3cc03a61f633143d03f8bfa1063242de8797bfa
2,703
import os def create_graph(filepath, nodes_data, legend=False): """Visualizes the energy system as graph. Creates, using the library Graphviz, a graph containing all components and connections from "nodes_data" and returns this as a PNG file. ---- Keyword arguments: filepath : obj:...
85ef4f541750845ec9147d5faf89c1f89dfa7f31
2,704
import shlex import subprocess def exec_cmd(cmd, secrets=None, timeout=600, ignore_error=False, **kwargs): """ Run an arbitrary command locally Args: cmd (str): command to run secrets (list): A list of secrets to be masked with asterisks This kwarg is popped in order to not in...
be6defec9e131f1d22992cb6dae955fd2372c091
2,705
def timeParser(dstr): """ parse clock time string into array """ hh, mm, ss = dstr.split(':') return np.array([hh, mm, ss]).astype(int)
3b4f72ceaf4f2e9bd5fc93664d896537ad0f9884
2,706
import struct def get_43_ai_core_data(input_file=None): """Function for getting datas from aicore: ov/cnt/total_cyc/ov_cyc/pmu_cnt/stream_id.""" result_data = [] with open(input_file, 'rb') as ai_core_file: while True: line_ = ai_core_file.read(128) if line_: ...
03c9a62a4fd2a2041489cbcb19e2e8e4788e6b0d
2,707
from typing import Type def get_configuration_class_with_attributes( klass: Type[AlgorithmConfiguration], ) -> Type[AlgorithmConfiguration]: """Get AlgorithmConfiguration with set attributes. Args: klass: a class to be used to extract attributes from. Returns: a class with the attrib...
ae8ea9b30781854269eb97da6889d1a61ae29935
2,708
def get_token_symbol(token_address: str): """ Gets the token symbol If not have the external method `symbol` to get the score symbol, it will raise JSONRPCException. """ call = CallBuilder()\ .from_(wallet.get_address())\ .to(token_address)\ .method("symbol")\ .b...
9c84fbcb893345f701d8ce0d24509dd595139d8c
2,709
def iceil(x): """ Return the ceiling of the input, element-wise. The ceil of the scalar `x` is the smallest integer `i`, such that `i >= x`. It is often denoted as :math:`\lceil x \rceil`. Parameters ---------- x : array_like Input data. Returns ------- y : {numpy.nda...
bdc893fe00f073393240b1a861e79c9c4667abc4
2,710
from typing import Optional import yaml def get_repo_version(filename: str, repo: str) -> Optional[str]: """Return the version (i.e., rev) of a repo Args: filename (str): .pre-commit-config.yaml repo (str): repo URL Returns: Optional[str]: the version of the repo """ wit...
821653bdeb60a86fce83fb3a05609996231ec5d4
2,711
from typing import Iterator from typing import Tuple import torch def plot_grad_flow(named_parameters: Iterator[Tuple[str, torch.nn.Parameter]]) -> plt.Figure: """ Plots the gradients flowing through different layers in the net during training. Can be used for checking for possible gradient vanishing / ex...
cc0bd23b8cea9359e003cff7c414ce80fcbf5b1b
2,712
from typing import Dict from typing import Any def mk_cli_context_settings( mk_db: CliCtxDbBase.MkFnT, ) -> Dict[str, Any]: """Create initial click context parameters for this cli application. This is currently used as input for autocompletion. Example: `@click.group(context_settings=mk_cli_...
09f232936ef3c09a5c00edada04a31a64058aaad
2,713
import requests import ast def get_file_action(header: 'dict[str,str]') -> str: """Gets action file form main repo Args: header (dict[str,str]): Header with auth token Raises: get_aciton_file_e: Raised when no aciton file was collected Returns: str: T...
d1c6eb349aea156e2180f5218e247e86a8a60f3c
2,714
from typing import Union from typing import Callable import warnings def sensor(raw_input_shape: StandardizedTensorShape, f: SensorFunction = None, sensor_id: str = None, history: int = None) \ -> Union[Callable[[SensorFunction], SensorLambda], SensorLambda]: """Decorator for creating sensors f...
0bfa60c70cc43cd0929a8db840469d8fd6ffbac7
2,715
def convert_event(ui_event): """Converts ui.event into ecs.event This maps keyboard entries into something that the system can handle TODO: Add a movement system """ if isinstance(ui_event, KeyboardEvent): vim_movement_mapper = { # Cardinal KeyboardEvent("h"): vecto...
ecf396823f3bc48fda696abd96a13e34b82a6b06
2,716
def collection(collection, _pod=None): """Retrieves a collection from the pod.""" return _pod.get_collection(collection)
6d95c9afbcdbb2fe81f71b9d4f17be50aec1aea4
2,717
def appif(cfg): """ Return interface belonging to application """ return get_interface_of_network(appnet(cfg)['name'])
e13f7cee8f4785e82bc558500d5d4938a3c728f2
2,718
def f(x): """ Try and have the NN approximate the xor function. """ if x[0] == x[1]: return 0. else: return 1.
8111e53f0ff0dfdd75f08d845e5176bc287a65e1
2,719
import pandas import json def dataframe_to_list(df: pandas.DataFrame) -> list: """ Use caution with datetime columns, as they may not be de/serialized as desired """ return json.loads(df.to_json(orient="records"))
244f76f1970364f13ddf6bb53a6280962d0ae45a
2,720
def decimal_to_binary(integer,nbits=8,grouped=0): """Converts integer to binary string of length nbits, sign bit and then m.s.b. on the left. Negative numbers are twos-complements, i.e., bitwise complement + 1.""" # Just remember that minus sign and ignore it if integer < 0: negative = True...
89cef0feaad6d1c25dd67b97a0caf2212ea4a55d
2,721
def line_integrals(state, uloc, vloc, kind="same"): """ calculate line integrals along all islands Arguments: kind: 'same' calculates only line integral contributions of an island with itself, while 'full' calculates all possible pairings between all islands. """ vs = state.v...
4a8b32246a9a60d9a42368d7643bc6ddea1c44d0
2,722
def _BBANDS(kwargs): """ 布林带 技术参数 ------- 使用21天,2倍 """ df = kwargs.get('df') limit_start = kwargs.get('limit_start') limit_end = kwargs.get('limit_end') ndays = 21 inds = indicators( 'BBANDS', df, timeperiod=ndays).loc[limit_start:limit_end, :] traces = [] fo...
ee19ee06b5fb6a306f6d43285a616e61584c65a8
2,723
from typing import Optional from typing import Iterable from typing import Tuple def make_colors(color: OpColor, fill_color: OpColor, colors: Optional[Iterable[OpColor]]) -> Tuple[OpColor, ...]: """Creates final colors tuple.""" if colors is None: return conform_color(color), conform_color(fill_color)...
8bba1bef72543fb4bd497ada924d23ebf2692f7c
2,724
def print_qa(questions, answers_gt, answers_gt_original, answers_pred, era, similarity=dirac, path=''): """ In: questions - list of questions answers_gt - list of answers (after modifications like truncation) a...
01b44361066668462868abed00f49811e0648d11
2,725
def recast_to_supercell(z, z_min, z_max): """Gets the position of the particle at ``z`` within the simulation supercell with boundaries ``z_min`` y ``z_max``. If the particle is outside the supercell, it returns the position of its closest image. :param z: :param z_min: :param z_max: :retur...
2d144a656a92eaf3a4d259cf5ad2eadb6cfdf970
2,726
def list_services(request): """ Should probably move this to an Ajax JSON request like the probe. """ if request.method == "POST": action = request.POST.get("action") sid = request.POST.get("id") logger.debug(f"-- action: {action} sid: {sid}") if action == "delete": l...
bd4d9b9dd9300c127b97fb838aa5085979904701
2,727
from typing import Union from pathlib import Path def open_sat_data( zarr_path: Union[Path, str], convert_to_uint8: bool = True, ) -> xr.DataArray: """Lazily opens the Zarr store. Args: zarr_path: Cloud URL or local path pattern. If GCP URL, must start with 'gs://' """ _log.debug("Open...
ccc79f02bb086b552f69d2e8f9440f02ef121b95
2,728
from typing import List from typing import Optional import io import csv async def get_pedigree( internal_family_ids: List[int] = Query(None), response_type: ContentType = ContentType.JSON, replace_with_participant_external_ids: bool = True, replace_with_family_external_ids: bool = True, include_h...
5ecf064d82a6391d3ed025aeac2bf070710d5ebe
2,729
def lang_string_set_to_xml(obj: model.LangStringSet, tag: str) -> etree.Element: """ serialization of objects of class LangStringSet to XML :param obj: object of class LangStringSet :param tag: tag name of the returned XML element (incl. namespace) :return: serialized ElementTree object """ ...
f49a1d73f1fd4354c245427bc1277600c67a5d99
2,730
def grasp_from_contacts(contact1,contact2): """Helper: if you have two contacts, this returns an AntipodalGrasp""" d = vectorops.unit(vectorops.sub(contact2.x,contact1.x)) grasp = AntipodalGrasp(vectorops.interpolate(contact1.x,contact2.x,0.5),d) grasp.finger_width = vectorops.distance(contact1.x,contac...
945ff950a59b1442efc6abdce68861957b0a60a7
2,731
import random def choose_move(data: dict) -> str: """ data: Dictionary of all Game Board data as received from the Battlesnake Engine. For a full example of 'data', see https://docs.battlesnake.com/references/api/sample-move-request return: A String, the single move to make. One of "up", "down", "lef...
62d663720c4592c6e97215cd6e4ec772f3038ae2
2,732
import os def get_fremont_data(filename='Fremont.csv', url=FREMONT_URL, force_download=False): """Download and cache the fremont data Parameters ---------- filename : string (optional) location to save the data url : string (optional) web location of t...
28a2abdf390f42964aebe058206c77f3e51a0d88
2,733
def boolean_dumper(dumper, value): """ Dump booleans as yes or no strings. """ value = u'yes' if value else u'no' style = None return dumper.represent_scalar(u'tag:yaml.org,2002:bool', value, style=style)
40a6a270d1ad1a289947c064c7f85edb1d589bb7
2,734
def preprocess_data_4_catboost(data_df, output_path=None): """ preprocess data for working with gradient boosting techniques specifically with the catboost library. since this is going to use the preprocessing built into the catboost library there are slightly different steps to be done """ ...
9bc60ca096963fe6fb8a30e19442d870694f1339
2,735
def conv_current_to_electrons_second(current): """ Convert a current in Amps to a number of electrons per second. """ return int(current / const.electron_charge)
76051a529c230b54a6d07f282c97b48d4ea59758
2,736
import json def get_users(): """ Use urllib3 to make a REST call to get list of Okta Users for a given Okta Application """ request_url = f"{OKTA_URL}/apps/{OKTA_APP_ID}/users" okta_users_request = HTTP.request( 'GET', request_url, headers={'Content-Type': 'application/...
b94816de46d843a3a80a53c569d52b17e142d4e9
2,737
def n_sample_per_class_train_set(df, n_samples=3, class_column="category"): """ returns a subset of the provided df that contains n_samples instances of each class :param df: panda dataframe that contains hidden_reps with class labels :param n_samples: number of samples per class :param class_column: column w...
107d9845b8e5efb3da09f13d11ae796fc560b874
2,738
def clip_count(cand_d, ref_ds): """Count the clip count for each ngram considering all references.""" count = 0 for m in cand_d.keys(): m_w = cand_d[m] m_max = 0 for ref in ref_ds: if m in ref: m_max = max(m_max, ref[m]) m_w = min(m_w, m_max) count += m_w return count
f33ad8c5a9de8e136ea97684de3bd64779471bb6
2,739
def container_wrapper(directive, literal_node, caption, classes): """adapted from https://github.com/sphinx-doc/sphinx/blob/master/sphinx/directives/code.py """ container_node = docutils.nodes.container( '', literal_block=True, classes=classes) # ['literal-block-wrapper'] parsed = docutils....
17e9db3f494174a721cd80c179514bbc3db773c1
2,740
def get_current_and_next_quarters(request, num): """ Returns the current and next num uw_sws.models.Term objects in a list for the current quarter refered in the user session. Returns the next num -1 quarters along with the current one. """ term = get_current_quarter(request) quarters = [ter...
26f5d268148d3f0395d1d41739d51b1f06a0bd6a
2,741
from typing import Tuple from typing import Dict def _create_metadata_from_dat_df( csv_df: pd.DataFrame, ) -> Tuple[Dict[int, tuple], Pitch]: """Creates meta information from the CSV file as parsed by pd.read_csv(). Parameters ---------- csv_df: DataFrame Containing all data from the posi...
d53e66ff343c2391058e2717dde5bbe7c11a2c44
2,742
def main(): """ Main function used in script, primarily used as a handle to get the output into stdout. """ # There are no args, but parse them just so help works print(process_files_json(), end="") return None
495af3e19cdd823ee6853f516b17df0c489f34f9
2,743
import torch import os import time from datetime import datetime import sys def train_generator(train_loader, test_loader, num_epoch=500, lr=0.0001, beta1=0.9, beta2=0.999): """Train a generator on its own. Args: train_loader: (DataLoader) a DataLoader wrapping the training datase...
714b6f9a9e21cda960430a2458fdc939fb48f36b
2,744
def expand(doc, doc_url="param://", params=None): """ ASSUMING YOU ALREADY PULED THE doc FROM doc_url, YOU CAN STILL USE THE EXPANDING FEATURE USE mo_json_config.expand({}) TO ASSUME CURRENT WORKING DIRECTORY :param doc: THE DATA STRUCTURE FROM JSON SOURCE :param doc_url: THE URL THIS doc CAME...
d8a8045cb6afea089f1241dc1a47bf6c95fc3628
2,745
def get_model_creator(hparams): """Get the right model class depending on configuration.""" if hparams.architecture == 'peng': model_creator = model.Model """vanilla lstm, seq2seq""" return model_creator
84c65108e6be1a723184778db564b75ea333d52f
2,746
import unittest def extra(): """Tests faint.extra. That is, less central faint code, possibly requiring extensions (e.g. tesseract or GraphViz dot). """ return unittest.defaultTestLoader.discover("py_tests/test_extra", top_level_dir="py_tests/")
c6fc2694144e852edaef219d95bc384b5b394d7d
2,747
def cmd_te_activate(abs_filename): """最前面に持ってくる(テキストエディタ向け) ファイルが含まれるVisual Studioを探し出して最前面に持ってくる。 abs_filename- ファイル名の絶対パス (Ex.) c:/project/my_app/src/main.cpp """ return _te_main2(cmd_activate,abs_filename)
2a4922c89360f049c50cc2b2b81509c48d32968e
2,748
def search(search_domain, fmt=None): """Handle redirect from form submit.""" domain = tools.parse_post_data(search_domain) if domain is None: return handle_invalid_domain(search_domain) if fmt is None: if features.enable_async_search(): return flask.redirect('/search?ed={}'...
4be9a751fad12fae67a34b7c4bda2b2be3d7ff89
2,749
def get_graph_from_particle_positions( particle_positions, box_lengths, cutoff_distance, store_positions=False ): """Returns a networkx graph of connections between neighboring particles Args: particle_positions (ndarray or dataframe): Shape (`n_particles`, `n_dimensions`). Each of ...
a51ecbfd83fe08ae07f4e6952f2796eba9f79f0a
2,750
import numpy as np def cca(x,y): """ canonical correlation analysis cca wx, wy, r = cca(x,y) returns wx, wy two matrices which columns [:,i] correspond to the canonical weights (normalized eigenvectors) and a vector r containing the canonical correlations, all sorted in decreasing order. cca assumes...
f0d734fc927789d6ecca0685a85f727e48b334df
2,751
from pathlib import Path def get_assay_table_path(dataset: TemplateDataset, configuration: dict) -> Path: """Retrieve the assay table file name that determined as a valid assay based on configuration. Specifically, defined in subsection 'ISA meta' :param dataset: A dataset object including a metadata com...
57efa60ec4e3b6d16bfa39a28b9057aa864c2506
2,752
def train_models(vae, emulator, em_lr, vae_lr, signal_train, dataset, val_dataset, epochs, vae_lr_factor, em_lr_factor, vae_min_lr, em_min_lr, vae_lr_patience, em_lr_patience, lr_max_factor, es_patience, es_max_factor): """ Function that train the models simultaneously :par...
a3301f178aade90cb5a5b441ccf7607e2f13c776
2,753
def get_next_term(cfg): """ Gets the next term to be added. Args: cfg: Expression config """ term = {} if np.random.choice(['quantity', 'number'], p=[cfg.ratio, 1 - cfg.ratio]) == 'quantity': idx = np.random.choice(range(len(cfg.quants))) if cfg.reuse: term['...
edaf22a93ce1a0c51f4193c3ea022202c8bbaaef
2,754
def demand_share_per_timestep_constraint_rule(backend_model, group_name, carrier, timestep, what): """ Enforces shares of demand of a carrier to be met by the given groups of technologies at the given locations, in each timestep. The share is relative to ``demand`` technologies only. .. container::...
65cfc120a9a7a5f26b4057a21b7a38a32a335955
2,755
def b2str(data): """Convert bytes into string type.""" try: return data.decode("utf-8") except UnicodeDecodeError: pass try: return data.decode("utf-8-sig") except UnicodeDecodeError: pass try: return data.decode("ascii") except UnicodeDecodeError: ...
05cbe6c8072e1bf24cc9ba7f8c8447d0fa7cbf7f
2,756
def plotalphaerror(alphaarr,errorarr,errorlagarr): """ This will plot the error with respect then alpha parameter for the constraint. """ sns.set_style('whitegrid') sns.set_context('notebook') Nlag=errorlagarr.shape[-1] nlagplot=4. nrows=1+int(sp.ceil(float(Nlag)/(2*nlagp...
e87c771212a3e39b1f4d7a1a74fc18c1d2e85f87
2,757
def fill_space(space, dim, size, minval, maxval, factor): """Fill a dim-dimensional discrete space of ℕ^{size} with some random hyperplane with values ranging from minval to maxval. Returns a ℕ^{size} array. Changes space in-place.""" offsets=[np.array([0]*dim)] return ndim_diamond_square_rec(space, dim, size, of...
7744cb465438b40019f3edae9db04143b16d19b1
2,758
def fracorder_lowshelving_eastty(w1, w2, G1, G2, rB=None): """ Parameters ---------- w1: float Lower corner frequency. w2: float Upper corner frequency. G1: float Target level at lower corner frequency in dB. G2: float Target level at upper corner frequency in...
379a87b024ff993c0abf0b75a482a8ab66a67546
2,759
def get_cookie_date(date): """ Return a date string in a format suitable for cookies (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Date) :param date: datetime object :return: date string in cookie format """ return date.strftime("%a, %d %b %Y %H:%M:%S GMT")
f2b4d6decab72cf1f25754bc7e290f62eae92156
2,760
def fill_block_with_call(newblock, callee, label_next, inputs, outputs): """Fill *newblock* to call *callee* with arguments listed in *inputs*. The returned values are unwraped into variables in *outputs*. The block would then jump to *label_next*. """ scope = newblock.scope loc = newblock.loc ...
76e9edbeca59a75d9854e6ffa2d02658da7511ab
2,761
from typing import Dict from typing import List import sys import json def terraform_write_variables(configs: Dict, variables_to_exclude: List) -> str: """Write out given config object as a Terraform variables JSON file. Persist variables to Terraform state directory. These variables are used on apply /...
f8ab21569328e0f1a9a30a177ad30ec2ad44b62f
2,762
def data_context_service_interface_pointuuid_media_channel_service_interface_point_spec_mc_pool_available_spectrumupper_frequencylower_frequency_frequency_constraint_get(uuid, upper_frequency, lower_frequency): # noqa: E501 """data_context_service_interface_pointuuid_media_channel_service_interface_point_spec_mc_p...
412f0b48a050e9201e6d52450a04a6bef0f4a0f3
2,763
def image_to_string(filename): """Generate a string representation of the image at the given path, for embedding in code.""" image = pyglet.image.load(filename) data = image.get_data('LA', 16) s = '' for x in data: s += "\\x%02x" % (ord(x)) return s
19dea26d51dd29449759c5e1a3b4c9fc098702f3
2,764
def mpf_connectome( mc, num_sampled, max_depth, args_dict, clt_start=10, sr=0.01, mean_estimate=False ): """Perform mpf statistical calculations on the mouse connectome.""" args_dict["max_depth"] = max_depth args_dict["total_samples"] = num_sampled[0] args_dict["static_verbose"] = False args_dic...
6ae8ddb7c3355ddbf072a5bf97f57fe4e13b500e
2,765
def valuedict(keys, value, default): """ Build value dictionary from a list of keys and a value. Parameters ---------- keys: list The list of keys value: {dict, int, float, str, None} A value or the already formed dictionary default: {int, float, str} A defa...
44283bac3be75c3569e87a890f507f7cff4161b6
2,766
async def chunks(request): """A handler that sends chunks at a slow pace. The browser will download the page over the range of 2 seconds, but only displays it when done. This e.g. allows streaming large files without using large amounts of memory. """ async def iter(): yield "<html><hea...
590fe83c5ee53c603b973063e0e077ab87a220ae
2,767
import os import subprocess import json def start_vitess(): """This is the main start function.""" topology = vttest_pb2.VTTestTopology() keyspace = topology.keyspaces.add(name='user') keyspace.shards.add(name='-80') keyspace.shards.add(name='80-') keyspace = topology.keyspaces.add(name='lookup') keysp...
3643c780118aaa72485b059a34891d938aff7328
2,768
def get_zero_ranges(*args): """ get_zero_ranges(zranges, range) -> bool Return set of ranges with zero initialized bytes. The returned set includes only big zero initialized ranges (at least >1KB). Some zero initialized byte ranges may be not included. Only zero bytes that use the sparse storage method (S...
bd95dbb237ca0b2934e8653b1198d10d25abc553
2,769
def fista_step(L, Wd, X, alpha, last_Z): """ Calculates the next sparse code for the FISTA algorithm Dimension notation: B - Number of samples. Usually number of patches in image times batch size K - Number of atoms in dictionary d - Dimensionality of atoms in dictionary ...
6e237a01e631d08efcc425068c646b792d984cdd
2,770
def get_and_validate_certs_for_replacement( default_cert_location, default_key_location, default_ca_location, new_cert_location, new_key_location, new_ca_location): """Validates the new certificates for replacement. This function validates the new specified certi...
9a4a3b46609fc1e5e7cc525b84397b9adba86b32
2,771
def build_model(cfg): """ Built the whole model, defined by `cfg.model.name`. """ name = cfg.model.name return META_ARCH_REGISTRY.get(name)(cfg)
b106eca0f110007cb852dce9760e5e0ee08940a8
2,772
def download_n_parse_3k(url): """ Gets the article's metadata Args: url: The article's URL """ article3k = Article(url) try: article3k.download() article3k.parse() except Exception: print(f"Download or Parse:\t{url}") return return article3k.text
fa63fc7c03b63c5e08004d61488074be538c714b
2,773
def crop_to_square(img, target_size=None): """ Takes numpy array img and converts it to a square by trimming :param img: np.array representing image :param target_size: optionally specify target size. If None, will return min(l, w) x min(l, w) :return: np.array """ l, w = img.shape img_c...
2ad566c7d0a0c719ff207bc06d33e70208a7a03f
2,774
def reboot(name, path=None): """ Reboot a container. path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt 'minion' lxc.reboot myvm """ ret = {"result": True, "changes...
2519f9ad5434dbb9ff0a48f5280483829584ebb1
2,775
import networkx def find(domain): """ Finds connected domains within a domain. A domain is defined to be a connected region of lattice points, subject to periodic boundary conditions. Parameters ---------- domain : :py:class:`~fieldkit.mesh.Domain` The set of nodes to seek connected ...
3ea2128f84104686be88d359cda3df2554013f41
2,776
def url_to_license(url): """Given a URL, return the license as a license/version tuple""" (scheme, netloc, path, *remainder) = urlparse(url) path_parts = path.split('/') if len(path_parts) < 4: raise LicenseException("Did not get 4 path segments, probably not a CC license URL") license = pa...
e6ae2d67f1dbd02c0fe0885231dbac4ae112b0d3
2,777
def dsystem_dt(request): """Test systems for test_discrete""" # SISO state space systems with either fixed or unspecified sampling times sys = rss(3, 1, 1) # MIMO state space systems with either fixed or unspecified sampling times A = [[-3., 4., 2.], [-1., -3., 0.], [2., 5., 3.]] B = [[1., 4.],...
faaf22165fc147955b69b1d983fbc37dafb34772
2,778
import types def update_attributes(dsFolder: types.GirderModel, data: dict): """Upsert or delete attributes""" crud.verify_dataset(dsFolder) validated: AttributeUpdateArgs = crud.get_validated_model(AttributeUpdateArgs, **data) attributes_dict = fromMeta(dsFolder, 'attributes', {}) for attribute_...
d58dfecf68822d4b45688ea16ec39e97e999d458
2,779
def machado_et_al_2009_matrix_protanomaly(severity): """Retrieve a matrix for simulating anomalous color vision. :param cvd_type: One of "protanomaly", "deuteranomaly", or "tritanomaly". :param severity: A value between 0 and 100. :returns: A 3x3 CVD simulation matrix as computed by Machado et al ...
a99a07a7f447fc741ee1a4bd239bda5ed8079e6b
2,780
def derivative_compliance(coord, connect, E, v, rho, alpha, beta, omega_par, p_par, q_par, x_min_m, x_min_k, xval, disp_vector, lam): """ calculates the derivative of the compliance function. Args: coord (:obj:`numpy.array`): Coordinates of the element. connect (:obj:`numpy.array`): Element con...
2d6e9467c410c3960fb149cb20a306cff85374e5
2,781
def test_status_string(app, authed_client, status_code, status): """The status string should populate itself based on status code.""" @app.route('/test_endpoint') def test_endpoint(): return flask.jsonify('test'), status_code response = authed_client.get('/test_endpoint') assert response.g...
2af688a5f0db42ae2ad13eae86a09a04b3745b07
2,782
def lanc(numwt, haf): """Generates a numwt + 1 + numwt lanczos cosine low pass filter with -6dB (1/4 power, 1/2 amplitude) point at haf Parameters ---------- numwt : int number of points haf : float frequency (in 'cpi' of -6dB point, 'cpi' is cycles per interval. ...
bcfc9dac83fa517a7a564b1d58aba4e4d901b828
2,783
from ete3 import NCBITaxa def normalize_target_taxa(target_taxa): """ Receives a list of taxa IDs and/or taxa names and returns a set of expanded taxids numbers """ ncbi = NCBITaxa() expanded_taxa = set() for taxon in target_taxa: taxid = "" try: taxid = int(taxon...
cc88ba730495fea54bbab86eb83521d88da692fc
2,784
import types def filled (a, value = None): """a as a contiguous numeric array with any masked areas replaced by value if value is None or the special element "masked", get_fill_value(a) is used instead. If a is already a contiguous numeric array, a itself is returned. filled(a) can be used to be...
aabc4772cc4f318d794ef509f22a54116c14764c
2,785
import configparser def get_generic_global(section, prop): """Generic getter for getting a property""" if section is None: raise GlobalPropertyError("Section cannot be null!") elif prop is None: raise GlobalPropertyError("Property cannot be null!") global_conf = configparser.ConfigP...
09e87d4f915e0591193a57505ad9a8e5d28d271e
2,786
def get_mspec_descriptors(mod, mod_lim=20, freq_lim=8000, n_mod_bin=20, n_freq_bin=20): """ Parameters ---------- mod : 2D Numpy array Modulation spectrogram mod_lim : int Upper limit of modulation frequency. The default is 20. freq_lim : int Upper limit of frequency. Th...
0a5fd0739d46ec6fa4539d96ed406dfcf540f2d2
2,787
def mustachify( file, mustache_file="mustache.png", rotation=True, perspective=False, # TODO add perspective transformation modelsize="small", ): """ Pastes a mustache on each face in the image file :param file: image file name or file object to load :param mustache_file: file...
f1ae14f813b15a685c5c8e2d8c0a8e38629284d5
2,788
import subprocess def get_available_gpus(): """Return a list of available GPUs with their names""" cmd = 'nvidia-smi --query-gpu=name --format=csv,noheader' process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.co...
9ef81b08aad25e0109604cdd538b5c9e6902c4d1
2,789
def register_image_array(img, img_name, img_desc, project_id, sample_id, usr, pwd, host, port=4064): """ This function imports a 5D (time-points, channels, x, y, z) numpy array of an image to an omero server using the OMERO Python bindings Example: register_image_array(hypercube, "tomo_0", "thi...
2dec56554280a45e2421192e95896683743939aa
2,790
def count_symbols (val): """ Counts the number of symbols in a string. A symbol is defined as any character that is neither a lowercase letter, uppercase letter or digit. Args: val (str): The string to count symbols in. Returns: int: The number of symbols in the string. """ re...
6c96454cf6a508942719458ba2c28644ffaa6d7d
2,791
import math def arctan(dy, dx): """ Returns the arctan of angle between 0 and 2*pi """ arc_tan = math.atan2(dy, dx) if arc_tan < 0: arc_tan = arc_tan + 2 * np.pi return arc_tan
e3b8d35f97b25983a9ba05f306a45c2852ae2b42
2,792
def meshsize(mesh: dolfin.Mesh, kind: str = "cell") -> dolfin.MeshFunction: """Return the local meshsize `h` as a `MeshFunction` on cells or facets of `mesh`. The local meshsize is defined as the length of the longest edge of the cell/facet. kind: "cell" or "facet" """ if kind not in ...
8cd66227ab46acb85c9ea8907e0164eee142a9ae
2,793
def dep_graph_parser_parenthesis(edge_str): """Given a string representing a dependency edge in the 'parenthesis' format, return a tuple of (parent_index, edge_label, child_index). Args: edge_str: a string representation of an edge in the dependency tree, in the format edge_label(parent_wor...
a3f96ebec6fdcb00f3f64ea02e91147df16df196
2,794
def measure_crypts_props_no_paneth(crypt_objs, label_mask, edu_objs, df, row, col, fld): """Measure crypt level properties for all crypts in image Args: crypt_objs (array): labeled cell objects (e.g. nuclei segmentation) label_mask (array): labeled crypt objects edu_objs (list): ids of cell obje...
28e689a3812cceb5d3165b92d286965b397f6ef1
2,795
import math def intersection_angle(m1, m2): """ Computes intersection angle between two slopes. """ return math.degrees(math.atan((m2-m1) / (1+m1*m2)))
244192d3d1fe74130d64350606e765d8f2d4831b
2,796
import click from pathlib import Path def create_zappa_project( project_name, stack_name, session, client, username, email, password ): """Create the Zappa project.""" aws_rds_host = get_aws_rds_host(stack_name, session) with open('.env', 'a') as file: file.write('AWS_RDS_HOST={}\n'.format(aw...
0b5d9dd0f74604b96cb39ef131c46480d5a0b84f
2,797
import os def erase_create_HDF(filename): """Create and return a new HDS5 file with the given filename, erase the file if existing. See https://github.com/NelisW/pyradi/blob/master/pyradi/hdf5-as-data-format.md for more information on using HDF5 as a data structure. open for writing, truncate if exi...
04539ee0f5a8de817265285c3396c85eeda907b4
2,798
def cast2dtype(segm): """Cast the segmentation mask to the best dtype to save storage. """ max_id = np.amax(np.unique(segm)) m_type = getSegType(int(max_id)) return segm.astype(m_type)
e877502f8a7d6c8e212338d2edf74bafc051e051
2,799