content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _feature_normalization(features, method, feature_type): """Normalize the given feature vector `y`, with the stated normalization `method`. Args: features (np.ndarray): The signal array method (str): Normalization method. 'global': Uses global mean and standard deviation values ...
0479363651a4bcf1622e7bdb0906b55e3adb1cce
12,500
def get_constraint(name): """ Lookup table of default weight constraint functions. Parameters ---------- name : Constraint, None, str Constraint to look up. Must be one of: - 'l1' : L1 weight-decay. - 'l2' : L2 weight-decay. - 'l1-l2' : Combined L1-L2 weight-decay. - Constraint : A custom implementa...
09927531f4c6770e86ad603063e4edb0b0c4ff48
12,501
def player_count(conn, team_id): """Returns the number of players associated with a particular team""" c = conn.cursor() c.execute("SELECT id FROM players WHERE team_id=?", (team_id,)) return len(c.fetchall())
cfced6da6c8927db2ccf331dca7d23bba0ce67e5
12,502
def _RedisClient(address): """ Return a connection object connected to the socket given by `address` """ h1, h2 = get_handle_pair(conn_type=REDIS_LIST_CONN) c = _RedisConnection(h1) #redis_client = util.get_redis_client() redis_client = util.get_cache_client() ip, port = address chan...
fc8bab786bb521fbd0715da3ab690575d1df865e
12,503
import math def format_timedelta(value, time_format="{days} days, {hours2}:{minutes2}:{seconds2}"): """Format a datetie.timedelta. See """ if hasattr(value, 'seconds'): seconds = value.seconds + value.days * 24 * 3600 else: seconds = int(value) seconds_total = seconds minutes ...
19dc2b175beb1d030f14ae7fe96cb16d66f6c219
12,504
def random_account_user(account): """Get a random user for an account.""" account_user = AccountUser.objects.filter(account=account).order_by("?").first() return account_user.user if account_user else None
5fe918af67710d0d1519f56eee15811430a0e139
12,505
def overwrite(main_config_obj, args): """ Overwrites parameters with input flags Args: main_config_obj (ConfigClass): config instance args (dict): arguments used to overwrite Returns: ConfigClass: config instance """ # Sort on nested level to override shallow items first args = dict(s...
98ee9cf034a9b714ae18e737761b06bfd669bfa4
12,506
def max_delta(model, new_model): """Return the largest difference between any two corresponding values in the models""" return max( [(abs(model[i] - new_model[i])).max() for i in range(len(model))] )
faf4a9fb2b24f7e7b4f357eef195e435950ea218
12,507
def wiener_khinchin_transform(power_spectrum, frequency, time): """ A function to transform the power spectrum to a correlation function by the Wiener Khinchin transformation ** Input:** * **power_spectrum** (`list or numpy.array`): The power spectrum of the signal. * **frequency** (`lis...
3cf8916c75632e3a0db52f907ce180eb766f9f2e
12,508
def child_is_flat(children, level=1): """ Check if all children in section is in same level. children - list of section children. level - integer, current level of depth. Returns True if all children in the same level, False otherwise. """ return all( len(child) <= level + 1 or child...
e14f9210a90b40b419d21fffa1542212429d80be
12,509
from pathlib import Path def load_dataset(name, other_paths=[]): """Load a dataset with given (file) name.""" if isinstance(name, Dataset): return name path = Path(name) # First, try if you have passed a fully formed dataset path if path.is_file(): return _from_npy(name, classes=...
3f3d2e7e7ec577098e1a1599c74638ced5d3c103
12,510
def isqrtcovresnet101b(**kwargs): """ iSQRT-COV-ResNet-101 model with stride at the second convolution in bottleneck block from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix Square Root Normalization,' https://arxiv.org/abs/1712.01034. Parameters: ----------...
fdf166fa3ce9e893e8e97d1057dac89d084d2217
12,511
def get_data(name: str, level: int, max_level: int) -> str: """從維基頁面爬取資料 參數: name: 程式或節點名稱 level: 欲查詢的等級 回傳: 爬到的資料 """ reply_msg = [] for dataframe in read_html(generate_url(name)): if (max_level < dataframe.shape[0] < max_level + 3 and dataframe...
4e0f11a33c81993132d45f3fdad5f42c1288bbe5
12,512
import os def is_processable(path: str, should_match_extension: str): """ Process scandir entries, copying the file if necessary """ if not os.path.isfile(path): return False filename = os.path.basename(path) _, extension = os.path.splitext(filename) if extension.lower() != should...
5d99b821d3653ff452acac1e5fe48cab559c509e
12,513
def insert_data(context, data_dict): """ :raises InvalidDataError: if there is an invalid value in the given data """ data_dict['method'] = _INSERT result = upsert_data(context, data_dict) return result
c631016be36f1988bfa9c98cea42a7f63fddc276
12,514
import time def timestamp(): """Get the unix timestamp now and retuen it. Attention: It's a floating point number.""" timestamp = time.time() return timestamp
8e56a61659da657da9d5dda364d4d9e8f3d58ed2
12,515
from datetime import datetime def _n64_to_datetime(n64): """Convert Numpy 64 bit timestamps to datetime objects. Units in seconds""" return datetime.utcfromtimestamp(n64.tolist() / 1e9)
a25327f2cd0093635f86f3145f5674cc1945d3f8
12,516
import itertools def cycle(iterable): """Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. This function uses single dispatch. .. seealso:: :func:`itertools.cycle` """ re...
13f479fca709dffa77eeca3d32ff7265c81588bf
12,517
def get_availability_zone(name=None,state=None,zone_id=None,opts=None): """ `.getAvailabilityZone` provides details about a specific availability zone (AZ) in the current region. This can be used both to validate an availability zone given in a variable and to split the AZ name into its compone...
6cb20524c1e0a2539e221711f1153949ab72f8e1
12,518
def _add_u_eq(blk, uex=0.8): """Add heat transfer coefficent adjustment for feed water flow rate. This is based on knowing the heat transfer coefficent at a particular flow and assuming the heat transfer coefficent is porportial to feed water flow rate raised to certain power (typically 0.8) Args: ...
f6b34a8e75367b43dbe759d273aa4be7dc371c12
12,519
def find_process_in_list( proclist, pid ): """ Searches for the given 'pid' in 'proclist' (which should be the output from get_process_list(). If not found, None is returned. Otherwise a list [ user, pid, ppid ] """ for L in proclist: if pid == L[1]: return L r...
19eab54b4d04b40a54a39a44e50ae28fbff9457c
12,520
def solution(s, start_pos, end_pos): """ Find the minimal nucleotide from a range of sequence DNA. :param s: String consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence :param start_pos: array with the start indexes for the intervals to check :p...
25ef2f7e9b009de0534f8dde132c0eb44e3fe374
12,521
def validate_address(value: str, context: dict = {}) -> str: """ Default address validator function. Can be overriden by providing a dotted path to a function in ``SALESMAN_ADDRESS_VALIDATOR`` setting. Args: value (str): Address text to be validated context (dict, optional): Validator c...
65e04a4780432608aa049687da98bd05a527fbad
12,522
import os import random def select_images(img_dir, sample_size=150, random_seed=42): """Selects a random sample of image paths.""" img_paths = [] for file in os.listdir(img_dir): if file.lower().endswith('.jpeg'): img_paths.append(os.path.join(img_dir, file)) if sample_size is not...
999bf71eb6b8072bd91cbb98d9fe1b50d5e9b8ac
12,523
import os import json def load_period_data(period): """ Load period data JSON file If the file does not exist and empty dictionary is returned. """ filename = os.path.join(PROTOCOL_DIR, PERIOD_FILE_TEMPLATE % period) if not os.path.exists(filename): return {} with open(filename,...
c6c4c7121c55e1fd54d47a964054520f1f2fde97
12,524
from pathlib import Path def _get_hg_repo(path_dir): """Parse `hg paths` command to find remote path.""" if path_dir == "": return "" hgrc = Path(path_dir) / ".hg" / "hgrc" if hgrc.exists(): config = ConfigParser() config.read(str(hgrc)) if "paths" in config: ...
773ab4b45ba6883446c8e4a7725b7ac9d707440f
12,525
def array_to_string(array, col_delim=' ', row_delim='\n', digits=8, value_format='{}'): """ Convert a 1 or 2D array into a string with a specified number of digits and delimiter. The reason this exists is that the basic nump...
9e7f189049b1ad3eff3679568a84e7151e2c643c
12,526
def get_dp_logs(logs): """Get only the list of data point logs, filter out the rest.""" filtered = [] compute_bias_for_types = [ "mouseout", "add_to_list_via_card_click", "add_to_list_via_scatterplot_click", "select_from_list", "remove_from_list", ] for log in...
e0a7c579fa9218edbf942afdbdb8e6cf940d1a0c
12,527
from typing import List from typing import Dict def assign_reports_to_watchlist(cb: CbThreatHunterAPI, watchlist_id: str, reports: List[Dict]) -> Dict: """Set a watchlist report IDs attribute to the passed reports. Args: cb: Cb PSC object watchlist_id: The Watchlist ID to update. reports: T...
92bb0369211c1720fa4d9baa7a4e3965851339f2
12,528
def visualize_filter( image, model, layer, filter_index, optimization_parameters, transformation=None, regularization=None, threshold=None, ): """Create a feature visualization for a filter in a layer of the model. Args: image (array): the image to be modified by the fea...
09940c0484361240929f61f04c9a96771b440033
12,529
def subtraction(x, y): """ Subtraction x and y >>> subtraction(-20, 80) -100 """ assert isinstance(x, (int, float)), "The x value must be an int or float" assert isinstance(y, (int, float)), "The y value must be an int or float" return x - y
203233897d31cb5bc79fca0f8c911b03d7deb5ba
12,530
import aiohttp async def paste(text: str) -> str: """Return an online bin of given text.""" session = aiohttp.ClientSession() async with session.post("https://hasteb.in/documents", data=text) as post: if post.status == 200: response = await post.text() return f"https://has...
d204f6f1db3aa33c98c4ebeae9888acc438f7dc3
12,531
def lr_step(base_lr, curr_iter, decay_iters, warmup_iter=0): """Stepwise exponential-decay learning rate policy. Args: base_lr: A scalar indicates initial learning rate. curr_iter: A scalar indicates current iteration. decay_iter: A list of scalars indicates the numbers of iteration when the lear...
b8cfe670aba0bed1f84ae09c6271e681fad42864
12,532
def apo(coalg): """ Extending an anamorphism with the ability to halt. In this version, a boolean is paired with the value that indicates halting. """ def run(a): stop, fa = coalg(a) return fa if stop else fa.map(run) return run
a1e64d9ed49a8641095c8a8c20ae08c1cc6e9c19
12,533
def cat_sample(ps): """ sample from categorical distribution ps is a 2D array whose rows are vectors of probabilities """ r = nr.rand(len(ps)) out = np.zeros(len(ps),dtype='i4') cumsums = np.cumsum(ps, axis=1) for (irow,csrow) in enumerate(cumsums): for (icol, csel) in enumer...
30009b31dba0eff23010bfe6d531e8c55e46873c
12,534
def download_network(region, network_type): """Download network from OSM representing the region. Arguments: region {string} -- Location. E.g., "Manhattan Island, New York City, New York, USA" network_type {string} -- Options: drive, drive_service, walk, bike, all, all_private Retu...
d77c9464641c90cc029adc0649739b499298d173
12,535
def extract_text(text): """ """ l = [] res = [] i = 0 while i < len(text) - 2: h, i, _ = next_token(text, i) obj = text[h:i] l.append(obj) for j, tok in enumerate(l): if tok == b'Tf': font = l[j-2] fsize = float(l[j-1]) elif tok ==...
9b0746be6f6fa39548fd34f3bffda7e8baf4a6ef
12,536
def add_pruning_arguments_to_parser(parser): """Add pruning arguments to existing argparse parser""" parser.add_argument('--do_prune', action='store_true', help="Perform pruning when training a model") parser.add_argument('--pruning_config', type=str, default=...
2a94e0986564f4af8fe580ca3500f06c04598f14
12,537
import itertools from functools import reduce import copy def invokeRule(priorAnswers, bodyLiteralIterator, sip, otherargs, priorBooleanGoalSuccess=False, step=None, debug=False, buildProof=False): """ Con...
66be56a818a620c5c47a7537b612e91341c7d334
12,538
def read_ult_meta(filebase): """Convenience fcn for output of targeted metadata.""" meta = _parse_ult_meta(filebase) return (meta["NumVectors"], meta["PixPerVector"], meta["ZeroOffset"], meta["Angle"], meta["PixelsPerMm"], meta["FramesPerSec"], ...
b2237a2dab9faf98179f69de9e9a5f1dc7289f78
12,539
from typing import Iterable from typing import List def safe_identifiers_iterable(val_list: Iterable[str]) -> List[str]: """ Returns new list, all with safe identifiers. """ return [safe_identifier(val) for val in val_list]
6b80d90cfac2ea527ace38cc6550571b5f120a7f
12,540
def encode_varint(value, write): """ Encode an integer to a varint presentation. See https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints on how those can be produced. Arguments: value (int): Value to encode write (function): Called per byte that needs ...
075286208008a0b7507eafe19158eebdb2af66b7
12,541
def heap_sort(li): """ [list of int] => [list of int] Heap sort: divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element from it and inserting it into the sorted region. It does not waste time with a linear-time scan of...
a72be31e5256c880c157636aa7a15df013ce651d
12,542
def vector_field(v, t, inf_mat, state_meta): """vector_field returns the temporal derivative of a flatten state vector :param v: array of shape (1,mmax+1+(nmax+1)**2) for the flatten state vector :param t: float for time (unused) :param inf_mat: array of shape (nmax+1,nmax+1) representing the infection...
31c8023966fd3e5c35b734759a3747f0d2752390
12,543
def newton(start, loss_fn, *args, lower=0, upper=None, epsilon=1e-9): """ Newton's Method! """ theta, origin, destination = args[0], args[1], args[2] if upper is None: upper = 1 start = lower while True: if loss_fn(start, theta, origin, destination) > 0: start ...
bbd04297639fbc964c55a8c964e5bd5fb24d6e22
12,544
import torch def eval_det_cls(pred, gt, iou_thr=None): """Generic functions to compute precision/recall for object detection for a single class. Args: pred (dict): Predictions mapping from image id to bounding boxes \ and scores. gt (dict): Ground truths mapping from image id ...
762f70d95261509778a1b015af30eab68f951b15
12,545
import pathlib from typing import List from typing import Dict import tqdm def parse_g2o(path: pathlib.Path, pose_count_limit: int = 100000) -> G2OData: """Parse a G2O file. Creates a list of factors and dictionary of initial poses.""" with open(path) as file: lines = [line.strip() for line in file.r...
6c766401220849e337279e8b465f9d67477a1599
12,546
def _som_actor(env): """ Construct the actor part of the model and return it. """ nactions = np.product(env.action_shape) model = keras.models.Sequential() model.add(keras.layers.Flatten(input_shape=(1,) + env.observation_space.shape)) model.add(keras.layers.Dense(400)) model.add(keras....
e3bc1f675b16b2d728b1c070324139f0d99071a7
12,547
def sendEmail(): """email sender""" send_email('Registration ATS', ['manavshrivastava@hotmail.com'], 'Thanks for registering ATS!', '<h3>Thanks for registering with ATS!</h3>') return "email sent to manavshrivastava@hotmail.com...
e9125c32adac8267aaa550e59e27db4a10746ace
12,548
import scipy def Pvalue(chi2, df): """Returns the p-value of getting chi2 from a chi-squared distribution. chi2: observed chi-squared statistic df: degrees of freedom """ return 1 - scipy.stats.chi2.cdf(chi2, df)
1a2198e5d47396fc785a627d96513ded1d6894e0
12,549
def template(template_lookup_key: str) -> str: """Return template as string.""" with open(template_path(template_lookup_key), "r") as filepath: template = filepath.read() return template
d03bbc2baa8cb18174a468579bdea1da906de09d
12,550
def filter_rows(df, condition, reason): """ :param reason: :param df: :param condition: boolean, true for row to keep :return: filter country_city_codes df """ n_dropped = (condition == False).sum() print( f"\nexcluding {n_dropped} locations ({n_dropped / df.shape[0]:.1%}) due to...
7e5e6925bfb7d90bc90b42fda202d80e8ef5e3f6
12,551
def parse_projected_dos(f): """Parse `projected_dos.dat` output file.""" data = np.loadtxt(f) projected_dos = {"frequency_points": data[:, 0], "projected_dos": data[:, 1:].T} pdos = orm.XyData() pdos_list = [pd for pd in projected_dos["projected_dos"]] pdos.set_x(projected_dos["frequency_points"...
89c280e92c7598e3947d8ccda20b921c601c9b10
12,552
def get_from_parameters(a, b, c, alpha, beta, gamma): """ Create a Lattice using unit cell lengths and angles (in degrees). This code is modified from the pymatgen source code [1]_. Parameters ---------- a : :class:`float`: *a* lattice parameter. b : :class:`float`: *b* la...
076763f30da86b12747ede930993d99fc3b742d8
12,553
import random def random_chinese_name(): """生成随机中文名字 包括的名字格式:2个字名字**,3个字名字***,4个字名字**** :return: """ name_len = random.choice([i for i in range(4)]) if name_len == 0: name = random_two_name() elif name_len == 1: name = random_three_name() elif name_len == 2: n...
c86232cb81c492e2301837f5e330e6140ee503f3
12,554
def power_list(lists: [list]) -> list: """ power set across the options of all lists """ if len(lists) == 1: return [[v] for v in lists[0]] grids = power_list(lists[:-1]) new_grids = [] for v in lists[-1]: for g in grids: new_grids.append(g + [v]) return new_grids
135e3cde20388d999456e2e8a2fed4d98fac581d
12,555
import time def send_email(from_email, to, subject, message, html=True): """ Send emails to the given recipients :param from_email: :param to: :param subject: :param message: :param html: :return: Boolean value """ try: email = EmailMessage(subject, message, from_email,...
28751bc30f51148c0389d4127229e6352a18cacb
12,556
import random def attack(health, power, percent_to_hit): """Calculates health from percent to hit and power of hit Parameters: health - integer defining health of attackee power - integer defining damage of attacker percent to hit - float defining percent chance to hit of attacker ...
83a74908f76f389c798b28c5d3f9035d2d8aff6a
12,557
def signal_requests_mock_factory(requests_mock: Mocker) -> Mocker: """Create signal service mock from factory.""" def _signal_requests_mock_factory( success_send_result: bool = True, content_length_header: str = None ) -> Mocker: requests_mock.register_uri( "GET", "h...
543f73ec004911c87e9986cbd940a733f03287bf
12,558
def test_dwt_denoise_trace(): """ Check that sample data fed into dwt_denoise_trace() can be processed and that the returned signal is reasonable (for just one trace)""" # Loma Prieta test station (nc216859) data_files, origin = read_data_dir('geonet', 'us1000778i', '*.V1A') trace = [] trace = ...
4c526e7e76c8672322bec0323974ca2ee20e25dd
12,559
def get_networks(project_id=None, auth_token=None): """ Get a list of all routed networks """ url = CATALOG_HOST + "/routednetwork" try: response_body = _api_request(url=url, http_method="GET", project...
c2c9bfe05cfa416c9e37d04aefcc640d5d2250f7
12,560
def feature_registration(source,target, MIN_MATCH_COUNT = 12): """ Obtain the rigid transformation from source to target first find correspondence of color images by performing fast registration using SIFT features on color images. The corresponding depth values of the matching keypoints is then use...
d5839ef3586acd84c57341f19700de38660f9a9f
12,561
def set_metadata(testbench_config, testbench): """ Perform the direct substitutions from the sonar testbench metadata into the the testbench Args: testbench_config (Testbench): Sonar testbench description testbench (str): The testbench template """ for key, value in testbench_co...
375712b92f7467ee4d49e5d9e91250464c81337d
12,562
def index(a, x): """Locate the leftmost value exactly equal to x""" i = bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError
f77aed5c55750b848fdf51b66b38f3774c812e23
12,563
def convert_secondary_type_list(obj): """ :type obj: :class:`[mbdata.models.ReleaseGroupSecondaryType]` """ type_list = models.secondary_type_list() [type_list.add_secondary_type(convert_secondary_type(t)) for t in obj] return type_list
d84d20f6d82b462bda5bf04f6784effea47a0265
12,564
import matplotlib.pyplot as plt def run(inputs, parameters = None): """Function to be callled by DOE and optimization. Design Variables are the only inputs. :param inputs: {'sma', 'linear', 'sigma_o'}""" def thickness(x, t, chord): y = af.Naca00XX(chord, t, [x], return_dict =...
65c1951fb4bbed8ab2832ce4892a6c6308439f79
12,565
import json def load_data(path): """Load JSON data.""" with open(path) as inf: return json.load(inf)
531fc2b27a6ab9588b1f047e25758f359dc21b6d
12,566
from pathlib import Path def get_extension(file_path): """ get_extension(file) Gets the extension of the given file. Parameters ---------- file_path A path to a file Returns ------- str Returns the extension of the file if it exists or None otherwise. ...
7b1c4ba4f20ac913bb38292d4a704869cab6937e
12,567
def rank_in_group(df, group_col, rank_col, rank_method="first"): """Ranks a column in each group which is grouped by another column Args: df (pandas.DataFrame): dataframe to rank-in-group its column group_col (str): column to be grouped by rank_col (str): column to be ranked for...
f2ae45641339bf4bc71bc48a415a28602ccf8da3
12,568
import six def get_layer_options(layer_options, local_options): """ Get parameters belonging to a certain type of layer. Parameters ---------- layer_options : list of String Specifies parameters of the layer. local_options : list of dictionary Specifies local parameters in a m...
e40945395c4a96c0a0b9447eeb1d0b50cf661bd7
12,569
def expr(term:Vn,add:Vt,expr:Vn)->Vn: """ expr -> term + expr """ return {"add":[term,expr]}
f66475ecbd255ac4c4a04b0d705f1c052c4ee123
12,570
import json def gene_box(cohort, order='median', percentage=False): """Box plot with counts of filtered mutations by gene. percentage computes fitness as the increase with respect to the self-renewing replication rate lambda=1.3. Color allows you to use a dictionary of colors by gene. ...
851c166246144b14d51863b4c775baa88ab87205
12,571
from typing import Union from typing import List def _clip_and_count( adata: AnnData, target_col: str, *, groupby: Union[str, None, List[str]] = None, clip_at: int = 3, inplace: bool = True, key_added: Union[str, None] = None, fraction: bool = True, ) -> Union[None, np.ndarray]: ""...
20673965557afdcf75b3201cf743fff100981ec3
12,572
def create_training_patches(images, patch_size, patches_per_image=1, patch_stride=None): """ Returns a batch of image patches, given a batch of images. Args: images (list, numpy.array): Batch of images. patch_size (tuple, list): The (width, height) of the patch to return. ...
5fce19d2d13f790500e0cbd42934dd6e83c6b084
12,573
import time def get_prover_options(prover_round_tag='manual', prover_round=-1) -> deephol_pb2.ProverOptions: """Returns a ProverOptions proto based on FLAGS.""" if not FLAGS.prover_options: tf.logging.fatal('Mandatory flag --prover_options is not specified.') if not tf.gfile.Exists(FL...
ee1ee9fb7ce573c543f0750d6b8fd1eed98deec9
12,574
def bracketpy(pystring): """Find CEDICT-style pinyin in square brackets and correct pinyin. Looks for square brackets in the string and tries to convert its contents to correct pinyin. It is assumed anything in square brackets is CC-CEDICT-format pinyin. e.g.: "拼音[pin1 yin1]" will be converted int...
0499047ec45e6b9c66c27dd89663667b13ddbfb1
12,575
import psutil def get_ram_usage_bytes(size_format: str = 'M'): """ Size formats include K = Kilobyte, M = Megabyte, G = Gigabyte """ total = psutil.virtual_memory().total available = psutil.virtual_memory().available used = total - available # Apply size if size_format == 'K': ...
990987078b0ad3c2ac2ee76dcf96b7cdf01f0354
12,576
def weighted_crossentropy(weights, name='anonymous'): """A weighted version of tensorflow.keras.objectives.categorical_crossentropy Arguments: weights = np.array([0.5,2,10]) # Class one at 0.5, class 2 twice the normal weights, class 3 10x. name: string identifying the loss to differentiate whe...
071ab00a723d54194b4b27c889c638debe82f10a
12,577
def _get_package_type(id): """ Given the id of a package this method will return the type of the package, or 'dataset' if no type is currently set """ pkg = model.Package.get(id) if pkg: return pkg.type or u'dataset' return None
c84e137e2b0adaf8719d757f178aa47d4a63c46a
12,578
def _find_protruding_dimensions(f, care, fol): """Return variables along which `f` violates `care`.""" vrs = joint_support([f, care], fol) dims = set() for var in vrs: other_vars = vrs - {var} f_proj = fol.exist(other_vars, f) care_proj = fol.exist(other_vars, care) if (c...
02da5718645652288c9fa6fcedc07198afe49a58
12,579
import os import glob def prepare_data(train_mode, dataset="Train"): """ Args: dataset: choose train dataset or test dataset For train dataset, output data would be ['.../t1.bmp', '.../t2.bmp',..., 't99.bmp'] """ # Defines list of data path lists for diffe...
08a17868b36b20c495253e366fcb00a1d105cfa0
12,580
import random def simulate_relatedness(genotypes, relatedness=.5, n_iter=1000, copy=True): """ Simulate relatedness by randomly copying genotypes between individuals. Parameters ---------- genotypes : array_like An array of shape (n_variants, n_samples, ploidy) where each element...
e319f4e15c4c08eb90260b77efc25ea330aac4c9
12,581
def pages_substitute(content): """ Substitute tags in pages source. """ if TAG_USERGROUPS in content: usergroups = UserGroup.objects.filter(is_active=True).order_by('name') replacement = ", ".join(f"[{u.name}]({u.webpage_url})" for u in usergroups) content = content.replace(TAG_U...
13c2138256a0e1afa0ad376994849f2716020540
12,582
def vcfanno(vcf, out_file, conf_fns, data, basepath=None, lua_fns=None): """ annotate a VCF file using vcfanno (https://github.com/brentp/vcfanno) """ if utils.file_exists(out_file): return out_file if lua_fns is None: lua_fns = [] vcfanno = config_utils.get_program("vcfanno", da...
808488bd07c56b541694715193df4ae1cb51869c
12,583
def clean(params: dict) -> str: """ Build clean rules for Makefile """ clean = "\t@$(RM) -rf $(BUILDDIR)\n" if params["library_libft"]: clean += "\t@make $@ -C " + params["folder_libft"] + "\n" if params["library_mlx"] and params["compile_mlx"]: clean += "\t@make $@ -C " + params["folder_mlx"] + "\n" retur...
fb7dd0e7a2fbb080dd8b0d5d4489e9c5ef1367ec
12,584
import re def mathematica(quero: str, meta: str = '') -> bool: """mathematica Rudimentar mathematical operations (boolean result) Args: quero (_type_, optional): _description_. Defaults to str. Returns: bool: True if evaluate to True. """ # neo_quero = quero.replace(' ', '')...
b05777e880688d8f3fc90ba9d54098f341054bd7
12,585
import sys def fasta2vcf(f): """convert fasta to vcf dataframe Input ----- Fasta file, _ref is recognized as ref and _alt is used as alt, these are two keywords Output ------ vcf dataframe: chr, pos, name, ref, alt, reference sequence """ my_dict = {} for r in SeqIO.parse(f, "fasta"): my_dict[r.id] ...
673e69e644b6caf68f0738cfaa8204b80877a412
12,586
def time_pet(power,energy): """Usage: time_pet(power,energy)""" return energy/power
11e9c82b8c1be84995f9517e04ed5e1270801e27
12,587
def compute_sigma0( T, S, **kwargs, ): """ compute the density anomaly referenced to the surface """ return compute_rho(T, S, 0, **kwargs) - 1000
300d5552c70e6fd6d8708345aa3eed53795309cf
12,588
def get_neighbors_radius(nelx, nely, coord, connect, radius): """ Check neighboring elements that have the centroid within the predetermined radius. Args: nelx (:obj:`int`): Number of elements on the x axis. nely (:obj:`int`): Number of elements on the x axis coord (:obj:`numpy.array`):...
669e11d3a2890f1485e33e021b2671ff6f197c03
12,589
import copy def merge_with(obj, *sources, **kwargs): """ This method is like :func:`merge` except that it accepts customizer which is invoked to produce the merged values of the destination and source properties. If customizer returns ``None``, merging is handled by this method instead. The customizer...
94a16ae7d3f3e73ef8e27b32cd38a09c61ad1b2b
12,590
def count_class_nbr_patent_cnt(base_data_list, calculate_type): """ 统计在所有数据中不同分类号对应的专利数量 :param base_data_list: :return: """ class_number_patent_cnt_dict = dict() for base_data in base_data_list: class_number_value = base_data[const.CLASS_NBR] calculate_class_number_patent_co...
6dfe06c2233fbfafc8083dc968d32520564319f8
12,591
def plot_pta_L(df): """ INPUTS -df: pandas dataframe containing the data to plot OUTPUTS -saves pta graphs in .html """ title = generate_title_run_PTA(df, "Left Ear", df.index[0]) labels = {"title": title, "x": "Frequency (Hz)", "y": "Hearing Threshold (dB HL...
ec82b58a6a476bee5e864b8678bb90d2998d4a02
12,592
def create_graph(edge_num: int, edge_list: list) -> dict: """ Create a graph expressed with adjacency list :dict_key : int (a vertex) :dict_value : set (consisted of vertices adjacent to key vertex) """ a_graph = {i: set() for i in range(edge_num)} for a, b in edge_list: a_graph...
6ec1a71cf82a3a669090df42ac7d53e1286fda2d
12,593
from typing import Optional from typing import Callable from typing import Any from typing import List import inspect def multikey_fkg_allowing_type_hints( namespace: Optional[str], fn: Callable, to_str: Callable[[Any], str] = repr) -> Callable[[Any], List[str]]: """ Equivalent of :fun...
33e04169618bae3e5d7239e5256afaa9f65355f6
12,594
def get_current_version() -> str: """Read the version of the package. See https://packaging.python.org/guides/single-sourcing-package-version """ version_exports = {} with open(VERSION_FILE) as file: exec(file.read(), version_exports) # pylint: disable=exec-used return version_exports["...
c283d58881aa381503bb3500bd7d745f25df0f7e
12,595
import random def seed_story(text_dict): """Generate random seed for story.""" story_seed = random.choice(list(text_dict.keys())) return story_seed
0c0f41186f6eaab84a1d197e9335b4c28fd83785
12,596
from pathlib import Path import sys def detect_conda_env(): """Inspect whether `sys.executable` is within a conda environment and if it is, return the environment name and Path of its prefix. Otherwise return None, None""" prefix = Path(sys.prefix) if not (prefix / 'conda-meta').is_dir(): # No...
2cb88ebfbb8a2919300e1d0072540e448dcf35ad
12,597
def _get_rel_att_inputs(d_model, n_heads): # pylint: disable=invalid-name """Global relative attentions bias initialization shared across the layers.""" assert d_model % n_heads == 0 and d_model % 2 == 0 d_head = d_model // n_heads bias_initializer = init.RandomNormalInitializer(1e-6) context_bias_layer = c...
57f58f29a586571f1cc8fa1fc69956a4168cbf16
12,598
def two_time_pad(): """A one-time pad simply involves the xor of a message with a key to produce a ciphertext: c = m ^ k. It is essential that the key be as long as the message, or in other words that the key not be repeated for two distinct message blocks. Your task: In this problem you will b...
d4c45312f32b372a065365c78a991969e2bc53be
12,599