content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def is_config_or_test(example, scan_width=5, coeff=0.05): """Check if file is a configuration file or a unit test by : 1- looking for keywords in the first few lines of the file. 2- counting number of occurence of the words 'config' and 'test' with respect to number of lines. """ keywords = ["unit ...
0e2823897b72a916afd9672beed904190bb2c1c2
701,404
import json def prepare_clean_listing_record(listing_serializer_record): """ Clean Record Sample Record (record_json) after clean { "id": 316, "title": "JotSpot 28", "description": "Jot things down", "unique_name": "ozp.test.jotspot.28", "description_short": "Jot stuff d...
7330b24f90345be14966f28d61e7665b0785a9e6
701,405
def has_shape(data, shape, allow_empty=False): """ Determine if a data object has the provided shape At any level, the object in `data` and in `shape` must have the same type. A dict is the same shape if all its keys and values have the same shape as the key/value in `shape`. The number of keys/val...
f04add860bb6b886bb693ddc85b3d4877245d749
701,406
def RR_calc(classes, TOP): """ Calculate Global performance index (RR). :param classes: confusion matrix classes :type classes: list :param TOP: number of positives in predict vector per class :type TOP: dict :return: RR as float """ try: class_number = len(classes) ...
814a11c339b25dc687d537efd3244ddad9c0f8fd
701,408
import torch def view_complex_native(x: torch.FloatTensor) -> torch.Tensor: """Convert a PyKEEN complex tensor representation into a torch one using :func:`torch.view_as_complex`.""" return torch.view_as_complex(x.view(*x.shape[:-1], -1, 2))
14e74f1c8b5e6de673c962e4381e74026d3d3db2
701,410
def cross_corr_norm(patch_0, patch_1): """ Returns the normalized cross-correlation between two same-sized image patches. Parameters : patch_0, patch_1 : image patches """ n = patch_0.shape[0] * patch_0.shape[1] # Mean intensities mu_0, mu_1 = patch_0.mean(), patch_1....
213100b174993baa07ea685b23541d3dfe49ace8
701,411
def get_flip_set(index): """Make flip set""" n = 1 while n <= index: n *= 2 def get(n, j): if j <= 1: return {b for b in range(j)} n_half = n // 2 if j < n_half: return get(n_half, j) f = {b + n_half for b in get(n_half, j - n_half)} ...
3174b9bab59ae67e9f869fddd9c0a6669f742a45
701,412
def site_stat_stmt(table, site_col, values_col, fun): """ Function to produce an SQL statement to make a basic summary grouped by a sites column. Parameters ---------- table : str The database table. site_col : str The column containing the sites. values_col : str T...
c704d5687effd3c12abb3feecde9041eb88aae7a
701,413
def _format_source_error(filename, lineno, block): """ A helper function which generates an error string. This function handles the work of reading the lines of the file which bracket the error, and formatting a string which points to the offending line. The output is similar to: File "foo.py", li...
32d093e53811415338877349ca8e64b0e9261b1d
701,414
def calc_exposure(k, src_rate, bgd_rate, read_noise, neff): """ Compute the time to get to a given significance (k) given the source rate, the background rate, the read noise, and the number of effective background pixels ----- time = calc_exposure(k, src_rate, bgd_rate, read_noise, neff) ...
993853d244cfa5c6619300def02294a2497d78df
701,415
def type_or_null(names): """Return the list of types `names` + the name-or-null list for every type in `names`.""" return [[name, 'null'] for name in names]
72cbefcbba08c98d3c4c11a126e22b6f83f4175b
701,416
def variables_pool(variable, question='Variable to analyze'): """ :param variable: the variable chosen from variable pool in your dataframe :param question: default parameter ("Variable to analyze") don't :return: """ def guide(diz): """ function that guides user to chose the ri...
fcff9eaa1467d96251ba08eaa433aa05b7b769f2
701,417
import torch def quadratic_matmul(x: torch.Tensor, A: torch.Tensor) -> torch.Tensor: """Matrix quadratic multiplication. Parameters ---------- x : torch.Tensor, shape=(..., X) A batch of vectors. A : torch.Tensor, shape=(..., X, X) A batch of square matrices. Returns ----...
78335f6a57f34701f3f1fe9b8dd74e9b8be686a3
701,418
def get_global_step(estimator): """Return estimator's last checkpoint.""" return int(estimator.latest_checkpoint().split("-")[-1])
11b4a96f74d029f9d9cc5a0fcc93da7504729eb7
701,419
import torch def box_iou(boxes1, boxes2): """Compute pairwise IoU across two lists of anchor or bounding boxes. Defined in :numref:`sec_anchor`""" def box_area(boxes): return ((boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])) # Shape of `boxes1`, `boxes2`, `a...
c358c15b99d0e742487a92630ff927606ad6d896
701,420
import os def getBranchPath(path): """Get a path rooted in the current branch. @param path: A path relative to the current branch. @return: A fully-qualified path. """ currentPath = os.path.dirname(__file__) fullyQualifiedPath = os.path.join(currentPath, '..', path) return os.path.abspath...
57897e58b57c704cea63549d437f22f96830d226
701,421
import uuid def rand_uuid(): """Generate a random UUID string :return: a random UUID (e.g. '1dc12c7d-60eb-4b61-a7a2-17cf210155b6') :rtype: string """ return str(uuid.uuid4())
fc35e154eeab62988bcd96799ce0f688f4ec427a
701,423
def filter_linksearchtotals(queryset, filter_dict): """ Adds filter conditions to a LinkSearchTotal queryset based on form results. queryset -- a LinkSearchTotal queryset filter_dict -- a dictionary of data from the user filter form Returns a queryset """ if "start_date" in filter_dict: ...
96a7e816e7e2d6632db6e6fb20dc50a56a273be9
701,424
import csv def get_column(path, c=0, r=1, sep='\t'): """ extracts column specified by column index assumes that first row as a header """ try: reader = csv.reader(open(path, "r"), delimiter=sep) return [row[c] for row in reader] [r :] except IOError: print('list_rows: f...
036a1630417224474e8bfe7a9c038a04bd3ea0d5
701,425
def find_in_list(list_one, list_two): """Find and return an element from list_one that is in list_two, or None otherwise.""" for element in list_one: if element in list_two: return element return None
9376b38a06cadbb3e06c19cc895eff46fd09f5c1
701,427
import sys import pickle def load_pickle(fname): """Loads a pickle file to memory. Parameters ---------- fname : str File name + path. Returns ------- dict/list Data structure of the input file. """ assert fname, 'Must input a valid file name.' if sys.version...
d5890aec8fd491b89b81e9e6c01ee658b1a843bd
701,429
def _real_freq_filter(rfft_signal, filters): """Helper function to apply a full filterbank to a rfft signal """ nr = rfft_signal.shape[0] subbands = filters[:, :nr] * rfft_signal return subbands
0bee4822ac1d6b5672e4ad89bb59f03d72828244
701,430
def _strip_extension(name, ext): """ Remove trailing extension from name. """ ext_len = len(ext) if name[-ext_len:] == ext: name = name[:-ext_len] return name
aa1e6f8c68e09597e2566ecd96c70d2c748ac600
701,431
def get_uuid_from_url(url: str) -> str: """ Strip the URL from the string. Returns the UUID. """ return url.split('/')[-1]
d9e0ea9ed186d1ba19c40ead9d08108c45dbf850
701,433
def texFrac(frac): """ Tex render for Fractions""" return ["\\frac{" , str(frac._num) , "}{" , str(frac._denom) , "}"]
fd0ed6af8b50f8a4b89e0d83d7cb3e3c3a5f3a90
701,434
from typing import List from typing import Optional def span_to_label(tokens: List[str], labeled_spans: dict, scheme: Optional[str] = 'BIO') -> List[str]: """ Convert spans to label :param tokens: a list of tokens :param labeled_spans: a list of tuples (start_idx, e...
dbd572d4c306f31202c93b5983f5dd4cdd237074
701,435
import argparse import os def build_args(): """ Constructs command line arguments for the vulndb tool """ parser = argparse.ArgumentParser( description="Fully open-source security audit for project dependencies based on known vulnerabilities and advisories." ) parser.add_argument( ...
ee24006780a225803cd503fb612264d49e37c7b2
701,436
def unimodal_converter(data): """ Returns ground truth labels when data is split modally to text and image data: dataframe object """ for column in ["string", "numeric"]: unimodal_image, unimodal_text = [], [] for i in range(len(data)): temp_val = data.loc...
623208e7b8ee9e4f1e494c95d7ec0c16558f85b9
701,437
def convert_ids_to_tokens(inv_vocab, ids): """Converts a sequence of ids into tokens using the vocab.""" output = [] for item in ids: output.append(inv_vocab[item]) return output
da1aa84d271fe46cedf530c2871ee54c57e676e2
701,438
import aiohttp async def remove_device( ws_client: aiohttp.ClientWebSocketResponse, device_id: str, config_entry_id: str ) -> bool: """Remove config entry from a device.""" await ws_client.send_json( { "id": 1, "type": "config/device_registry/remove_config_entry", ...
095926990c48a5f61267eb059591a80c48f7e3eb
701,439
import logging import pickle import time def load_obj(path): """ return the python object saved in the given path :param path: the path to be loaded :return: """ logger = logging.getLogger("load_obj") retry_count = 3 while retry_count > 0: try: with open(path, 'rb'...
d486846bdf284366a89a48e7d7ad0f86239b9f83
701,440
import importlib def _check_import(package_name): """Import a package, or give a useful error message if it's not there.""" try: return importlib.import_module(package_name) except ImportError: err_msg = ( f"{package_name} is not installed. " "It may be an optional ...
c4cb7c5a49071663d23e9530155bdee3304a5f72
701,441
import getpass def prompt(identifier) -> tuple: """Credential entry helper. Returns: Tuple of login_id, key """ login_id = input(f"API Login ID for {identifier}: ") key = getpass.getpass(f"API Transaction Key for {identifier}: ") return (login_id, key)
be0ed9be1a60c2c29753d6a9ca8b3f12294f183b
701,442
import torch def rotation_3d_in_axis(points, angles, axis=0): """Rotate points by angles according to axis. Args: points (torch.Tensor): Points of shape (N, M, 3). angles (torch.Tensor): Vector of angles in shape (N,) axis (int, optional): The axis to be rotated. Defaults to 0. R...
f9ae51e59e8531e25d376267b16746f5e88575e0
701,443
import pathlib def get_managed_environment_log_path(): """Path for charmcraft log when running in managed environment.""" return pathlib.Path("/tmp/charmcraft.log")
1d8c66d480094a728820ea80bdf1ad65a8859fe7
701,444
import time def generate_timestamp(expire_after: float = 30) -> int: """ :param expire_after: expires in seconds. :return: timestamp in milliseconds """ return int(time.time() * 1000 + expire_after * 1000)
16f2fcd77de9edb1e167f1288e37a10491469c22
701,445
import base64 def b64e(s): """b64e(s) -> str Base64 encodes a string Example: >>> b64e("test") 'dGVzdA==' """ return base64.b64encode(s)
2562f5d18ac59bbe4e8a28ee4033eaa0f10fc641
701,446
import yaml import random import string def tmp_config_file(dict_: dict) -> str: """ Dumps dict into a yaml file that is saved in a randomly named file. Used to as config file to create ObservatoryConfig instance. :param dict_: config dict :return: path of temporary file """ content = yaml...
d4ea42a8dc1824757df7f9823f44f7fc181b29aa
701,447
def computeAlleleFrequency (f_C, f_T): """3 f_C = minor allele count f_T = major allele count minor_allele_frequency = f_C/ (f_C+f_T) 7""" minor_allele_frequency = f_C/(f_C+f_T) return minor_allele_frequency
984a7364bfd3ff2c724c885dedd97f61f959b7e6
701,448
def microcycle_days(weekly_training_days, weeks): """generates indexes of training days during the weeks""" training_day_indexes = [] for w in range(weeks): for d in weekly_training_days: training_day_indexes.append(w * 7 + d.value) return training_day_indexes
5c0364b1dc58d2c0205d4e6442d590a23519e5f4
701,449
import pprint def check_overlapping(features): """Check for elements of `features` with overlapping ranges. In the case of overlap, print an informative error message and return names and positions of overlapping features. """ features = features[:] overlapping = [] for i in range(len(fea...
6a246aca29c01b32091d7890b6a55d66367e8e14
701,450
def compute_level(id, tree): """ compute the level of an id in a tree """ topic = tree[id] level = 0 while (id != 0): level += 1 id = topic['parent'] topic = tree[id] return(level)
fb7fbc1c1f97e85c03abdd453a3deb3411960e45
701,451
import torch import math def eval_gather_inds(len_, num_samples=7): """ get the gather indices """ inds = torch.arange(0, num_samples, dtype=torch.long) mul = math.ceil(len_ / num_samples) output = inds.repeat(mul)[:len_] return output
516ca54ff5c3b442bc93becd15d1bdabd8c8025f
701,452
def none_or_valid_float_value_as_string(str_to_check): """ Unless a string is "none", tries to convert it to a float and back to check that it represents a valid float value. Throws ValueError if type conversion fails. This function is only needed because the MATLAB scripts take some arguments eithe...
54f3c63fab0752678cb5a69723aa7790ab11a624
701,453
def S_moving_average_filter(_data_list, _smoothing=1): """ Returns moving average data without data lag. Use the smoothing factor to get required overall smoothing where the smoothing factor is greater than zero. """ ma_data = [] ds = len(_data_list) s = _smoothing mas = int((ds...
763bff294c6225260cb67e2e38440eb4d514c126
701,454
def get_expanse_certificate_context(data): """ provide custom context information about certificate with data from Expanse API """ return { "SearchTerm": data['search'], "CommonName": data['commonName'], "FirstObserved": data['firstObserved'], "LastObserved": data['lastOb...
cf5c1d38ae7ed3474171ccff7d437d7b622cbcec
701,455
from datetime import datetime def convert_time(time_str): """Convert iso string to date time object :param time_str: String time to convert """ try: dt = datetime.strptime(time_str, "%Y-%m-%dT%H:%Mz") return dt except Exception: return time_str
4ba3d5b8af4305cc44afb60d02eeb1b1d041fab9
701,456
def suck_out_formats(reporters): """Builds a dictionary mapping edition keys to their cite_format if any. The dictionary takes the form of: { 'T.C. Summary Opinion': '{reporter} {volume}-{page}', 'T.C. Memo.': '{reporter} {volume}-{page}' ... } In other ...
a0db907839573ca53f7c96c326afe1eac5491c63
701,457
def cast_bytes(data, encoding='utf8'): """ Cast str, int, float to bytes. """ if isinstance(data, str) is True: return data.encode(encoding) elif isinstance(data, int) is True: return str(data).encode(encoding) elif isinstance(data, float) is True: return str(data).enco...
01ac5d7cd4a728e401075334900808a6a579deef
701,458
def B(i,j,k): """ Tensor B used in constructing ROMs. Parameters ---------- i : int j : int k : int Indices in the tensor. Returns ------- int Tensor output. """ if i == j + k: return -1 elif j == i + k or k == i + j: return 1 el...
b4969759fd2f07bd2bd2baed48a2adfd8669987a
701,459
import io def format_data(data, indent): """Format a bytestring as a C string literal. Arguments: data: Bytestring to write indent: Indentation for each line, a string Returns: A multiline string containing the code, with indentation before every line including the first. There is...
260e2b296addeb1113d657b086302197a8e365bb
701,460
def sample(bn, cond=None): """ Sample every variables of a Bayesian Network :param bn: a Bayesian Network :param cond: dict, given variables :return: """ g = bn.DAG cond = cond if cond else dict() if any(nod not in cond for nod in bn.Exo): raise ValueError('Exogenous nodes do...
81606afea08f1e80b73d115ed6a6a2581c13890c
701,461
def psf_to_inhg(psf): """Convert lb/ft^2 to inches of mercury.""" return psf * 0.014139030952735
c1a482c71ad86ae31efece5f1a395fa354db8c3e
701,462
def get_version(v): """ Generate a PEP386 compliant version Stolen from django.utils.version.get_version :param v tuple: A five part tuple indicating the version :returns str: Compliant version """ assert isinstance(v, tuple) assert len(v) == 5 assert v[3] in ('alpha', 'beta', 'rc...
946c9ea382ac7da0da1c74373cf981df174737c1
701,463
def get_nuc2prot(): """ Returns a dict of nucleotide accessions numbers as keys and protein acession numbers as values. """ nuc2prot_acc = {} with open("./data/download/nucleotide2protein", "r") as handle: line = handle.readline() while line: prot, nuc = line.split("...
8f6e0ab5ad76cfaa63d8c0bf12f84e18b759e750
701,464
def tadsize_chart(genome_name): """ Determine the distance threshold to build coverage tracks. Args: genome_name (string): name of the reference genome; ex: mammals, drosophila, c_elegans, s_pombe, c_crescentus Returns: dist_thresh (int): integer specifying dist...
844744424845a1d240fa93023b9786a7ed2cc12c
701,465
def convert_results_to_table(results, aggregation="average"): """ Convert results to table Args: results (dict): results dictionary aggregation (str): aggregation method, either average or sum """ headers = [] columns = [] for target_task, source_tasks in results.items(): ...
51d38a52cb5428568c89e518df86624c5f438cf6
701,466
import mmap def is_word_in_file(fname, word): """ Search word in given file. This function skips empty files. """ f = open(fname) try: s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) if s.find(word) != -1: return True return False except ValueError: ...
c16b94bb450807fefdab35470535c0752a9ecbbd
701,469
def emat(st1, yt, t, a=None): """ returns exponential moving average for a t-period EMA and incremental value where st1 is the previous average, yt is the incr value, and t is the size of the avg a can optionally be overridden with a specific coefficient, else 2/(t-1) is used """ # St = a...
484403ca5ba13bd960bcda6220846eef9ac09114
701,470
import os def relpath(path, cwd=None): """ Find relative path from current directory to path. Example usage: >>> from Ska.File import relpath >>> relpath('/a/b/hello/there', cwd='/a/b/c/d') '../../hello/there' >>> relpath('/a/b/c/d/e/hello/there', cwd='/a/b/c/d') 'e/hello/t...
a743e02cb51ee352d7bbef047af13152c5834c14
701,471
def get_service_type(f): """Retrieves service type from function.""" return getattr(f, 'service_type', None)
fb4d98a4b4db0d10ab97d94d98ccfe21cea05fe9
701,472
def compute_error(model_data, reference_data): """Returns the summ of the squared differences between model and reference data.""" error = ((model_data - reference_data) ** 2).sum() return error
66e80326b85eed67008b517dfeff99cc8352bffd
701,474
import json import sys def read_json_file(json_path): """ Read inventory as json file """ tf_inv = {} try: with open(json_path) as json_handler: try: tf_inv = json.load(json_handler) except json.decoder.JSONDecodeError: print( ...
6758e50c441c10ed3e0c7e68b1ed87abbbeff6b1
701,476
import json def dj(_dict): """Converts dicts to JSON and safely handles non-serializable items""" return json.dumps( _dict, default=lambda o: 'ERROR: Item not JSON serializable', sort_keys=True, indent=3)
042fdc731a084e1d74175a1ac22bc5b4204050c6
701,477
def is_decorated(field_spec): """ is this spec a decorated one :param field_spec: to check :return: true or false """ if 'config' not in field_spec: return False config = field_spec.get('config') return 'prefix' in config or 'suffix' in config or 'quote' in config
b44d13fbcadc67ac191d07b1c304f2ec5ce1f081
701,478
def split_path(path): """ Normalise S3 path string into bucket and key. Parameters ---------- path : string Input path, like `s3://mybucket/path/to/file` Examples -------- >>> split_path("s3://mybucket/path/to/file") ['mybucket', 'path/to/file'] """ if path.startswi...
446f7643066864937e11b915d4ff842f21c65dd6
701,479
def unixtime2mjd(unixtime): """ Converts a UNIX time stamp in Modified Julian Day Input: time in UNIX seconds Output: time in MJD (fraction of a day) """ # unixtime gives seconds passed since "The Epoch": 1.1.1970 00:00 # MJD at that time was 40587.0 result = 40587.0 + unixtime / (2...
670e915b7a5de8cd9ced28e6b4d32c51ac916d54
701,480
def vecdist3(coord1, coord2): """Calculate vector between two 3d points.""" #return [i - j for i, j in zip(coord1, coord2)] # Twice as fast for fixed 3d vectors vec = [coord2[0] - coord1[0], coord2[1] - coord1[1], coord2[2] - coord1[2]] return (vec[0]*vec[0] + vec[1]*vec[1] + ...
0315ec921c051eb46da9f073e6bc76b2a0a448bb
701,481
def num_active_calls(log, ad): """Get the count of current active calls. Args: log: Log object. ad: Android Device Object. Returns: Count of current active calls. """ calls = ad.droid.telecomCallGetCallIds() return len(calls) if calls else 0
a6674df1e8e539478db6ab1a640fbce1cf0b6b4c
701,482
import os def create_dir(ctx, param, value): """ a command option callback to create parent directories if does not exist """ pardir = os.path.dirname(value.name) if hasattr(value, 'name') else None if pardir: os.makedirs(pardir, exist_ok=True) return value
6a573ebbc0ddc5c4a8f0f15fa0fc91566610bc28
701,484
def density_standard(components): """ Natural gas density at standard temperature, kg/m3 :param components: (list) List of gas components. Each item is an object of class GasComponent :return: (float) The density of natural gas an standard parameters, kg/m3 """ return sum([component.density_sta...
c087ce6ae1a3486dd092341286023c56606380a3
701,485
import re def range_address_number(num, include_last=True): """ '5-7' -> [5, 6, 7] '5' -> ['5'] :param num: :return: """ range_re = re.search('(\d+)-(\d+)', num) if range_re: min, max = list(map( lambda i: int(i), list(range_re.groups()) )) ...
3c67ddcba2a25915fce89c198d4d4f2a11f5ef60
701,486
def generate_test_uuid(tail_value=0): """Returns a blank uuid with the given value added to the end segment.""" return '00000000-0000-0000-0000-{value:0>{pad}}'.format(value=tail_value, pad=12)
f113eef54eba9d8d1fb5234c87af3cb6290ea25e
701,487
def format_revision_list(revisions, use_html=True): """Converts component revision list to html.""" result = '' for revision in revisions: if revision['component']: result += '%s: ' % revision['component'] if 'link_url' in revision and revision['link_url'] and use_html: result += '<a target="...
d49e91069a1f33a7ee32963e81a3e19ea768d3ea
701,488
from typing import Dict async def total() -> Dict: """ Sum of a list of numbers --- tags: - Total get: parameters: - N/A response: 200: description: returns a dictionary with a total sum of a list of numbers """ retu...
67c1d1abf6c76c533d8ea776dbb46a4184b0fca5
701,489
from bs4 import BeautifulSoup def bishijie_info_parse(parse_str:str = ''): """ 传入一个待解析的字符串 """ # html_info = etree.HTML(parse_str,parser=None) soup = BeautifulSoup(parse_str,features="lxml") info_list = soup.find_all('div',class_="content") result_info_list = [] for info in info_list:...
e89a875f9c98b3b9cabeed2eb362ad1196b14275
701,490
def extractAliasFromContainerName(containerName): """ Take a compose created container name and extract the alias to which it will be refered. For example bddtests_vp1_0 will return vp0 """ return containerName.split("_")[1]
a5ab9487ae31ee1a4b2ed9b67062817488107983
701,491
def HexToByte( hexStr ): """ Convert a string hex byte values into a byte string. The Hex Byte values may or may not be space separated. """ # The list comprehension implementation is fractionally slower in this case # # hexStr = ''.join( hexStr.split(" ") ) # return ''.join( [...
eab4fd7ecaae10add8411cf51c03d1bf5b902700
701,492
def get_string(request, key): """Returns the first value in the request args for a given key.""" if not request.args: return None if type(key) is not bytes: key = key.encode() if key not in request.args: return None val = request.args[key][0] if val is not None and typ...
ae43bb3e11cf21deb8f726ed6a2321c51099e4f3
701,494
def map_serial_number(facilities) -> str: """Map serial number.""" facility = facilities.get("body", {}).get("facilitiesList", [])[0] return str(facility.get("serialNumber", None))
81491de02a2583d30ee31833a427b4ffdebe6a88
701,496
def _get_maxmem(profile_df): """ Get current peak memory :param pandas.core.frame.DataFrame profile_df: a data frame representing the current profile.tsv for a sample :return str: max memory """ return "{} GB".format(str(max(profile_df['mem']) if not profile_df['mem'].empty else 0))
2e628d48f7b4e0e3c1465f09da7aa795d2954a06
701,497
import torch def MaskedNLL(target, probs, balance_weights=None): # adapted from https://gist.github.com/jihunchoi/f1434a77df9db1bb337417854b398df1 """ Args: target: A Variable containing a LongTensor of size (batch, ) which contains the index of the true class for each corr...
17132ad088b00ae096f16946f5026ed2133c8eeb
701,499
async def process_headers(headers): """Filter out unwanted headers and return as a dictionary.""" headers = dict(headers) header_keys = ( "user-agent", "referer", "accept-encoding", "accept-language", "x-real-ip", "x-forwarded-for", ) return {k: header...
32feeb40c12c4b69d65da1c178e396e85fc9e557
701,500
def by_circ(x, y): """ Sort circRNAs by the start and end position """ return x.end - y.end if x.start == y.start else x.start - y.start
5d8205389960b92f10c450fdb6385678a279406b
701,503
import yaml def get_rest_of_manifest_values(): """ If an existing manifest is present then we do not want to overwrite any fields the user may have filled out. So we want to read in everything but the resources: section and use that when generating the file. """ stream = open('hardening_manifest/harde...
03cc8afbcdf26a91596d189bafecce08c9cf2895
701,504
import sys import gc def nogc(func): """disable garbage collector Python's garbage collector triggers a GC each time a certain number of container objects (the number being defined by gc.get_threshold()) are allocated even when marked not to be tracked by the collector. Tracking has no effect on ...
cdc9a1f48608d84b8a3e568bb0b50a6f12ffa34a
701,505
def _normalize_longitude(lon: float) -> float: """Normalize longitudes between [-180, 180]""" return ((lon + 180.0) % 360.0) - 180.0
e50dc8fee9a0499a2e32f3ccf8b2e9a634581bba
701,507
def get_tf_tensor_shape(tensor): """Get tensor shape, if there is unkown tensor, set it as None""" shape = [] try: shape = tensor.get_shape().as_list() if any(s is None for s in shape): return None return shape except Exception: # pylint: disable=broad-except shape = None return shape
33c7e17102ad2f7d407c1f86b13c7cdfa61ca677
701,508
def _update_selected_experiment_table_rows( last_select_click, last_clear_click, experiment_table_indices ): """The callback to select or deselect all rows in the experiment table. Triggered when the select all or clear all button is clicked. """ last_select_click = last_select_click if last_select...
7a527272c780750ea9cbc076f0d947fe9b68a460
701,509
def rc4Decrypt(data, key): """RC4 algorithm""" x = 0 box = list(range(256)) for i in range(256): x = (x + int(box[i]) + int(key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] x = y = 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 ...
91c959cf03410626378647ab6d85391e5b0970d2
701,510
def _move_tutor_version_groups(table): """Tutored moves are never the same between version groups, so the column collapsing ignores tutors entirely. This means that we might end up wanting to show several versions as having a tutor within a single column. So that "E, FRLG" lines up with "FRLG", there h...
5b9d43a11d5e5d92351ac5b93a7ada5b8d5daa36
701,511
import textwrap def make_code_format(light_theme: bool = False) -> str: """Create code format template for rich.""" theme = "light" if light_theme else "dark" code_format = textwrap.dedent( f"""\ <div class="terminal-container"> <div class="terminal {theme}-terminal"> ...
deb5d97f3bce85c1ef91d4c9e88b68474d70c173
701,512
def _wrapped_value_and_num(value): """Returns a list containing value plus the list's length.""" if isinstance(value, (list, tuple)): return value, len(value) else: return [value], 1
811521a18dffd9ee046751c74d4d8a097662c8cd
701,514
def perform_fit(cfmclient, fabric_uuid, name, description): """ Request a full fit across managed Composable Fabrics. :param cfmclient: CFM Client object :param fabric_uuid: Valid Fabric UUID of an existing fabric :param name: Simple name of the fit :param description: Longer Description of the ...
66d6462c97b1354ef11b6378b82912030ed40a94
701,515
def make_task_hashable(task): """ Makes a task dict hashable. Parameters ---------- task : dict task that shall be made hashable. Returns ------- TYPE hashable task. """ if isinstance(task, (tuple, list)): return tuple((make_task_hashable(e) for e in task)...
4e27fe4c27c4ae220ed8b15ce701f2d87796b715
701,516
from pathlib import Path def parent(path: str): """Returns the parent `Path` of the given path.""" return Path(path).parent.resolve()
d86b37bc8310b024eb0a78c1b1de404cf6c2c85a
701,517
def get_phone_number(phone_number): """ Following suggested RFC 3966 protocol by open id expect: +111-1111-111111 format """ if '-' in phone_number: phone_split = phone_number.split('-') if len(phone_split) > 2: #if had country code return phone_split[2] ...
287d3dde0cabc3c7730ac48bf94b2c4fc809f123
701,518
def mes_com_acentos(mes_a_mudar): """Retorna Mês com Maiúsculas e Acentos.""" meses_a_exibir = { 'janeiro': 'Janeiro', 'fevereiro': 'Fevereiro', 'marco': 'Março', 'abril': 'Abril', 'maio': 'Maio', 'junho': 'Junho', 'julho': 'Julho', 'agosto': 'Agos...
8361d7e747d524242eeb572b839305d58021b35d
701,519
import base64 def b64encode(value): """ Encode a value in base64 """ return base64.b64encode(value)
988abf5a9d2c0c1f38f16fbf8f80fd43aa115223
701,520
import os def get_audio_embedding_model_path(input_repr, content_type): """ Returns the local path to the model weights file for the model with the given characteristics Parameters ---------- input_repr : "linear", "mel128", or "mel256" Spectrogram representation used for model. c...
8a3d0a5d09896467b672e8dde47b1a6a500cdce8
701,521