content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def tokenized_dataset(dataset, tokenizer): """ tokenizer에 따라 sentence를 tokenizing 합니다.""" concat_entity = [] for e01, e02 in zip(dataset['subject_entity'], dataset['object_entity']): temp = '' temp = e01 + '[SEP]' + e02 concat_entity.append(temp) tokenized_sentences = tokenizer( concat_entity,...
33697b168a2d465c476d982e98968aab884c183d
47,503
def barycentricCoordinatesOfE2(P, A, B, C): """ Implementation from Christer Ericson's book Real-Time Collision Detection """ #return barycentricCoordinatesOf(P, A, B, C, areaFunc=triangleSignedAreaE2) v0 = B - A v1 = C - A v2 = P - A d00 = v0.dot(v0) d01 = v0.dot(v1) d11 = v1.do...
23d39c4a6eaa754f06b1599b5ce8238c28042e3a
47,504
def parse_unit(units): """Parses the MatML Units node (dictionary) with units u and power p into a string of the format u1p1u2p2u3p3...""" # if units is not a list, put it in a list units = units if isinstance(units, list) else [units] unit_str = '' for unit in units: unit_name = unit.get(...
903b2bcffa8c0fa93c41903afe2860b5d0bd765f
47,505
def are_all_0(lists, index): """Check if the values at the same index in different list are all to 0. :param list lists: a list of lists to check the value in. :param int index: the index of the values to check in the lists. :returns: True if all the values at the index in the lists are set to 0, Fals...
1fe4f8777618eed459907b2995170691be639e5b
47,506
def modify(boxes, modifier_fns): """ Modifies boxes according to the modifier functions. Args: boxes (dict or list): Dictionary containing box objects per image ``{"image_id": [box, box, ...], ...}`` or list of bounding boxes modifier_fns (list): List of modifier functions that get applied ...
386cb12b0b985a3702d0fe6a3dc7a38e712c7dc1
47,508
def remap_keys(key_func, d): """ Create a new dictionary by passing the keys from an old dictionary through a function. """ return dict((key_func(key), value) for key, value in d.items())
be7125b7bab735522e684d766c75b4745a8c11b3
47,510
import re def calculatedNormalisedDataForLines(lines): """ Get normalised data for the lines of the file. This function is intended as an example. With the help of the function the velocity data of the file are normalized to the absolute value of 1 to be able to measure the profile later wit...
adbde503fa0152da6ffcd7eaec985f21636d4f6e
47,511
def velocity_diff_squared(particles,field_particles): """ Returns the total potential energy of the particles in the particles set. :argument field_particles: the external field consists of these (i.e. potential energy is calculated relative to the field particles) >>> from amuse.datamodel import...
57b153b89ee8ec258b3dbc07800cc27a14e36837
47,513
import itertools def serialize(*args, **kwargs) -> str: """Serialize function arguments.""" return ", ".join(itertools.chain(map(repr, args), (f"{key}={repr(value)}" for key, value in kwargs.items())))
67a3ad2fd93977d43aadec4369f0421e53a01884
47,514
from typing import List import subprocess def checkForExternalPrerequisites() -> List[str]: """ Returns a list of missing prerequisites """ missing = [] try: subprocess.run(["xvfb-run", "--help"], capture_output=True, check=True) except Exception as e: missing.append("xvfb") ...
24fe4d0c2ce927b9552483e9954395309e0df81c
47,515
import pandas as pd def scheduler_progress_df(d): """ Convert status response to DataFrame of total progress Consumes dictionary from status.json route Examples -------- >>> d = {"ready": 5, "in-memory": 30, "waiting": 20, ... "tasks": 70, "failed": 9, ... "processing": 6, ...
4cd65b93850094d8e138e30ee89b1a22a59afd6c
47,517
import math def solve(n, m): """ this is the alghorithm to calculate the permutation since it's said that it wants only the one starts with 1 so we just need to calculate m-1+n permutatiton """ mod = 10**9 + 7 m = m-1 tot_factorial = math.factorial(m+n)%mod n_factorial = math.facto...
9c0eb44e09fd91a8ba77062bc0d543e0aff9ebf2
47,522
def cached(func): """Memoize a function result.""" ret = None def call_or_cache(*args, **kwargs): nonlocal ret if ret is None: ret = func(*args, **kwargs) return ret return call_or_cache
9a62a211e0aa49dc8394cc32614ec68cab4399f1
47,523
def is_time_invariant(ds): """Test if the dataset is time-invariant (has no time coordinate) Args: ds (xarray.Dataset or xarray.DataArray): Data Return: bool : True if no 'time' coordinate detected, False otherwise """ return 'time' not in list(ds.coords.keys())
06254dc660171f34f911ab4e99b9d14e7a789751
47,524
def pygame_rrdt_sampler_paint(sampler): """Visualisation function for rrdt sampler :param sampler: sampler to be visualised """ def get_color_transists(value, max_prob, min_prob): """ :param value: :param max_prob: :param min_prob: """ denominator = m...
af0babdcb01e5edd6755b7ab0ee1f79ae2966fa9
47,525
def merge_dict(d1, d2): """Merge two dictionaries, i.e. {**d1, **d2} in Python 3.5 onwards.""" d12 = d1.copy() d12.update(d2) return d12
26c1e1700873c40bec46f5513c7eb5dbc0595325
47,526
import sys def py25_format(template): """Helper for testing under Python 2.5.""" return template if sys.version_info >= (2, 6) else template.replace("{", "%(").replace("}", ")s")
71a4be4cf3ebd79e5a67b050293e4cd05c5af273
47,527
def only_one(arr): """Many JSON RPC calls return an array; often we only expect a single entry """ assert len(arr) == 1 return arr[0]
7740a4b812e36a1ee3f9e1db7088ef4a87437bff
47,528
def table_all_row(list_rows): """function table_all_row Args: list_rows: Returns: """ rsp = ''' | file | type | name | List functions | | ------- | --- | --- | -------------- | ''' for row in list_rows: rsp += f'{row}\n' return rsp
c4d9a5a17b54ae9ac160ccd80c554935ff6fa38d
47,529
def crystal_search(crystals, histogram_type): """Creating a dictionary of values list ​​divided into centering types for a given histogram type. Parameters ---------- crystals : list A list of crystal. histogram_type : unicode str (on py3) Type of histogram e.g. 'a', 'gamma'....
406ff81a3865a594e43cb95e5e92330617af48df
47,531
def mean(ls): """ Takes a list and returns the mean. """ return float(sum(ls))/len(ls)
213632c6b905317175dbecbbf4f175392451af2e
47,532
def is_iscsi_uid(uid): """Validate the iSCSI initiator format. :param uid: format like iqn.yyyy-mm.naming-authority:unique """ return uid.startswith('iqn')
8670c7970e1ee5e077de3de02f2fb754fa4352aa
47,533
def equal(l1,l2): """ Parameters ---------- l1 : unicode char A character in unicode. l2 : unicode char A character in unicode. Returns ------- boolean True if l1 equals or equivalent to l2. """ if l1 == l2: return True equivalent = { ...
ce274031c895f03f4a34244305fb19caca8b5846
47,537
from typing import cast from typing import Iterable import itertools def _test_for_equality_nestedly_and_block_implicit_bool_conversion( o1: object, o2: object ) -> bool: """test objects, or sequences, for equality. sequences are tested recursively. Block implicit conversion of values to bools. >>> ...
351fb24ec20f8967559ecfff54d1608213c04f8b
47,539
def _get_duration_in_seconds(selected_duration): """ Converts hours/minutes to seconds Args: selected_duration (string): String with number followed by unit (e.g. 3 hours, 2 minutes) Returns: int: duration in seconds """ num_time, num_unit = selected_duration.split(' ')...
0f17f3f4ed678dfb9fdf0d4ed819cb2308311981
47,541
async def handle_async_reader(reader, writer): """Read from the asynchronous reader until EOF, simultaneously logging read bytes to `buffer` and accumulating read bytes. Args: reader: A byte reader with an async read method writer: A byte writer to log read bytes to Returns...
91be72adb83f51594fe4a3668e4cae83f9346d04
47,542
def check_sentence_quality(left_match_right): """ Take a tuple with the left and right side of the matched word and check a few conditions to determine whether it's a good example or not Args: left_match_right (tuple): a tuple of three strings: the left side of the NKJP match, the m...
7a50e860d251e2f2ed2fd1f1c7e7ea406a7a4043
47,543
def cropImage(img, windowSize): """ crop the supplied image & center within specified window; return Rect """ # find center coords of image imgCenterX, imgCenterY = img.get_rect().center # calculate the upper left corner coords for crop mark x1 = imgCenterX - (windowSize[0]/2) y1 = imgCenterY - (windowSize[1]/2)...
b35b0dd20dac86703dfe3b258ce7388d7201b31b
47,544
def toggle_legend_collapse(_, is_open): """Open or close legend view. :param _: Toggle legend btn was clicked :param is_open: Current visibility of legend :return: New visbility for legend; opposite of ``is_open`` :rtype: bool """ return not is_open
50aeccdeb79dde4a6941a94cdd05ee77494cd1b9
47,546
def multiples(m, n): """ Builds a list of the first m multiples of the real number n. :param m: an positive integer value. :param n: an real integer number. :return: an array of the first m multiples of the real number n. """ return [n * x for x in range(1, m + 1)]
3a182d95dafa1d56ce120ff1d04f108f9d9c5e37
47,547
import re def get_version_string(init_file): """ Read __version__ string for an init file. """ with open(init_file, 'r') as fp: content = fp.read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", content, re.M) if version_matc...
22a9faa0d6686106de7d5cb736762859cc9c483a
47,549
def has_primary_repo_remote(repo, verbose=False): """ Checks to see if the repo has a primary remote. """ return False
ccb0e366c2ac7e984e6d1c90e6e22801dbea2a57
47,550
import base64 def addResult(rDB, passFail, tcName, desc, expect, seen, tag, identifier=None): """ addResult() adds a new result to the existing database Variable | Description ----------+-------------------------------------------------------------------------------- rDB ...
db5f256e22223f297a97d5fcf1b5340485551de8
47,551
import re def compute(sample: str, substr: str) -> list[int]: """ Given two strings s and t, t is a substring of s if t is contained as a contiguous collection of symbols in s (as a result, t must be no longer than s). The position of a symbol in a string is the total number of symbols found to its left, incl...
ed3a157fa74e953e56d2ed1d13e0b757da23c135
47,552
def fib(n): """ fib(number) -> number fib takes a number as an Argurment and returns the fibonacci value of that number >>> fib(8) -> 21 >>> fib(6) -> 8 >>> fib(0) -> 1 """ y = {}; if n in y.keys(): return y[n] if n <= 2: f = 1 else: f = fib(n-1) + fib(n-...
a8bc29e4631ef71483cd46b43b6681aff48b9aa5
47,553
def V_terms(Q_x, Q_u, Q_xx, Q_ux, Q_uu, K, k): """ Quadratic approximation of value function """ V_x = Q_x.T + Q_u.T @ K + k @ Q_ux + k.T @ Q_uu @ K V_xx = Q_xx + K.T @ Q_ux + Q_ux.T @ K + K.T @ Q_uu @ K return V_x, V_xx
8b357d9e9b3827f43d7d215a7683e1a67927c220
47,554
import math def softmax(y_pred: dict): """Normalizes a dictionary of predicted probabilities, in-place. Parameters ---------- y_pred """ if not y_pred: return y_pred maximum = max(y_pred.values()) total = 0.0 for c, p in y_pred.items(): y_pred[c] = math.exp(p -...
c77d81c3d88116e84e517b045471846ea40e5fde
47,555
def onRequest(event): """ req is parserd dict like this: { 'pathParameters': { 'action': action }, 'queryStringParameters': dict(request.args), 'body': body if _.predicates.is_dict(body) else json.loads(body or '{}'), 'headers': dict(request.headers) } """ body = event['body'] ac...
120edca6b5a579d53e27d38849abf3a3f43e00f7
47,556
def block_combine(arr, nrows, ncols): """Combine a list of blocks (m * n) into nrows * ncols 2D matrix. Arguments: arr {3D np.array} -- A list of blocks in the format: arr[# of block][block row size][block column size] nrows {int} -- The target row size after combination. nc...
e6330606ea63eb16faee305d646b60b8327785ac
47,557
def return_cash(cash): """ A fake deposit slot function to return cash that user requests with withdrawal transaction """ return True if cash else False
ec654161d6fcd0ab82ca945fc5ecc78dd3513f21
47,560
def getCentroids(layer): """ This function calculates the centroids for the polygons of a map and returns it as a dictionary with the coordinates of each area's centroid. For computational efficiency it's recommended to store the results on the layer database using the addVariable layer functio...
5409ff6e379cf22e2fb85b0e6c2a57b63feba011
47,563
from typing import Tuple import torch def truncated_normal_fill(shape: Tuple[int], mean: float = 0, std: float = 1, limit: float = 2) -> torch.Tensor: """ truncate normal """ num_examples = 8 tmp = torch.empty(shape + (num_exam...
6c11583ee3114be9bf754958ef88e69010085264
47,564
import hashlib def hash_code(source): """get hash """ hash = hashlib.sha256() hash.update(source.encode()) return hash.hexdigest()
83a14b41d5401e8fcf097cfe624e0ebfca4f559a
47,565
import torch def get_token_distances(trigger_spans, arg_spans): """ Just returns distances as a basic metric """ trigger_starts = trigger_spans[:,:,0].unsqueeze(2) # (batch_size, num_triggers, 1) trigger_ends = trigger_spans[:,:,1].unsqueeze(2) # (batch_size, num_triggers, 1) arg_starts = ar...
aebc08a4aefe13c6faa2ea92920db8266aca4d58
47,566
def trailing(target="close", days=40, over_under="under"): """ | Calculates the if the target is trailing under or over the current in the past days. | Name: trailling\_\ **over\_under**\ \_\ **days**\ \_of\_\ **target** :param target: Data column to use for the calculation, defaults to "close" :ty...
cb2b55e23db328913623729f27ca5281bbb13ae0
47,567
import math def get_interactions_stats(S_edgelist, embedding, target_adjacency): """ Interactions are edges between chains that are connected in the source adjacency. Args: S (iterable): An iterable of label pairs representing the edges in the source graph. embedding (dict): ...
69b6f818b25a2cb164cf3e2d6f24a80fc7a73efc
47,568
def replace_None_zero(data, col_kwargs): """Replace all missing values with 0.""" return data.fillna(0)
9035e117168f1415563cafe97a8eda17a2f34f0d
47,569
def fklist(self, kpoi="", lab="", **kwargs): """Lists the forces at keypoints. APDL Command: FKLIST Parameters ---------- kpoi List forces at this keypoint. If ALL (default), list for all selected keypoints [KSEL]. If KPOI = P, graphical picking is enabled and all remaini...
dfcb4547520d8840763ba11fd4f993ffee70279d
47,570
def taken(diff): """Convert a time diff to total number of microseconds""" microseconds = diff.seconds * 1_000 + diff.microseconds return abs(diff.days * 24 * 60 * 60 * 1_000 + microseconds)
64e8022bb0a80fcccc1a755fffb79121e61cad17
47,571
from typing import List from typing import Counter def remove_rare(sentences: List[List[str]]) -> List[List[str]]: """ Remove rare words (those that appear at most once) from sentences. Parameters ---------- sentences: List of tokenized sentences. """ counts: Counter = Counter() ...
1af60b7bb0393abf99db02abf6f4fea9d9529c15
47,572
def _general_direction(model_rxn1, model_rxn2): """ picks the more general of the two directions from reactions passed in """ r1d = model_rxn1.get_direction() r2d = model_rxn2.get_direction() if r1d == r2d: return r1d else: return '<=>'
362ee4a6f033323328f869ef6e5650cc9fef9fa3
47,574
import os def get_file_structure(base_folder,cameras,extension='.MP4'): """ Returns directory listing matching extension for each camera. """ structure = [] for i,camera in enumerate(cameras): path = os.path.abspath(os.path.join(base_folder, camera)) structure.append( [] ) ...
85751ac268b45a3cdffa5499ad5f04ed8fd7c0d1
47,575
def get_test_dict(): """Without "include" lines. """ return { 'backend': { 'default': 'gcp', 'providers': { 'Local': { 'actor-factory': 'cromwell.backend.impl.sfs.config.ConfigBackendLifecycleActorFactory', 'config': { ...
44711f57db5275507bfecf3b0a2381e5ece2140a
47,577
import subprocess def probe_command_availability(cmd): """Try to run 'cmd' in a subprocess and return availability. 'cmd' should be provided in the format expected by subprocess: a string, or a list of strings if multiple arguments. Raises RuntimeError if the called process crashes (eg, via Ctrl+C) ...
3580c53b160f10045a12c61b03963aa2e445c64d
47,578
def del_non_numeric(dataframe): """ This function deletes the non-numeric rows of the resultant dataframe. It is particularly useful for those functions that sometimes return stastical results for non-numeric function (e.g. calculate_max_and_min()). This is because of the underlying structure of certain...
729675b4cfa77b39d8fb591ef0af655421abe6d7
47,580
def get_reciprocal_weighting_function(): """ Returns a function that weights its input by raising the input to the -1 power; see :ref:`selection-strategy` The reciprocal weighting function is useful in cases where fitness should be minimized as the function results in granting higher selection probabilities to i...
65eced160111ee757ba64c16b25a41638471a09c
47,581
def _getTableKeys(table): """Return an array of the keys for a given table""" keys = None if table == "Users": keys = [ "Id", "Reputation", "CreationDate", "DisplayName", "LastAccessDate", "WebsiteUrl", "Location", ...
d645b013e40407c6d537100a7e55338d25244cca
47,582
def get_subset(df, age, gender): """ This function returns a subset of a data frame based on gender and/or age. :param dataframe df: a dataframe containing marathon split times for individuals :param str age: an age group, originally selcted via user input :param str gender: a gender category, origi...
18fe30992dba71c329d95297847a56827f8c52c7
47,583
import random import copy def sample_and_rank_results(cdf_results_list, ranked_results, random_seed=None): """ :param cdf_results_list: output of annotations.build_cdf_sampling_list(results) :param ranked_results: list of results, usually initallized with [] :param random_seed: value to guarantee cons...
d3624cf3daee407fae2d242d342e3da1311ca34d
47,584
def read_table(filename, usecols=(0, 1), sep='\t', comment='#', encoding='utf-8', skip=0): """Parse data files from the data directory Parameters ---------- filename: string Full path to file usecols: list, default [0, 1] A list of two elements representing the columns to be parsed...
81e70a1db8530940d73cf8242b791c3cab473b9c
47,585
import time def time_it(func, *args, **kwargs): """Benchmarks a given function.""" start = time.time() res = func(*args, **kwargs) print(f'{func.__name__} t: {time.time() - start:.{8}f} s') return res
07023c77f29ca03171ac8f725e41212f605bcdaf
47,586
def is_isogram(word): """This method check if given word is isogram.""" chars = set() if len(word) == 0: return True for letter in word: letter = letter.lower() if letter.isalpha() and letter in chars: return False chars.add(letter) return True
7890439112c46dd9d2a3eb803ec9ce22dedb6797
47,587
def retimePadding(frame, retime, size): """ Return the frame with the padding size specified. """ return str(int(frame) + int(retime)).zfill(int(size))
728e63aa4730b4a7d1510e53c74c821a5511d130
47,590
def define_limit_offset(request): """ Define limit and offset variables from request.args """ if request.args: try: limit = int(request.args['limit']) offset = int(request.args['offset']) except: # Default limit and offset limit = 12 offset = 0 else: # Default limit and offset limit = 12 of...
31ef7fbc70ec67c0d646024c580b591238cfecbf
47,591
import re def comment_cleaner(dirty_text): """ Remove blank lines and special characters from text data collected from surveys. Input: dirty_text -- raw text data. Output: clean text data """ if dirty_text is not None: text = dirty_text.replace("(<br>)", "") # remove blank li...
b54ceb211d830b48686c8df1f4a71aa940fc42e0
47,592
def denormalize_dict(source, lower_site_req, upper_site_req, separator="."): """ Only denormalizes a single level and only dicts, so "k.k1":v will get transformed into "k": {"k1": v} """ result = {} for k, v in source.items(): if separator in k: top, lower = k.split(separator) ...
f1ec52640b2684bb31e4154ba333dfe3d29f71db
47,593
def _dot(fqdn): """ Append a dot to a fully qualified domain name. DNS and Designate expect FQDNs to end with a dot, but human's conventionally don't do that. """ return '{0}.'.format(fqdn)
53ee7c41dab6b88523a68fd1ee387031c0314eb1
47,594
def _stringListEncoderHelper( n, maxLenS ): """ helper method for string encoding for list iterator """ maxLenS[0]= max( maxLenS[0], len( n ) ) return n.encode( "ascii", "ignore" )
63d9375a5a2a6fea7e8a6a8b8142dab8730b28a8
47,595
import re import os def create_input_lists(bids_dir: str): """This function creates the input lists that are used to run the patient-wise analysis in parallel Args: bids_dir (str): path to BIDS dataset folder Returns: all_subdirs (list): list of subdirs (i.e. path to parent dir of n4bfc an...
75a3c917599e94f2e5f60efa620dff53bdfdf211
47,596
def intersect1D(min1, max1, min2, max2): """ Return the overlapping state on a 1 dimensional level. :param int/float min1: :param int/float max1: :param int/float min2: :param int/float max2: :return: Overlapping state :rtype: bool """ return min1 < max2 and min2 < max1
2ad6b9926614b3785aab2a28ee2afb088170d2b9
47,597
import os import re def generateDisorder(fastas, outDir, vsl2): """ Generate predicted protein disorder information by bysing VSL2 software. Parameters ---------- file : file the file, which include the protein sequences in fasta format. vsl2: the VSL2 software path VSL2 software path, which could be dow...
fb1ad560f0182e000d32666599275c9183b4ee1d
47,598
def hex_from_evenr(newsystem, coord): """convert from hex coordinate to evenr coordinate""" x = coord.x - (coord.y + (coord.y&1)) // 2 z = -coord.y y = -x+z return newsystem.coord(x=x, y=y, z=z)
ca74da9b2ed80ce21b0d58049fbd3f801add922e
47,599
from typing import Optional def _format_key(key: str, prefix: Optional[str] = None) -> str: """Prepend prefix is necessary.""" if prefix is None: return key return f"{prefix}.{key}"
14720afa7e6825d07696c12ab1c689e6485cda1a
47,600
def add(g, start, end): """ Add edge information into g @type: g, graph (2D array) @param: g, adjacency list @type: start, integer @param: start, start vertex point for edge @type: end, integer @param: end, end vertex point for edge """ g[start].append(end) g[end].append(start) return g
30032f20717034dce57b1e5adfb09e45ce2614be
47,601
def file_size(file, unit): """ Convert the size from bytes to other units like KB, MB or GB Adapted from: https://thispointer.com/python-get-file-size-in-kb-mb-or-gb-human-readable-format/ """ base = 1024 if unit == 'KB': size = file.size/base elif unit == 'MB': size =...
cab5c01470489c126470c0c5179bb3da8d30072b
47,602
import torch def warp_points(points, homographies, device='cpu'): """ Warp a list of points with the given homography. Arguments: points: list of N points, shape (N, 2(x, y))). homography: batched or not (shapes (B, 3, 3) and (...) respectively). Returns: a Tensor of shape (N, 2) or ...
779be021b06eb3b00e4ae154f2ba203f4be706cd
47,603
def degrees_as_hex(angle_degrees, arcseconds_decimal_places=2): """ Takes degrees, returns hex representation. TESTS OK 2020-10-24. :param angle_degrees: any angle as degrees. [float] :param arcseconds_decimal_places: dec. places at end of hex string (no period if zero). [int] :return: same angle in hex...
87c362b3504ddcee16a07c7a7ac4c4e9db2cb17f
47,605
def get_topic_name_by_arn(topic_arn): """ function for handling the somewhat tricky built topic-arns used for topic targeting """ i = 0 topic_name = '' for character in topic_arn: if i == 5: topic_name += character if character == ":": i += 1 retu...
48768ece1a2662d056c441917fb613e88551f5d1
47,607
def read_mappings_from_dict(index_mapping): """ Read event_class and event_type mappings from a python dict. """ evclass = [[], [], []] evtype = [[], [], []] for v in index_mapping['classes']: evclass[0].append(v[0]) evclass[1].append(v[1]) evclass[2].append(v[2]) fo...
cdf2706fed3cdf5786cc238e090401eeae99a8c2
47,608
def most_similar(indices, values, similarity): """Find the value with greatest score of similarity. """ max_result = None, None, None for (rang, index) in enumerate(indices): score = similarity(values[index]) max_score = max_result[0] if score == 1: return score, rang...
4fc45c9e5b8a9df128c125d21a879b3f4e40702c
47,609
import torch def top_p_filter( logits: torch.Tensor, top_p: float, min_tokens_to_keep: int, is_probs: bool = False ) -> torch.Tensor: """Helper function for nucleus sampling decoding, aka. top-p decoding. :param logits: :param top_p: :param min_tokens_to_keep: :param is_probs: ...
7e54e5cc87afa4eb90ca7316e48b947f9647f210
47,610
def standard_formats(workbook): # Add standard formatting to a workbook and return the set of format objects # for use when writing within the workbook """the formats used in the spreadsheet""" # darkgray = '#413839' # optima_blue = '#18C1FF' atomica_blue = "#98E0FA" optional_orange = ...
c1b4915cf5b7e89c0c255f4a167bbd60afa8382e
47,611
def table_to_report(table, measure): """Return a report by taking arguments table and measure. Args: table: an instance generated by c.fetchall(). table is a list of tuples and each tuple has only two values. measure: a unit of measure in string format. Returns: A report in...
e3417b159cd7b826c856697d48c34aecd1a81719
47,612
def escape(t): """HTML-escape the text in `t`. This is only suitable for HTML text, not attributes. """ # Convert HTML special chars into HTML entities. return t.replace("&", "&amp;").replace("<", "&lt;")
e7a81959969829ac2477cdcb6af081e7011685bc
47,613
def has_code(line: str) -> bool: """ Return True if there's code on the line (so it's not a comment or an empty line). """ return not line.strip().startswith("#") or (line.strip() == "")
ef0975ee21deda1206a1bfc728f47d1119132c70
47,614
def PairsFromGroups(groups): """Returns dict such that d[(i,j)] exists iff i and j share a group. groups must be a sequence of sequences, e.g a list of strings. """ result = {} for group in groups: for i in group: for j in group: result[(i, j)] = None return ...
f449612579e54e1365da459d936e633f38d0ceac
47,615
import re import itertools def digestInSilico(proteinSequence, cleavageRule='[KR]', missedCleavage=0, removeNtermM=True, minLength=5, maxLength=55): """Returns a list of peptide sequences and cleavage information derived from an in silico digestion of a polypeptide. :param proteinSeque...
2acbab8b585bf31defc77cabb09f8e32ad7a020a
47,616
def set_focus_on_entry(entry): """sets focus on a given entry""" entry.focus() return "break"
91657ec5613a95f11965f495b38248ca2ef9e23f
47,617
def currentTurn(turn): """ Simply returns the string version of whose turn it is as opposed to adding if/else everywhere """ if turn == 0: return "Red Team" elif turn == 1: return "Blue Team"
81f8ec74bae351951d18539b08bb7a454be5359b
47,618
def _version_to_tuple(version): """Converts the version string ``major.minor`` to ``(major, minor)`` int tuple.""" major, minor = version.split('.') return (int(major), int(minor))
921a3855fd23a597f13dab27f660cf4b0113926b
47,620
def parseExtn(extn=None): """ Parse a string representing a qualified fits extension name as in the output of `parseFilename` and return a tuple ``(str(extname), int(extver))``, which can be passed to `astropy.io.fits` functions using the 'ext' kw. Default return is the first extension in a fit...
ddbc2c3e16161431ce458eb2ff441ab8a21145ee
47,622
import json def get_config(): """Read the config file""" try: with open('default.json', mode='r', encoding='utf-8') as config_file: return json.load(config_file) except FileNotFoundError: with open('config.json', mode='r', encoding='utf-8') as config_file: r...
e39d96d34df9915dad97bd42b446ea0298a40628
47,623
def list_to_str(seq, sep="-"): """Transform the input sequence into a ready-to-print string Parameters ---------- seq : list, tuple, dict Input sequence that must be transformed sep : str Separator that must appears between each `seq` items Returns ------- str P...
e666ae9beff7733bf3f050a6ff65b69dddd8edcc
47,624
def makeTokenSet(): """ Make a token set The set of tokens must be the same as it used for trainning the DNN Here we make a CPP56X token set of C++ tokens Returns a dictionary of tokens: - Key is a string representing the token - Value is integer value of token """ #CPP56 OPERATORS ...
c77e4b38cf62a22d1cf36eac1fd10a91222dfa9c
47,630
import requests def check_http_response(response, expected_status_code): """ validate http status code """ status = response.status_code if status == expected_status_code: return True if status == 401: # unauthorized msg = "ERROR: status = %s - Invalid credentials?" % status ...
d8715acba9a8e7dd60bc0c778235ff9989827d93
47,634
def create_pyramid(wall, ip): """ Shorten the rows to relevant values - integers in range 800-999 under the initial position brick.""" ni = ip # Negative index pi = ip+1 # Positive index for row in range(0, len(wall)): if row % 2 == 0 and row != 0: pi += 1 elif ro...
26722fae0b02d974545e597203d708c042a5669e
47,636
def _report_body(*, image: str, repo: str, run: str, stacktrace: str) -> str: """Format the error report.""" return ( f"Repo: {repo}\n" f"Run URL: {run}\n" f"Image ID: {image}\n" f"Stacktrace:\n```py\n{stacktrace}\n```\n" )
a81ea924078f0225aba3ab441aef42c3393118cb
47,637
import importlib import time def time_algo(call_string, module_name): """ Times the execution of a python call string. :param call_string: str string that calls a python module and executes an algorithm :param module_name: str name of module from which function is called :return run_time: floa...
f24e708c04a765487b3c009b7ef5f9929e4c885b
47,638
import torch def normalizePi(pi, logPi, mu): """Apply squashing function. See appendix C from https://arxiv.org/pdf/1812.05905.pdf. """ # action_max = envEval.action_space.high[0] # action_min = envEval.action_space.low[0] # action_scale = torch.tensor((action_max - action_min).item() / 2.) ...
bdc8db77b9f650bd3cbb5b17b573fd6d7aada3b7
47,639
def compute_columns(n_items, n_rows): """Compute the required number of columns given a number of items n_items to be displayed in a grid n_rows x n_cols""" if n_rows > n_items: return n_items, 1 d = n_items // n_rows n_cols = d + (1 if n_items % n_rows else 0) return n_rows, n_cols
dbc4a87d0d335055ea8f8b6115289b94cb15a655
47,640