content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def import_words(filename): """Imports words from a given .txt file and returns it. """ # Initialize resuts variable results = [] # This with statement ensures the file is only open for a certain amount of time. # This can save RAM and processing speeds in larger projects # Rename the spri...
56954768e1bcff7c857c1b104cf1b5dff93e1124
643,367
def order_to_degree(order): """Compute the degree given the order of a B-spline.""" return int(order) - 1
f2078b7fd7c19202d3bc7826807cbed53cd2a1d7
643,369
def _get_object_from_classname(classname, data): """ Returns an object instance for given classname and data dictionary. Args: classname (str): Full classname as string including the modules, e.g. repo.Y if class Y is defined in module repo. data (dict): dictionary of data used to initialize th...
28f965a819efcbdc595d2eb4528ed4550459cef5
643,373
import zlib def anonymize(user_uid: str, user_ip: str) -> str: """Make a user-readable hashed identity.""" if user_uid: return "Goog#%d" % (zlib.adler32(user_uid.encode()) % 10000,) return "Anon#%d" % (zlib.adler32(user_ip.encode()) % 10000,)
3304ac298c605211a4c010dfbf9cc462ddaa315b
643,374
import math def deg2num(lat_deg, lon_deg, zoom): """Convert latitude and longitude to x/y tile coordinates.""" lat_rad = math.radians(lat_deg) n = 2.0 ** zoom xtile = int((lon_deg + 180.0) / 360.0 * n) ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n) ...
fad28865630fa73827fd95945783ba4e6269e6e9
643,375
import random def hex_rand(n): """ Generates a hexadecimal string with `n` random bits. """ return "%x" % random.SystemRandom().getrandbits(n)
8531068ab3c99433d1a244556f548b91f0ea1e2e
643,376
def is_tcp_rst(tcp_data): """is TCP RST?""" return tcp_data["flags"]["rst"] == 1
8f6f77c097e054e766863516300830656082084a
643,382
import copy def merge_dicts(dict1, dict2, recycle=True): """ Recursively merge two dictionaries. dict2's values will override dict1's :param recycle: if True then write the merged dictionary into dict1, otherwise do not modify dict1 :return: a single dictionary """ assert type(dict1) is dict...
e390593e62aec70a598be5517e4a0639a243a575
643,385
def serialize_config( config_data ): """ Generate a .ini-formatted configuration string to e.g. save to disk. """ return "[syndicate]\n" + "\n".join( ["%s=%s" % (config_key, config_value) for (config_key, config_value) in config_data.items()] )
45cd607770341efa0600c6c253b9a68e8617af0c
643,389
def clamp(num): """ Return a "clamped" version of the given num, converted to be an int limited to the range 0..255 for 1 byte. """ num = int(num) if num < 0: return 0 if num >= 256: return 255 return num
8b5eb6160c7763216b4361a75938e9492e9fc97c
643,394
def name(cls): """Get a nice name for this object.""" return cls.__class__.__name__
9db47520de07a1940320380e5171e4560a60ca71
643,395
from typing import List from typing import Tuple def partition_data(data: List[List[str]] ) -> Tuple[List[List[str]], List[List[str]]]: """Partitions data into train and test partitions. The train partition consists of 80% of the data. The test partition consists of 20% of the data. ...
ef89fdef573f1cf1807ecac7cdbc5df7cc2a3fef
643,396
def _first(iterable, what, test='equality'): """return the index of the first occurance of ``what`` in ``iterable`` """ if test=='equality': for index, item in enumerate(iterable): if item == what: break else: index = None else: raise N...
0421ac9aa5c6c2f0e2f55a913fa49d9bf79edb63
643,397
def equal_probs(num_values): """Make an array of equal probabilities.""" prob = 1.0 / num_values probs = [prob for i in range(num_values)] return probs
bf72642ada23a8f408167d1af36b34ec58d85437
643,398
def _GenerateLocalProperties(sdk_dir): """Returns the data for project.properties as a string.""" return '\n'.join([ '# Generated by //build/android/gradle/generate_gradle.py', 'sdk.dir=%s' % sdk_dir, ''])
e4cf034c1d597650bc2132a183448f8dc4790f76
643,399
def set_contourf_properties(stroke_width, fcolor, fill_opacity, level, unit): """Set property values for Polygon.""" return { "stroke": fcolor, "stroke-width": stroke_width, "stroke-opacity": 1, "fill": fcolor, "fill-opacity": fill_opacity, "title": "{} {}".format...
0585253cf9fc6a5be2974584c48cbd645d8b4085
643,403
def _preprocess_padding(padding): """Convert keras' padding to tensorflow's padding. # Arguments padding: string, `"same"` or `"valid"`. # Returns a string, `"SAME"` or `"VALID"`. # Raises ValueError: if `padding` is invalid. """ if padding == 'same': padding = 'S...
6f50f6d99df0f55c7015d60c2abe39165ab736fe
643,408
from bs4 import BeautifulSoup def check_length(caption: str, limit: int = 1024) -> str: """checks length of message against Telegram limits Args: caption (str): Message string. limit (int, optional): Message length limit. Defaults to 1024. Returns: str: If caption length minus en...
4cb4ed635d05eada6ff1e86f9b3d9cb07d0cec28
643,410
def get_target_dimension_order(out_dims, direction_to_names): """ Takes in an iterable of directions ('x', 'y', 'z', or '*') and a dictionary mapping those directions to a list of names corresponding to those directions. Returns a list of names in the same order as in out_dims, preserving the order ...
f208f9d7e287a92968ecfebddeee92e6afcd2155
643,412
def add_claims_to_jwt_token(user): """ Return the claims that should be added to the JWT token. This function is called whenever create_access_token is called. """ return { "roles": list(map(lambda r: r.name, user.roles)), "permissions": list(map(lambda p: p.name, user.permissions))...
cdbb2dc11c54e085d758535e5a7e874251fa0871
643,417
def create_titoli(conn, titoliTuple): """ Create a new record into the titoli table :param conn: :param titoliTuple: :return: titoliRecord id """ sql = ''' INSERT INTO titoliCounter('cvid', 'titolo-01', 'titolo-02','titolo-03','titolo-04','titolo-05','titolo-06','titolo-07','titolo-08','titolo-09','titolo-10','t...
f66cc4bc107026650de69d97d57710c9b4778c05
643,420
def status(level, solved, err): """Calculate status from status and err.""" if solved: if err: status = 'multiple solution' else: status = 'level ' + str(level) else: if err: status = 'no solution' else: status = 'give up' r...
616c9468e07e978146f7f64bfbcd9acae744a436
643,422
def get_target_info(target): """Return target information as a version tuple.""" return tuple(int(x) for x in target)
82010bc8f6bfbc5773ba79e365dabc2f60e42951
643,424
def to_string(number): """ Convert float/int to string >>> to_string(13) '13' """ return str(int(number))
7f1d0f90c6de7cde246b755f020a121975330ddf
643,425
def custom_returns(prices, predicted_prices, is_returns, frequency=252): """ Calculates expected return from user fed predicted prices or returns. :param prices: historical price data :type prices: pd.DataFrame :param predicted_prices: predicted data of asset prices or returns :type predicted_...
d6f26ce5587816c1308bbaac40766b474dfb0e36
643,428
def binary_search(source, target): """二分探索. 計算量: O(log n) """ start, end = 0, len(source) while start <= end: index = (start + end) // 2 # index: 中央値 if source[index] == target: # 見つかったらそのindexを返す return index elif source[index] < target: # 検索範囲...
c9e9adf63149deb74112d5beafd27eb412bc3eb5
643,429
from typing import Tuple from typing import List def cell_regions( x_len: float, y_len: float, factor: float = 2 / 3, buffer: float = 3.5 ) -> Tuple[List[List[float]], ...]: """Calculate the boundary of the different regions used for classification. When running an interface simulation there is a region ...
91fedc00ee899175b5bbfdc523ba59510aa0462b
643,430
def get_post_match(child, args, index, child_dict): """ matching function for post nodes Args: child: the matched child from which we check post tokens. args: list of incoming tokens. index: position in args list where comparison continues. child_dict: the dictionary that is ...
e1ed82c7e83e37bea3c812be7c6a5c1e657d75b1
643,434
def cursorNextOrNone(cursor): """ Given a Mongo cursor, return the next value if there is one. If not, return None. :param cursor: a cursor to get a value from. :returns: the next value or None. """ try: return cursor.next() # noqa - B305 except StopIteration: return N...
8445490505c74ac128da94de41ad805019e05812
643,436
from typing import Tuple def _parse_block(block: str) -> Tuple[str, str]: """Extract question and answer from a text block.""" question_start = block.find('\n', block.find('Вопрос')) + 1 question_end = block.find('\n\n', question_start) question = block[question_start:question_end] question = " "....
033c2e94e942ce2d570cc39d5cef26ce2c5685d4
643,438
import torch def sinc3(t): """ sinc3: t -> (t - sin(t)) / (t**3) """ e = 0.01 r = torch.zeros_like(t) a = torch.abs(t) s = a < e c = (s == 0) t2 = t[s] ** 2 r[s] = 1/6*(1-t2/20*(1-t2/42*(1-t2/72))) # Taylor series O(t^8) r[c] = (t[c]-torch.sin(t[c]))/(t[c]**3) return r
211f44157edc90ef6e6974d85a02c6bcf2837777
643,441
import random import socket def find_unbound_port(start=None, increment=False, port_range=(10000, 50000), verbose=False, logger=None): """ Find a unbound port. Parameters ---------- start : int The por...
e1fe772c054887ada0744e9764e166365eb6165b
643,442
import csv def read_csv_file(file_path, delimiter, remove_header=False): """ Reads a csv file with records separated by delimiter""" rows = [] with open(file_path) as csv_file: csv_reader = csv.reader(csv_file, delimiter=delimiter) for row in csv_reader: rows.append(row) if...
3d108d5613c18bd9ae77e8ab7283d7dff0a821af
643,446
def _mask_for_bits(i): """Helper function for read_bitpacked to generage a mask to grab i bits.""" return (1 << i) - 1
252381ddfe00663675280db89ef03034a4e32239
643,450
def to_float(val, sub_val): """Try to convert 'val' to a float. If it fails, return 'sub_val' instead. Remove any commas before trying to convert. """ try: if isinstance(val, str): # remove any commas before converting. val = val.replace(',', '') return float(val...
8082ab3e1838ecfd76d7ea18fd46ec50ae9b9232
643,452
def get_make_targets(benchmarks, fuzzer): """Return pull and build targets for |fuzzer| and each benchmark in |benchmarks| to pass to make.""" return [('pull-%s-%s' % (fuzzer, benchmark), 'build-%s-%s' % (fuzzer, benchmark)) for benchmark in benchmarks]
e614f4655bffe80f69584f76a6a86b3fe654ccee
643,454
def get_optimal(opt_file, optimisation): """Returns the optimal value given the specified optimisation. Args: opt_file: The file with optimal results. optimisation: The optimisation value to return. Returns: Optimal value. """ f = open(opt_file, "r") profile = '' for lin...
09a8d91fadeed236b5e9fc6eeb53474ed3ebc6ad
643,469
import json def to_json(obj: object, *args, **kwargs): """Serialize a nested object to json. Tries to call `to_json` attribute on object first.""" def serialize(obj: object): return getattr(obj, 'to_json', getattr(obj, '__dict__') if hasattr(obj, '__dict__') else str(obj)) return json.dumps(obj, ...
7798bc28196f9598645751803f81fe711836ada9
643,470
def get_context(seq, pos, n=1, s=1): """ Gets context from a sequence at a given position. :param seq: the sequence :param pos: target position :param n: context size (each side) :param s: size of the target region, displaces the position of right context :return: a string matching [ACTG]*[....
c7b9b09ddea2037e10539c129851734105ad70b6
643,474
def get_host_batchid_map(workspec_list): """ Get a dictionary of submissionHost: list of batchIDs from workspec_list return {submissionHost_1: {batchID_1_1, ...}, submissionHost_2: {...}, ...} """ host_batchid_map = {} for workspec in workspec_list: host = workspec.submissionHost ...
8a0e1565b439137fce77d49811a828931a07aaa1
643,479
def decExponential(agent,state): """ Implements a decreasing-epsilon method which starts with a high exploration rate and then decreases exponentially with time """ return (0.5 ** (agent.episodesSoFar + state.trial))
ba40c91e4b8410b8e99f7d0f0fb9e25d1c5f32a1
643,482
def consistent_typical_range_stations(stations): """ returns the stations that have consistent typical range data Inputs ------ stations: list of MonitoringStation objects Returns ------ a list of stations that have consistent typical range data """ consistent_station_list = [...
fd8192088665d7f37943b1376a681104f1f0d6c2
643,484
import math def get_direction(x, y): """Gets a direction from two differences in coordinates""" return math.atan2(y, x)
12face987142c897add55da3c9e7a2dee5b702b7
643,485
def weighted_sum(df, var, wt="s006"): """ Return the weighted sum of specified variable Parameters ---------- df: Pandas DataFrame data overwhich to compute weighted sum var: str variable name from df for which to computer weighted sum wt: str name of weight variable...
c312131f57150dba3dc5d4d401136b3ec2c2420c
643,486
def _axes_all_finite_sized(fig): """Return whether all axes in the figure have a finite width and height.""" for ax in fig.axes: if ax._layoutbox is not None: newpos = ax._poslayoutbox.get_rect() if newpos[2] <= 0 or newpos[3] <= 0: return False return True
37a4501a445df5e4c3c69c1e3a5300fa5d049d49
643,487
from typing import Counter def compute_state_distribution(interactions): """ Returns the count of each state for a set of interactions. Parameters ---------- interactions : list of tuples A list containing the interactions of the match as shown at the top of this file. Return...
71015ba279b291a580e41fcfe3b106dc61fea138
643,493
import hashlib def calculahash(cadena): """Devuelve el hash SHA256 de una cadena dada como entrada :param cadena: texto de entrada para calcular su hash :return: el hash calculado con SHA256 """ return hashlib.sha256(cadena.encode()).hexdigest()
6b2e04c00b13471e470ba52ab6c5e500b84c15c3
643,494
def modify_df(df, sentence_length): """ Convert the columns STB_Text from a string of list to a list. Gather length of STB_Text/Ref_Text list and filter based on sentence length argument. Explode STB_Text and Ref_Text as separate dataframes. Filter repetitive sentences within a topic. Create a c...
c049566164e21a367bcb5017089083dbee1ed0fb
643,498
import requests from bs4 import BeautifulSoup def get_definition(search): """ Get the first definition of the word using merriam-webster dictionary online. :param search: Word to find the definition of. :return: Definition of search. """ # Read HTML website req = requests.get("https://merr...
7bc375736f9c0cc8c0a64f06926fbade8681518a
643,500
def absolutelyNonDecreasing(buffer,item,attempts): """ Stops after the buffer has seen an absolute value larger than the one being searched for. The example halting condition given in the documentation. """ if abs(buffer._cache[-1])>abs(item): return True return False
c96f593b47b2d4c695959b7ca494ffd757bada63
643,501
import re def parse_quicklook_key(key): """ Parse quicklook key and return dictionary with relevant fields. Input: key(string): quicklook key Output: dict with the following keys: satellite(string): e.g. CBERS4 camera(string): e.g. MUX path(string): 0 padded path, 3 dig...
6138b5a680e39bc5af3dfeaf8826bec81ab928cb
643,503
def qobj_to_dict_current_version(qobj): """ Return a dictionary representation of the QobjItem, recursively converting its public attributes. Args: qobj (Qobj): input Qobj. Returns: dict: dictionary representing the qobj. """ return qobj.as_dict()
d7f71f853441e1c338872333340e534825f80cd9
643,504
def get_batch_appliance_tunnels_config( self, ne_pk: str, tunnel_id_list: list, ) -> bool: """Get appliance tunnel configuration for specified tunnels .. note:: This API Call is not in current Swagger as of Orch 9.0.3 .. list-table:: :header-rows: 1 * - Swagger Section ...
58886650e1c6c330771f129a0a39e684324f12b0
643,506
def escape_jsonpointer_part(part: str) -> str: """convert path-part according to the json-pointer standard""" return str(part).replace("~", "~0").replace("/", "~1")
f30776c6ae620b892165bc9e6d7b51b889483a70
643,508
def soil_heat_conductivity(w, T, ro, soil_type): """ Heat conductivity of a soil, W/(m2*K) :param w: humidity, % :param T: temperature, K :param ro: density of a soil, kg/m3 :param soil_type: (str) type of a soil :return: heat conductivity of a soil, W/(m2*K) """ ro = ro / 1000 r...
da1b20e58bad1825fb23e69c08c2d55d9db53d7c
643,511
import math def split_equally(lst, nparts): """Splits equally list into nparts. If length of the list cannot be devided without residue the functions splits list in the way when some parts have n items and some n-1, so lengths of them are almost equal. """ data_size = len(lst) ratio...
d93c7de166812727739f2b16f18141e0c1ed9f59
643,515
import re def version_parts(version): """ Split a version string into numeric X.Y.Z part and the rest (milestone). """ m = re.match(r'(\d+(?:\.\d+)*)([.%]|$)(.*)', version) if m: numver = m.group(1) rest = m.group(2) + m.group(3) return numver, rest else: return...
e67d205552cfa09c01cd7209fc591a6214172fef
643,516
def is_cmp(op): """ Tests whether an operation requires comparing two types. """ return op in ['<', '<=', '==', '!=', '>', '>=']
44c80ef8b2da0ea46e8cf21d36706c09d5be0f63
643,517
def datetime_to_text(datetime_object): """ covert python3 datetime object to text string to store in sqlite3 database :param datetime_object: python3 datetime object :return: string containing datetime in format MM-DD-YYYY HH:MM:SS """ return str(datetime_object)
519ac8f01f48e3a69eaa56a7a217c22c2f374011
643,519
def subst_variables_in_str(line: str, values: dict, start_char: str = "%") -> object: """ Replace variables inside the specified string :param line: String to replace the variables in. :param values: Dictionary, holding variables and their values. :param start_char: Character used to i...
adbf0f2b37488d58fff98732ab46e9efef62577a
643,522
def alt2ambiguousnucleotide(alts): """Translate list of alt nucleotides to single IUPAC abmiguity symbol Uses http://www.dnabaser.com/articles/IUPAC%20ambiguity%20codes.html Args: alts: List of alternate nucleotides of a SNP Raises: KeyError: when multi alt is not in translation map ...
052cc8188d257cf02a6e109d1edd092f9c76bd81
643,526
def lt_log_determinant(L): """ Log-determinant of a triangular matrix Args: L (Variable): Lower-triangular matrix to take log-determinant of. """ return L.diag().log().sum()
dc7e0a75e71eddb2b284c1cb511d4b9902559371
643,528
def get_update_author_profile(d_included, base_url): """Parse a dict and returns, if present, the URL corresponding the profile :param d_included: a dict, as returned by res.json().get("included", {}) :type d_raw: dict :param base_url: site URL :type d_raw: str :return: URL with either company...
e50254c60a552bffa87e3c1913e1884e2aabad7f
643,534
def isLucky(n): """ isLucky takes in an integer and return True if the sum of its right half == sum of the right half :param n: :return: """ # l = list(map(int, str(n))) # return sum(l[0:len(l) // 2]) == sum(l[len(l) // 2:]) s = str(n) return sum(map(int, s[: len(s) // 2])) == ...
255a19b1047f4a8c317aae656b5c5ad69aa2b750
643,535
def get_area(pos): """ Args pos: [B, N, 4] (x1, x2, y1, y2) Return area : [B, N] """ # [B, N] height = pos[:, :, 3] - pos[:, :, 2] width = pos[:, :, 1] - pos[:, :, 0] area = height * width return area
aa65cfb7313f5cdf204592a51ba17115709a2e6c
643,536
import re def cache_key(query): """Make filesystem-friendly cache key""" key = query key = key.lower() key = re.sub(r"[^a-z0-9-_;.]", "-", key) key = re.sub(r"-+", "-", key) return key
7d98352bb0c04666e175b6cd748b49c612838084
643,542
async def _get_post_id(db, author, permlink): """Get post_id from hive db.""" sql = "SELECT id FROM hive_posts WHERE author = :a AND permlink = :p" return await db.query_one(sql, a=author, p=permlink)
be64e63c81ebf9e70c5e8f97b1d57256ed756cd5
643,543
def sum(a: int, b: int) -> int: """ Let's sum two integers! >>> sum(1,2) 3 :param a: An integer :param b: Another integer :return: the sum of both parameters """ return a + b
595b50ca6445d325a9c17b31b15e0352caa16fa0
643,545
def find_header(path: str) -> int: """find_header this function counts the lines of the header (i.e. how many lines there are until the first line with doesn't start with a '#' is encountered) Parameters ---------- path : str file path Returns ------- int number of ...
6bfd83f82762f4292f605917dc034e10d2850bd4
643,550
def split_addresses(email_string_list): """ Converts a string containing comma separated email addresses into a list of email addresses. """ return filter(None, [s.strip() for s in email_string_list.split(",")])
4fab1508179d2d974f285cec517a6fc322ac4ada
643,554
def order(replay1, replay2): """ An ordered tuple of the given replays. The first element is the earlier replay, and the second element is the later replay. Parameters ---------- replay1: Replay The first replay to order. replay2: Replay The second replay to order. Retu...
0f85dd8c56eae59caed8d5efff33f744a2f8dc17
643,555
def teardown(teardown_method): """Decorator for declaring teardown methods for test cases.""" teardown_method._is_teardown_method = True return teardown_method
3d5465909020e55b433561479f5b00a8f3cdfe49
643,558
import re def removeMultEspaços(string: str) -> str: """ Remove espaços ectras entre as palavras Parameters ---------- string : str string com multiplos espaços Returns ------- string : str string com apenas um espaço entre palavras """ string_arru...
b522590855e6d2e4d1b95ca08912a2249c2dbf7b
643,562
def parse_log(logfile, body, param): """" Parse log file for one of a body's initial conditions and return it. This is useful for when a parameter is not outputted but one needs it later on for bigplanet analysis. Parameters ---------- logfile : str path to the logfile body : s...
ce8b7e4781175b7aa22d52f68d899b3744c04b49
643,569
def generate_spec(key_condictions): """get mongo query filter by recursion key_condictions is a list of (key, value, direction) >>> generate_spec([ ... ('a', '10', 1), ... ('b', '20', 0), ... ]) {'$or': [{'$and': [{'a': '10'}, {'b': {'$lt': '20'}}]}, {'a': {'$gt': '10'}}]} """ ...
d6401eb4abab78f498e2a73fef1d5db8a2b0b9f6
643,571
from datetime import datetime def convert_time_searchable(ts): """converts timestamps from time.time() into reasonably searchable string format""" return datetime.fromtimestamp(ts).strftime("%Y%m%d%H%M%S")
a66402b526c897fb5a106744b7fd21d6565c5e76
643,573
def bioconductor_tarball_url(package, pkg_version, bioc_version): """ Constructs a url for a package tarball Parameters ---------- package : str Case-sensitive Bioconductor package name pkg_version : str Bioconductor package version bioc_version : str Bioconductor ...
78f93baa524f69efb3abf4d23a5286d42ecd5030
643,576
def evaluate_using_acc(model, X_test, y_test, batch_size): """ Evaluation function using accuracy. # Arguments: model: Model to be evaluated. X_test: Inputs of the testing set. y_test: Outputs of the testing set. batch_size: Batch size. # Returns: Accuracy of the gi...
51aa46c229ec257285263be0f72f6ec730901c27
643,582
def _calculate_mid_points(bounds): """ Calculate middle points based on the geometry bounds Parameters ---------- bounds : array_like array containing xmin, ymin, xmax, ymax Returns --------- x_mids : mid points of x values y_mids : mid points of y values """ # Cal...
f194e03b03c81d42f9c4bd43f3044af473ad4bf7
643,587
def get_mapping_data(name, field, integral, region=None, integration='volume'): """ General helper function for accessing reference mapping data. Get data attribute `name` from reference mapping corresponding to `field` in `region` in quadrature points of the given `integral` and `integration` type...
e029fdc6604b66f12381b966f1d89a607f3cbfc0
643,588
from datetime import datetime import calendar def formatted_timestamp_utc_time(timestamp_str, format_str): """ Converts a formatted timestamp timestamp string to UTC time NOTE: will not handle seconds >59 correctly due to limitation in datetime module. :param timestamp_str: a formatted timestamp s...
c46efd70cc3a8417fbcc62c18ae551e25ebe7e53
643,589
import itertools def _get_permutations_draw(draw): """Helper to get all permutations of a draw (list of letters), hint: use itertools.permutations (order of letters matters)""" return list(it for i in range(1, 8) for it in itertools.permutations(draw, i))
ddf34e86428d54313010d20bba77fdf3d7082113
643,596
def generate_early_stop_file_path(experiment_path_prefix, net_number): """ Given an 'experiment_path_prefix', return an early-stop-file path with 'net_number'. """ return f"{experiment_path_prefix}-early-stop{net_number}.pth"
c0b93cc62791f7f6d69a4235191497258f147325
643,604
def ver_str_to_tuple(ver_str): """Convert a version string into a version tuple.""" out = [] for x in ver_str.split("."): try: x = int(x) except ValueError: pass out.append(x) return tuple(out)
55ec5b9fa8f0f84827ebbe827936d5c78c39249b
643,605
def distance(color_one: tuple, color_two: tuple) -> float: """Finds the distance between two rgb colors. Colors must be given as a 3D tuple representing a point in the cartesian rgb color space. Consequently the distance is calculated by a simple cartesian distance formula. Returns a float representing...
889b1d43205c1ecb076e5c6f3b5c9a6755aad64d
643,608
def get_artist_ids(db_session): """Returns a list of all artist ID's.""" c = db_session.cursor() c.execute("""SELECT artist_id FROM artists""") l = [] for row in c: l.append(row[0]) #db_session.commit() c.close() return l
d73cb9f5d0eac3f0421706f0f3fbb00379c2e2d7
643,611
def nearest(items, pivot): """ :param items: list of type datetime :param pivot: the one pivot we are referring to :return: return the nearest item in items to the pivot """ return min(items, key=lambda x: abs(x - pivot))
0bb79ea35fdd9c2feaf71d17bf66a6184065ba93
643,612
def p2f(x): """Convert percent string to float. """ return float(x.strip('%')) / 100.
b49a8e1b3ca6e3167f37b3872bc24bfecb68728f
643,614
def isKColRequired(config, num): """A quick helper function that checks whether we need to bother reading the k column. The logic here is the same as for `isGColRequired`, but we check for output files that require the k column rather than g1,g2. Parameters: config (dict): The configuration f...
3a0be7198773b129d4a3fd5ef0cddc48ff659791
643,615
from typing import List def generate_equally_spaced_scopes(num_envs: int, num_agents: int) -> List[int]: """Generate a list of equally spaced scopes for the agents :param num_envs: Number of environments :type num_envs: int :param num_agents: Number of agents :type num_agents: int :raises Va...
f6a7d28f321818cc3178b5748151b74e69004482
643,616
def GetFieldNumber(field_tuple): """Get the field number from the tuple returned by `Message.ListFields`.""" return field_tuple[0].number
054b215c83a18b6071eda5d44bd3f9ed099c1f5e
643,617
import torch def reshape(tensor, shape): """ Reshapes a tensor. Parameters ---------- tensor : tensor A Tensor. shape : tensor Defines the shape of the output tensor. Returns ------- A Tensor. Has the same type as tensor """ return torch.reshape(tenso...
dff861f6c32427d3710502f986ff441125af0206
643,618
def get_package_url(data): """Get the url from the extension data""" # homepage, repository are optional if "homepage" in data: url = data["homepage"] elif "repository" in data and isinstance(data["repository"], dict): url = data["repository"].get("url", "") else: url = "" ...
a100ac87cd28a2bf0fcd9e6491ba915377e827c8
643,626
import re def stream_name_match(stream_reg: str, stream_name: str) -> bool: """Decide whether a stream regex matches a stream_name (fullmatch). Currently, Zulip considers stream names to be case insensitive. """ return re.fullmatch(stream_reg, stream_name, flags = re.I) is not None
0c6667937e8c5ffb35b50677a37562b775b8fed4
643,630
def image_destroy(client, image_id): """Destroy the image or raise if it does not exist.""" return client.image_destroy(image_id=image_id)
3d174b0b0857467bd4fe95a2d22abfed097f0c76
643,635
def bids_for_doc(doc_top_list, td, reviewers): """ Generate bids for the document for all provided reviewers """ bids = [] for rev in reviewers: rev_top_dict = dict(td.rev_top[rev.name()]) score = 0 for t_id, t_prob in doc_top_list: score += rev_top_dict.get(t_id,...
5dbcc3246734c444147c75b0eaaf4db2c30b42d3
643,637
def diff(b: list, d: list) -> list: """ Sorting 2 list numbers without same numbers >>> diff([1, 2, 3, 6, 4, 7], [1, 2, 36, 96, 78, 99]) [3, 4, 6, 7, 36, 78, 96, 99] """ # Making set of list x = set(b) y = set(d) # Find numbers which are not same in lists p = y.difference(x) ...
d2f892f6890f74d239487bcfe066b4ce4840c689
643,639
def _is_extended_slice(s): """Return whether a slice is an extended slice.""" return s.step is not None and s.step != 1
7e8b6f37bcd953b90a9ef445a6debe39b19dcfe4
643,646
def padded_batch(dset, batch_size, sequence_length, label_shape=()): """Pads examples to a fixed length, and collects them into batches.""" # We assume the dataset contains inputs, labels, and an index. padded_shapes = { 'inputs': (sequence_length,), 'labels': label_shape, 'index': (), } #...
7e379e47cbdfee7426175d3b50eb86d21efe84eb
643,651
def security_header_tween_factory(handler, registry): """Add security-related headers to every response.""" def security_header_tween(request): resp = handler(request) # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy # # Browsers should respect the last...
be61d46595c7e542e06d9d1ae55eac38e1b4362d
643,653