content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def find_or_create_role(name, desc): """ Find existing role or create new role """ role = Role.query.filter(Role.name == name).first() if not role: role = Role(name=name, desc=desc) return role return role
414b960488d55ea6c2cc41121132f06f0d677abd
4,183
def parse_nrrdvector(inp): """Parse a vector from a nrrd header, return a list.""" assert inp[0] == '(', "Vector should be enclosed by parenthesis." assert inp[-1] == ')', "Vector should be enclosed by parenthesis." return [_to_reproducible_float(x) for x in inp[1:-1].split(',')]
3e3c793d3ee53198c4cdb01832062be4f0c02876
4,185
def _estimate_gaussian_covariances_spherical(resp, X, nk, means, reg_covar): """Estimate the spherical variance values. Parameters ---------- responsibilities : array-like of shape (n_samples, n_components) X : array-like of shape (n_samples, n_features) nk : array-like of shape (n_components...
6f08d04528f5e515d5ae75d4dc47753cc4cebc7b
4,186
def map_min(process): """ """ param_dict = {'ignore_nodata': 'bool'} return map_default(process, 'min', 'reduce', param_dict)
33dcc2192fd8b979e7238c1fdbe5e9bec551dd3f
4,189
def geoname_exhaustive_search(request, searchstring): """ List all children of a geoname filtered by a list of featurecodes """ if request.query_params.get('fcode'): fcodes = [ s.upper() for s in request.query_params.get('fcode').split(',')] else: fcodes = [] limit = request.qu...
5a04a158a146e7e0ad3265d89520774b65c3780a
4,190
def count_reads(regions_list, params): """ Count reads from bam within regions (counts position of cutsite to prevent double-counting) """ bam_f = params.bam read_shift = params.read_shift bam_obj = pysam.AlignmentFile(bam_f, "rb") log_q = params.log_q logger = TobiasLogger("", params.verbosity, log_q) #sending...
ffd8cc6afc6c0b5b92d82292ab9d4a54ef918641
4,192
def rgbImage2grayVector(img): """ Turns a row and column rgb image into a 1D grayscale vector """ gray = [] for row_index in range(0, len(img)): for pixel_index, pixel in enumerate(img[row_index]): gray.append(rgbPixel2grayscaleValue(pixel)) return gray
a93bbb2dfa29cb3d4013334226e77f6beb526a13
4,193
def compute_MSE(predicted, observed): """ predicted is scalar and observed as array""" if len(observed) == 0: return 0 err = 0 for o in observed: err += (predicted - o)**2/predicted return err/len(observed)
e2cc326dde2ece551f78cd842d1bf44707bfb6db
4,194
def log_sum(log_u): """Compute `log(sum(exp(log_u)))`""" if len(log_u) == 0: return NEG_INF maxi = np.argmax(log_u) max = log_u[maxi] if max == NEG_INF: return max else: exp = log_u - max np.exp(exp, out = exp) return np.log1p(np.sum(exp[:maxi]) + np.sum(...
f2c7917bc806dc7ec3fbbb1404725f590a82e194
4,195
def special_value_sub(lhs, rhs): """ Subtraction between special values or between special values and numbers """ if is_nan(lhs): return FP_QNaN(lhs.precision) elif is_nan(rhs): return FP_QNaN(rhs.precision) elif (is_plus_infty(lhs) and is_plus_infty(rhs)) or \ (is_minus...
df64cf6c306c3192ba28d08e878add7ce0f27a2c
4,197
def parse_git_repo(git_repo): """Parse a git repository URL. git-clone(1) lists these as examples of supported URLs: - ssh://[user@]host.xz[:port]/path/to/repo.git/ - git://host.xz[:port]/path/to/repo.git/ - http[s]://host.xz[:port]/path/to/repo.git/ - ftp[s]://host.xz[:port]/path/to/repo.git/...
5eddf3aa9016996fb8aa1720b506c2f86b2e9c14
4,198
def make_wavefunction_list(circuit, include_initial_wavefunction=True): """ simulate the circuit, keeping track of the state vectors at ench step""" wavefunctions = [] simulator = cirq.Simulator() for i, step in enumerate(simulator.simulate_moment_steps(circuit)): wavefunction_scrambled = step....
af33d4a7be58ccfa7737deb289cbf5d581246e86
4,199
def if_else(cond, a, b): """Work around Python 2.4 """ if cond: return a else: return b
4b11328dd20fbb1ca663f272ac8feae15a8b26d9
4,200
def _update_machine_metadata(esh_driver, esh_machine, data={}): """ NOTE: This will NOT WORK for TAGS until openstack allows JSONArrays as values for metadata! """ if not hasattr(esh_driver._connection, 'ex_set_image_metadata'): logger.info( "EshDriver %s does not have function '...
2733a809ac8ca7d092001d2ce86a9597ef7c8860
4,201
from datetime import datetime def timedelta_to_time(data: pd.Series) -> pd.Series: """Convert ``datetime.timedelta`` data in a series ``datetime.time`` data. Parameters ---------- data : :class:`~pandas.Series` series with data as :class:`datetime.timedelta` Returns ------- :cla...
d660e7fea7e9e97ae388f3968d776d9d08930beb
4,202
def nms(boxes, scores, iou_thresh, max_output_size): """ Input: boxes: (N,4,2) [x,y] scores: (N) Return: nms_mask: (N) """ box_num = len(boxes) output_size = min(max_output_size, box_num) sorted_indices = sorted(range(len(scores)), key=lambda k: -scores[k]) select...
c6fe28e44d4e4375af39c22edd440e8cdff44917
4,203
def get_db(): """Connect to the application's configured database. The connection is unique for each request and will be reused if this is called again """ if 'db' not in g: g.db = pymysql.connect( host='localhost', port=3306, user='root', password='', database='qm', charset='utf8' ) return...
8a8ce077f98e1e6927c6578e7eff82e183cea829
4,204
def read_stb(library, session): """Reads a status byte of the service request. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :return: Service request status byte. """ status = ViUInt16() library.viReadSTB(session, byref(status)) ...
96d74ae6909371f2349cc875bd5b893d41d550f8
4,205
def one_particle_quasilocal(sp, chli, chlo, Es=None): """ Calculate the one-particle irreducible T-matrix T(1). Parameters ---------- s : Setup Setup object describing the setup chi : int Input schannel cho : int Output channel Es : ndarray List of partic...
089204f48c9decb3bf58e909ec46e7ffb844ebf1
4,207
from typing import List def get_spilled_samples(spills: List, train_dataset: Dataset): """ Returns the actual data that was spilled. Notice that it returns everything that the __getitem__ returns ie. data and labels and potentially other stuff. This is done to be more general, not just work with d...
04414e59ed43b6068188bc3bb0042c4278bd3124
4,209
from typing import List from pathlib import Path import logging def reshard( inputs: List[Path], output: Path, tmp: Path = None, free_original: bool = False, rm_original: bool = False, ) -> Path: """Read the given files and concatenate them to the output file. Can remove original files on...
8c90c2d0e42d4e6d1bbb59d541284450d59f0cd1
4,210
def on_intent(intent_request, session): """ Called when the user specifies an intent for this skill """ print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) intent = intent_request['intent'] intent_name = intent_request['intent']['name'] # Dispatch t...
040c0d80802503768969859a9fe6ccef8c9fdf06
4,211
def load_twitter(path, shuffle=True, rnd=1): """ load text files from twitter data :param path: path of the root directory of the data :param subset: what data will be loaded, train or test or all :param shuffle: :param rnd: random seed value :param vct: vectorizer :return: :raise ValueE...
863f39faef6f4175dc18d076c3c9601d09331523
4,212
def parse_vtables(f): """ Parse a given file f and constructs or extend the vtable function dicts of the module specified in f. :param f: file containing a description of the vtables in a module (*_vtables.txt file) :return: the object representing the module specified in f """ marx_module = Mod...
01786447982c15b55ee1411afe71990a1752dec3
4,213
import datasets def getCifar10Dataset(root, isTrain=True): """Cifar-10 Dataset""" normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) if isTrain: trans = transforms.Compose([ transforms.RandomHorizontalFlip(), tra...
b5c103838e4c46c445e39526b61bb9c8fa3832ee
4,214
import pyclesperanto_prototype as cle def histogram(layer, num_bins : int = 256, minimum = None, maximum = None, use_cle=True): """ This function determines a histogram for a layer and caches it within the metadata of the layer. If the same histogram is requested, it will be taken from the cache. :ret...
65197010bfaec66a58798772e61f4e1640b7ea89
4,215
import re def get_tbl_type(num_tbl, num_cols, len_tr, content_tbl): """ obtain table type based on table features """ count_very_common = len([i for i, x in enumerate(content_tbl) if re.match(r'^very common',x) ]) count_common = len([i for i, x in enumerate(content_tbl) if re.match(r'^common',x) ]) count...
19c06766c932aab4385fa8b7b8cd3c56a2294c65
4,216
def decode_EAN13(codes): """ คืนสตริงของเลขที่ได้จากการถอดรหัสจากสตริง 0/1 ที่เก็บใน codes แบบ EAN-13 ถ้าเกิดกรณีต่อไปนี้ ให้คืนสตริงว่าง (สาเหตุเหล่านี้มักมาจากเครื่องอ่านบาร์โค้ดอ่านรหัส 0 และ 1 มาผิด) codes เก็บจำนวนบิต หรือรูปแบบไม่ตรงข้อกำหนด รหัสบางส่วนแปลงเป็นตัวเลขไม่ได้ เลขหลักที่ 13...
2f65b488c61cbafae0c441d68f01e261141569dd
4,217
def GiveNewT2C(Hc, T2C): """ The main routine, which computes T2C that diagonalized Hc, and is close to the previous T2C transformation, if possible, and it makes the new orbitals Y_i = \sum_m T2C[i,m] Y_{lm} real, if possible. """ ee = linalg.eigh(Hc) Es = ee[0] Us0= ee[1] Us = matrix(e...
d4ba72e57079ab18f7e29b9d1b2ce68f2c112fb4
4,218
import unicodedata def normalize(form, text): """Return the normal form form for the Unicode string unistr. Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'. """ return unicodedata.normalize(form, text)
6d32604a951bb13ff649fd3e221c2e9b35d4f1a1
4,219
def handle_internal_validation_error(error): """ Error handler to use when a InternalValidationError is raised. Alert message can be modified here as needed. :param error: The error that is handled. :return: an error view """ alert_message = format_alert_message(error.__class__.__name__...
996552cf26b01f5a4fd435a604fe1428669804bd
4,220
def bbox_encode(bboxes, targets): """ :param bboxes: bboxes :param targets: target ground truth boxes :return: deltas """ bw = bboxes[:, 2] - bboxes[:, 0] + 1.0 bh = bboxes[:, 3] - bboxes[:, 1] + 1.0 bx = bboxes[:, 0] + 0.5 * bw by = bboxes[:, 1] + 0.5 * bh tw = targets[:, 2] -...
547c098963b9932aa518774e32ca4e42301aa564
4,221
def cipher(text: str, key: str, charset: str = DEFAULT_CHARSET) -> str: """ Cipher given text using Vigenere method. Be aware that different languages use different charsets. Default charset is for english language, if you are using any other you should use a proper dataset. For instance, if you are ci...
ef6ac915f0daf063efbc587b66de014af48fbec6
4,222
def product_delete(product_id): """ Delete product from database """ product_name = product_get_name(product_id) res = False # Delete product from database if product_name: mongo.db.products.delete_one({"_id": (ObjectId(product_id))}) flash( product_name + ...
600a4afa9aab54473cdeb423e12b779672f38186
4,223
def getBoxFolderPathName(annotationDict, newWidth, newHeight): """ getBoxFolderPathName returns the folder name which contains the resized image files for an original image file. Given image 'n02085620_7', you can find the resized images at: 'F:/dogs/images/n02085620-Chihuahua/boxes_64_64/' ...
75d5470373e4c119e7bb8bd327f6d83884680a9d
4,225
def _download_artifact_from_uri(artifact_uri, output_path=None): """ :param artifact_uri: The *absolute* URI of the artifact to download. :param output_path: The local filesystem path to which to download the artifact. If unspecified, a local output path will be created. """ ...
219c4be3cd41741e6e93a1ca46696284c9ae1b80
4,226
import json def api_get_project_members(request, key=None, hproPk=True): """Return the list of project members""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: if not settings.PIAPI_REALUSERS: users = [generate_user(pk=...
653a60fccf7e81231790e4d00a1887c660f5ad4f
4,227
import re def clean_weight(v): """Clean the weight variable Args: v (pd.Series): Series containing all weight values Returns: v (pd.Series): Series containing all cleaned weight values """ # Filter out erroneous non-float values indices = v.astype(str).apply( lamb...
7bcfb05fdb765ad0cc7a6b3af48f8b6cfa2f709b
4,230
def get_yield(category): """ Get the primitive yield node of a syntactic category. """ if isinstance(category, PrimitiveCategory): return category elif isinstance(category, FunctionalCategory): return get_yield(category.res()) else: raise ValueError("unknown category type with instance %r" % cat...
54fbbc67ea70b7b194f6abd2fd1286f7cd27b1f2
4,231
def box(type_): """Create a non-iterable box type for an object. Parameters ---------- type_ : type The type to create a box for. Returns ------- box : type A type to box values of type ``type_``. """ class c(object): __slots__ = 'value', def __init...
5b4721ab78ce17f9eeb93abcc59bed046917d296
4,232
def rssError(yArr, yHatArr): """ Desc: 计算分析预测误差的大小 Args: yArr:真实的目标变量 yHatArr:预测得到的估计值 Returns: 计算真实值和估计值得到的值的平方和作为最后的返回值 """ return ((yArr - yHatArr) ** 2).sum()
429dd6b20c20e6559ce7d4e57deaea58a664d22b
4,233
def initialize_vocabulary(vocabulary_file): """ Initialize vocabulary from file. :param vocabulary_file: file containing vocabulary. :return: vocabulary and reversed vocabulary """ if gfile.Exists(vocabulary_file): rev_vocab = [] with gfile.GFile(vocabulary_file, mode="rb") as f:...
fcfbed41c5d1e34fcdcc998f52301bff0e1d5dd8
4,234
def mock_create_draft(mocker): """Mock the createDraft OpenAPI. Arguments: mocker: The mocker fixture. Returns: The patched mocker and response data. """ response_data = {"draftNumber": 1} return ( mocker.patch( f"{gas.__name__}.Client.open_api_do", return_...
43f5fdc7991eefbf965662ccd0fadaa5015c2e00
4,235
import tqdm def to_csv(data_path="data"): """Transform data and save as CSV. Args: data_path (str, optional): Path to dir holding JSON dumps. Defaults to "data". save_path (str, optional): Path to save transformed CSV. Defaults to "data_transformed.csv". """ elements = [] for dat...
a6a28c4d2e1e1dfad9b7286e49289d012de0a9b4
4,236
def get_language_file_path(language): """ :param language: string :return: string: path to where the language file lies """ return "{lang}/localization_{lang}.json".format(lang=language)
9be9ee9511e0c82772ab73d17f689c181d63e67c
4,238
def evaluate(expn): """ Evaluate a simple mathematical expression. @rtype: C{Decimal} """ try: result, err = CalcGrammar(expn).apply('expn') return result except ParseError: raise SyntaxError(u'Could not evaluate the provided mathematical expression')
94518c3a225f62540e045336f230a5fb2d99dcaf
4,242
from typing import Optional def get_user(is_external: Optional[bool] = None, name: Optional[str] = None, username: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetUserResult: """ Use this data source to retrieve information about a Ranch...
c15a13e6a0633bc46fd1bdc8a3d914bfbd1d6b34
4,244
import random def randbytes(size) -> bytes: """Custom implementation of random.randbytes, since that's a Python 3.9 feature """ return bytes(random.sample(list(range(0, 255)), size))
0ea312376de3f90894befb29ec99d86cfc861910
4,245
def path_to_model(path): """Return model name from path.""" epoch = str(path).split("phase")[-1] model = str(path).split("_dir/")[0].split("/")[-1] return f"{model}_epoch{epoch}"
78b10c8fb6f9821e6be6564738d40f822e675cb6
4,246
def _cpp_het_stat(amplitude_distribution, t_stop, rates, t_start=0.*pq.ms): """ Generate a Compound Poisson Process (CPP) with amplitude distribution A and heterogeneous firing rates r=r[0], r[1], ..., r[-1]. Parameters ---------- amplitude_distribution : np.ndarray CPP's amplitude dist...
fd62c73f5ef6464d61b96ebf69b868f12245c305
4,247
def validate_uncles(state, block): """Validate the uncles of this block.""" # Make sure hash matches up if utils.sha3(rlp.encode(block.uncles)) != block.header.uncles_hash: raise VerificationFailed("Uncle hash mismatch") # Enforce maximum number of uncles if len(block.uncles) > state.config[...
5a0d51caae5ca42a31644316008cd949862713cb
4,248
def quote_index(q_t,tr_t): """Get start and end index of quote times in `q_t` with the same timestamp as trade times in `tr_t`.""" left, right = get_ind(q_t,tr_t) right[left<right] -=1 # last quote cannot be traded on, so shift index left -=1 # consider last quote from before the timestamp of the trad...
2de223b3d08e99113db56c8e9522a1d0066c76b7
4,249
def calculate_learning_curves_train_test(K, y, train_indices, test_indices, sampled_order_train, tau, stop_t=None): """Calculate learning curves (train, test) from running herding algorithm Using the sampled order from the sampled_order indexing array calculate the ...
d7bf3484e95d7e97eac4ba8b68b485e634b2f7f2
4,250
def removeString2(string, removeLen): """骚操作 直接使用字符串替换""" alphaNums = [] for c in string: if c not in alphaNums: alphaNums.append(c) while True: preLength = len(string) for c in alphaNums: replaceStr = c * removeLen string = string.replace(rep...
57d01d7c2a244b62a173fef35fd0acf1b622beed
4,251
from typing import Union from datetime import datetime import hashlib def process_filing(client, file_path: str, filing_buffer: Union[str, bytes] = None, store_raw: bool = False, store_text: bool = False): """ Process a filing from a path or filing buffer. :param file_path: path to proc...
aafbe010615b6aeb1a21760a43a9680fa9c2a37f
4,252
def _get_anchor_negative_triplet_mask(labels): """Return a 2D mask where mask[a, n] is True iff a and n have distinct labels. Args: labels: tf.int32 `Tensor` with shape [batch_size] Returns: mask: tf.bool `Tensor` with shape [batch_size, batch_size] """ # Check if labels[i] != labels...
4c67bcc4e17e091c039c72a1324f501226561557
4,254
def random_k_edge_connected_graph(size, k, p=.1, rng=None): """ Super hacky way of getting a random k-connected graph Example: >>> from graphid import util >>> size, k, p = 25, 3, .1 >>> rng = util.ensure_rng(0) >>> gs = [] >>> for x in range(4): >>> G = ...
98609e31790fc40229135f3a2c0dedd2eb123e9b
4,255
from typing import Optional from typing import Dict from typing import Any from typing import FrozenSet import json def _SendGerritJsonRequest( host: str, path: str, reqtype: str = 'GET', headers: Optional[Dict[str, str]] = None, body: Any = None, accept_statuses: FrozenSet[int] = frozenset([2...
81bd115083c1d8ae4a705270394cf43ca1918862
4,257
def readTableRules(p4info_helper, sw, table): """ Reads the table entries from all tables on the switch. :param p4info_helper: the P4Info helper :param sw: the switch connection """ print '\n----- Reading tables rules for %s -----' % sw.name ReadTableEntries1 = {'table_entries': []} Read...
267bb6dcdf2d3adf37bcfa62f8d4581d9a9deda7
4,258
def binary_to_string(bin_string: str): """ >>> binary_to_string("01100001") 'a' >>> binary_to_string("a") Traceback (most recent call last): ... ValueError: bukan bilangan biner >>> binary_to_string("") Traceback (most recent call last): ... ValueError: tidak ada yang diinput...
f22dd64027ee65acd4d782a6a1ce80520f016770
4,260
def load_texture_pair(filename): """Function what loads two verions of the texture for left/right movement""" return [ arcade.load_texture(filename), arcade.load_texture(filename, flipped_horizontally=True) ]
782a79395fe25c8f391877dc9be52bf9d29f63f9
4,262
from typing import Tuple def bytes2bson(val: bytes) -> Tuple[bytes, bytes]: """Encode bytes as BSON Binary / Generic.""" assert isinstance(val, (bytes, bytearray)) return BSON_BINARY, pack_i32(len(val)) + BSON_BINARY_GENERIC + val
2c481d6585c12732f4b26a2c25f5738a5f8352bb
4,263
def tabindex(field, index): """Set the tab index on the filtered field.""" field.field.widget.attrs["tabindex"] = index return field
c42b64b3f94a2a8a35b8b0fa3f14fe6d44b2f755
4,264
def compute_GridData(xvals, yvals, f, ufunc=0, **keyw): """Evaluate a function of 2 variables and store the results in a GridData. Computes a function 'f' of two variables on a rectangular grid using 'tabulate_function', then store the results into a 'GridData' so that it can be plotted. After calcula...
64c95b4ce6e7735869a31eb29e06c6e6c324a844
4,265
import functools from typing import Any import collections def decorator_with_option( decorator_fn, ): """Wraps a decorator to correctly forward decorator options. `decorator_with_option` is applied on decorators. Usage: ``` @jax3d.utils.decorator_with_option def my_decorator(fn, x=None, y=None): ...
2e9a4a772d7c072b579ac49e183d6ca00e9feacf
4,266
import math def chebyshev_parameters(rxn_dstr, a_units='moles'): """ Parses the data string for a reaction in the reactions block for the lines containing the Chebyshevs fitting parameters, then reads the parameters from these lines. :param rxn_dstr: data string for species in reaction bl...
fb1ae476d17a7f6546f99c729139bf55b4834174
4,267
def _gen_matrix(n, *args): """Supports more matrix construction routines. 1. Usual contruction (from a 2d list or a single scalar). 2. From a 1-D array of n*n elements (glsl style). 3. From a list of n-D vectors (glsl style). """ if len(args) == n * n: # initialize with n*n scalars dat...
eea482c20dfa5c30c9077185eba81bc3bd1ba8ce
4,268
import time import math def temperature(analog_pin, power_pin = None, ground_pin = None, R = 20000, n = 100): """Function for computing thermister temperature Parameters ---------- adc_pin: :obj:'pyb.Pin' Any pin connected to an analog to digital converter on a pyboard ...
a526595bcab6e824a82de7ec4d62fbfc12ee39f8
4,269
import json def submit_form(): """ Submits survey data to SQL database. """ if request.method == "POST": data = request.data if data: data = json.loads(data.decode("utf-8").replace("'",'"')) student, enrollments, tracks = processSurveyData(data) insert = '...
2d5a10c5af906a7993559cf71f23eea1a35ec993
4,270
def get_target_external_resource_ids(relationship_type, ctx_instance): """Gets a list of target node ids connected via a relationship to a node. :param relationship_type: A string representing the type of relationship. :param ctx: The Cloudify ctx context. :returns a list of security group ids. ""...
27077d3118ca10a6896ba856d9d261f1b8ab9d56
4,271
def split_multibody(beam, tstep, mb_data_dict, ts): """ split_multibody This functions splits a structure at a certain time step in its different bodies Args: beam (:class:`~sharpy.structure.models.beam.Beam`): structural information of the multibody system tstep (:class:`~sharpy.utils.datas...
25d3d3496bdf0882e732ddfb14d3651d54167adc
4,272
def qname_decode(ptr, message, raw=False): """Read a QNAME from pointer and respect labels.""" def _rec(name): ret = [] while name and name[0] > 0: length = int(name[0]) if (length & 0xC0) == 0xC0: offset = (length & 0x03) << 8 | int(name[1]) ...
d08a6c286e2520807a05cbd2c2aa5eb8ce7a7602
4,273
def coordinates_within_board(n: int, x: int, y: int) -> bool: """Are the given coordinates inside the board?""" return x < n and y < n and x >= 0 and y >= 0
6359343bde0c9d7658a484c45d9cd07893b4e00d
4,274
def hook_name_to_env_name(name, prefix='HOOKS'): """ >>> hook_name_to_env_name('foo.bar_baz') HOOKS_FOO_BAR_BAZ >>> hook_name_to_env_name('foo.bar_baz', 'PREFIX') PREFIX_FOO_BAR_BAZ """ return '_'.join([prefix, name.upper().replace('.', '_')])
b0dabce88da8ddf8695303ac4a22379baa4ddffa
4,276
def get_coefficients(): """ Returns the global scaling dictionary. """ global COEFFICIENTS if COEFFICIENTS is None: COEFFICIENTS = TransformedDict() COEFFICIENTS["[length]"] = 1.0 * u.meter COEFFICIENTS["[mass]"] = 1.0 * u.kilogram COEFFICIENTS["[time]"] = 1.0 * u.yea...
7acd77fdbb0604ff97aa24bb7ce4f29bb32889b0
4,277
def get_distance_from_guide_alignment(data, guide_data, reference_index_key="position", minus_strand=False): """Calculate the distance of input data alignment to the guide alignment. :param data: input data with at least "raw_start", "raw_length", and reference_index_key fields :param guide_data: guide alig...
1a1150a470c75e4e836278fafb263839a67f7da4
4,278
def get_info(font): """ currently wraps the infoFont call, but I would like to add a JSON represenation of this data to better display the individual details of the font.""" return pyfiglet.FigletFont.infoFont(font)
40ae5238701754a12c4b1c75fff54412f7e33d4f
4,279
def readline_skip_comments(f): """ Read a new line while skipping comments. """ l = f.readline().strip() while len(l) > 0 and l[0] == '#': l = f.readline().strip() return l
c4b36af14cc48b1ed4cd72b06845e131015da6c6
4,280
def _verify_weight_parameters(weight_parameters): """Verifies that the format of the input `weight_parameters`. Checks that the input parameters is a 2-tuple of tensors of equal shape. Args: weight_parameters: The parameters to check. Raises: RuntimeError: If the input is not a 2-tuple of tensors wit...
9ec018c66d48e830250fd299cd50f370118132cc
4,281
import requests def send_notification(lira_url, auth_dict, notification): """Send a notification to a given Lira. Args: lira_url (str): A typical Lira url, e.g. https://pipelines.dev.data.humancellatlas.org/ auth_dict (dict): Dictionary contains credentials for authenticating with Lira. ...
1f6c28f9b12458cd2af6c3f12f5a9a6df6e64f49
4,282
from exojax.spec.molinfo import molmass from exojax.utils.constants import kB, m_u def calc_vfactor(atm="H2",LJPparam=None): """ Args: atm: molecule consisting of atmosphere, "H2", "O2", and "N2" LJPparam: Custom Lennard-Jones Potential Parameters (d (cm) and epsilon/kB) Returns: ...
a48fe55216bcf9848eece92d45f03d2c1e3fdee3
4,283
def _crc16_checksum(bytes): """Returns the CRC-16 checksum of bytearray bytes Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html Initial value changed to 0x0000 to match Stellar configuration. """ crc = 0x0000 polynomial = 0x1021 for byte ...
2b00d11f1b451f3b8a4d2f42180f6f68d2fbb615
4,284
from typing import Callable from typing import Dict import select import math def method_get_func(model, fields="__all__", need_user=False, **kwargs)->Callable: """生成一个model的get访问""" async def list(page: Dict[str, int] = Depends(paging_query_depend), user: User = Depends(create_current_act...
2a9b31aa6261d99da94f7a971a9096dfec291e86
4,286
def get_mysqlops_connections(): """ Get a connection to mysqlops for reporting Returns: A mysql connection """ (reporting_host, port, _, _) = get_mysql_connection('mysqlopsdb001') reporting = HostAddr(''.join((reporting_host, ':', str(port)))) return connect_mysql(reporting, 'scriptrw')
25fb3cba8db11d28450e142a35ff763313c4c360
4,287
def reverse(segment): """Reverses the track""" return segment.reverse()
74632b8a8a192970187a89744b2e8c6fa77fb2cf
4,289
def rmse(y, y_pred): """Returns the root mean squared error between ground truths and predictions. """ return np.sqrt(mse(y, y_pred))
c3d2e20d1e9ebf40c704c5f14fb0dd35758f2458
4,290
from typing import Dict from typing import Any def cdm_cluster_location_command(client: PolarisClient, args: Dict[str, Any]): """ Find the CDM GeoLocation of a CDM Cluster. :type client: ``PolarisClient`` :param client: Rubrik Polaris client to use :type args: ``dict`` :param args: arguments...
b0001969177dcceb144d03edece589a84af48dc1
4,291
def prepare_cases(cases, cutoff=25): """ clean cases per day for Rt estimation. """ new_cases = cases.diff() smoothed = new_cases.rolling(7, win_type='gaussian', min_periods=1, center=True).mean(std=2).round(...
71b41959178e6fb8480ba2f6549bfeb6f02aded4
4,292
def utility(board): """ Returns 1 if X has won the game, -1 if O has won, 0 otherwise. """ if winner(board) == 'X': return 1 elif winner(board) == 'O': return -1 else: return 0
77f4e503882a6c1a6445167d2b834f342adbc21e
4,293
def shard(group, num_shards): """Breaks the group apart into num_shards shards. Args: group: a breakdown, perhaps returned from categorize_files. num_shards: The number of shards into which to break down the group. Returns: A list of shards. """ shards = [] for i in range(num_shards): shar...
635af47ac15c5b3aeeec8ab73ea8a6a33cd0d964
4,294
def is_bond_member(yaml, ifname): """Returns True if this interface is a member of a BondEthernet.""" if not "bondethernets" in yaml: return False for _bond, iface in yaml["bondethernets"].items(): if not "interfaces" in iface: continue if ifname in iface["interfaces"]: ...
521186221f2d0135ebcf1edad8c002945a56da26
4,295
def get_id(group): """ Get the GO identifier from a list of GO term properties. Finds the first match to the id pattern. Args: group (List[str]) Returns: str """ return first_match(group, go_id).split(':',1)[1].strip()
de99e159c3de1f8984cce40f952ff14568c8a1a5
4,296
import random import math def generateLogNormalVariate(mu, sigma): """ RV generated using rejection method """ variateGenerated = False while not variateGenerated: u1 = random.uniform(0, 1) u2 = random.uniform(0, 1) x = -1*math.log(u1) if u2 > math.exp(-1*math.pow(...
048bc1c2123fbdd9a750aac86bd6922aaf42de27
4,297
import re def replace_color_codes(text, replacement): """Replace ANSI color sequence from a given string. Args: text (str): Original string to replacement from. replacement (str): String to replace color codes with. Returns: str: Mutated string after the replacement. """ ...
a0c3e1b1060ae475a16b936c237669edab8cfc91
4,298
def get_uti_for_extension(extension): """get UTI for a given file extension""" if not extension: return None # accepts extension with or without leading 0 if extension[0] == ".": extension = extension[1:] if (OS_VER, OS_MAJOR) <= (10, 16): # https://developer.apple.com/doc...
50e147d9fb267d7c4686dd9e53cd3404a9eaae6f
4,299
async def anext(*args): """Retrieve the next item from the async generator by calling its __anext__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopAsyncIteration is raised. """ if len(args) < 1: raise TypeError( f"anext expected at leas...
60f71e2277501b1c274d691cef108937a2492147
4,301
from typing import List def get_service_gateway(client: VirtualNetworkClient = None, compartment_id: str = None, vcn_id: str = None) -> List[RouteTable]: """ Returns a complete, unfiltered list of Service Gateways of a vcn in the compartment. """ ser...
d1635dac2d6e8c64617eb066d114785674e9e8b3
4,303
def get_road_network_data(city='Mumbai'): """ """ data = pd.read_csv("./RoadNetwork/"+city+"/"+city+"_Edgelist.csv") size = data.shape[0] X = np.array(data[['XCoord','YCoord']]) u, v = np.array(data['START_NODE'], dtype=np.int32), np.array(data['END_NODE'], dtype=np.int32) w = np.a...
1d014e50b2d2883b5fda4aba9c2de5ca5e9dae2a
4,304
from apps.jsonapp import JSONApp def main_json(config, in_metadata, out_metadata): """ Alternative main function ------------- This function launches the app using configuration written in two json files: config.json and input_metadata.json. """ # 1. Instantiate and launch the App log...
302ba667a775dd09a6779235a774a4a95f26af32
4,305
def _infection_active(state_old, state_new): """ Parameters ---------- state_old : dict or pd.Series Dictionary or pd.Series with the keys "s", "i", and "r". state_new : dict or pd.Series Same type requirements as for the `state_old` argument in this function apply. Retu...
a81376ee1853d34b1bc23b29b2a3e0f9d8741472
4,306