content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def get_last_conv(m): """ Get the last conv layer in an Module. """ convs = filter(lambda k: isinstance(k, torch.nn.Conv2d), m.modules()) # print('convs:', convs) # print('list(convs)[-1]:', list(convs)[-1]) return list(convs)[-1]
1a8c7fa6f37fd7dabd766f7ad9f78eab2f7401a2
575,387
def _process_chunk(fn, chunk): """ Processes a chunk of an iterable passed to map. Runs the function passed to map() on a chunk of the iterable passed to map. This function is run in a separate process. """ return [fn(*args) for args in chunk]
f5e43a55d629f034fb193a82a3b494e6204264ad
575,389
def stretch(seq, n): """ Form a new sequence by duplicating every sample in seq n times. """ stretched = [] for s in seq: for _ in range(n): stretched.append(s) return stretched
cb69f5e98f6f21df04fb37cd42549f2f65373a8e
575,390
import warnings def viscosity_H2O(temp): """ Calculates the viscosity (Pa*s) of water at temperature T in Kelvin. Warning ------- Function is a fit to data of the viscosity of water at different temperatures [0, 100]. Do not use it outside this range! References ---------- C...
1af1c1dc9855168788a18dd596930c29a334a032
575,392
def num_trace_events(data): """Returns the total number of traces captured """ return len(data["traceEvents"])
1e13906ff0bd59a44a0ce9d5838c90bf89378e55
575,393
def str_join_instruction_options(dct): """ Build a string from the given dict that represents key/value pairs of optional instruction arguments. :param dct: Collection key/value pairs to join :return: Formatting string with double-dash options """ return ''.join(('--{}={}'.format(k.lower(), v) ...
2a1464d0a08b479175ce32ae0c805d9f13d0e5fc
575,394
import hashlib def HashFile(f): """Returns SHA-256 hash of a given file.""" if type(f) is list: f = f[0] try: return hashlib.sha256(open(f,'rb').read()).hexdigest() except: return 'UNKNOWN'
c776724d2e6e17204fd562f74a4ef30248e9b935
575,395
def has_parameter(param, params): """ Checks whether the parameter param is present in the params map. Args: param A parameter name params A dictionary of parameters Returns: True if params contains param. Returns False otherwise. """ return params.has_key(param)
37f6844779ed877f398eee0e6c36512478c46ff2
575,398
import requests def get_linked_status(gh_headers, linked_issue_info): """ Returns the open/closed status of the linked issue """ lorg, lrepo, lnum = linked_issue_info print(f"::set-output name=linkedIssueInfo::Found a \ linked issue: {lorg} {lrepo} {lnum}") issue_url = f"https://api...
1874833868cf8132457e75b95eb02ffe17078c54
575,401
def make_channel_dict(ordered_index): """Creates a Dictionary of the the indexes for each Channel's features in the ordered_index Parameters: ----------- ordered_index: list Index of Features for Feature Dropping [list] -> (Tuple) Power: [Num of Features] -...
4b9882d5e7bfe54bd646d84e4a3c21c0d4d8e7ef
575,406
def hyphen_range(s): """ Takes a range in form of "a-b" and generate a list of numbers between a and b inclusive. Also accepts comma separated ranges like "a-b,c-d,f" will build a list which will include Numbers from a to b, a to d and f""" s = "".join(s.split()) #removes white space r = set() ...
829b8f536cc73532f6f36f283ca9bbecf119710d
575,411
def count_diff(str1, str2): """ Counting the number of different chars between two string. Assuming len(str1) == len(str2) """ count = 0 for i in range(len(str1)): if str1[i] != str2[i]: count += 1 return count
de9411ff2c233d30972cb92598d4d317614438c7
575,416
def select_time(da, **indexer): """Select entries according to a time period. Parameters ---------- da : xarray.DataArray Input data. **indexer : {dim: indexer, }, optional Time attribute and values over which to subset the array. For example, use season='DJF' to select winter values, ...
605fec77f1ad58194d5c5e2d5cb132509677ea64
575,417
from typing import List from typing import Any def line_to_csv(line: List[Any]) -> str: """ Turn a list of Python objects into a comma separated string. Args: line: List to turn into CSV Returns: Line represented as a comma separated string """ items = [] for item in lin...
8e641c169045e85b0157d8236c06b67fac91f408
575,422
def createc_auxadc_7(stm): """ Function to return the LHe temperature as float number in Kelvin Parameters ---------- stm : createc.CreatecWin32 Createc instance Returns ------- temperature : float """ stm.client.setparam('MEMO_STMAFM', '') # dummy function to 'manuall...
0c890f58e77c3fd80e3c93e1217dc96d6bd004ac
575,423
def _path_names(xpath): """Parses the xpath names. This takes an input string and converts it to a list of gNMI Path names. Those are later turned into a gNMI Path Class object for use in the Get/SetRequests. Args: xpath: (str) xpath formatted path. Returns: list of gNMI path names. """ if not x...
ef6c65b6807dee0038b1e7298309bef2c04ae068
575,425
def parser_argument(parser): """short name of the parser with dashes and with -- prefix""" return f'--{parser}'
95ae231b57f8a2f28cb561154a88d4f10dd3ac34
575,427
import array def square_wave(sample_length: int = 2): """Generate a single square wave of sample_length size""" square = array.array("H", [0] * sample_length) for i in range(sample_length // 2): square[i] = 0xFFFF return square
e6dbdbc3cc730c19a0117ab0407032bb37e17432
575,429
def split_str(text): """Split a string on comma. Required for the pickling of the vectoriser.""" return text.split(',')
e18f8c4e296c38332c04fe1f88688480c65eec2e
575,439
def mark_no_copy_rules(grammar): """ Takes a 'simple' grammar where each rule is not marked as being a copy rule or not, and returns the same grammar but with an extra field that marks that this rule is not a copy rule (False) """ return [ (lhs,[ (r,False) for r in rhs ]) for (lhs,rhs) in grammar ]
626718d06bf623463270351147d84da79b99952b
575,441
import csv def split_table(table_ref, schema_required=True): """ Returns schema and table name given list of input values. table_ref (List): Table reference i.e ['my.schema.my_table'] scehma_required (boolean): Indicates whether schema is required. A source table reference requires schema. A target t...
8900024626e6d83f4dff44ff6aa0dcfb4bb8d84c
575,443
def good_suffix_mismatch(i, big_l_prime, small_l_prime): """ Given a mismatch at offset i, and given L/L' and l' arrays, return amount to shift as determined by good suffix rule. """ length = len(big_l_prime) assert i < length if i == length - 1: return 0 i += 1 # i points to leftmo...
7aa6f28be6e39858795e781f84b8774bc87870d5
575,447
def is_label_on_pull_request(repo, pull_request, label_name): """Returns True if the given label is on the pull request with the given pull request number. False otherwise.""" labels = list(repo.issue(pull_request.number).labels()) return any(label_name == issue_label.name for issue_label in labels)
2bf3f97335a91ac3a622342c1b4d647a11cd59b2
575,452
def get_json_data(context): """Retrieve JSON data.""" json_data = context.response.json() assert json_data is not None, \ "JSON response from the previous request does not exist" return json_data
055482ea5e3b69ca38ce2fe283502b627b4f92f2
575,453
def normalize_photo_name(instance, filename): """Renames avatar image to match the username.""" return u'img/user_photos/%s_avatar.%s' % ( instance.user.username, filename.split('.')[-1])
271c382d0ab1b81c3cff816cac12b19e98910a7f
575,454
def anyMoreThanOne(dict, keys): """ Checks if any of a list of keys in a dictionary has a value more than one. Arguments: dict -- the dictionary keys -- the keys Returns: True if any key exists in the dictionary and the value is at least one, otherwise false """ for key in keys: if key in dict and...
f9bfaa95da224a1899543be0d5e20609a1556a3d
575,455
def sanitise_config(config): """Return a sanitised configuration of a switch device. :param config: a configuration dict to sanitise. :returns: a copy of the configuration, with sensitive fields removed. """ sanitised_fields = {"password"} return { key: "******" if key in sanitised_fiel...
ee446c9cd514c43a238952e2fee41ffdb8c99a86
575,457
import time def expect(functional, expected, interval=0.2, timeout=2): """Helper function to run a function with expected latency""" delay = 0 result = None while result is None or len(result) != expected: try: result = functional() if len(result) == expected: break ...
7bf4167f410856f1a4b4b6b27c5c94863073448c
575,460
def convert_to_prob(Matrix): """Conver count transition matrix to probability.""" prob_matrix = [[r/sum(row) if sum(row) != 0 else r for r in row] for row in Matrix] return prob_matrix
99dc4674f4cebce7b4090290f50a8e8b3b389099
575,466
def voxels_are_isotropic( nifti_header ): """Given just a NIfTI-1 header object, returns True if voxel pixdims (header.structarr['pixdim'][1:4]) are all the same; False otherwise.""" pixdim = nifti_header.structarr['pixdim'][1:4] if pixdim[0] != pixdim[1] or pixdim[0] != pixdim[2] or pixdim[1] != pixdi...
9351e507faf955b9db5bfe696bab311bc1b36283
575,467
def get_chromosome_priority(chrom, chrom_dict={}): """ Return the chromosome priority Arguments: chrom (str): The cromosome name from the vcf chrom_dict (dict): A map of chromosome names and theis priority Return: priority (str): The priority for this chromosom """ ...
bcb077f9eeabed69612df90d1e5ae4fb8ccd65bb
575,472
import numbers def fibonacci(n): """Restituisce l'n-esimo numero della sucessione di Fibonacci Parameters ---------- n : int Numero intero maggiore o uguale a 1. Returns ------- fib : int N-esimo numero della sucessione di Fibonacci. """ if not isinstance(n, numbe...
7d056f8508f5c41f22ed287e38e51faa2c190591
575,477
def js_quote(string): """Prepare a string for use in a 'single quoted' JS literal.""" string = string.replace('\\', r'\\') string = string.replace('\'', r'\'') return string
0a00bd23b5aa237c0689dcb1a6f9845456808b55
575,479
def is_empty(in_str): """ return empty string with default value "na" """ if len(str(in_str)) > 0: return str(in_str) else: return "na"
fb023c4e72e12a6feca4d9e19c69dddbf623f50f
575,480
def fig_size(width_pt, fraction=1, ratio=(5 ** .5 - 1) / 2, subplots=(1, 1)): """ Returns the width and heights in inches for a matplotlib figure. :param float width_pt: document width in points, in latex can be determined with \showthe\linewidth :param float fraction: fraction of the width with which ...
239849f276af34411fa8f789c1c144c577fd3ff7
575,482
def main_sail_area(boom, mast): """ boom is usually called E, mast is usually called P >>> main_sail_area(15, 45) 375.0 """ return (boom*mast)/1.8
27b98481aeedc849e47f42f5ad2a2735e1d6bee0
575,490
def merge_usage_periods(periods, new_period): """Merge a time period into an existing set of usage periods""" outlist = [] for period in periods: if new_period[0] > period[1]: # No overlap - past the end outlist.append(period) continue if new_period[1] < p...
d4705ca0bd088431e5f6f5e1b90bb75cf431a34b
575,495
def create_tasks(clips, **kwargs): """Create metadata dictionaries to send as Celery tasks'""" # Append project details to each clip tasks = [dict(item, **kwargs) for item in clips] return tasks
826fc43cf203e331e1bb5d2993def648da1c6467
575,497
def escape_dn_for_filter(anything: str) -> str: """Escape an LDAP distinguished name so that it can be used in filters without confusing the server. Distinguished names already have some special characters escaped or encoded, so we must use this function instead of the generic escape function, which would e...
5f7932ac8935f31426ea60edb73a3eb0502d6f96
575,509
def norm_path(path): """Normalizes directory paths to be consistent. Parameters ---------- path : str Path to a directory. Returns ------- str Normalized path. """ normd_path = path # Initializes path variable. # Makes sure path ends with forward slas...
dcebc2f373f27d724defc6544350ae85135cfab9
575,510
import logging def filter_under_n(all_trees: list, n: int) -> list: """ Takes a list of tree dictionaries and filter trees that have under n nodes. Arguments: all_trees {list} -- list of dictionary conversation trees like [{'node_id: node object}] n {int} -- the minimum number of nodes a...
9b86c44fab863b1deb5205bcf7cf4300b1e73268
575,512
def R (Rmin, beta): """ Calculates the actual reflux number. Parameters ---------- R_min : float The minimal reglux number, [dismensionless] beta : float The overflow of reflux, [dismensionless] Returns ------- R : float The actual reflux number, [dismensi...
9541d74b45d20b48e349814a89195e1864d12cdc
575,513
def convert_geo_id_to_tract_id(geo_id): """ Converts an 11-digit GEOID to a Chicago census tract id. (Assumes the geo_id refers to a place in Chicago). :param geo_id: The US Census Gazetteer GEOID to convert. :return: The last six digits of the GEOID, equivalent to the census tract id. """ retur...
3061b0dea955abb588ec7a535550ccd92166d38b
575,514
def negate(sub_filter): """ Negate a filter, opposing its meaning. """ return ~sub_filter
11f4575c7808785e5ee5a97747bb45cd9d706cba
575,518
def format(dt): """Returns date in YYYYMMDD format.""" return dt.strftime('%Y%m%d')
06c0823dfc593be0ed5b441640c82aa1eb3edea7
575,522
import struct def parse_aurinkopenkki(hex_str, port=None): """ Parse payload like "3a2c0000018906438046933f478a773cc82a00003501000000000000113b00002f000000" float values :param hex_str: EnergiaBurk hex payload :param port: LoRaWAN port :return: dict containing float values """ b = bytes.fr...
6f7e9d2d968cb00ecf08ca1df7f02c9aa9ed2350
575,525
import torch def remove_bbx_abnormal_z(bbx_3d): """ Remove bounding box that has negative z axis. Parameters ---------- bbx_3d : torch.Tensor Predcited 3d bounding box, shape:(N,8,3) Returns ------- index : torch.Tensor The keep index. """ bbx_z_min = torch.mi...
b598da809600ef50c84c14b42554490c3b0131bf
575,526
def mild_in(item, container): """Returns true iff item, or its reverse, is already in container""" assert len(item) == 2 return item in container or tuple(reversed(item)) in container
691dc5d3783a165b24671aca5acd7f81859fdee0
575,528
def pl_psd(f, Si, fL): """ Return the power spectral density P(f) = (f / yr) ^ {-Si} * Theta(f - fL) @param f: Frequency @param Si: Spectral index @param fL: Low-frequency cut-off """ rv = f**(-Si) rv[f < fL] = 0.0 return rv
9565725fd54e9738ec505e7c3789646cd0f93c94
575,532
def get_users_for_domain(service, domain, query): """ Get all users for a specified domain via Google API. :param service: Authenticated directory service object :param domain: The domain for users :return: List of all users """ results = service.users().list( domain=domain, ...
5d017c24fb60e6c6f19f0025e38224c559d6106e
575,535
def get_colors(all_palettes=False): """ Generates a dictionary of standard colors and returns a sequential color palette. Parameters ---------- all_palettes : bool If True, lists of `dark`, `primary`, and `light` palettes will be returned. If False, only the `primary` palette wi...
baf26aa376a2b4edef3df74c14e084079d5a0891
575,537
def clampVariable(v, min, max): """Make sure variable is on the range [min,max]. Return clamped variable. """ if v < min: v = min elif v > max: v = max return v
05fa11eae9475d39659cb8954459022c69a4ac23
575,538
import re def _to_snake_case(s: str) -> str: """Transforms a string from CapWords to snake_case. Args: s: The string to transform Returns: The transformed string """ return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s).lower()
e8bd0005ae379de56a6e15606370dda20317d8e0
575,539
def make_decision(network, player_ship, enemy_ship): """ Create the input list based on the ship positions and then calculate and return the decision made by the NN Args: network : The network that must make this decision player_ship (PlayerShip): The player ship enemy_ship (En...
0a9f8deb7d97c04a73068a044f1e821ae71f983e
575,540
def dummy_job(job, return_value): """ This job will return whatever it was passed as an argument :param return_value: Any object of any pickle-able type :return: return_value """ return return_value
36c0ddc454886038f74abc322e7fc939a93b2760
575,541
def load_permutations(filename="preferences.csv"): """ Load all student permutations from a file Parameters ---------- filename: string Path to a file Returns ------- animals: A list of animals in alphabetical order raters: dictionary( string (Ranker's name): l...
dd7566fd7285a28c7cf647c9b83f5bb208b26f49
575,543
def average(lst): """ Count average from the list of numbers """ return sum(lst) / len(lst)
997fcbcdbc7f185028c854f3789a0a176a4b89c8
575,546
def required_points(order: int, accuracy: int) -> int: """Compute the number of points necessary to achieve an approximation of the given accuracy. Important note: this function assumes that the points will arranged symmetrically around 0. Corollary 7 from https://arxiv.org/pdf/1102.3203.pdf then says that...
027ec02fce54c3e3dead612f53699a2c1db9083d
575,549
import json def sample_event() -> dict: """Get sample SQS event from local filesystem""" f_sample_event = open('./data/sample_event.json') json_sample_event = json.load(f_sample_event) f_sample_event.close() return json_sample_event
27ffe4e35282d83b59dfb7e856adb546ed27b53b
575,554
def _top_k(indices, indptr, data, k_per_row): """ Parameters ---------- indices: np.ndarray, shape [n_edges] Indices of a sparse matrix. indptr: np.ndarray, shape [n+1] Index pointers of a sparse matrix. data: np.ndarray, shape [n_edges] Data of a sparse matrix. k_pe...
a56586d858085ef12b37ca04114646e420dbeefa
575,555
import unittest def get_testsuites_in_module(module): """ Return a list of unittest.TestSuite subclasses defined in module. """ suites = [] for name in dir(module): obj = getattr(module, name) if isinstance(obj, type) and issubclass(obj, unittest.TestSuite): suites.append(obj) return suites
9e0243e345380548cc072597ee6b81ddef8d1ca5
575,559
def first(seq, f): """Returns first item in seq where f(item) is True, or None. To invert the function, use lambda f: not f """ for s in seq: if f(s): return s
cca3b9bd5ee9c94ea020b46946b9a065491e6f4d
575,561
def spdk_get_version(client): """Get SPDK version""" return client.call('spdk_get_version')
9521e051bdde25d190e4a133418728573bedb73b
575,563
def get_counts(content): """ Returns a tuple (iteration_count, kernel_count) from the times contained in the file. """ iteration_count = 0 kernel_count = 0 for t in content["times"]: if "cpu_times" in t: iteration_count += 1 if "kernel_name" in t: kernel_count...
385577001f11dd7cdc3b3f3fdfd73924f6cd7323
575,567
def _sample_batch_size(sample): """ get the batch size of a sample, while not knowing how many lists are in the input object. """ if isinstance(sample[0], (list, tuple)): return _sample_batch_size(sample[0]) else: return sample[0].shape[0]
d5cb8c6bdeb6dd3783d0992b97e48690204a68a3
575,569
def test(train_dict, x, y): """ Test network for one iter Args: train_dict (dict): dictionary containing network, optimizer, loss and loader x (torch.tensor): input image from dataset y (torch.tensor): actual y value from dataset Returns: torch.tensor: mse loss torch.tensor: ...
5d195b0a49cfd8483c03a6bd079e9ee5a55be1bb
575,570
def string2number(i): """ Convert a string to a number Input: string (big-endian) Output: long or integer """ return int(i.encode('hex'), 16)
552a40383bbed73f8cba668a38b3770431e740a3
575,571
def html_encode(text): """ Encode ``&``, ``<`` and ``>`` entities in ``text`` that will be used in or as HTML. """ return (text.replace('&', '&amp;').replace('<', '&lt;'). replace('>', '&gt;'))
adf32f4385e8a1d85d3e5750cc2e043cc76aea0f
575,574
import re def remove_single_tag(tag_exp, text): """ Receives a tag as regex and remove all occurrences in the text. """ while True: matched = re.search(tag_exp, text) if not matched: break text = text[:matched.start()] + " " + text[matched.end():] return text
1db743c122bc36271037a66ad6d6401401467ec5
575,576
def flatten(fields): """Returns a list which is a single level of flattening of the original list.""" flat = [] for field in fields: if isinstance(field, (list, tuple)): flat.extend(field) else: flat.append(field) return flat
ceebeea653f70c8cae41734f8c1cb1eec0fe86a9
575,578
def to12hrs(militarytime, pad=False): """Convert simple military time string to AM/PM format Example: input: 2130 output: 9:30 pm """ hours = int(militarytime[0:2]) minutes = int(militarytime[2:]) meridiem = '' formater = '%d:%02d %s' if hours > 12: hours = hours...
80993faf85adde8616324427be93db210054b31a
575,580
import re def natural_sort(list, key=lambda s: s): """ Sort the list into natural alphanumeric order. """ def get_alphanum_key_func(key): convert = lambda text: int(text) if text.isdigit() else text return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))] sort_key = get_alphanum_key_fun...
f6ba49179ab731bb4723be1ffb99a650509014c7
575,581
def name_to_number(name): """Take string name as input (rock-spock-paper-lizard-scissor) and returns integer (0-1-2-3-4) """ if name == "rock": return 0 elif name == "spock": return 1 elif name == "paper": return 2 elif name == "lizard": return 3 elif name...
4f3e84876ad7a0d69f38a854124caf618c6e2a9f
575,583
from pathlib import Path def get_file_base(path: Path) -> Path: """Removes all extensions (as in everything after the first dot in the filename) from a Path :param path: Original Path obj :return: Path obj without any extensions """ return Path(path.parent, path.name.split(".")[0])
c01d534c265bd9dfda74799a261ca71cd343e5f1
575,585
import base64 def oauth_basic_authentication(app_id, cert_id): """Get the basic authentication header string for OAuth2 authentication based on App ID and Cert ID. """ enc = base64.b64encode(f'{app_id}:{cert_id}'.encode('utf8')) return f'Basic {enc.decode()}'
931f70232909de756d2072c43482cc1b8ef93439
575,587
import re def get_cache_name(url): """Return cache file name from url.""" a = re.sub('^https?://','', url) a = re.sub('^ftp://', '', a) a = re.sub('[^a-zA-Z0-9.?]', "_", a) return a + ".cache"
0ae5ff389a9e1948105153ffa690a84da038291a
575,589
def configure(simulator, co_simulation, nb_neurons=10000): """ configure NEST before the simulation modify example of https://simulator.simulator.readthedocs.io/en/stable/_downloads/482ad6e1da8dc084323e0a9fe6b2c7d1/brunel_alpha_simulator.py :param simulator: nest simulator :param co_simulation: bool...
09f701fccd1ba36500bd5f4a8198f47edd1b0a00
575,590
import sqlite3 def sample_in_db(sample, serie, db, table): """Check if sample-serie combi is in database. Return boolean.""" sql = """SELECT * FROM {} WHERE(SAMPLE='{}' AND SERIE='{}') """.format(table, sample, str(serie)) conn = sqlite3.connect(db) c = conn.cursor() c.execute(sql) i...
ca31681b36c694f64a35ec3ac8041af2383066a2
575,591
import random def generate_code(code_len=6): """生成指定类型、长度的验证码 Args: code_len (int, optional): 选择验证码的长度. Defaults to 6. Returns: Staring/int: 生成验证码 """ # 包含数字和字母大小写 # all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' # 包含数字和大写字母 # all_chars =...
0395d531423b19f458f9edbd0f952994fb4bfa0d
575,594
import math def morse_energy(dist, params): """The Morse interaction energy :param dist: The distance between the two interacting atoms. :param params: The Morse parameters. :returns: The interaction energy. """ de, a, r0 = params return de * (( math.exp(a * (r0 - dist)) - 1 ...
6f29c090eab8d5fb07b4470457007f38943403a7
575,598
def copy(ary, **kwargs): """ Return an array copy of the given object. :type ary: :obj:`mpi_array.globale.gndarray` :param ary: Array to copy. :type order: :samp:`{'C', 'F'}` :param order: Only :samp:`'C'` implemented. Whether to store multi-dimensional data in row-major (C-style) ...
84dc14d616a5f7e725142dfc14b2e4c7b851edb2
575,600
def generate_day_dict(days, tasks): """ Creates a dictionary of days as keys and values as dictionaries of tasks with keys as empty lists :param days: days to use as keys :param tasks: tasks to use in the inner dicts :return: dictionary """ day_dict = {} task_dict = {} for task in ta...
df875d01795e400e552b75e59fbb620c66a434b7
575,601
def pairwise_disjoint(c): """Return whether elements in `c` are pairwise disjoint.""" union = set().union(*c) n = sum(len(u) for u in c) return n == len(union)
2adc21d5167f76e5356020a5b25a21124dbe1198
575,602
def _snake_to_pascal_case(model_name: str) -> str: """Convert model name from snake case to Pascal case. Args: model_name (str): Model name in snake case. Returns: str: Model name in Pascal case. """ return "".join([split.capitalize() for split in model_name.split("_")])
fb48b6597ba6ec02a400fc235fa9f5e6d956d9a5
575,603
import pathlib def check_sub_path_create(sub_path): """ 检查当前路径下的某个子路径是否存在, 不存在则创建; :param: * sub_path: (string) 下一级的某路径名称 :return: * 返回类型 (tuple),有两个值 * True: 路径存在,False: 不需要创建 * False: 路径不存在,True: 创建成功 举例如下:: print('--- check_sub_path_create dem...
9da09ce812b78733f230aab9493a9d0031b8224f
575,604
import torch def hot_to_indices(hot): """Convert an element of one-hot encoding to indices """ hot = torch.tensor(hot) _,max_index=hot.max(1) return max_index.data.cpu().numpy().tolist()
71a911d1ecb809c439bf42e8e8503e968f3d5cf8
575,605
def erb_bandwidth(fc): """Bandwidth of an Equivalent Rectangular Bandwidth (ERB). Parameters ---------- fc : ndarray Center frequency, or center frequencies, of the filter. Returns ------- ndarray or float Equivalent rectangular bandwidth of the filter(s). """ # In...
10459eb15c6baab5890bf51e12039533f36d6e9b
575,610
def arithmetical_expr(cont_frac, with_spaces=True, force_floats=False): """Generates the arithmetical expression as string of a continued fraction. The string is ready to be evaluated by a functions like `eval()` or by other programming languages or calculators. Beware of integer division instead of tr...
efee02ad034ae7f727b18e1c470477faba2ffbe3
575,612
def cal_neighbors(pnx: int, pny: int, pi: int, pj: int, rank: int): """Calculate neighbors' rank. Arguments --------- pnx, pny : int Number of MPI ranks in x and y directions. pi, pj : int The indices of a rank in the 2D MPI topology in x and y directions. rank : int The...
8e556b852219fe3581ca78ddf25682989b057841
575,613
import calendar def datetime_to_int(ts): """ accepts: datetime object (tz aware) returns: integer (unix time - seconds) """ if (ts.tzinfo == None): raise Exception("timestamps must not be naive") return int(calendar.timegm(ts.utctimetuple()))
0ef65faf72cd09c8c9263a306c7e8c32f84bffb5
575,615
def completeChildHierarchy(GOdict): """ Generates the entire GO tree's child structure. By iterating over the parents of each GO object, each term's recursive_children attribute will be filled with a set of all recursively found child terms. NOTE: completeParentsHierarchy() must be run prior to th...
4cc3397566b9c8045923a341d08c391316d2ae60
575,616
def is_numeric_possible(test_str: str): """ Is the test string a valid possible numerical with /or w/o units. Arguments: test_str (str): Test string Returns: bool: Is the test string a valid possible numerical """ return test_str[0].isdigit() or test_str[0] in ['+', '-', '.'] ...
572240c0da292b79db868f610eb5fae58d4b9327
575,636
from typing import List def merge(left: List[int], right: List[int]) -> List[int]: """ Merges two sublists together, one left and one right. Used as implementation detail for the merge_sort method. :param left: is the left sublist. :param right: is the right sublist. :return: the sorted result...
82ca4fc3bdf4514382249660e5c838d5e99042dc
575,638
import re def parse_roll(roll='111111', d='6'): """Takes a string of numbers and returns array of integers. Roll is 0 to (d-1)""" pattern = re.compile('^[1-{}]+$'.format(d)) if pattern.match(roll): return [(int(die) - 1) for die in list(roll)] else: return None
dbf86cf62c907de39568776133123004c53f082e
575,639
def keywordInStr(keywordList, string): """ Decision if there is any keyword from the keywordList in the string, return True or False """ return any(keyword in string for keyword in keywordList)
e79d0aaa8626df3bec9d632963b367292fb90b98
575,643
def parse_float_tuble(par_tup): """ Formates the raw input from ConfigParser (e.g. '(0, 0, 1)') to (0.0, 0.0, 1.0) """ return tuple([float(i) for i in par_tup.strip('(').strip(')').split(',')])
14b39a0d50604d22f4e2ec51d50c22b049c9fbf1
575,644
def class_is_assignable(target, src): """Return whether or not src is a subclass of target.""" def compatible_types(cls, seen): compat = [cls] for i in cls.__bases__: if i not in seen: compat.extend(compatible_types(i, seen=compat)) return compat return t...
83a3762ef16d0a466443a1c1d4970e85e67b4b96
575,647
def filter_commands(commands, invalid_query_starts=('DROP', 'UNLOCK', 'LOCK')): """ Remove particular queries from a list of SQL commands. :param commands: List of SQL commands :param invalid_query_starts: Type of SQL command to remove :return: Filtered list of SQL commands """ commands_wit...
b8f3e46c134c99f77f0cde5f5f892663f8e0cfb1
575,648
def _bin_to_int(binstring: str) -> int: """Converts a binary string representation of an integer to an integer. """ return int(binstring, 2)
c23a94efc896f62d2442ce1118346c930a2c9136
575,652
def _entry_dict(entry): """Convert entry to API format.""" return { 'config_entries': list(entry.config_entries), 'connections': list(entry.connections), 'manufacturer': entry.manufacturer, 'model': entry.model, 'name': entry.name, 'sw_version': entry.sw_version, ...
1702960d467f258d55af403e743277602bd23554
575,656