content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _get_patients_from_encounters(encounters): """Input list of encounters, return a list of all the patients within those encounters""" patients = set() for enc in encounters: patients.add(enc.visit.patient.uuid) return patients
1b2d99c4441609e58be161c9729d6f2cbc6625d6
574,273
from typing import Tuple from typing import Any def map_link(position: Tuple[float, Any, float], zoom: int = 6) -> str: """ Return a link to the map at the specified position :param tuple[float,Any,float] position: The position to return a map link to, only the first and last items are used :param in...
3495a4709def2b6c4a26d9cde0f3b71188442055
574,277
def get_uid(item): """ 获取item的uid :param item: item数据,dict型 :return: item的uid """ return item.get('uid')
574566eb100db4d06b8b05a6269df45f343671cb
574,278
def parse_kstar(kstar): """ Parses the kstar string labels into kstar values to select merger types Parameters ---------- kstar : `string` specifies the merger types for the primary and secondary stars where kstar = '13_14' contains both NSs and BHs and kstar = '13' just...
684636e7d15b93f0c1181eb5ba6a6b3c8612c636
574,280
def getitem(obj, key=0, default=None): """Get first element of list or return default""" try: return obj[key] except: return default
120053e058bf12d28c67f0df525ace0896351361
574,282
import torch def getBatch(batch_size, correlations, anticorrelations): """Make inputs and outputs for a single output model. Arguments: batch_size (int) : Number of elements in a batch. correlations (torch.tensor): Probabilities of each input being 1 when the target output ...
09e4520263cde54db70bffce5c99065009f9ec12
574,283
def filter_rare_cards(df, rarity_num=5, card_column='CRD_NO', date_column='dates'): """ Removes rare cards. Takes only cards which have more than rarity_num bills (different days) Args: df: Dataframe with bills rarity_num: Minimum num bills per crd card_column: Column that contains c...
a14eb7829cf37ee77232f4c98cda3ac211fd38ad
574,289
def index_vector(v): """ Return an index for values in the given sequence >>> index_vector( (9, 8, 7)) {9: 0, 8: 1, 7: 2} """ return { v[i] : i for i in range(len(v)) }
597e5a927cbcc834a39868232b32e52d0fafc01f
574,292
import torch def one_hot(labels, class_size): """ Create one hot label matrix of size (N, C) Inputs: - labels: Labels Tensor of shape (N,) representing a ground-truth label for each MNIST image - class_size: Scalar representing of target classes our dataset Outputs: - targets: One-ho...
ec9bcc0d9db4fe49e07c9c9879a8ba5f24050215
574,294
def obter_pos_l(pos): """ Devolve a linha da posicao. :param pos: posicao :return: string """ return pos[1]
60fc5c441529df087d698215c332d59b1bf08e7f
574,296
def calc_total_capacitance(eps_fluid, lamb, Cdl, Cd, Cbuff): """ Total capacitance from Debye layer, dielectric layer, and buffer """ beta = Cbuff/Cd delta = Cdl/Cd total_capacitance = (eps_fluid/lamb)*((1+beta/delta)/(1+delta+beta)) return total_capacitance, beta, delta
9df823dc048e0dacbff18a00ab8da0b972f8c1b1
574,297
def del_doublon(values): """ delete duplicated data in list >>> a = [1,2,2,3,3,4,4,4,5,5,6] >>> del_doublon(a) [1, 2, 3, 4, 5, 6]""" return list(set(values))
cd7642d0d800856471898bdfb4ce274af936e304
574,300
def text_ends(text, pattern, case_sensitive=True): """ Checks whether the text (also known as `text`) contains the text specified for `pattern` at the end. The no-data value None is passed through and therefore gets propagated. Parameters ---------- text : str Text in which to find some...
e1b821f1c1769e0658d251c521680246884d728b
574,305
def is_retweet(tweet: dict): """Return True if the passed tweet is a retweet. :param tweet: JSON dict for tweet """ try: text = tweet["tweet"]["full_text"] except KeyError: text = tweet["tweet"]["text"] if text.startswith("RT @"): return True return False
a974463890e19f8b9b1c9946b0d36c421a124245
574,306
def basic_variant_dict(request): """Return a variant dict with the required information""" variant = { 'CHROM': '1', 'ID': '.', 'POS': '10', 'REF': 'A', 'ALT': 'C', 'QUAL': '100', 'FILTER': 'PASS', 'FORMAT': 'GT', 'INFO': '.', 'info...
ff4c15e1c5308176951812f2e259332d59ce5dc8
574,309
def create_private_google_access_dns_zone(context): """Creates a DNS Zone for the use of Private Google Access The DNS Zone config depends on the VPC network having been completely instantiated, so it includes a dependsOn reference to the list of resources generated by the network sub-template. Args: co...
c397c92b8b2334f9e4e1191ba6e07db4dad53ff0
574,311
def modulo(num1, num2): """ MODULO num1 num2 outputs the remainder on dividing ``num1`` by ``num2``; both must be integers and the result is an integer with the same sign as num2. """ return num1 % num2
cd4ab6c278c7b9250b263f5476d1ccc46f5b91d0
574,313
def _sha256(ctx, artifact): """Create an action to compute the SHA-256 of an artifact.""" out = ctx.new_file(artifact.basename + ".sha256") ctx.action( executable = ctx.executable._sha256, arguments = [artifact.path, out.path], inputs = [artifact], outputs = [out], mnemonic = "SHA256...
4e35d96c746efd979cb2802cfa46d3cd8eb49523
574,314
def flip_exchange(exc): """Flip amount and formula of an exchange""" exc['amount'] = -1 * exc['amount'] if 'formula' in exc: exc['formula'] = '-1 * ({})'.format(exc['formula']) return exc
82debf8fa2021c7682e894632beb88bd304213c0
574,315
def equivalent(t1, t2): """Check two tasks for equivalence.""" return ((t1.summary == t2.summary) and (t1.owner == t2.owner) and (t1.done == t2.done))
d9ff9a2fd87fec9460ab7619cda9691089d89d91
574,316
import json def load_zapp(filename): """Loads and parses the ZApp json file.""" return json.load(open(filename, 'r'))
e99cfa2bf8d482fc9d6af657a50bb74708a9f154
574,317
def get_side_nav_menu(html_soup): """ Returns -> [list] list of side navigation menus[type dict] Menu -> [Dict] attrs: 'name' -> [str] name of menu 'link' -> [str] link for the menu 'image' -> [str] URL for menu image Params -> [requests.HTML object] HTML of web page. """ ...
bf222548b9b55dd032c76e52cfce73570b12f9fe
574,322
def load_data(data_dir): """Load train and test corpora from a directory. Directory must contain two files: train.txt and test.txt. Newlines will be stripped out. Args: data_dir (Path) -- pathlib.Path of the directory to use. Returns: The train and test sets, as lists of sentenc...
72bdf5da3512c8bef03703e09608abaa7121f087
574,326
def get_grouped_metric(df, group_column, metric_column, operation): """Group by a specified column, then perform a mathematical operation on a given metric column and return the value so it can be assigned to the DataFrame. For example, group by ID and sum the value of orders placed by the ID. :param d...
55e431acc33c4c7abb71b25b584edcf827555c7a
574,328
import requests def get_latest_release_from_hashicorp(*, project: str) -> str: """Get the latest release of a project from hashicorp""" response = requests.get( f"https://checkpoint-api.hashicorp.com/v1/check/{project}" ).json() return response["current_version"]
42d08b08e78edb16d76db9a22ed68ae1fdd34e67
574,330
def readLines(filename: str, start: int = 0, skip: int = 0) -> list: """ Read lines from file and return as a list. :param filename: the path of the file :param start: the number of lines to be skiped at the header :param skip: skip lines between two line. """ result = [] with open(filen...
e934dde38eb65e70f9df75d11e84a9d1df0adb02
574,332
def SedovTaylorSolution(time,energy,density): """ Adiabatic solution for a blastwave See http://www.astronomy.ohio-state.edu/~ryden/ast825/ch5-6.pdf Parameters ---------- time : float/array time(s) to calculate at in seconds energy : float energy of the blastwave in erg ...
ebb4ca11df81b22fae81f94f6d2e10e5c2239407
574,333
def centroid(X): """ Calculate the centroid from a vectorset X. https://en.wikipedia.org/wiki/Centroid Centroid is the mean position of all the points in all of the coordinate directions. C = sum(X)/len(X) Parameters ---------- X : np.array (N,D) matrix, where N is points ...
9e36676d6760ed3b7cde32377eb33a2f7cfde980
574,335
import six import locale def _decode_preferred_encoding(s): """ Decode the supplied byte string using the preferred encoding for the locale (`locale.getpreferredencoding`) or, if the default encoding is invalid, fall back first on utf-8, then on latin-1 if the message cannot be decoded with utf-8....
4eca2475689650d1beff4023f9a2d6e1b1bcf1ce
574,336
def find(S, val): """Return index j such that S[j] == val, or -1 if no such element.""" n = len(S) j = 0 while j < n: if S[j] == val: return j # a match was found at index j j += 1 return -1
6bc67f9a9766ce852832e2182965a2b355913138
574,338
import pickle def load_api(api_path, check_readiness=True): """Load a GridAPI instance, possibly waiting until it becomes ready. Parameters ---------- api_path : path_line Path where the instance is pickled. check_readiness : bool (optional, default True) Whether ...
4b16621dadfb25dd96d5c74d2678b973ce65a2a6
574,341
def R_prob(from_state, to_state, dt): """Probability that to_state follows from_state, after a deterministic position update.""" if (from_state.v == to_state.v) and\ (to_state.x == (from_state.x + from_state.v * dt)): return 1 else: return 0
c62bf22e00eb0fea0e6c057310441ac904f75ec8
574,342
def padovan_pythonic(number: int) -> int: """ Examples: >>> assert padovan_pythonic(2) == 1 >>> assert padovan_pythonic(5) == 3 """ p0 = p1 = p2 = 1 for _ in range(number): p0, p1, p2 = p1, p2, p0 + p1 return p0
e84764be857324fbcc67425f1e9e996765408b52
574,346
def Lv(parameters, T): """ Returns an expression for the latent heat of vaporisation of water. :arg parameters: a CompressibleParameters object. :arg T: the temperature in K. """ L_v0 = parameters.L_v0 T_0 = parameters.T_0 c_pl = parameters.c_pl c_pv = parameters.c_pv return L...
598b00be88f30fa20d2b1a12e9af90a852672795
574,358
def which_columns(df, test_func): """Return a list of column names that evaluate to True when passed to test_func.""" return list(df.columns[df.apply(test_func)])
2253f9e514ee5764a909764c105beaeab6e34f40
574,359
def id_bytes_to_str(id_bytes: bytes) -> str: """Convert a byte array from `id_int_to_str` back into string. Args: id_bytes: ID represented as a byte array. Returns: str: Hash as string. """ return hex(int.from_bytes(id_bytes, byteorder='big'))[2:]
6422afed70d68ba645aa5a5a1b98a549df7ea718
574,360
def group(text, size): """Group ``text`` into blocks of ``size``. Example: >>> group("test", 2) ['te', 'st'] Args: text (str): text to separate size (int): size of groups to split the text into Returns: List of n-sized groups of text Raises: ValueE...
55e8cc79de23651b764648a655d41220253f90b8
574,364
def change_eigen_param(self, param_name, new_value): """ Used to change a param in eigen params area. Parameters ---------- param_name : str name of parameter to change new_value : ? the new value to the parameter Returns ------- True if successful """ if par...
2dc9d97fe154ce6c3a6ccee9c93fe03e9c139d3b
574,366
def read_cstring(file_object): """ Read the 0-terminated string from file_object and return the bytes object (terminator excluded). """ cstring = b"" while True: char = file_object.read(1) if char and char != b"\x00": cstring += char else: break return...
91cea6e1ea9a1c227d3797d0709ea9a6c618e4d3
574,368
def label_smooth(num_classes, epsilon, encoded_data_point): """ Simple label smoothing Input: num_classes: number of classes epsilon: epsilon value encoded_data_point: one hot encoded data point """ smoothed_point = encoded_data_point * [1. - epsilon] + (1. - encoded_data_poi...
60a36b73c31538b8946afc41d94984ef5df1589b
574,372
def remove_dir_from_path(path: str, directory: str): """Remove a directory form a string representing a path Args: path: String resembling path directory: String resembling directory to be removed from path Returns: String resembling input path with directory removed """ re...
8b289e5d998d7b399e5ed75aabe55328f6b49dbe
574,377
def check_line_intersection(line1, line2): """Given two line segments (each defined by two (x,y) pairs), return true if the two segments intersect and false if they do not.""" x1, y1 = line1[0] x2, y2 = line1[1] x3, y3 = line2[0] x4, y4 = line2[1] denom = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4) if...
65472158505b832bb77f74eb1be244c6eef9ce2c
574,379
import time import webbrowser def sendmsgafter(message_text,seconds): """ Open whatsapp share page after the seconds given to send given message to any contact Parameters ---------- message_text:- String,For new line character Use '%0a' instead of '\n' seconds-int """ message_text=str(messag...
5c0bb075f570f36f8ec2c51ce28334a265089aa6
574,385
def boolean_to_xml(obj: bool) -> str: """ serialize a boolean to XML :param obj: boolean :return: string in the XML accepted form """ if obj: return "true" else: return "false"
969a0866d4bea4dd07c0368946a6910fce13bc7a
574,389
def rgb_to_hex(r, g, b): """ Map r, g, b values to a hex string. """ return "%02x%02x%02x" % (r, g, b)
ae722d114bf77156d412c336ca65c0c643e72123
574,392
import functools def mutually_exclusive(keyword, *keywords): """Decorator raises a TypeError if input function arguments are not mutually exclusive.""" keywords = (keyword,)+keywords def _wrapper(func): @functools.wraps(func) def inner(*args, **kwargs): if sum(k in keywords for...
d759cfd41e67346c116475c1d940544706677e1b
574,394
def email_mark_unread(imap, uid): """Remove the 'Seen' flag from an email based on passed-in UID. """ status, response = imap.store(str(uid), '-FLAGS', '\Seen') return status, response
bccd98c96ec47a39304b66eb889e1f2a10c473aa
574,396
def should_split(split): """ given split proportions checks if should split Examples: >>> should_split([10,0,0]) False >>> should_split([1,.1,.2]) True """ return max(split) / sum(split) != 1.
6d790afe81386033981374823cdecc860cd4b9d6
574,397
def for_each_inlet(fn): """Runs the test for each inlet returned from :any:`InletTester.get_inlet`""" def wrapper(test_kls, *args, **kwargs): for inlet in test_kls.inlets: inlet._metadata = {**test_kls.inlet._metadata, **test_kls.gmetadata} test_kls.inlet = inlet wit...
d3fa8aa08bb7243d54ac531b6cb579329fcc5e8c
574,400
import requests def check_csv(url: str) -> bool: """Checks if the CSV from URL file is available. Args: url: str - an URL link or a filepath to a CSV file Returns: bool: True if the CSV file is available """ status_code = requests.get(url).ok if status_code: print("C...
1e696bba28b49b527aad24db9d176562b534dee3
574,403
def vars_recurse(obj): """ Recursively collect vars() of the object. Parameters ---------- obj : object Object to collect attributes Returns ------- params : dict Dictionary of object parameters. """ if hasattr(obj, '__dict__'): params = vars(obj) for k in params.keys(): if hasattr(params[k], '__...
d8f9282a7955df5a91fa8388dd1c91eb2a482ec5
574,405
from typing import List def get_columns(cur, table: str) -> List[str]: """Get the columns from MySQL database.""" cur.execute(f"SHOW COLUMNS FROM {table};") columns = [column[0] for column in cur] return columns
6df95df9c410078d59527bc387b1eb68bf396084
574,406
def read_timit_block(stream): """ Block reader for timit tagged sentences, which are preceded by a sentence number that will be ignored. """ line = stream.readline() if not line: return [] n, sent = line.split(' ', 1) return [sent]
e90d69e603590d38e08ce0e49e06b3069cb92039
574,409
def replace_tag(tag, value, file): """Replaces a tag in a file with the specified value and returns a new file name.""" with open(file, "r") as origin: with open(file+".replaced", "w") as dest: dest.write(origin.read().replace(tag, str(value))) return file+".replaced"
277724529116168d7782834148f1894a686bad84
574,415
def even_divisible_min(range_ceiling: int, range_floor=1) -> int: """ Gets the smallest number that is evenly divisible by all the numbers in the range specified :param range_ceiling: The upper limit of the range of numbers to be divided by :param range_floor: The smallest...
45db5640a420967f89e44d28d5100acf20c1ad01
574,416
def cstr_design_eq(x_out, x_in, vol, nuo, k): """ PFR design eq for HW3 problem 1, set up for f(Xi) = 0 for fsolve function :param x_in: initial conversion (unitless) :param x_out: final conversion (unitless) :param vol: PFR volume in L :param nuo: volumetric flow in L/min :param k: rate coe...
898994e61da79be4bae5cd94efacc2768f90cc24
574,421
import re def _is_ignored(filename, ignored_paths): """ Check if the file should be ignored :type filename: str :param filename: Name of file check :type ignored_paths: list :param ignored_paths: List of regular expressions we should validate against :returns: bool -- True if the file...
4e5512248627306d9bc7d04157a25fc569130f04
574,422
def get_layer(router_id, num_of_routers, num_of_layers): """Get the layer of a router.""" return router_id // (num_of_routers / num_of_layers)
e8be9c2fde4d1b38988c51e87e1e16bcf4bf06d3
574,424
import struct def get_blockheader(f): """ Unpack block header parameters into a list. Reads the 28-byte block header from f and unpacks into a list. Endianness is corrected as needed. Returned list contents: = ======== ======================== N Variable Description = =...
75e0ae69f6bf168101109a70e9be9d49972045ab
574,429
def make_filename(params, run): """Generate a filename based on params and run. params: (net, seed, freq, weight)""" nets = ['net_tunedrev', 'net_nofeedbackrev', 'net_disinhibitedrev'] return (f"population_vectors_{nets[int(params[0])]}" f".TunedNetwork_{params[1]}_{...
b1ab86ecc9c34ee990fc215a178ee93e52303757
574,433
def table_row(k, v, html): """Output a key-value pair as a row in a table.""" if html: return ''.join(['<tr><td class="e">', k, '</td><td class="v">', v, '</td></tr>']) else: return k + '\n' + v + '\n\n'
fce6e56a9763bd13e69c2a9f8f10f3f4615a6b9c
574,434
def gimme_save_string(opt): """ Taking the set of parameters and convert it to easy-to-read string, which can be stored later. Args: opt: argparse.Namespace, contains all training-specific parameters. Returns: string, returns string summary of parameters. """ varx = vars(opt) ...
e6f522d82436c77ed73756be1cb78c56d53a6b7f
574,440
def classify_by_composition(structures): """ Classify the different IStructures by composition. :param structures: List of structures :return: Dictionary of composition strings with a List of the corresponding IStructures. """ comp_dic = {} for structure in structures: if comp_di...
d7df6a6d678bec641e3007328bbc7d1f9ca8f323
574,442
def find_pfc_wwpn_by_name(vios_w, pfc_name): """Returns the physical port wwpn within a VIOS based off the FC port name. :param vios_w: VIOS wrapper. :param pfc_name: The physical fibre channel port name. """ for port in vios_w.pfc_ports: if port.name == pfc_name: return port.ww...
1f513fd7b90db2395c5000c901e707ad92d6fa7a
574,445
def get_other_cluster(this_cluster, clusters): """Return the cluster in clusters, which is not this_cluster. Args: this_cluster (str): name of this_cluster clusters (list): list of two cluster names. Returns: the name of the other cluster. """ return clusters[0] if clusters...
4e95e138250795e4e46279d7277c48900ca8c45e
574,447
def get_key_value(key, article_raw): """ Searches for an entry in article_raw (which is a list of dicts) that has the 'key'. Then it returns the value associated to that key. If the key is not found, return None. """ sel = list(filter(lambda d: d['key']==key, article_raw)) if len(sel)==0: ...
12694484fce2ab0ed3259e2a634a523ab817e664
574,450
def get_region_index(nodes): """Get region index""" return nodes['NEM_REGION'].unique().tolist()
f4265c2803721eba6cd5b3b260684716b3e5cd4a
574,451
from typing import OrderedDict import copy def merge_dicts_with_list(first_dict, second_dict): """ Create new dict that contains all elements from the first one and from the second one. Function assumes that all value elements are lists. In case if one key appears in both dicts function will merge...
1fc1f7db565da2ef82f2f5f5fcd8f61a376ab320
574,452
import re def md_correct_image_link(md: str, image_name: str, image_path: str) -> str: """Change image link at markdown text from local source to image_path. Args: md (str): Markdown text to process. image_name (str): Name for image file. image_path (str): Dir name for images at desti...
55daa60d384c2e6d3566e7272b98e218e348c919
574,453
def recursive_to_cuda(tensors, device): """ Recursively iterates nested lists in depth-first order and transfers all tensors to specified cuda device. Parameters: tensors (list or Tensor): objects to move to specified device (can be nested) """ if device is None: # keep on cpu r...
5f3fb232cc93c01a10954247d1909b891019c4da
574,455
import requests import re def download_song(url): """ takes a URL and downloads the lyrics from that URL """ headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} seite = requests.get(url, headers=header...
20399be47f86fe4f45ab30975dae51e30e3af914
574,458
def retr_radiroch(radistar, densstar, denscomp): """ Return the Roche limit Arguments radistar: radius of the primary star densstar: density of the primary star denscomp: density of the companion """ radiroch = radistar * (2. * densstar / denscomp)**(1. / 3.) re...
c7a949022734bb763d2205b360ad7b9a72a84972
574,459
def parse_boolean(value: str, default=False, invert=False): """ Parses a boolean value from a string. String must contain "yes" to be considered True. Parameters ---------- value: :class:`str` The string containing an integer. default: :class:`bool`, optional The value to re...
e42d4e190e0ab8d41e8c58d9266502df7d4f201b
574,464
def status_eq(status): """ Returns a function that matches to the specified status codes. """ return lambda m: m.status == status
89c0d8f518154998612f50b992b803e06ece2788
574,465
def fail_rate(num_fail, num_pass): """Computes fails rate, return N/A if total is 0.""" total = num_fail + num_pass if total: return "{:.3f}".format(round(num_fail / total, 3)) return "N/A"
60792d39d84532eaefc0c3832234ac668387e38f
574,468
from typing import List from typing import Optional def _present(word: str, p_chars: List) -> Optional[str]: """ Checks a word for presence of characters from a User defined list. :param word: String containing the word to test against the list of characters present. :param p_chars: List of characters...
00c47b9a907ead8451ff88f7b81343e982f37087
574,469
from typing import Tuple def parse_dms_coordinate(coordinate: str) -> Tuple[int, int, float]: """Parse a degree-minute-second coordinate from a DTED coordinate string. The DTED coordinate string has the following format: [D]DDMMSS[.S] where: D - Degree M - Minute S - Secon...
08544a74b50cc0553537dffab13b53e8972f5d1f
574,472
def includes(collection, sought, start=None): """Is sought in collection, starting at index start? Return True/False if sought is in the given collection: - lists/strings/sets/tuples: returns True/False if sought present - dictionaries: return True/False if *value* of sought in dictionary If strin...
a786b7190cd684b4fae780edf9113a077ab9f12a
574,475
import typing def is_generic_type(type_): """Check if the given type is a generic type (parameters may be specified or not). Tuple and Union types are excluded. param type_: Type object to check. :rtype: bool """ return isinstance(type_, type) and typing.Generic in type_.__mro__
2d2933368a5390bae82913aa998692c5eb695d6b
574,480
def pathdata_first_point(path): """ Return the first (X,Y) point from an SVG path data string Input: A path data string; the text of the 'd' attribute of an SVG path Output: Two floats in a list representing the x and y coordinates of the first point """ # Path origin's default values are use...
f346fcd66e152a6e34c7c6449ce38e2fd7f919e9
574,484
def filename_sane_replace(some_string): """Replace non-alphanumeric characters in a strong with dashes. Should make it safe to write out to any sane (i.e. non-MS) filesystem.""" return "".join((c if c.isalnum() else '-') for c in some_string)
99a186b985df47051545924b5522839a2b967fbc
574,485
def element_coords_to_xyz(name: str, x: float, y: float, z: float) -> str: """Convert element to XYZ formatted line :param name: Element name :type name: str :param x: X coordinate :type x: float :param y: Y coordinate :type y: float :param z: Z coordinate :type z: float :return...
fce1b3e8b1a5f491009c0cf7b8ab38c21dee7226
574,487
def romanian_preprocessing(text): """Sennrich's WMT16 scripts for Romanian preprocessing, used by model `xlm-mlm-enro-1024`""" # https://github.com/rsennrich/wmt16-scripts/blob/master/preprocess/normalise-romanian.py text = text.replace("\u015e", "\u0218").replace("\u015f", "\u0219") text = text.replace...
17c8f8fc1f6f8424552ae36b28b1a27c4341cf42
574,490
from typing import Sequence from typing import Tuple from typing import Optional def get_fan_in_fan_out( shape: Sequence[int]) -> Tuple[Optional[int], Optional[int]]: """Returns (fan_in, fan_out) of a weight variable of the given shape.""" if not shape: return None, None if len(shape) < 1: return 1,...
231372e76b549ffd44482b0835634bbb29c07a49
574,492
import random def shuffle_cards(cards): """ Given a card of elements, shuffle the cards. Solution: iterate through the card, swapping each element with a random element """ for i in range(len(cards)): rand = random.randint(0,i) # temp = cards[rand] ...
6fe70c85895e801aeb526d409b1acf9f0e325838
574,493
import string def cover_alphabet(sentence: str) -> bool: """Method that returns true if it covers all alphabet at least once otherwise false""" alphabet = set(string.ascii_lowercase) return set(sentence.lower()) >= alphabet
5923d853aec631f3e71ec289156dd845c936b045
574,494
def is_interesting_transaction(txdata, all_addresses): """Check if the transaction contains any deposits to our addresses.""" return any([(detail["category"] == "receive" and detail["address"] in all_addresses) for detail in txdata["details"]])
d0464981581cd6976c96ed7810f660559e4a76cc
574,496
def process_boss_input(data:list[str]): """ Process boss file input and return tuple of hit_points, damage and armor Args: data (List[str]): input file lines Returns: tuple: hit_points, damage, armor """ boss = {} for line in data: key, val = line.strip().split(":") ...
d51078e51b5c63589d3e97a2cfdf9bb99cbf7b71
574,503
def linecount(doc: str, end: int, start: int = 0): """Returns the number of lines (by counting the number of newline characters \\n, with the first line being line number one) in the string *doc* between the positions *start* and *end*. """ return (doc.count('\n', start, end) + 1)
14dc063a4a9203611f63f55428de2958f8e9341b
574,506
import torch def mold_image_tensor(images, config): """Takes RGB images with 0-255 values and subtraces the mean pixel and converts it to float. Expects image colors in RGB order. """ return images - torch.from_numpy(config.MEAN_PIXEL).float().cuda().unsqueeze(1).unsqueeze(2).unsqueeze(0).expand_a...
2adc51a8f71ab02266a6d0b1ad53b8daa3e4efcc
574,508
def bin_to_ip(ip_bin): """ This function converts binary IP-address to dec Parameters: ----------- ip_bin: binary IP-address Returns: -------- ipaddr: dec IP-address """ ipaddr = "" j = 0 for i in ip_bin: j += 1 if j <= 8: ...
657eaba909c891a2839bb35fcc6b323b24734193
574,510
def get_stationary_indicator(data, window='10s', stdtol=15 / 1000): """ Return a boolean pandas.Series indicating stationary (low movement) periods. :param data: A pandas.DataFrame of acceleration time-series. It must contain at least columns `x,y,z` and the index must be a DateTimeIndex. :typ...
c91c99a9667ff1dea511f464c3c8161211dc90ba
574,521
import torch def gen_data(n_data, args): """ Generate data tuples. Letter sequence and ground truth ordering. """ # n_data = args.n_data n_labels = args.num_labels all_data = torch.stack([torch.randperm(n_labels) for _ in range(n_data)]) # vals, all_labels = torch.topk(all_data, k=n_labels...
d3a73bc85dec2dfc9290c01423ad9a1c6af8c914
574,522
from typing import Union import math def hf_size(size_bytes: Union[str, int]) -> str: """Human friendly string representation of a size in bytes. Source: https://stackoverflow.com/questions/5194057/better-way-to-convert-file-sizes-in-python Arguments: size_bytes {Union[str, int]} -- size of obje...
0cf917ba6d941a10478ab2a8a8334851bcc225cc
574,527
from typing import Dict import requests def getPeeringDB(ASN: str) -> Dict: """Function to connect to peeringDB and fetch results for a given ASN Args: ASN: ASN to query against PeeringDB's API. Returns: r.json: a dict containing the results from PeeringDB """ pdb_url = f"https:...
8c1533ebdc1f41fac5b109f240a0e2a5a3add6d9
574,528
def reshape_sum_backward(gy, x_shape, axis, keepdims): """Reshape gradient appropriately for dezero.functions.sum's backward. Args: gy (dezero.Variable): Gradient variable from the output by backprop. x_shape (tuple): Shape used at sum function's forward. axis (None or int or tuple of in...
afb274d59a4f3b39c8ad70c98a089b3ad6041f1e
574,531
def inject_headers_for_remote_refs(request_callable, request_headers): """Inject request_headers only when the request is to retrieve the remote refs in the swagger spec (vs being a request for a service call). :param request_callable: method on http_client to make a http request :param request_headers...
20b324b145aa8cf3ec756a642d6abedac83b38f3
574,534
from typing import List def search(lst: List[str], search_item: str): """ Searches a list for an item Parameters ---------- lst : List[str] The list of strings to search search_item : str The item to search for in the strings """ for i, val in enumerate(lst): ...
c78882191cf9337fc489bb184da172281ac88dab
574,538
import string import random def random_string(stringLength=8): """https://pynative.com/python-generate-random-string/ Args: stringLength (int, optional): length of string. Defaults to 8. Returns: str: random string """ letters = string.ascii_lowercase return ''.join(random.ch...
72d95f37e943a6002243973a76e1c767be09fd3a
574,545
from typing import Callable import time import logging def main_runner(*functions: Callable) -> Callable: """Returns a main function that calls given functions in order Progression is logged. """ def wrapper() -> None: n_steps = len(functions) t = time.perf_counter() for i, f...
c91683c2d2daf800bb3f5e6b40c27d962e459955
574,548