content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def is_prime(N: int)->bool: """ 素数判断函数,True 是, False 否。 Input: any integer which is greater than 1. Output: bool True represent integer is prime number. 不需要用math.sqrt()函数,也不用乘方(**0.5),改用 i*i < N. 首先排除素数 2 和大于 2 的偶数 don't use math.sqrt,at first skip all even number except 2 >>> is_prime(2) ...
23ed441f5f18caa7705ddf88053cb50be9b4de0a
234,704
def in_bisect(s,target): """Returns true if target is in sorted list. s: sorted list target: item to search for """ # Base case, down to one element. if len(s)==1: if s[0] == target: return True return False if s[0] <= target <= s[-1]: mid_index = int(len(...
2ca888536ea5b63c972b9caf04523c45ebff6aa9
477,182
import requests def _get_token(ZC, username, password): """Gets the client's token using a username and password.""" url = '{}/oauth/token/'.format(ZC.HOME) data = {'username': username, 'password': password, 'noexpire': True} r = requests.post(url, json=data) if r.status_code != 200: r...
192c113d6e904f6d7756e28e7a80147b9d20cb54
662,891
import csv def read_snp(handle): """ Reads a mummer snp file """ dialect = csv.Sniffer().sniff(handle.read(1024)) handle.seek(0) reader = csv.DictReader( handle, fieldnames=[ "pos_ref", "allele_ref", "allele_query", "pos_query", ...
46cb06d8aedca29af5779d7628c5e9ad4c4f0f4b
198,474
def _CredentialFrom(messages, credential_data): """Translate a dict of credential data into a message object. Args: messages: The API message to use. credential_data: A dict containing credential data. Returns: An Credential message object derived from credential_data. """ basic_auth = messages.B...
c96acdf28dab1ba60acc0c5b1bee73585c20106f
44,843
def rsync(s, d, test=False, config='dts', reverse=False): """Set up rsync command. Parameters ---------- s : :class:`str` Source directory. d : :class:`str` Destination directory. test : :class:`bool`, optional If ``True``, add ``--dry-run`` to the command. config : ...
74d02e5ae5abbc6acfe3b3622f64942865e86c0b
116,858
import torch def random_choice(x, n, dim=0): """Emulate numpy.random.choice.""" assert dim == 0, 'Currently support only dim 0.' inds = torch.randint(0, x.size(dim), (n,), device=x.device) return x[inds]
91c6601b6e4c6f4c4e19c0b44eadb5c8aad967ef
443,309
def create_adj_elem(root): """ Small helper function to add left/right nodes to adj list """ out = [] if root.left is not None: out.append('node' + str(root.left.nid)) if root.right is not None: out.append('node' + str(root.right.nid)) return out
31eca3e2b75c8e45d088993aaf30d4d14a4df8d4
443,190
def get_class_split(num_classes, num_gpus): """ split the num of classes by num of gpus """ class_split = [] for i in range(num_gpus): _class_num = num_classes // num_gpus if i < (num_classes % num_gpus): _class_num += 1 class_split.append(_class_num) return class...
73bb06dc8ec5a828cece3c36387b1649466529b8
303,449
import array import math def _fold_sizes(num_rows, num_folds): """Generates fold sizes to partition specified number of rows into number of folds. :param num_rows: number of rows (instances) :type num_rows: integer :param num_folds: number of folds :type num_folds: integer :returns: an array....
f621bd5564b7e6c0614af6f4dd6757a026b4e313
599,798
import torch import math def _get_survey_extents_one_side(pad, side, source_locations, receiver_locations, shape, dx): """Get the survey extent for the left or right side of one dimension. Args: pad: Positive float specifying padding for the side side: 'left' ...
761fe0e282fd30c1bbd8cbbc9a9d5249b7a8c04f
128,236
def luma(p): """ Returns brightness of a pixel, based on relative luminance This is based on ITU-R BT.709. Note that human eyes are most sensitive to green light. :param p: A tuple of (R,G,B) values :return: The relative luminance of a pixel (in the range [0, 255]). """ return 0.2126*p[0] + ...
9996673dfd9dad54e38236627b2639bc2047aed8
509,399
def xywh_to_xyxy(a): """ Converts a single box from XYWH to XYXY format a: box in XYWH coordinates """ return [a[0], a[1], a[0]+a[2]-1, a[1]+a[3]-1]
66acb23bad07d0ca658091bc8be67a572c0ab192
476,335
from datetime import datetime def timestamp_to_weekday(timestamp): """ Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. """ return int(datetime.fromtimestamp(timestamp / 1000.0).strftime("%w"))
fad8b84ee638adc80774993888ee4152ee76fc18
669,517
def boundary_overflow(posX, posY): """ Correct coordinates for boudary overflow Treating the 8x8 boundaries as if they don't exist. (8,8) is the same as (0,0), (-1,-1) same as (7,7) """ x_field = posX y_field = posY if x_field > 7: x_field = 0 if x_field < 0: x_f...
decc28d060eb302bc9a12b91e5f1d3cbaf7dde4c
274,005
def smallest_prime_factor(n): """Return the smallest k > 1 that evenly divides n.""" k = 2 while n % k != 0: k = k + 1 return k
1b19c3aeae1a814a1836023bb646c3a72acfa87e
524,869
def get_max_sense(instance_dict, instances=None): """ Return a list of senses with maximum graded sense score. >>> d = {1: [('s1', 9), ('s2', 8.9), ('s6', 12)], 2: [('s2', 1), ('s3', 7)]} >>> get_max_sense(d) ['s6', 's3'] >>> get_max_sense(d, [1]) ['s6'] """ if instances is not Non...
b2357f81049d0ce10dbc8cad949d859e8ff2f188
300,640
def preprocessLines(sourceLines): """ Delete comments from the lines and change them to upper case sourceLines - array of assembly lines with comments return: resulting array of lines """ for i, line in enumerate(sourceLines): line = line.upper() line = line.split(";")[0] # trim ...
6909d36cb62359c429b7637f50b31722d534d875
483,019
from typing import List def assert_empty_line_between_description_and_param_list( docstring: List[str] ) -> List[str]: """ make sure empty line between description and list of params find first param in docstring and check if there is description above it if so, make sure that there is empty line ...
d03eb05064609928020c84785b561cd6b7bfa1f6
685,412
import hashlib def hash(value): """Generate a hash from a given value :param value: :rtype: str """ hash_ = hashlib.md5() hash_.update(repr(value).encode('utf8')) return hash_.hexdigest()
8c7bc042cedccafa3a2c3d39e34a32d4c2fff3a4
516,861
def edge_overlap(A, B): """ Compute edge overlap between two graphs (amount of shared edges). Args: A (sp.csr.csr_matrix): First input adjacency matrix. B (sp.csr.csr_matrix): Second input adjacency matrix. Returns: Edge overlap. """ return A.multiply(B).sum() / 2
f2d87e1a7b7a0f90bc240c57c6505ab37c6f55f4
392,812
def FormatUserScoreSum(element): """Format a KV of user and their score to a BigQuery TableRow.""" user, total_score = element return {'user': user, 'total_score': total_score}
9a7e6bd8945bf2b14d1b7ae7429e96c0de974cf0
197,377
def symmetric_tour_list(n_cities, start_index = 0): """ Returns a numpy array representiung a symmetric tour of cities length = n_cities + 1 First and last cities are index 'start_index' e.g. for start_index = 0 then for 5 cities tour = [0, 1, 2, 3, 4, 0] """ tour = [x for x in range(n_...
cbd56e827dba952e18a1e5b1b5996777c932e7c0
587,590
import torch def conv1x1(in_planes, out_planes, init='no', cnv_args={ 'bias': True, 'kernel_size': 1, }, std=0.01): """1x1 convolution""" cnv = torch.nn.Conv2d(in_planes, out_planes, **cnv_args) # init weights ... if init == 'no': pass elif init == 'normal0.01': cnv.weight.data.normal_(0., std) if cn...
15d54e38b1574cfed3659642a3d86e635c124e20
113,689
def concat_environment(env1, env2): """ Concatenate two environments. 1 - Check duplicated keys and concatenate their values. 2 - Update the concatenated environment. Parameters ---------- env1: dict (mandatory) First environment. env2: dict (mandatory) Second environment. ...
25f7aee5a9316ab0604f2e38538a1f67a5333b08
15,072
import glob def get_possible_sites(user): """Returns a set of sites available for the specified user. Each site is represented by an image in the 'images' directory. """ files=() if user.lower().endswith("ur"): #ASSERT: the username indicates unrelated condition files=(file.replace('images/', '') for file in...
8f8bddaaaefcf1d414ea11002828c94040b93868
275,119
def find_all(text, pat): """Returns list of all overlapping occurrences of a pattern in a text. Each item in the (sorted) list is the index of one of the matches. """ result = [] last = 0 try: while 1: curr = text.index(pat, last) result.append(curr) ...
cfdb8f0f53a0d016a433c2a9d180595883ad0ca8
383,759
def pmelt_T_iceV(T): """ EQ 3 / Melting pressure of ice V """ T_star = 256.164 p_star = 350.1 theta = T / T_star pi_melt = 1 - 1.18721 * (1.0 - theta ** 8) return pi_melt * p_star
9d4f830c498b58e1d244c8ca32c20cfff6f827df
242,198
import math def angle_rad(coord, origin=(0.0, 0.0)): """ Absolute angle (radians) of coordinate with respect to origin""" return math.atan2(coord[1] - origin[1], coord[0] - origin[0])
34b35f945c4c226c4f64aa4584286116c206b872
92,521
from typing import List from typing import Tuple def nondegenerate_tests_two_variables() -> List[Tuple[float, float, float, float, float]]: """Each entry in the list represents two Gaussian variables X1, X2 in the following format: (mean1, mean2, sigma1, sigma2, correlation between X1 and X2) """ retu...
913ee09bbf9dc08505d38308b8dfb2f8c96899b5
397,815
import math def some_function(n: float) -> float: """ An approximation of the gamma function. >>> round(some_function(4), 3) 24.0 """ s = sum( ( 1, 1/((2**1)*(6*n)**1), 1/((2**3)*(6*n)**2), -139/((2**3)*(2*3*5)*(6*n)**3), -57...
a260c9570627143a52195b1fe912cd980c83c454
547,656
def filter_for(mapper, filter_fn): """Filter records out during the mapping phase. Examples: >>> @dataclass ... class Foo: ... id: int >>> items = [Foo(id=1), Foo(id=2), Foo(id=3)] Normally the mapper would be the thing that turns raw json into the above `items` ...
fe5e828f788952ce3db32dfb6b4c015243429749
187,288
def getCurrencyPair(baseCurrency, cryptoCurrency): """Returns the currency pair in the format expected in Coinbase Pro""" return cryptoCurrency + "-" + baseCurrency
3a0f8e206f6b3a153a89ff4a6d8aaf9c0116930c
203,378
def iterate_array(client, url, http_method='GET', limit=100, offset=0, params=None): """ Get a list of objects from the Podio API and provide a generator to iterate over these items. Use this for e.g. to read all the items of one app use: url = 'https://api.podio.com/comment/item/{}/'.format(...
745e3209e5add0b0a8a64aea1878ac5b2897afb9
47,311
def is_file_included(filename, model): """ Determines if a file is included by a model. Also checks for indirect inclusions (files included by included files). Args: filename: the file to be checked (filename is normalized) model: the owning model Returns: True if the file ...
f50d83a7288494408df8b540c79f2b52053ee87a
582,253
def has_equal_properties(obj, property_dict): """ Returns True if the given object has the properties indicated by the keys of the given dict, and the values of those properties match the values of the dict """ for field, value in property_dict.items(): try: if getattr(obj, field...
d96b17124121af5db31c9db096b5010aff01b233
8,972
def mass_surface_balsa_monokote_cf( chord, span, mean_t_over_c=0.08 ): """ Estimates the mass of a lifting surface constructed with balsa-monokote-carbon-fiber construction techniques. Warning: Not well validated; spar sizing is a guessed scaling and not based on structural analysis....
fa0d9a3cda6fa01e973fa01e0a02f7e4a69b991b
593,735
def flatten(x): """Converts a list of lists into a flat list Args: x (list): An input list Returns: list: A flat list """ output = [_ for z in x for _ in z] return output
4069dd52f755a0ffdb4cb7a3a6f20367ee2bc723
195,757
import re def extract_build_info_from_filename(content_disposition): """ >>> extract_build_info_from_filename( ... 'attachment; filename=CommCare_CommCare_2.13_32703_artifacts.zip' ... ) ('2.13', 32703) >>> try: ... extract_build_info_from_filename('foo') ... except ValueError...
fcb43a8f5eaf3e8b999472d65f5f7d2066885af6
377,268
def last_added_num(path): """ Returns last added frame number for a `path` directory. `path` is a pathlib.Path object. Return 0 if no files in directory. """ files = list(path.iterdir()) if not files: return 0 # Get all frame numbers. numbers = [int(str(file.name).spl...
ba92d0b625772693fc92670c3d4cb42546aa8903
338,630
import json def getdata_from_file(file_path): """Retrieve json data from a file by filepath""" with open(file_path, 'r') as file: data = json.load(file) return data
bc9f6b8d53879c42ac501ab9d4ec7ff10344538b
460,879
def get_protected_attr_values(attr, df, privileged_group, privileged=True): """Retrieves all values given the privileged_group argument. If privileged is True and privileged_group[attr] is a list then it returns the list, if it's a function then values of df[attr] for which the function returns True. ...
5bff379b4564917f6786abeede86e32b10a0f5a1
239,105
def AttachUserList(client, ad_group_id, user_list_id): """Links the provided ad group and user list. Args: client: an AdWordsClient instance. ad_group_id: an int ad group ID. user_list_id: an int user list ID. Returns: The ad group criterion that was successfully created. """ ad_group_criter...
84b49c98158f56b3d05220ff1f1049f40fdcf6a8
244,756
def _convert_int_to_i64(val): """Convert integer to signed int64 (i64)""" if val > 0x7FFFFFFFFFFFFFFF: val -= 0x10000000000000000 return val
51df23605ce76e4ebe1b18cb94e53b94f6c0e6a3
451,958
def calc_recall(TP, FN): """ Calculate recall from TP and FN """ if TP + FN != 0: recall = TP / (TP + FN) else: recall = 0 return recall
8f3513e11f8adad111eee32740c271aad31fbe28
706,992
def __get_skip_select_quit(prompt): """Repeatedly prompts the user until they return a valid selection from skip/select/quit.""" while True: response = input(prompt + " [enter to skip, 's' to select, 'q' to quit]") if response == "": return "skip" if response == "s": ...
d88ce8e88d17aa1d531f5b850798137037c7fac6
605,969
from pathlib import Path import filecmp def are_dirs_equal(dir1: Path, dir2: Path) -> bool: """Compare the content of two directories, recursively.""" comparison = filecmp.dircmp(str(dir1), str(dir2)) return comparison.diff_files == []
69895f6f0ba4111a0daa5656cc7aed2199f63e98
519,980
import math def distance(pos1, pos2): """ Euclidean distance """ return math.sqrt((pos1[0] - pos2[0])**2 + (pos1[1] - pos2[1])**2)
04af24bfb1a5e6501f615ed2eb9d72efac531626
291,650
def wordCount(cleantext): """ This function counts words from a text and returns a dictionary. Does not fix for punctuation and special characters, so for example 'why' and 'why?' will be counted as two different words. This doesn't matter in the case of youtube subtitles. INPUT: string O...
aefade151775bff1a392c96f4690165caf96098f
491,210
import torch def get_random_seed() -> int: """Get a randomly created seed to use for seeding rng objects.""" seed = int(torch.empty((), dtype=torch.int64).random_(to=2**32).item()) return seed
4945f41f9504b3df4e67e8d9700e7b1180175a4c
475,646
def H_simple(t, T, **params): """ Implements Eq. 9.123 from Nawalka, Beliaeva, Soto (pg. 460) """ if params['risk_free']: delta = params['delta'] else: delta = params['delta'] + params['spread'] return delta * (T - t)
54eae4741dc973af9d083b3c99894d91bb085d7f
397,789
def get_vgroups(variables): """ Returns a list of unique vgroup found in the given variables object. Parameters ---------- variables : list Decipher variables object, which is a list of dictionaries Returns ------- vgroups : list List of unique vgroups found in variable...
118fd6da0c62ad80caf39f157bac786bb27e6110
481,611
def to_str(membership): """Convert membership array to pretty string. Example: >>> from graphy import partitions >>> print(partitions.to_str([0,0,0,1,1,1])) [0 0 0 1 1 1] Parameters ---------- membership : np.array or list Membership array to convert Returns ------- ...
2500fbf4a953aff812cb9b4b639e5d3129af2229
271,651
def get_private_indicator(data): """Gets the private section indicator from the given section data Parses the given array of section data bytes and returns the private section indicator. If True, then this is a private table. If False then it is a normal mpeg ts table (PAT, PMT, CAT). """ if data[1] & int('01000...
e804b96647b73e551e4cae842b1774d792a42ed3
133,556
def get_document_shortcut(connection, document_id, instance_id, error_msg=None): """Retrieve a published shortcut from the document definition. Args: connection: MicroStrategy REST API connection object document_id (string): Document ID instance_id (string): Instance ID error_...
36e26344248782d4e346e8cb32add35a63771f80
221,206
def getCombineSet(listDict, names): """ Calculate the union of a dict of lists. Parameters ---------- listDict : dict of list of any The dict of lists to be combined. names : list of str The keys of lists to be combined. Returns ------- list of any The union...
40cd68648b7d00614eeff4f3858b784c3a675c62
257,975
import re def meant_to_say(client, channel, nick, message, matches): """ A plugin so users can correct what they have said. For example:: <sduncan> this is a foo message <sduncan> s/foo/bar <helga> sduncan meant to say: this is a bar message """ try: last = client.last...
f59ff2555588dbb8b45393b9a6384a6c3351dff7
52,950
def load_class(class_path): """ Load and return the class from the given module. Args: class_path (str): full path to class to be loaded, e. g. sklearn.linear_model.LinearRegression Returns: class """ module_path, class_name = class_path.rsplit('.', 1) mod = __i...
90cebbef4e305fde84adea8e7c2b42a1eac7d402
182,839
def replace_cpi_escapes(cpi: str) -> str: """Replace escaped characters in CPI URIs Args: cpi (str): CPI pure identity URI Returns: str: CPI escaped URI """ return cpi.replace("%23", "#").replace("%2F", "/")
454c7b6c1421ee55b35a36573e922578788cf6c7
417,436
def _nindent(msg, n, char=' '): """Add custom indentation to a line""" tab = '' for i in range(n): tab += char return tab+msg
c78686a652bc2dfb5645c661e9f314322901e452
478,269
def normalize_weights(weights): """Normalises a list of numerical values (weights) into probabilities. Every weight in the list is assigned a probability proportional to its value divided by the sum of all values. Args: weights (list): A list of numerical values Returns: list: A l...
9ba33102b89d168463042756fee1c14066855583
205,474
def button_control_name(v, idx=None): """Return the name of a setting's button v - the setting idx - if present, the index of one of several buttons for the setting """ if idx is None: return "%s_button" % (str(v.key())) else: return "%s_button_%d" % (str(v.key()), idx)
3d98aca881d6ba14bc8e6b934b5abfe2d3b1c846
515,977
import uuid def is_uuid_valid(value: str) -> bool: """Validate if is uuid. Args: value (str): uuid. Returns: bool: true if is valid else false. """ try: uuid.UUID(value) return True except ValueError: return False
c597c297f8f8e45ddee95e767e8d27e263f1d988
378,251
def evidence_type_number_to_name(num: int) -> str: """ Transforms evidence type number to it's corresponding name :param num: The evidence type number :return: The string name of the evidence type """ name: str = str() supported_types = ['Network', 'Process', 'File', 'Registry', 'Security', ...
1f6a8e57334e08e997a3f86e629df04cb9602594
699,699
def to_flag(arg_str: str) -> str: """ Utility method to convert from the name of an argparse Namespace attribute / variable (which often is adopted elsewhere in this code, as well) to the corresponding flag :param arg_str: Name of the arg :return: The name of the flag (sans "--") """ retu...
0ced03481b70b82ca7fdadd9474f72cb443bda1f
221,611
def set_configuration_atoms_from_ase(config, ase_atoms): """ Set the atom positions of a configuration given a set of ASE atoms :param config: (gt.Configuration) :param ase_atoms: (ase.Atoms) """ for i, coord in enumerate(ase_atoms.get_positions()): config.atoms[i].coord = coord r...
3175682efd3ad629044f54c06ac4f8924b912e05
505,641
def get_column_letter(column_index): """ Returns the spreadsheet column letter that corresponds to a given index (e.g.: 0 -> 'A', 3 -> 'D') Args: column_index (int): Returns: str: The column index expressed as a letter """ if column_index > 25: raise ValueError("Cannot ...
78a25887caa88ba2d2298f8eccc71b5fca2421a4
381,714
def from_lane_to_hex_string(lane, w): """Convert a lane value to a string of bytes written in hexadecimal""" lane_hex_b_e = ((b"%%0%dX" % (w // 4)) % lane) # Perform the conversion temp = b'' length = len(lane_hex_b_e) // 2 for i in range(length): offset = (length - i - 1) * 2 t...
1ac34c30fef88f9a49d91eeacd86b8d14caf6551
337,999
def clean_row_author_info(row_author_info): """Returns a string of author info stripped of parentheses or numericals""" clean_row_author_info = "" for i in range(len(row_author_info)): undesirable_characters = "()-" if row_author_info[i].isnumeric() or row_author_info[i] in undesirable_characters: continue ...
1b3e930d016bd872ddc9099f6f0a9604d0c58d29
573,667
def should_skip_request(pin, request): """Helper to determine if the provided request should be traced""" if not pin or not pin.enabled(): return True api = pin.tracer.writer.api return request.host == api.hostname and request.port == api.port
fe10521efda0bc6803e02a76d20e8e0f4038e20f
584,445
def infer_action(player_before, player_after): """Reconstruct that action that leads to the next state.""" if not player_before.active: return "inactive" if player_after.speed > player_before.speed: return "speed_up" if player_after.speed < player_before.speed: return "slow_down"...
0b10e7e7ffbb1cde84a9790ecf38a29c8ed33fef
314,587
def get_vd_dialogue(d_id, dataset): """Retrieve a VisDial dialogue.""" caption = dataset['data']['dialogs'][d_id]['caption'] + '.' turns = [] for qa in dataset['data']['dialogs'][d_id]['dialog']: q = dataset['data']['questions'][qa['question']] + '? ' a = dataset['data']['answers'][qa['a...
57797674712770647af5ba5cb74628e6b227986a
468,360
def solve_new_captcha(line): """ >>> solve_new_captcha('1212') 6 >>> solve_new_captcha('1221') 0 >>> solve_new_captcha('123425') 4 >>> solve_new_captcha('123123') 12 >>> solve_new_captcha('12131415') 4 """ return sum(int(x) for x, y in zip(line, line[len(line) // 2 :]...
b4e9d117006b6f9d9d45e78bfd4bed196e62e882
93,773
def truncate_hour(tval): """Truncate tval to nearest hour.""" return((int(tval)/3600) * 3600)
bc0a9177a14ad3d222b19bdaf5fa2e118f0ee8c7
433,582
import token def trailing_comma(node): """Determine if there is a trailing comma""" if node.children: return node.children[-1].type == token.COMMA return False
0a7a1a4c1b6d9998152b910f2b510f3377c1c964
427,183
def openFile(file_name): """Opens file and returns the contents unmodified Args: file_name (str): file name Returns: (str): file content """ with open(file_name, 'r') as fp: return fp.read()
d48003a1be34686bdd33dffa3ad869b411edeaeb
496,273
def getValueListName(protocolResponseClass): """ Returns the name of the attribute in the specified protocol class that is used to hold the values in a search response. """ return protocolResponseClass.DESCRIPTOR.fields_by_number[1].name
910c0bbc1539b16f4a34811e97b496442e708d66
298,566
def get_target_shape(shape, size_factor): """ Given an shape tuple and size_factor, return a new shape tuple such that each of its dimensions is a multiple of size_factor :param shape: tuple of integers :param size_factor: integer :return: tuple of integers """ target_shape = [] fo...
83c60a72e19cca5606995c9cdf324017156012ac
682,273
def harmonic_number(n, s): """Returns the generalized harmonic number Hn,s.""" return sum(1 / (i**s) for i in range(1, n+1))
98905e80c362f2b87bf68f89beaeaf9d46bbf071
503,851
import re def strip_ansi_sequences(text): """Return a string cleaned of ANSI sequences""" # This snippet of code is from Martijn Pieters # https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]...
89699eb64ae6053c6b440844810b7b56721c39de
120,712
import pytz from datetime import datetime def is_it_june() -> bool: """ determines if it is currently June in Madison, Wisconsin Returns: True if it is June, False otherwise """ tz = pytz.timezone("US/Central") the_now = datetime.now(tz) return datetime.date(the_now).month == 6
e1018f1ec92fd7fadf9b305d338dfdf234d3db46
660,974
def preprocess_input(cin: str): """ Maps user input into matrix indexes Parameters ---------- cin : str For example F5 Returns ------- If the case was F5, it will return 4, 5 """ letter = cin[0] number = int(cin[1]) d = {'A': 0, 'B': 1, 'C': 2, 'D': 3,...
54a85b79b8b1bb49d740d78a0a3894c203c82b6a
626,019
def hydro_area_lookup(area_id, df_ref, area_key): """Get max row in data file of a particular area's grid cells to reduce row count for performance :param area_id: ID of area to find it's grid cells :type area_id: int :param df_ref: Reference dataframe ...
e50ba88508b93e1cea681d14bf6f426c3f562223
396,975
def adjust_var_name(var_to_check, var_names): """ Check if upper or lower case version of name is in namelist and adjust. Parameters ---------- var_to_check : Str. var_names : List of Str. Returns ------- var_to_check : Str. """ if var_to_check not in var_names: fo...
850f3261f6f359cde8243c15b1ea790372d057fb
622,924
import types def monkeypatch_wagtail_as_syntax(image_node): """ If you use wagtails 'as' syntax like this: {% srcset_image photo width-300 as thumbnail %} image_node["attrs"] are not resolved. This patch resolves srcset and attaches it to the returned rendition. It's a bit hacky but should w...
6420bdf57cd30aa6acac8bee7c65e70e4e60d35d
537,384
def parseOptions(userOptions, jobOptions): """ Verifies that user supplied options fit the criteria for a set of job options Args: userOptions: a set of user supplied options jobOptions: an option schema for a job Returns: a list of errors (can be empty) options to s...
166ce216cbe511b5a2c25e6b928b94e0ffd1f66e
80,837
def null_count(df): """ This function will return the number of null values contained within a DataFrame """ return df.isnull().sum().sum()
089c9ff3ecb39449eec4e61923031fa38fcbeb28
132,488
def _get_submission_submitter(syn, submission): """Get submitter id and name from a submission object""" submitterid = submission.get("teamId") if submitterid is not None: submitter_name = syn.getTeam(submitterid)['name'] else: submitterid = submission.userId submitter_name = syn...
dbfa16f989a5a11ac78d56f6fb7e097d53bcdeb6
454,487
import torch def _compute_dx(x, grid): """ x: [n_batch, n_dim] grid: [n_batch, n_dim, n_grid] returns dx: [n_batch, n_dim, n_grid] """ x = x.unsqueeze(-1) # grid = grid.unsqueeze(0) dx = x - grid dx = torch.cat([dx[..., [0]], dx], dim=-1) ...
43166e113370a89111a276c418f47fbe1be0ecbe
168,387
def D_rvmu(r: float, v: float, mu: float) -> float: """ D = r * v * v / mu :param r: radius vector :type r: float :param v: velocity :type v: float :param mu: G * (m1 + m2) :type mu: float :return: D :rtype: float """ return r * v * v / mu
cd46798a793f444035ea7c42a74a96311f488b47
432,140
import csv def read_csv(filepath): """Returns a list of dictionaries where each dictionary is formed from the data. Parameters: filepath (str): a filepath that includes a filename with its extension Returns: list: a list of dictionaries where each dictionary is formed from the data "...
37a507090e71009cd2f0fa944cab35087e834d76
295,755
def empty_string_to_none(string): """Given a string, return None if string == "", and the string value (with type str) otherwise """ if string == '': return None else: return str(string)
3510cc65306e56f5845a9f0fbad737e3660d4f2e
665,113
def is_two_qubit_gate_layer(moment): """Helper function to check whether a moment in a circuit contains one- or two-qubit gates.""" if len(next(iter(moment)).qubits) == 1: return False return True
bbfede1f73dd1b5782f0d3d3a2dbce1faf00577a
216,113
def validate_identity_token(connection, identity_token): """Validate an identity token. Args: connection: MicroStrategy REST API connection object identity_token: Identity token Returns: Complete HTTP response object. """ return connection.get( url=f'{connection.bas...
f3946117433f08a2580e16dcebcbecd01fd10d5d
517,915
def get_abs_part(poly): """Returns a part of a polynomial which contains absolute errors""" result = [m.copy() for m in poly if m.abs_errs] return result
3cfff0b95296b332ffe735db240d6ce0b100c32d
186,959
import itertools def split_every(n, iterable): """Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have less than n elements. See http://stackoverflow.com/a/22919323/503377.""" items = iter(iterable) return itertools.takewhile(bool, (list(itertools.islice(items...
de47464f0d0dba19540d7f1fc56ed7ce5c6e2c0b
604,532
def top_n(lis, n): """Get index of top n item from list with value Args: lis:``list`` list n:``int`` number of top value Return: dict of top value and index: ``dict`` """ top = sorted(range(len(lis)), key=lambda i: lis[i], re...
2aec294faf07b7a42d3ac1cba45f9a145c48964a
477,452
def unquote(name): """Remove string quotes from simple `name` repr.""" return name.replace("'","").replace('"','')
ccfaa777215a111a12e5374e28efbebc41688fbd
230,200
def sample(i): """Helper method to generate a meaningful sample value.""" return 'sample{}'.format(i)
492be8f764c6cd5b7bf799a802ecf7435b62e7c4
556,847
def aggregate_values(values_list, values_keys): """ Returns a string with concatenated values based on a dictionary values and a list of keys :param dict values_list: The dictionary to get values from :param str[] values_keys: A list of strings to be used as keys :return str: """ output = ""...
2d867560f41e1487c55e498ccdca74ef0c280d32
663,410