content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def linear_forward(A, W, b): """ Implement the linear part of a layer's forward propagation. Arguments: A -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current layer, size of previous layer) b ...
db9120f983b20ea67e9806c71b32463f47fe2839
26,568
from typing import Sequence from typing import Match import glob async def mp_force(p: 'Player', m: 'Match', msg: Sequence[str]) -> str: """Force a player into the current match by name.""" if len(msg) != 1: return 'Invalid syntax: !mp force <name>' if not (t := await glob.players.get(name=' '.jo...
58f8d0c8ad0e623973b49792253344cba430b8d5
26,570
def draw_concat(Gs, Zs, reals, NoiseAmp, in_s, mode, opt): """get image at previous scale""" G_z = in_s if Gs: if mode == 'rand': count = 0 for G, Z_opt, real_curr, real_next, noise_amp in zip(Gs, Zs, reals, reals[1:], NoiseAmp): if count == 0: ...
a52db339e6e657148dcf74ef815dd265929f545f
26,571
def read(filename): """ Read TOUGHREACT chemical input file. Parameters ---------- filename : str Input file name. """ with open_file(filename, "r") as f: out = read_buffer(f) return out
acf88a707048bed3f0c59aab3c1f328a5f0d8bf5
26,573
def visit_bottomup(f, d): """Visits and rewrites a nested-dict ``d`` from the bottom to the top, using the ``f`` predicate.""" if isinstance(d, dict): return f({k: visit_bottomup(f, v) for (k, v) in d.items()}) else: return f(d)
9fb4884f1280afe06a1819a44e3055c1173284b1
26,574
def processNonTerminal(nt): """ Finds the rule expansion for a nonterminal and returns its expansion. """ return processRHS(grammar.getRHS(nt))
c938ee877e8b66d9ed9aad6cf3708b5d2241279d
26,576
def get_attributes_as_highlighted_html(rid): """Get column descriptions for a given CSV file. The columns are described in EML attribute elements. """ return { k: dex.util.get_etree_as_highlighted_html(v) for k, v in get_attributes_as_etree(rid).items() }
0e19ccca6d09b6cdaac9361a02c5e38e84ae9190
26,577
import timeit import multiprocessing import itertools def bound_update(unary,X,kernel,bound_lambda,bound_iteration =20, batch = False, manual_parallel =False): """ Here in this code, Q refers to Z in our paper. """ start_time = timeit.default_timer() print("Inside Bound Update . . .") N,K...
c5b1be8fb881d2b2bb8596843747441c5e6ca99a
26,578
from typing import List def get_walkable_field_names(model: Model, field_types: List[Field] = None) -> List[str]: """Get a list with names of all fields that can be walked""" if field_types is None: field_types = [ManyToManyField, ManyToOneRel] fields_to_walk = [] fields = getattr(model, '_met...
0ef53ce31072913861e6e78a22eb387b2e185ca8
26,579
def normalize(email): """ Returns a NormalizedEmail with the appropriate contents """ try: v = validate_email(email) return NormalizedEmail(v['email']) except EmailNotValidError as e: return NormalizedEmail(str(e), error=True)
4379966f68810b22c06b81597b706454f46a8247
26,580
def valid_flavor_list(): """ this includes at least 'BIAS', 'LIGHT' based on forDK.tar.gz samples capitalization inconsistent in forDK.tar.gz samples need to keep an eye out for additional valid flavors to add """ # not sure how to deal with reduced image flavors that I've invented: # R...
b12451ff4725f5fcea3592373ef6e53cbe04b23c
26,581
from pathlib import Path async def show_tile_with_body( request: Request, response: Response, body: TileRequest, path: Path = Depends(imagepath_parameter), extension: OutputExtension = Depends(extension_path_parameter), headers: ImageRequestHeaders = Depends(), config: Settings = Depends(get_s...
6f6767f4831496796e2cf622a0362fab11dee844
26,583
def create_mesh(ob_name, coords, edges=[], faces=[]): """Create point cloud object based on given coordinates and name. Keyword arguments: ob_name -- new object name coords -- float triplets eg: [(-1.0, 1.0, 0.0), (-1.0, -1.0, 0.0)] """ # Create new mesh and a new object me = bpy.data.mesh...
b57baf08c2a2b07516e36e741b2aa55054883bf8
26,584
def get_time_from_datetime(data): """ Returns a timedelta64 series the form "hh:mm:ss" from data, being a datetime64 series """ time = data.apply(lambda x: np.timedelta64(x.hour, 'h') + np.timedelta64(x.minute, 'm') + np.timedelta64(x.second, 's')) return time
d7af50beadbb426d7b1d0671cabf16546707a1b6
26,585
def tokenize(text): """Converts text to tokens. Case-folds, removes stop words, lemmatises text. This is the same tokenization as is done on the training data for the model. """ # Set up dict for lemmatisation tag_map = defaultdict(lambda : "n") # by default, assume nouns tag_map['J'] = "a" #...
d7c6a124d13bd2d0360a22edc24a4d079bb9d93b
26,587
def do_command(client, command, indices, params=None): """ Do the command. """ if command == "alias": return alias( client, indices, alias=params['name'], remove=params['remove'] ) if command == "allocation": return allocation(client, indices, rule=para...
e33325a941ee4ed7e50c90cc8fb1067abe377d52
26,588
def filetostr(filename): """ filetostr """ try: with open(filename, "rb") as stream: return stream.read() except: return None
52683ada0008fb22e1c48301adf3fd7c48c21d06
26,589
def valid_for(days): """Return a text saying for how many days the certificate is valid for or years if it spans over years.""" delta = timedelta(days=days) value = '' if delta.days / 365 > 1: value += '%d years' % (delta.days / 365) else: value += '%d days' % delta.days retu...
fe26213d17477602a8c9dc60ed3fe62297df5390
26,590
def vcr_config() -> dict: """VCR config that adds a custom before_record_request callback.""" nessie_test_config.cleanup = False return { "before_record_request": before_record_cb, }
8b61e1c825e1470571445e60da8880fa8dbaa14b
26,592
import mimetypes import binascii def main(): # pylint: disable=R0914,R0912,R0915 """The main method""" images = {} materials = {} meshes = {} objects = {} groups = {} texts = {} # Set up our FileDescription fileid = FileId(filename = bpy.path.abspath(bpy.data.filepath)) file_d...
66494f7904c956f67614cb159c346ad3b0e5283b
26,593
import random def get_best(get_fitness, optimalFitness, geneSet, display, show_ion, target, parent_candidates, seed=None, hull=None, simplex=None, verbose=0, hull_bounds=[0, 1], inner_search=True, parent_cap=25, mutation_cap=1000): """ the primary public function of the ...
5ebc9757b4518eabf2968bda9dc6cabd10e5cdb1
26,594
from datetime import datetime def generate_info_endpoint_reply(request): """ This just returns a hardcoded introspection string. """ available_api_versions = {} for ver in optimade_supported_versions: available_api_versions[optimade_supported_versions[ver]] = request['baseurl'] + ver ...
93e0b818c95742d0b7db679e0b3d3ade034cc0e8
26,595
def M(s,o): """ M - s - array of predictions (or simulated) o - array of observations (or targets) """ s,o = np.array(s),np.array(o) return np.nansum( np.abs( np.divide(s-o,o) ))/len(o)
5c53c8b02c88a37204f478d71fb74f2536848af0
26,596
def check_link_exist(destination: str): """Check if link already exists and return otherwise return None""" session: Session = db_session.create_session() result = session.execute( f"SELECT short_link FROM links WHERE destination = '{destination}'", ) # fix possible SQL injection for row i...
57f27da14c4ee551f6eb1e9424cd2b446658ae2f
26,597
from communities.models import Community def smart_404(request): """Returns a 404 message that tries to help the user.""" base_url = settings.HOST_URL not_found = { 'type': None, 'redirect_url': base_url } path_arguments = request.path.split('/')[1:] if path_arguments and ...
62252efb658054b88933109ce7b162cd43962186
26,598
def get_basemap(): """ Use cached copy of basemap from the script's parent folder otherwise download basemap from imgur """ url = "https://i.imgur.com/yIVogZH.png" image = "basemap.png" location = PATH + image print(location) try: basemap = cbook.get_sample_data(location) ...
b1d8267da582206c60006268b5a576cabbe30d28
26,599
def pairs_to_annotations(annotation_pairs): """ Convert an array of annotations pairs to annotation array. :param annotation_pairs: list(AnnotationPair) - annotations :return: list(Annotation) """ annotations = [] for ap in annotation_pairs: if ap.ann1 is not None: annota...
b0e08889f541b14d596616d08b366f59b7f8ddd3
26,600
def sanitize_param(value, valid_characters=valid_chars, character_map=mapped_chars, invalid_character='X'): """Clean incoming parameters (strings or lists)""" if isinstance(value, string_types): return sanitize_text(value, valid_characters=valid_characters, character_map=character_map, invalid_character...
e3ed0d1a62bdbff0c2b3a204836d4d3afe467ced
26,601
def default_meta(inherit=True): """Initialize default meta for particular plugin. Default Meta is inherited by all children comparing to Meta which is unique per plugin. :param inherit: Whatever to copy parents default meta """ def decorator(plugin): plugin._default_meta_init(inherit)...
174b37f389160c007e7a609a78b5071031970004
26,602
def get_default_database_name(): """ gets default database name. :rtype: str """ return get_component(DatabasePackage.COMPONENT_NAME).get_default_database_name()
23bf228a284b5880a5155beced606ef4d6f81d16
26,603
def npm_local_packages(): """ Get list of local packages :return: a tuple of dicts """ local_dependencies = {} local_dev_dependencies = {} package_json = get_package_json() for name, version in package_json.get("dependencies", {}).items(): match = LOCAL_PACKAGE.match(version) ...
cb9f52bb97f402b00e3dac0c6a69332f2199ccd5
26,604
def lagrangian_descriptor(u, v, p_value = 0.5): """ Vector field equation for Lagrangian descriptor. Parameters ---------- v : ndarray, shape(n,2) Vector field at given point. p_value : float, optional Exponent in Lagrangian descriptor definition. 0 is the a...
ddd6bb7fb8538b6d44f2507e7b065cbe70338c39
26,605
def xymatch(x1, y1, x2, y2, tol=None, nnearest=1): """Fast cross-matching of xy coordinates: from https://gist.github.com/eteq/4599814""" x1 = np.array(x1, copy=False) y1 = np.array(y1, copy=False) x2 = np.array(x2, copy=False) y2 = np.array(y2, copy=False) if x1.shape != y1.shape: rais...
0c81add24308fdbe90144776fb4b72e9801ddd11
26,606
def get_infection_probas_mean_field(probas, transmissions): """ - probas[i,s] = P_s^i(t) - transmissions = csr sparse matrix of i, j, lambda_ij(t) - infection_probas[i] = sum_j lambda_ij P_I^j(t) """ infection_probas = transmissions.dot(probas[:, 1]) return infection_probas
70d5585b405bdff54f65bced166dead6ae45d26b
26,607
import time import ast def eval_task(algo, specific_testsets, measures, head_items, crossfold_index, save_path=None, load_path=None, uid_plus_iid_to_row=None): """ Evaluate on specific testsets. This function exists to make testset evaluation easier to parallelize. """ ret = [] if load_path an...
4f5171ea4473505237b2c353e164ba4b78d07357
26,608
def newton(RJ, x0, verbose = False, rtol = 1.0e-6, atol = 1.0e-10, miter = 50, linesearch = 'none', bt_tau = 0.5, bt_c = 1.0e-4): """ Manually-code newton-raphson so that I can output convergence info, if requested. Parameters: RJ function return the residual + jacobian x0 ...
b6baa3288c6f417ca4ec7284237ea35d4f2442dd
26,609
from typing import List from pathlib import Path def gen_oltp_trace( tpcc_weight: str, tpcc_rates: List[int], pattern_iter: int) -> bool: """ Generates the trace by running OLTP TPCC benchmark on the built database :param tpcc_weight: Weight for the TPCC workload :param tpcc_rates: Arrival ra...
8ac09fd8f85d7c83944759829775c3dbb1b0741e
26,610
def plot_hmesh(mesh, box=None, proj='pc', figsize=[9,4.5], title=None, do_save=None, do_lsmask='fesom', color_lsmask=[0.6, 0.6, 0.6], linecolor='k', linewidth=0.2, linealpha=0.75, pos_extend=None,): """ ---> plot FESOM2 horizontal mesh: ___INPUT:_____________________________...
9a921224440f359c33686822411b928ebd939550
26,611
def _get_feature_proportion(features_percentage: int, indices_number: int) -> int: """ Computes a number of features based on the given percentage. """ assert (isinstance(features_percentage, int) and 0 <= features_percentage <= 100 and isinstance(indi...
78a5d5515b479b20fcfbbf25cdd2339f0bc8b99f
26,612
def orthoProjectionMatrix(left, right, bottom, top, nearClip=0.01, farClip=100., out=None, dtype=None): """Compute an orthographic projection matrix with provided frustum parameters. Parameters ---------- left : float Left clipping plane coordinate. right : flo...
f1b80b8eeda514ff02142ffe6dcdd761cd789e73
26,613
def get_nsnames(zone): """Get list of nameservers names to query""" if Prefs.NO_NSSET: if not Prefs.ADDITIONAL: print("ERROR: -n requires specifying -a") usage() return Prefs.ADDITIONAL answers = dns.resolver.resolve(zone, 'NS', 'IN') return Prefs.ADDITIONAL + s...
1c5da972922afc0724144545a57bc1d01012dd11
26,614
def pbmcs_10x_cite_seq( save_path: str = "data/", protein_join: str = "inner", run_setup_anndata: bool = True, ) -> anndata.AnnData: """ Filtered PBMCs from 10x Genomics profiled with RNA and protein. Datasets were filtered for doublets and other outliers as in https://github.com/YosefLab/t...
eccb235496b6c466ffd2e234ab6b20487c7cf233
26,615
def binom(n, k): """Binomial coefficients for :math:`n choose k` :param n,k: non-negative integers :complexity: O(k) """ prod = 1 for i in range(k): prod = (prod * (n - i)) // (i + 1) return prod
73e06e4c312f6634d9a97914f330ade845a9ce00
26,616
def get_not_found_swagger_schema(): """ """ class NotFoundResponseModel(Schema): """ """ type = "object" properties = { "message": { "type": "string", } } return NotFoundResponseModel
c1ac8c85224c2e885ade68593a1d250af09a465b
26,618
def find_project(testrun_url): """ Find a project name from this Polarion testrun URL. :param testrun_url: Polarion test run URL :returns: project name eg "CEPH" or "ContainerNativeStorage" """ url_suffix = testrun_url[59:] index = url_suffix.index('/') return url_suffix[:index]
a19019846fa084398a4967cb99417e7aebc90499
26,619
def c2ip(c2, uname): """ return complete ip address for c2 with substituted username """ return c2['ip_address'].replace('USER', uname)
c6f79b2330e78c8ebc85a3fb99ce1c5be407f158
26,620
def beacon(config): """ Watch the configured directories Example Config .. code-block:: yaml beacons: watchdog: - directories: /path/to/dir: mask: - create - modify - delete ...
5981f150276c2f9b9512c33864de02b0ce37094e
26,621
import json def scenario(request): """ Retrieve the parameters and nodes for a scenario Parameters: model_uuid (uuid): required scenario_id (int): required Returns: HttpResponse Example: GET: /component/scenario/ """ model_uuid = request.GET['model_uuid'] scenario_id = ...
795bad706c97c20b566d9fcc999b7e01b0b79194
26,622
def already_voted(replied: str, user_id: str, db: dataset.Database) -> bool: """Search in the database for an existing vote of the user on the replied message Args: replied: id of the message which the vote is a reply user_id: id of the user who's voting Returns: The return value. ...
89ec426df156776ab4a494f0dab0079881b45db2
26,623
def create_bi_sequence_embedding(inputs, seq_lengths, repr_dim, vocab_size, emb_name, rnn_scope, reuse_scope=False): """ Bidirectional encoding :param inputs: tensor [d1, ... ,dn] of int32 symbols :param seq_lengths: [s1, ..., sn] lengths of instances in the batch :param repr_dim: dimension of embed...
1f160100745801ac4baf3d82d8ee7b76900c0547
26,624
import mmap async def input_checker(user_guess: str) -> bool: """Check if the user's input is actually a word. Method for checking if input is in text file: https://stackoverflow.com/a/4944929""" if len(user_guess) != 5: valid = False else: with open(wordfile_path, encoding='utf-8', ...
60ffad6529b1a7b6d68309cc9804ff6e39e2e539
26,625
def computeBasisFunctionsReferenceElement(edge_orientation, face_orientation, Nord, points): """Compute the basis function for the reference element. :param ndarray edges_orientation: orientation for edges :param ndarray faces_orientation: orientation for faces :param int Nord: polynomial order of nede...
10579b5b6af4d5d270faf043186197c345a593d2
26,627
def t_returns(inv, pfl, prices, date): """ Computes the total return of a portfolio. Parameters: - `inv` : :class:`list` investment session `db` row - `pfl` : :class:`string` name of the portfolio - `prices` : :class:`dict` latest investment's ticker prices - `date` ...
8a928e0806b0e87d2a0539ff905112ad0d3d66ae
26,630
def center_crop_pad(img, buffer=0, min_mean=10): """dynamically center crop image, cropping away black space left and right""" g = np.array(img).mean(-1) h, w = g.shape zeros = g.mean(0) zero_inds = np.where(zeros < min_mean)[0] lo, hi = zero_inds[zero_inds < w // 2].max(), zero_inds[zero_inds >...
97326539464826441f283303e21a17b6ae2954d6
26,631
def DiagPart(a): """ Diag op that returns only the diagonal elements. """ return np.diagonal(a),
4993f7034042303926f94f3dae28d7d8f8dc5058
26,633
def _ensure_webhook_access(func): """Decorate WS function to ensure user owns the webhook ID.""" @callback @wraps(func) def with_webhook_access(hass, connection, msg): # Validate that the webhook ID is registered to the user of the websocket connection config_entry = hass.data[DOMAIN][D...
c1b64e5f435f79e52e8c69788b4354481d2a6f5b
26,635
import copy def episode_to_examples(episode, histsz): """Converts an episode (list of Parleys) into self-feeding compatible examples WARNING: we no longer require a histz when making a self-feeding file. Shortening of the history is typically done in the teacher file or in interactive mode. """ e...
a95abd0183dc70e195312d82117b16720d2c4353
26,636
import torch def camera_from_polyhedron(polyhedronFcn, camera_distance=1, to_spherical=False, device='cuda:0'): """ Returns the positions of a camera lying on the vertices of a given polyhedron Parameters ---------- polyhedronFcn : callable the polyhedron creation function camera_dist...
30c782b616299c101cc7130703563fae1327d364
26,637
def cifar10(args, dataset_paths): """ Loads the CIFAR-10 dataset. Returns: train/valid/test set split dataloaders. """ transf = { 'train': transforms.Compose([ transforms.RandomHorizontalFlip(0.5), transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.pad...
867d3a6e7ff4ed72c02583c2eafab2885218c0ad
26,638
def read_words(file="words.txt"): """ Reads a list of words from a file. There needs to be one word per line, for this to work properly. Args: file: the file to read from Returns: An array of all the words in the file """ with open(file, "r") as f: return f.read()....
d3d82c4f9afc7db73b4f82f4715cab9b2e99973c
26,640
def get_intersphinx_label(is_map, cur_project_dir): """ The top set of keys in the intersphinx map are shortname labels that intersphinx uses to identify different projects A sub-tuple in the dict (here invdata[1]) is a list of possible locations for the project's objects.inv file This utility checks a...
87115f45c966b838566d6909d3a66af5359a2a1d
26,641
async def patch_user(user: User): """update a `user` in the list of users""" try: session = Session() selected_user = session.query( UserTable ).filter( UserTable.key == user.key ).first() selected_user.firstname = user.firstname selected_u...
911b2c3f5f5e5c2ec7aa7be7595b5106ccf17b0d
26,642
import torchvision def get_test_dataloader(mean, std, batch_size=16, num_workers=2, shuffle=True,task="cifar100",train=False): """ return training dataloader Args: mean: mean of cifar100 test dataset std: std of cifar100 test dataset path: path to cifar100 test python dataset b...
402e119430a3d260e0e15238e6f55b91f929848a
26,643
from typing import Set def get(tags: Set[str]): """ get options marked by `tags` Options tagged by wildcard '*' are always returned """ # use specifically tagged options + those tagged with wildcard * return (o for tag in ('*',) + tuple(tags) for o in _options[tag])
164e808c5dcd76febad488b8fb5bf0b76835ec2a
26,644
def jitter_boxes(boxes, noise_scale=0.025): """Jitter the box coordinates by some noise distribution. Args: boxes: a tensor whose last dimension is 4 representing the coordinates of boxes in ymin, xmin, ymax, xmax order. noise_scale: a python float which specifies the magnitude of noise. The ru...
e0ac4b003b77190390f397f3ef80a915ca5214d3
26,645
def soil_props(soil_type, depth): """ Parameters c, Ks, n, Beta, s_h, s_w, s_bal, s_fc, bulk_d: Laio et al., 2001, Plants in water-controlled ecosystems: active role in hydrologic processes and response to water stress: II. Probabilistic soil moisture dynamic Parameters p1 through p5: Ezlit et al.,...
a6d421d5606d4a00e6a621a513939af8ce2ad62c
26,646
from typing import List def DoMeshesBelongToSameMainMesh(list_mesh_identifiers: List[str]) -> bool: """checks whether all meshes given a list of mesh identifiers belong to the same main mesh Throws if an mesh identifier does not belong to a mesh """ main_mesh_identifiers = [] for mesh_identifier i...
2e8e47c0b5bf4e6d67adf5a0a46a35bacba42bce
26,647
def active_roles(account, days_back): """ Returns query for finding active roles (since days_back value). """ query_string = f"""SELECT DISTINCT useridentity.sessioncontext.sessionissuer.arn FROM behold WHERE account = '{account}' AND useridentity.type = 'AssumedRole' AND from_is...
e6842696aa40d4f0b30f17d0d53afdcc5d1d0de9
26,650
import asyncio async def run_command(*args, **kwargs): """Shortcut for asyncronous running of a command""" fn = asyncio.subprocess.create_subprocess_exec if kwargs.pop("shell", False): fn = asyncio.subprocess.create_subprocess_shell check = kwargs.pop("check", False) process = await fn(*ar...
948ccb127afb8cf1c2a1731a5198bc493a1e9fe4
26,652
import torch def scaled_dot_product_attention(q, k, v, mask=None): """ #计算注意力权重。 q, k, v 必须具有匹配的前置维度。 且dq=dk k, v 必须有匹配的倒数第二个维度,例如:seq_len_k = seq_len_v。 #虽然 mask 根据其类型(填充或前瞻)有不同的形状, #但是 mask 必须能进行广播转换以便求和。 #参数: q: 请求的形状 == (..., seq_len_q, depth) k: 主键的形状 == (..., seq_len...
3d51de38ca553c3b769bd1ba4936159034cd68e0
26,653
def _get_parent_entity(entities, entity_id): """ Gets the parent entity from the collection, or throws ParentDoesNotExist. """ try: return entities[entity_id] except KeyError: raise ParentDoesNotExist(object_type='Entity', key=entity_id)
d898252058f191a2685803fc6d4495eb75ce56eb
26,654
def tstop(f): """ Dust stopping time """ units = sutil.get_all_units(f) grainSize = f['u_dustGrainSize'] grainDensity = SimArray(sutil.get_snap_param(f, 'dDustGrainDensity'), units['rho_unit']) if sutil.is_isothermal(f): gamma = 1. else: gamma = sutil.get_snap_gamma(...
e1f13c3b87104d366dd0c5239dd5d24de954897c
26,655
def solve_2d_discrete_observations_continuous_modelling( cond_xy0s_list: tp.List[tp.Tuple[float, float]], cond_xytGammas_list: tp.List[tp.Tuple[float, float, float]], cond_f0s_list: tp.List[float], cond_fGammas_list: tp.List[float], a: float, b: float, c: float, ...
a8139c014c292b44aee1cf4533a7576413a7e685
26,656
import logging from typing import Callable from typing import Any def log_calls_on_exception( logger: logging.Logger, log_exception: bool = True ) -> GenericDecorator: """ Log calls to the decorated function, when exceptions are raised. Can also decorate classes to log calls to all its methods. ...
98a186d116547c2929c010b66b9395ba5d5c8603
26,657
def convert_2d_list_to_string(data): """Utility function.""" s = '' for row in data: c = '{' for e in row: c += str(e) + ',' s += c[:-1] + '},\n' return s[:-2]
a6ac2c05f481a339c68ffc3543baba1f1d0d5e8e
26,659
def get_info(sheet, row_num, percentage, sheet_name, mandatory_tables): """ Function is used to create a dictionary that contains the number of flawed records for a particular site. :param sheet (dataframe): pandas dataframe to traverse. Represents a sheet with numbers indicati...
76552ee6cd366642d29c945a289b69efda28ba37
26,661
def get_structural_topology_reactions(filename, dset_path="readdy/config/structural_topology_reactions"): """ Construct a dictionary where the keys are reaction ids and value is corresponding name. :param filename: the file name :param dset_path: path to the dataset :return: dictionary of reactions...
a3bb4f75740b540c8428d760c087df4dea782a4e
26,662
def PyMapping_Keys(space, w_obj): """On success, return a list of the keys in object o. On failure, return NULL. This is equivalent to the Python expression o.keys().""" return space.call_function(space.w_list, space.call_method(w_obj, "keys"))
452b384a421fd675a53ff20d868b8f7353eb3d79
26,663
import aiohttp import json import asyncio async def safebooru(ctx, tag, page='1'): """Searches safebooru. Usage: safebooru [tags]""" async with aiohttp.ClientSession() as session: invoker = ctx.message.author post = await fetch(session, "https://safebooru.org/index.php?page=dapi&s=post&q=index...
782000d62de1d36abc4b81e0bb4b025707e79940
26,664
import re def is_arabicrange(text): """ Checks for an Arabic Unicode block characters @param text: input text @type text: unicode @return: True if all charaters are in Arabic block @rtype: Boolean """ if re.search(u"([^\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff\u0750-\u077f])", text): ...
70862e901236eb94fec95ac6f7eb673729397e49
26,665
def del_pool(batch_client, config, pool_id=None): # type: (azure.batch.batch_service_client.BatchServiceClient, dict, # str) -> bool """Delete a pool :param batch_client: The batch client to use. :type batch_client: `azure.batch.batch_service_client.BatchServiceClient` :param dict config:...
fad5a672920a98305f12e9a7e7c6d665ff874f0a
26,666
def str_repeat(space, s, repeat): """Repeat a string.""" return space.newstr(s * repeat)
3e947da1fa3bf403b0836bd4e7ae0052d310636e
26,667
def alarm(duration=250): """ Red alarm; flashing bright red to dark red. :param int duration: The duration between hi/lo brightness,in milliseconds. :returns: An infinite Flow consisting of 2 transitions. :rtype: Flow """ return Flow(count=0, action=Action.recover, transitions=transitions....
a501c6a85c78cd37eadba200ca327660945dd4d7
26,668
def mkvc(x, numDims=1): """Creates a vector with the number of dimension specified e.g.:: a = np.array([1, 2, 3]) mkvc(a, 1).shape > (3, ) mkvc(a, 2).shape > (3, 1) mkvc(a, 3).shape > (3, 1, 1) """ if type(x) == np.matrix: ...
e749e0feadcdf69625355477fd22e2f9d363768f
26,669
def location_distance_meters(a: Location, b: Location) -> float: """Calculates the distance between two points. Returns: A number of meters between two points. """ return location_distance_kilometers(a, b).m
91179bc0fc2647d502a290ecc1df28eda8b149f5
26,670
import json def file_to_dict(file: str): """Dump json file to dictionary""" try: with open(file) as json_file: return json.load(json_file) except json.decoder.JSONDecodeError: print(f'File {file} is not a valid json file. Returning empty dict') return {} except File...
2265f2ad5e10931e93a08bafd8e8a7e20c91ae93
26,671
def fieldtype(field): """Return classname""" return field.__class__.__name__
afda2f7a13a2d0be991eadf31ac591762c519f05
26,672
from typing import Dict def basic_extractor( data: Dict, ) -> list: """ Returns list of the total_recieved token, the total sent token and the number of transactions the wallet participated in. """ return [data["total_received"],data["total_sent"],data["n_tx"]]
946611423cf98c6104fa49e0ccb82308d741f900
26,673
def expand_stages_cfg(stage_cfgs): """ For a list of stages """ assert isinstance(stage_cfgs, list) ret = [] for x in stage_cfgs: ret.append(expand_stage_cfg(x)) return ret
bb562da9ca5a547fc1c442e3ba8d73b7f7d0768e
26,674
def find_team(): """find a team by using filters from request arguments""" # partial -> allow skipping of required fields ts = TeamSchema( partial=True, only=( "name", "event_id", "team_identifier", "payment_status", "single", ...
98aa1a67450aa9c117c5d9d7c158c169c2f7969c
26,675
def clusterbased_permutation_1d_1samp_1sided(results, level=0, p_threshold=0.05, clusterp_threshold=0.05, n_threshold=2, iter=1000): """ 1-sample & 1-sided cluster based permutation test for 2-D results Parameters ---------- results : array A re...
ade205fdd4c256567e0f1ce908f7a711caad2f5d
26,676
def getObjectsContainers(mQueryObject = []): """ Return a list of containers that the passed in objects reside in. @param [] mQueryObject: list of objects you are wanting to know, in which container they exists. @return: key = container name, value = container MObject. @rtype: {} """ contai...
83da454e85067a2d74f2f251f255a74f3bba41ee
26,677
from webdnn.backend.webgl.attributes.texture_shape import TextureShape from webdnn.backend.webgl.attributes.channel_mode import ChannelMode from typing import Optional def dump_dot(graph: Graph, name: Optional[str] = None) -> str: # pragma: no cover """ Dumps graph into dot language for visualization. A...
61e993c7383e939109463fd872501a6d7bda3d0d
26,678
def RPL_LUSERCLIENT(sender, receipient, message): """ Reply Code 251 """ return "<" + sender + ">: " + message
4863c4d6945378f315932fadbf8f2615f020c611
26,679
def multiply_inv_gaussians_batch(mus, lambdas): """Multiplies a series of Gaussians that is given as a list of mean vectors and a list of precision matrices. mus: list of mean with shape [..., d] lambdas: list of precision matrices with shape [..., d, d] Returns the mean vector, covariance matrix, and p...
3239ee6c472506c0b0fcc90c8543deeca0edb02e
26,680
def replace_if_present_else_append( objlist, obj, cmp=lambda a, b: a == b, rename=None): """ Add an object to a list of objects, if that obj does not already exist. If it does exist (`cmp(A, B) == True`), then replace the property in the property_list. The names are c...
f76b3a76fe973ef91176f8ff4afd34d52ce89317
26,681
def rating_value(value): """Check that given value is integer and between 1 and 5.""" if 1 <= int(value) <= 5: return int(value) raise ValueError("Expected rating between 1 and 5, but got %s" % value)
cadb45a131a423940e1b3a763935f5e40d84285b
26,682
def hsc_to_hs(ctx): """Process all hsc files into Haskell source files. Args: ctx: Rule context. Returns: list of File: New Haskell source files to use. """ ghc_defs_dump = _make_ghc_defs_dump(ctx) sources = [] for f in ctx.files.srcs: if f.extension == "hsc": sources.append(_process_h...
7672ad9b3679fc663b461f4bcb9eb421293dc185
26,683
from shapely.geometry import Polygon def calculate_iou_box(pts1, pts2): """ Measure the two list of points IoU :param pts1: ann.geo coordinates :param pts2: ann.geo coordinates :return: `float` how Intersection over Union of tho shapes """ try: except (ImportError, ModuleNotFoundError)...
fe915dc952852e28214ce1a16f781c55600fc1ec
26,684
def nextafter(x, direction, dtype, itemsize): """Return the next representable neighbor of x in the appropriate direction.""" assert direction in [-1, 0, +1] assert dtype.kind == "S" or type(x) in (bool, float, int) if direction == 0: return x if dtype.kind == "S": return stri...
c14f6695eb4285afe3001ac6db019af26a95c78c
26,685