content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import re def identificador(soup): """ Return Lattes ID (number) """ ID = soup.find("li") ID_num = re.findall('lattes.cnpq.br/(.+?)<', str(ID))[0] return ID_num
67dbbc361901af9a1ea23e6e426d907279c4253d
551,591
def remove_numbers(words): """Remove all numbers from word list. Unlike words, numbers without any context are not expected to provide any explanatory value for topic classification. Parameters ---------- words : string Original word-token list Returns ------- new_words : list of strings List with all...
5231b3c84aa926b9898927c251a11d87de4c07e4
478,427
import torch def train(model, iterator, optimizer, criterion, clip): """ TRAINING: At each iteration: get the source and target sentences from the batch, $X$ and $Y$ zero the gradients calculated from the last batch feed the source and target into the model to get the output, $\hat{Y...
5bea27ca9b0ad40f04034ccf0e33109f17c9460a
104,098
import six def is_iterable(value): """ Custom iterable test that excludes string types Parameters ---------- value: object The value to test if iterable Returns ------- iterable: bool True if the value is iterable and not a string, false otherwise """ if isins...
b9dfed21aafd63148642668c5cac018f7a008ffd
171,910
def remove_exotic_char(entry): """remove any exotic character from the text to make it more compatible""" no_tag_pattern = {u"œ": u"oe", u"œ": u"oe", u"Œ": u"Oe", u"Æ": u"Ae", u"æ": u"ae"} for key, value in no_tag_pattern.items(): entry = entry.replace(key, value) return entry
33f8697fc16b9e737f036f8b5939b0735adf540b
363,260
def sanitize_smiles_file_name(file_name): """Sanitizes a file name which contains smiles patterns. Currently this method simply replaces any `/` characters with a `_` character. Parameters ---------- file_name: str The file name to sanitize Returns ------- The sanitized fil...
7b9922403fd598492b419db1d796bae0de8e920c
65,951
def is_candidate(wordlist, word): """True if word is a candidate for the homophone problem, in that it's five letters long, and removing either of the first two letters also results in a word. wordlist: dictionary of words word: string """ word1 = word[1:] word2 = word[0]+word[2:] # ...
46c86199993ab180fb430631568633f72f75a147
478,447
import inspect def is_bound_builtin_method(meth): """Helper returning True if meth is a bound built-in method""" return (inspect.isbuiltin(meth) and getattr(meth, '__self__', None) is not None and getattr(meth.__self__, '__class__', None))
a7a45f0f519119d795e91723657a1333eb6714e4
705,879
import functools import warnings def deprecated(func): """Decorator that marks functions or classes as deprecated (emits a warning when used).""" @functools.wraps(func) def inner(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn(f"Call to deprecated funct...
983e7a47a6d7c7a2da5af818a1fb253681fd61da
207,028
def distNDx(pt1, pt2, limit=0): """Returns distance between two nD points (as two n-tuples) It ignores items if they are not numeric, and also has an option to limit length of tuples to a certain length defined by the `limit` argument""" if limit > 0: return (sum((vv2 - vv1)**2.0 for i, (vv...
3d832dbb83c9fb6af84601c245f189302b43845f
197,968
def get_xpath_for_date_of_available_time_element(day_index: int) -> str: """ The element showing date of the available time is found in the div having the xpath: '/html/body/div[4]/div[2]/div/div[5]/div/div[2]/div[3]/div[N]/span' ^ where N ...
81a3cd1a88c47cfd2cb1b815354ce4a6d2f9dca8
655,557
def is_valid_output_minimize(ext): """ Checks if output file format is compatible with Obminimize """ formats = ["pdb", "mol2"] return ext in formats
fcc99113009f8821194f1a87150da4fb8a12a6d3
354,150
from typing import Any def is_less_than(value: Any, *, upper_bound: Any = 10) -> bool: """Checks whether the value is less than the upper_bound :param value: The value to check if is less than :param upper_bound: The upper bound :return: Whether the value is less than upper_bound """ return v...
0699fc80e34b772d97c81823d23a466c8884ac17
64,651
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 get_call_uri(ad, call_id): """Get call's uri field. Get Uri for call_id in ad. Args: ad: android device object. call_id: the call id to get Uri from. Returns: call's Uri if call is active and have uri field. None otherwise. """ try: call_detail = ad.droid.t...
b524891c0f3f66540889a156c93d666fbf240ce2
129,557
def find_multiples(integer, limit): """ Finds all integers multiples. :param integer: integer value. :param limit: integer value. :return: a list of its multiples up to another value, limit. """ return [x for x in range(1, limit + 1) if x % integer == 0]
36b438541f6f067a92aad6317f3ce919b6e4bde2
637,504
def create_alignment(df): """ Map the sentence position indexes of the abstract sentences for a whole papers dataframe. Used later to map the separately calculated sentence embeddings (due to performance gains in SBERT batch embedding) to the correct paper. :param df: The papers dataframe...
071a51b05e63b20716ae9449aabbbde9c8f5f37b
241,103
def sense_instances(instances, sense): """ Returns the list of instances in **instances** that have the sense **sense**. Example: sense_instances(senseval.instances('hard.pos'), 'HARD1') """ return [instance for instance in instances if instance.senses[0] == sense]
28f6c17f2308a424d3e7776a08aade60a058763c
116,554
def lustre_ost_id(fsname, ost_index): """ Return the Lustre client ID """ return "%s:%s" % (fsname, ost_index)
582845e7762f8705d930a023a296dc68344d41b0
640,060
from typing import MutableMapping def is_mapping(obj): """ Checks if the object is an instance of MutableMapping. :param obj: Object to be checked. :return: Truth value of whether the object is an instance of MutableMapping. :rtype: bool """ return isinstance(obj, MutableMapping)
ac909c3bbb5a67a17f322df8ba380b09076bb50c
407,223
import uuid def generate_event_id(worker_id): """ Return a unique id to use for identifying a packet for a worker. """ return '{}_{}'.format(worker_id, uuid.uuid4())
8f5c3ef9efc098c60161d8f22d41f2fc14a83f64
467,728
from typing import Dict from typing import Any def dict_without(data: Dict[str, Any], omit_key: str) -> Dict[str, Any]: """Return a dictionary without a given key if present.""" return {k: data[k] for k in data if k != omit_key}
7f3ecbe65ecfbc96d3de315ed7c31cf1887bd0f4
415,377
def Set(state,command,name,value=True): """Set the state variable Sets a state variable with 'name' to 'value'. If 'value' is not specified, variable is set to True. """ state.vars[name]=value return state
c489a7459f635e8dec6d21ad5d80a5253604ec05
420,591
import json def pretty_json(json_str): """Generates a pretty-print json from any json.""" return json.dumps(json.loads(json_str), indent=4)
e1d16fcc91c7d212130af115eb0cad2fbd73a99c
648,117
def remove_cell_with(cell, pattern): """ If a string string contains the specified pattern, None is returned. """ if pattern in cell: return None else: return cell
d8617f42d413f0ab7fcccc9118a9d240cf7cd214
194,469
def LCS(value: str) -> bytes: """ pack a string into a LCS """ return b'\x84' + str.encode(value) + b'\x00'
1b3d30685d72d9afff07ae875247ed5114df977d
85,236
def isPrime(i): """ This function returns if i is a prime number or not. """ if i <= 1: return False for k in range(2, int(i**0.5)+1): if i%k == 0: return False return True
145d46ff63ebb4d5ff028986679de24a3b77c0e4
153,245
def encode_member(member): """Encode a team member and return fields: - name - profileUrl (optional) """ res = { 'name': member.name, } if member.profile_url: res['profileUrl'] = member.profile_url return res
3522a8343823385a1e93af0f34c68a1cde286fe4
377,806
def title_case(sentence): """ Capitalize the first letter of every word in a sentence. Parameters ---------- sentence: string Sentence to be converted to title case Returns ------- result: string Input string converted to title case Example ------- >>> title_...
6c75490af1d6d6fd9bf47ebdebcaca11773950cc
504,926
from bs4 import BeautifulSoup def parse_pypi_index(text): """Parses the text and returns all the packages Parameters ---------- text : str the html of the website (https://pypi.org/simple/) Returns ------- List[str] the list of packages """ soup = BeautifulSoup(te...
68d831aab69f3ffdd879ea1fa7ca5f28fc1b1e75
4,380
def KFold(num, n_folds=5): """ k折叠交叉验证算法,如果份数不能整除数据的数量 会尽量分成相近的数量 :param num: 所有数据的数量 :param n_folds: k,分成k份 :return: """ folds = [] indics = list(range(num)) for i in range(n_folds): # 将一部分数据作为验证集 valid_indics = indics[(i * num // n_folds):((i + 1) * num // n_fo...
c515588dfa71f3cd2529a8a26786cdd7cd997159
414,640
def sq_dist(p1, p2): """ Calculate the non-square-root distance between two points. Args: p1, p2: 1x3 point coordinates. """ return (p1[0]-p2[0])**2+(p1[1]-p2[1])**2+(p1[2]-p2[2])**2
5d576b274c3d93b755f56565f15e280538d7c541
494,156
import tree_sitter from typing import Tuple def get_positional_bytes(node: tree_sitter.Node) -> Tuple[int, int]: """ Extract start and end byte. :param node: node on the AST. :return: (start byte, end byte). """ start = node.start_byte end = node.end_byte return start, end
08252fa9c6f63d7c81e92116cf95ad5f425edfda
316,682
def get_overlap(i1, i2, j1, j2): """ Get overlap between spans """ A = set(range(i1, i2)) B = set(range(j1, j2)) overlap = A.intersection(B) overlap = sorted(list(overlap)) return overlap
4a968b6cc85ad4e376a27e98161906ad96b42d30
177,013
def split_snake_case_name_to_words(name): """ 'snake_case_name' -> ['snake', 'case', 'name'] """ return [n for n in name.split('_') if n]
cf91f5bd86df4fd8ee290dcbb30999217af224ff
405,950
def get_leaf_decision(l_yes, l_no, parent_decision) -> int: """returns leaf decision with majority decision if not equal else returns it's parent decision""" leaf_value = 0 if l_yes > l_no: leaf_value = 1 elif l_yes == l_no: leaf_value = 1 if parent_decision else 0 return leaf_value
6e065617fbdbbf963a7e103a8154972e317dd586
566,656
def calculate_num_modules(slot_map): """ Reads the slot map and counts the number of modules we have in total :param slot_map: The Slot map containing the number of modules. :return: The number of modules counted in the config. """ return sum([len(v) for v in slot_map.values()])
efbb82a54843f093a5527ebb6a1d4c4b75668ebb
704,085
def index2label(index, label): """ Converts an indices tensor into its labelled values counterpart Parameters ---------- index : LongTensor the indices tensor label : list the labels values Returns ------- list a list of labels """ return [label[i] ...
728a10d866fba0149fe933d56927e6caad146390
210,998
def dummy_address_check( address ): """ Determines if values contain dummy addresses Args: address: Dictionary, list, or string containing addresses Returns: True if any of the data contains a dummy address; False otherwise """ dummy_addresses = [ "", "0.0.0.0", "::" ] if...
59b8a5fa1606a1898e20d3b95b74310e38752957
543,390
import uuid def create_id() -> str: # pragma: no cover """Creates an uuid.""" return str(uuid.uuid4())
a22df1382bc2da7d730aed6e9131301749720919
646,710
def my_task(**kwargs) -> None: """ Function used for testing, returns nothing. """ return None
3839c4ddb7ad6f9358fb6faac3fce50e9072647a
99,766
def inv_power(x, d): """Computes the d-th root of x if it is an integer. x must be >= 0 and d must be >= 1. Args: x (int): Integer x. d (int): Integer d. Raises: ValueError: Thrown when x < 0 or d < 1. Returns: int: The d-th root of x if it is an integer, otherwise...
4a425a56c0dde003229d32acaa6e69e1e0cd46bf
439,164
import random import string def randomstring(N): """ Generate a random string of length N """ return "".join( random.choice(string.ascii_letters + string.digits) for _ in range(N) )
914c21e180c4921ab29b48b704e36f008a213e81
595,035
def abi_crs(G, reference_variable="CMI_C01"): """ Get coordinate reference system for the Advanced Baseline Imager (ABI). Parameters ---------- G : xarray.Dataset An xarray.Dataset to derive the coordinate reference system. reference_variable : str A variable in the xarray.Datas...
b420ea4cda12f1acd4b9af6ecd9c2f70c756f761
24,097
def get_unit(a): """Extract the time unit from array's dtype""" typestr = a.dtype.str i = typestr.find('[') if i == -1: raise TypeError("Expected a datetime64 array, not %s", a.dtype) return typestr[i + 1: -1]
22f132af5ab751afdb75c60689086874fa3dfd99
674,274
def age_correction(start_year, T, age_vec): """Takes a start year, current year T and age vector of the upper bound of the age group (a_u) returns a vector of 0 and 1 to avoid transition to unwanted age groups """ vec = (T - start_year) > age_vec return vec.astype(int)[:-1]
6af68325be25fd85efeee97c67fba66c87183ed4
166,915
def length(*t, degree=2): """Computes the length of the vector given as parameter. By default, it computes the Euclidean distance (degree==2)""" s=0 for x in t: s += abs(x)**degree return s**(1/degree)
8f781651da482fd780266367b41baa844fac93c5
422,470
import filecmp def comp_fnames_file_equality(fname1, fname2): """ Compare filenames: File equality: Check if contents of files are identical. Equality = True/False. Uses filecmp byte-comparison (more efficient than md5). """ equality = filecmp.cmp(fname1, fname2, shallow=True) if equa...
61647f46d8d25484d15167f332f670c08ea1ad5b
104,625
def is_key_translated(verbose, obj_id, key, object_json): """ Checks if the given key of an object is translated in input JSON """ if key in object_json: return True if verbose: print(f"No translation for {obj_id} string '{key}' in dump file -- skipping") return False
b7c3966204463a06f019924b6df0cb78fca2052b
160,562
from typing import Union from typing import Callable from typing import Any def complement( expr: Union[bool, Callable[[Any], bool]] ) -> Union[bool, Callable[[Any], bool]]: """Takes in a predicate or a Boolean expression and returns a negated version of the predicate or expression. >>> complement(Tr...
eb768723701205b5ef4e2c2b79ed0f91cb632437
432,150
def as_si(x: float, decimals: int) -> str: """ Convert a number to scientific notation Parameters ---------- x : float number to convert decimals: float number of decimal places Returns ------- x_si : string x formatted in scientific notation """ s ...
5adbec315cf9eed2fd6e947f90d2f127f416fcc0
354,561
def replace_consts_with_values(s, c): """ Replace the constants in a given string s with the values in a list c. :param s: A given phenotype string. :param c: A list of values which will replace the constants in the phenotype string. :return: The phenotype string with the constants replaced...
c04b44e338288709130ad930b833d6de4f3fece2
671,143
def normalize(hypotheses, index=-1): """Normalize probabilities.""" total = 0 for probs in hypotheses.values(): total += probs[index] for probs in hypotheses.values(): probs[index] /= total return total
11d239c09d146cdb9d67b3532bababe0e20517ba
518,648
def get_file_id(service, file_name, mime_type=None, parent_id=None): """Return the ID of a Google Drive file :param service: A Google Drive API service object :param file_name: A string, the name of the file :param mime_type: A string, optional MIME type of file to search for :param parent_id: A st...
e8e371ea740ca4be55b35baa74c28207ca6b7b4d
697,787
def is_indent(xxx): """is character xxx part of indentation?""" return xxx in ['\t', '|', ' ', '+', '-', '\\', '/']
a50f5d44a97479d34f42f280fae9ea3f790f61d4
356,949
def question_json_maker(question_id, question, answer, answer_index=1, question_type='MC', difficulty=1, points=10): """ Generates JSON file for each question. :param question: input question.(str) :param answer: output answer(str or int) :param answer_index: index of the correct answer(int) :pa...
bae0b4d02a687f7680ac2e98171f14b4e9bf5baf
370,100
def warshall_floyd(dist): """ Args: Distance matrix between two points. Returns: Matrix of shortest distance. Landau notation: O(n ** 3). """ v_count = len(dist[0]) for k in range(v_count): for i in range(v_count): for j in range(v_count): ...
9d13c48aca39d69ab07b6a9c4be716102c6cc19b
408,465
def get_fragment(uri): """ Get the final part of the URI. The final part is the text after the last hash (#) or slash (/), and is typically the part that varies and is appended to the namespace. Args: uri: The full URI to extract the fragment from. Returns: The final part of t...
f1abd66c97b4e7d11873550d61755bb8e2fea78f
549,597
import requests def submit_request(url: str, token: str, query: str) -> requests.Response: """Post a query to an API access point, along with an authentication token. Retry with a progressive timeout window. """ MAX_REQUESTS = 3 TIMEOUT_INCREMENT = 5 response = None req_count = 1 whi...
9ccc1ef966b15ece39c3d2260adb06f4d327c9de
619,729
import json def json_pretty(obj): """Convert obj into pretty-printed JSON""" return json.dumps(obj, indent=4, sort_keys=True)
2c240eb7eb0c413f3da6d3477949968ea90ef5f9
621,319
def read_distance_file(dist_file, threshold): """ Read a previously created distance file and store it as a hash :param threshold: The threshold for the distances :type threshold: float :param dist_file: The file to read :type dist_file: str :return: A hash of rxn1 rxn2 -> distance :rtyp...
7e38543106e35fadb0a45fd158289e5985014477
111,670
import math def get_distance(a, b): """Return Euclidean distance between points a and b.""" return math.sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2))
89c66e586a37a88dbce25460ad3310a035044c73
43,031
from typing import Iterable def _n_name(invars: Iterable[str]) -> str: """Make sure that name does not exist in invars""" name = "n" while name in invars: name = "n" + name return name
fc3b5da0e762e1b212248c403ceda66c311a60f9
27,592
def createFromDocument(doc): """ Create an empty JS range from a document @param doc DOM document @return a empty JS range """ return doc.createRange()
3bd55c4f60b25bb089b592f9dfe65ea299230be8
688,185
def get_auth_dict(auth_string): """ Splits WWW-Authenticate and HTTP_AUTHORIZATION strings into a dictionaries, e.g. { nonce : "951abe58eddbb49c1ed77a3a5fb5fc2e"', opaque : "34de40e4f2e4f4eda2a3952fd2abab16"', realm : "realm1"', qop : "auth"' } """ amap =...
adb2c6dbcea429ae94c133b5b00148236da216e2
679,124
def extract_uuidlist_from_record(uuid_string_list): """Extract uuid from Service UUID List """ start = 1 end = len(uuid_string_list) - 1 uuid_length = 36 uuidlist = [] while start < end: uuid = uuid_string_list[start:(start + uuid_length)] start += uuid_length + 1 uui...
f6f4acdbdbfdf9aac909669d7ea3ad8492bed685
643,289
from typing import Union from typing import List from typing import KeysView from typing import ItemsView from typing import Any def copyList(tocopy: Union[ List, KeysView, ItemsView] ) -> List[Any]: """ Copies an iterable to another list :param tocopy: itarable to copy :return: the copied list """ return [ x f...
01b306225e33ee74e47421e94721d21ce0638cb3
347,686
def spacify(string): """Add 2 spaces to the beginning of each line in a multi-line string.""" return " " + " ".join(string.splitlines(True))
2403f3fc1f193ae59be2dcfe2ac4911d542701cd
77,442
def window(x, win_len, win_stride, win_fn): """ Apply a window function to an array with window size win_len, advancing at win_stride. :param x: Array :param win_len: Number of samples per window :param win_stride: Stride to advance current window :param win_fn: Callable window function. Takes ...
95ac180a57b6f0e3ca4517bdc8559f8875e94f94
676,710
import string def capwords(value, sep=None): """ Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a sin...
e481cab8af670b41130a1728869fa424e07ed5b8
689,786
def get_num_fsaverage_verts_per_hemi(fsversion=6): """ Return the number of vertices per fsaverage hemisphere. Returns ------- vertcount: int The number of vertices per fsaverage hemisphere. """ if fsversion == 6: return 163842 else: raise ValueError("Currently ...
c4db648da7b2746cf8304330d20c6fc31363d839
155,509
def to_format(phrase: str, param: str): """ The 'phrase' string is formatted taking 'param' parameter :param phrase: it must contain a {} that will be replaced by the 'param' parameter :param param: parameter :return: formatted string """ return phrase.format(param)
e85ff63425f9fbda909d4ed75544ee5c182daa29
113,130
def get_default_alignment_parameters(adjustspec): """ Helper method to extract default alignment parameters as passed in spec and return values in a list. for e.g if the params is passed as "key=value key2=value2", then the returned list will be: ["key=value", "key2=value2"] """ default_al...
79ab15863ef12269c3873f41020d5f6d6a15d745
674,510
async def ping(): """Inspects if the API instance is running.""" return {"ping": "pong"}
fb2cb7128a66bda332e0a0e65314bfd5e9fee305
630,524
def fahrenheit_to_celsius(temp_in_f): """ Actually does the conversion of temperature from F to C. PARAMETERS -------- temp_in_f: float A temperature in degrees Fahrenheit. RETURNS ------- temp_in_c: float The same temperature converted to degrees Celsius. """ return (temp_in_f-32)*5/9
702b501739f4fe482884280bf7b685a2f7cd6073
563,434
def extractdata(line): """For each line, return the x and y values, check whether there is reference value and if so return the reference value, otherwise return a reference value of 1 """ newArray = (line.split(',')) # if len(newArray) == 8: # convert the strings to floats xvalue = f...
c7cb553bedef333cf9950588757906c7f114d535
50,143
from typing import Counter import itertools def build_vocab(texts): """ Builds a vocabulary mapping from word to index based on the sentences. Returns vocabulary mapping and inverse vocabulary mapping. """ # Build vocabulary word_counts = Counter(itertools.chain(*texts)) # Mapping from index to word vocabular...
2f464abc4d8cc1ccef312907f4265d0882c8a6de
560,551
def get_building_coords(town): """ Generates a dictionary of all (x,y) co-ordinates that are within buildings in the town, where the keys are the buildings' numbers (or "pub" for the pub) and the values are lists of co-ordinates associated with the building. Data must have 25 houses (numbered as mu...
085c95d40d9d84569180155f5b0b150334dbc526
695,908
from typing import Iterable import glob def find_onewire_devices() -> Iterable[str]: """Get the list of files corresponding to devices on the one-wire bus. Args: Returns: Iterable[str]: The file paths. """ return glob.glob('/sys/bus/w1/devices/28*/w1_slave')
354f9927b24c41b2e121c8c44ae8f3e0c3cf9bc0
117,779
import pytz def utc_datetime_to_button_format(utc_dt): """ Convert a UTC datetime obj to the the date and time format we need for slack buttons in Eastern time. """ eastern = pytz.timezone('US/Eastern') east_conv = utc_dt.astimezone(eastern) time_text = east_conv.strftime("%H:%M") dat...
81bce6e8f44f62eaba595d9384b28f15db6d4de0
576,172
def delta_f(kA, kB, NA, NB): """ Difference of frequencies """ return kA / NA - kB / NB
e96b70a2aaccff6a3e13693dd83c8df171e019ba
203,513
def rgba(color): """ Return 4-element list of red, green, blue, alpha values. """ if color.startswith('rgba'): values = [int(v) for v in color[5:-1].split(',')] else: values = [int(v) for v in color[4:-1].split(',')] values.append(1) return values
e5468a52b74100bce23a26c51a4e395b7a0d2fe6
102,192
def check_all_matching_tags(tag_arg_dict, target_tag_dict): """ Return True if all tag sets in `tag_arg_dict` is a subset of the matching categories in `target_tag_dict`. """ return all( [ tags_set.issubset(target_tag_dict.get(tag_name, set())) for tag_name, tags_set ...
9b3ef0df9e34a515ecb17c02e0fb95c5491ffa11
288,980
def readSampleFile(filepath): """ Parse sample file into dictionary. Return sample dictionary and sample order list. """ samples = {} sOrder = [] with open(filepath, "r") as fh: for l in fh: l = l.rstrip("\n") s, r = l.split("\t") try: ...
6de5a601286cd17936eeda2bacd41ff28636c4ff
132,395
def gettypes(*a): """ Convert a list of objects to their types """ return list(map(type, a))
ff7bbf719cd115c178afd12c2cbd67243c7ecab7
168,492
import hashlib def hash(text): """Make a hash of the text :param text: text to make the hash :returns: hashed version of the text """ return hashlib.sha256(text.encode('utf-8')).hexdigest()
a4f1210f86fd520346a196bacd6c603ee6859eec
217,413
def glue_tracks(tracks): """ This functions glues all tracks in a single one, using the specified fade for each track, and returns the resulting audio. """ final = tracks[0][0] for audio, fade in tracks[1:]: final = final.append(audio, crossfade=fade) return final
d2fd8a0334a5d71f41045fd4495a4c7be2389365
263,240
def _text_repr(text, max_len=1000): """ Return the input text as a Python string representation (i.e. using repr()) that is limited to a maximum length. """ if text is None: text_repr = 'None' elif len(text) > max_len: text_repr = repr(text[0:max_len]) + '...' else: t...
350e6fdfba1f1b95914002ab1a38005da3c79fbc
154,293
from typing import Counter def sock_merchant(colors: list[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([1, 2, 1, 2, 1, 3, 2]) 2 """ return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values())
5493bfea83141e253e94ad2f7090f5c19922360c
580,592
def get_9s(percentile): """ Method that gets the amount of 9s in a percentile Args: percentile: The percentile to get the amount of 9s for Returns: The amount of 9s of the percentile, so 0.4->0, 0.92->1, 0.994->2, etc. """ counter = 1 # Limit to 20 nines, probably won't ever ...
9eb99415a5477818b309b04ac8aa80a421943860
321,672
import torch def count_parameters(model: torch.nn.Module) -> int: """Return the number of trainable parameters of a model. Taken from: https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325/7. Parameters ---------- model : torch.nn.Module The model to count...
f27b24834144a327df284f3c2961649da225807b
244,837
def ensure_complete_modality(modality_dict, require_rpc=False): """ Ensures that a certain modality (MSI, PAN, SWIR) has all of the required files for computation through the whole pipeline. :param modality_dict: Mapping of a certain modality to its image, rpc, and info files. :type modality_dict: ...
a35543009470c3f0f80cfc8f4137913aa26bfe80
287,506
import random def guess_by_random(agent, words): """A word-selection action that simply chooses a word from the given list of words at random, using `random.choice()`. Parameters: `agent`: An instance of an agent class that derives from `BaseRLAgent` `words`: The list of words to choose ...
8a61ed7b2252863ca3ec59b3137d68ae0a2f032f
165,673
def set_serialization_options(opts, output_folder=""): """ Enable / disable the serialization to disk of the compiled executables. .. code-block:: python # Create a device that will save to disk all the compiled executables. opts = create_ipu_config() opts = set_serialization_options(opts, ...
0bb11e812917cf94b9ccde7957e1d5c8b503b833
547,094
def submit(ds, entry_name, molecule, index): """ Submit an optimization job to a QCArchive server. Parameters ---------- ds : qcportal.collections.OptimizationDataset The QCArchive OptimizationDataset object that this calculation belongs to entry_name : str The base entr...
50a30a25af59906ce5636ce8a176e29befd27d60
1,861
def restore_path(p: list, v): """ Convert predecessors list to path list Parameters ---------- p : list predecessors v searched node Returns ------- path : list path[i] is the node visited in the ith step """ path = [v] u = p[v] while u != -...
6e2f970d2e08e16efb97ab20b774369a7f2edab7
281,190
import torch def compute_pdist_matrix(batch, p=2.0): """ Computes the matrix of pairwise distances w.r.t. p-norm :param batch: torch.Tensor, input vectors :param p: float, norm parameter, such that ||x||p = (sum_i |x_i|^p)^(1/p) :return: torch.Tensor, matrix A such that A_ij = ||batch[i] - bat...
ae997a59c7e208fca4dc80ee1f7865320edeff86
681,634
import copy def merge_objects(obj_of_values, obj_of_default_values): """ obj_of_values represents a sub sets of values, for example a selection of options values. obj_of_default_values represents the complete list of possible option values and their default values returns obj_of_values with all missi...
f2315e6165c9342c0177675ff9a65beb46d0f5cf
325,849
def get_col_names(cursor, table): """ Helper function to retrieve columns from SQLite memory table :param cursor: :param table: :return: """ cursor.execute('SELECT * FROM "{table}"'.format(table=table)) return [member[0] for member in cursor.description]
47c92e4317bd3d77ba62a9998ec3607d7ad67860
248,607
import gzip def open_file_helper(filename, compressed, mode="rt"): """ Supports reading of gzip compressed or uncompressed file. Parameters: ---------- filename : str Name of the file to open. compressed : bool If true, treat filename as gzip compressed. mode : str ...
a682924f68158f88552b96197c43735bb596afaa
604,130