content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def mask_pipe_mw(text: str) -> str: """ Mask the pipe magic word ({{!}}). :param text: Text to mask :return: Masked text """ return text.replace("{{!}}", "|***bot***=***param***|")
546d7c4b71ce3403da7a33883dac2cd3171224e6
697,433
import base64 def decodebase64(inputStr, decodeFlag=True): """ Decode base64 to real format """ if decodeFlag and inputStr: return base64.b64decode(inputStr) return inputStr
92047f7e1c798d3d0ca6a0a0f8f8d78fbecd1204
566,501
def relay_load_tuple(relay_loads): """ Create list of (relay, load) tuples """ relay_load_tuple = list() for r, loads in relay_loads.items(): for l in loads: relay_load_tuple.append((r,l)) return relay_load_tuple
420b5377f5b4f9c05cf140a1985457107daa019a
430,197
def CheckAttr(f): """Automatically set mock_attr based on class default. This function decorator automatically sets the mock_attr keyword argument based on the class default. The mock_attr specifies which mocked attribute a given function is referring to. Raises an AssertionError if mock_attr is left unspec...
4d6fd797e854339e53f5f9d40c17f5420c6940c9
616,390
import torch def sample_from_binary_logits(l, coord1, coord2): """ Args: l: B x 2 x H x W output of NN (logits) coord1 coord2 Returns: pixels: B x 1 pixel samples at location (coord1, coord2) in range [-1, 1] """ assert l.size(1) == 2 l = l[:, :, coord1, coord2...
5ed8a75c94899cc5c4fc7a153f4c184d2be68f8e
518,916
def clean_split(text, delim): """ Split texts and removes unnecessary empty spaces or empty items. :param text: Text to split :param delim: Delimiter :return: List of splited strings """ return [x1 for x1 in [x.strip() for x in text.split(delim)] if len(x1)>0]
bd454cd33989f6d198d32a0235a9f663df3fc4f8
308,845
def CompactArrayIndices(tree): """Makes a sparse tree dense. Returns a tree that may have been sparse, with its indices now compacted. Eg 'a.b.0.c', 'a.b.5.c' -> 'a.b.0.c', 'a.b.1.c'. Args: tree: or store. multi-level dict representing proto dbroot. Returns: The tree, compacted. """ new_tree...
afcc6a5bceed9274d0494ea63cd4ec07e6dedc4e
354,123
from zipfile import ZipFile def extract_shp(path): """Return a geopandas-compatible path to the shapefile stored in a zip archive. If multiple shapefiles are included, return only the first one found. Parameters ---------- path : Path Path to zip archive holding shapefile. Returns ...
273fb9917c5d5ecedee142e8e252a2376aac59b0
668,936
def length_of_overlap(first_start, first_end, second_start, second_end): """ Find the length of the overlapping part of two segments. Args: first_start (float): Start of the first segment. first_end (float): End of the first segment. second_start (float): Start of the second segment...
6d5779cf25bcd871f1db21f23adf0f5ed7d4447a
256,912
def upper(s: str) -> str: """Transforms string to upper-case letters.""" return s.upper()
a79e49a218869fdb71ba467cb09c99a784161784
277,343
def nice_pair(pair): """Make a nice string representation of a pair of numbers. If the numbers are equal, just return the number, otherwise return the pair with a dash between them, indicating the range. """ start, end = pair if start == end: return "%d" % start else: ...
07e8803a79150ac1fceb360717f0ad6e2af1324c
569,571
import socket import struct def int2ip(ip): """Convert an IP in an 32bit int to a string in dot-decimal notation. :param ip: int """ if not isinstance(ip, int): raise ValueError("ip must be int and is {0} instead".format(type(ip))) return socket.inet_ntoa(struct.pack('!I', ip))
63f2a6cbc7c1562bc820dc824dbe65633b6471ef
231,320
def pass_intermediate_value(contents): """Grabs the content sent in by the user and acts as a intermediate callback, so that other callbacks can share the data the user sent. Args: contents: content sent in from the user and the upload-image object. Returns: contents: content sent in f...
0a69c4af8c88fef7eb2538f4edaac45895e3426d
271,426
def focal_length_calculator(width_in_image, distance_in_image, real_width_of_object): """ This function is used to calculate the focal length for the distnace estimation using triangle similarity :param1 (width_in_image): The width of the object in the reference image :param2 (distance_in_image): T...
288a0dd064a960e3a6d1314476a4b4bccf7b7fd7
267,050
def lon2zone(lon): """ Convert longitude to numeric UTM zone, 1-60. """ zone = int(round(lon / 6. + 30.5)) return ((zone - 1) % 60) + 1
b33fcaf81038c6fc429f0fb036b9f2ace2436d4b
227,331
def filter_file_paths_by_extension(file_paths, ext='csv'): """ Filters out file paths that do not have an appropriate extension. :param file_paths: list of file path strings :param ext: valid extension """ valid_file_paths = [] for file_path in file_paths: ext = ".%s" % ext if ext[0...
6666434635b6054c736b1d54eb5adfdaeb422b7b
127,173
def function2path(func): """ simple helper function to return the module path of a function """ return f'{func.__module__}.{func.__name__}'
a9781334089b4e1127576957ab79b16a59688a9b
253,174
def cell_source(cell): """Return the source of the current cell, as an array of lines""" source = cell.source if source == '': return [''] if source.endswith('\n'): return source.splitlines() + [''] return source.splitlines()
610eae2ae60106d7d5d8d91bfab41679782ac84e
352,974
import pathlib def get_testdata_file_path(rel_path: str) -> pathlib.Path: """Gets the full path to a file in the testdata directory. Arguments: rel_path -- path relative to testdata/ Returns: pathlib.Path -- the full path to the file. """ return pathlib.Path(__file__).parent / "t...
48431abacceb289a8349bd10b911001525caf954
642,006
from typing import List def int_version(name: str, version: str) -> List[int]: """splits the version into a tuple of integers""" sversion = version.split('-')[0].split('+')[0].split('a')[0].split('b')[0].split('rc')[0] #numpy #scipy #matplotlib #qtpy #vtk #cpylog #pyNastran # '...
a9b0bd338526486b465379e131ebd0bfdacd306a
669,870
def parse_args(p): """ parses command-line arguments and returns an arguments object """ p.add_argument('-l', '--location', metavar='LOCATION', action='store', dest='location', choices=['dewick', 'Dewick', 'carm', 'Carm', 'carmichael', 'Carmichael'...
7fcd550bccc1324403edc4c8d7351a96af0179a7
405,640
def translate(parsed): """ translate a tuple (mod, args) to a string """ if isinstance(parsed, tuple): return '%s(%s)' % (parsed[0], ', '.join(map(translate, parsed[1]))) else: return parsed
aa67dee8433103cd5273374c2a46db8000d9ea8c
591,343
import re import keyword import six def _is_identifier(name): """Check if 'name' is a valid Python identifier. Source: https://stackoverflow.com/a/2545164 """ if name: if six.PY2: return re.match(r'^[a-z_][a-z0-9_]*$', name, re.I) and not keyword.iskeyword(name) else: ...
af02c86156179cb506fcb5c1b5d861306d622ae8
357,418
import random def get_random_start_end(len_genotype): """gets a random start and end type for genotype used to get start and end times for fragments, used in mutations Args: len_genotype (int): length of genotype list Returns: (int, int): tuple of two integers representing ra...
0fc216c917aaa2e96c44361022390aaa9401d0f3
435,814
def join_structures(src, dst, validate_proximity=False): """Joins two pymatgen structures""" for site in src.sites: dst.append( species=site.species, coords=site.coords, coords_are_cartesian=True, validate_proximity=validate_proximity, ) retur...
ab0674af9cb8a37b5b2a97f6ad3262a9f3e5b06f
134,722
def find_collNames(output_list): """ Return list of collection names collected from refs in output_list. """ colls = [] for out in output_list: if out.kind in {"STEP", "ITEM"}: colls.append(out.collName) elif out.kind == "IF": colls.append(out.refs[0].collName...
cfcd9a8d8343009b09758a075b6b98a98a3ac0ea
677,724
def OneLett_to_ThrLett(resi, cap = 'standard', suppress_alert = True): """ Usage: OneLett_to_ThrLett(resi, cap = 'standard', suppress_alert = True) This function receives resi, a one-letter amino acid code, and returns the three letter amino acid code. If cap(italization) is standa...
43fdbbf3f9a47846ee8ff07d162b975645b9e9bf
98,865
def get_sql_from_qbol_cmd(params): """ Get Qubole sql from Qubole command """ sql = '' if 'query' in params: sql = params['query'] elif 'sql' in params: sql = params['sql'] return sql
c1d87676458352db3ed97860f94b94757e7a5900
478,933
def maximum(num_list): """Return the maximum number between number list""" return_value = None for num in num_list: if return_value is None or num > return_value: return_value = num return return_value
c4c51b7ec13a8d651459617b71a374be713f53c6
291,596
def _create_chunks_from_list(lst, n): """Creates chunks of list. Args: lst: list of elements. n: size of chunk. """ chunks = [] for i in range(0, len(lst), n): chunks.append(lst[i:i + n]) return chunks
1da5ba267b8a3056a05c01087548a30d408661ab
382,981
def fix_line_problems(parts): """Fix problem alleles and reference/variant bases in VCF line. """ varinfo = parts[:9] genotypes = [] # replace haploid calls for x in parts[9:]: if len(x) == 1: x = "./." genotypes.append(x) if varinfo[3] == "0": varinfo[3] = "N" ...
dd33a042175b925c76261fbd477eabdcaafc61ee
537,526
def parse_agent_args(str): """Parse agent args given in , separated list.""" if str is None: return {} pieces = str.split(',') opts = {} for p in pieces: if '=' in p: key, val = p.split('=') else: key, val = p, 1 opts[key] = val return opts
1205e2e3f411a0055098939911e2308b8159a0ec
302,084
import hashlib def get_thing(secret): """Get dweet thing name from secret. """ m = hashlib.sha1() m.update(secret) return m.hexdigest()
73a32e981e36d2217d09eb58f6558078e35e10d1
490,103
def load_char_mappings(mapping_path): """ load EMNIST character mappings. This maps a label to the correspondent byte value of the given character return: the dictionary of label mappings """ mappings = {} with open(mapping_path) as f: for line in f: (key, val) = line.split()...
8653f22d8490add375747f2e4f1e3aa0bc006f47
101,973
from typing import Any def simple_repr(record: Any) -> str: """ Simple renderer for a SQL table :param record: A table record. :return: A string description of the record. """ out = '{:28}: {}\n'.format('token', record.token) columns = None # get the columns of the table, we'd like to ...
94d4eca0ea03336f9d4c62344914b244f42dfceb
182,370
def _parsedrev(symbol): """str -> int or None, ex. 'D45' -> 45; '12' -> 12; 'x' -> None""" if symbol.startswith(b'D') and symbol[1:].isdigit(): return int(symbol[1:]) if symbol.isdigit(): return int(symbol)
c3db8cee3b6a4fdb1c02efc2b931989ac6a1b19b
66,393
def analytical_domain(request): """ Adds the analytical_domain context variable to the context (used by django-analytical). """ return {'analytical_domain': request.get_host()}
2d1f32ada6524cdc14075596a7b61de3d82d2ea1
668,749
def calculate_fibonacci_number(n : int) -> int: """ Calculate and return the `n` th fibonacci number. Args: n (int) : specify term. Exceptions: - TypeError: when the type of `n` is not int. - ValueError: when `n` is negative. Note: This solution obtains the...
ae812418079d8b4c9756269da3a8dc62a8818969
123,632
import re def find_uptime(show_ver): """ Example: pynet-rtr1 uptime is 3 weeks, 1 day, 3 hours, 52 minutes """ match = re.search(r".* uptime is (.*)", show_ver) if match: return match.group(1) return ''
b8be152a6010156c274bbbca57c18b8383e84d27
607,407
import torch def nel_to_lne(tensor: torch.Tensor) -> torch.Tensor: """ Convert data layout. This conversion is required to use convolution layer. Parameters ---------- tensor: torch.Tensor (N, E, L) where N is the batch size, E is the embedding dimension, L is the sequence length....
1c4aa1d7bf4b033e617683767452d59bfac0a9be
208,174
def read_from_device(path, start, count): """ Read data from a device :param path: device path :type data: string :param start: starting offset for reading :type start: int :param count: lenght of data to read :type count: int :rtype: bytes """ with open(path, "rb") as f: ...
a8faa180762b66a35d32dc1d3cbad5784169e694
368,533
from typing import List from typing import Dict from typing import Any def filter_maxlen(items: List[Dict[str, Any]], maxlen: int) -> List[Dict[str, Any]]: """Returns only payloads not longer than maxlen.""" if maxlen <= 0: return items filtered = [] for item in items: if len(item["pa...
825ff7bb40a2698be2c2f91abaf4f1825d0f4d54
183,155
import json def readjson(fp): """Loads a JSON file""" with open(fp) as jsonfile: data = json.load(jsonfile) return data
42aec1b54d0252c94c0e2d3846c3e1969dd81881
544,697
def parse_text_rules(text_lines): """ A helper function to read text lines and construct and returns a list of dependency rules which can be used for comparison. The list is built with the text order. Each rule is described in the following way: {'target': <target name>, 'dependency': <set of ...
5b65fe082e92b3b2891c77e1cea69c71b9a1bb74
227,043
def _expand(key, shortcuts, breadcrumbs=None): """Given shortcut key and mapping of shortcuts expand the shortcut key. Return the key itself if it is not found in the mapping. Avoids expansion cycles by keeping track of expansion history in the `breadcrumbs` argument to recursive calls. """ bre...
f7d16176e17da549b138831f4cee18b400bece93
388,654
def source_key(resp): """ Provide the timestamp of the swift http response as a floating point value. Used as a sort key. :param resp: httplib response object """ return float(resp.getheader('x-put-timestamp') or resp.getheader('x-timestamp') or 0)
80d56dfe1e4e0ddc9e1eeabb20a05e9b19357cb8
652,505
def split_data(data, val_size=0, test_size=0): """ splits data to training, validation and testing parts """ #split based on percentage ntest = int(round(len(data) * (1 - test_size))) nval = int(round(len(data.iloc[:ntest]) * (1 - val_size))) df_train, df_val, df_test = data.iloc[:nval], da...
d3da49c2307fffd8a6494af76769991100a59b64
281,670
def filter_request(req): """ Extract request attributes from the request metadata """ res = {'path': req['environ']['PATH_INFO'], 'method': req['environ']['REQUEST_METHOD'], 'user-agent': req['environ']['HTTP_USER_AGENT'], 'remote_addr': req['environ']['REMOTE_ADDR'], ...
4a8cb624f6367249efba652296ad93044335f962
67,043
def update_seq_ack(packet_params, previous): """Increase Sequence and Acknowledgement number""" seq = packet_params.get("seq") + 1 ack = previous.seq +1 packet_params['seq'] = seq packet_params['ack'] = ack return packet_params
6e5b99e148608abc74ebcf44636e27025cd50553
239,447
def default_changelog_generator(item): """ Contruct the default changelog line for a given item (PR). """ title = item['title'] breaks_compat = 'compatibility' in item['labels'] pr_url = item['html_url'] if breaks_compat: compat_msg = "**WARNING: Breaks compatibility with previous v...
494c30cef1f36a7875d0456fcb4a414c0ec4bb41
390,190
import yaml def load_yaml_config(filename): """Read the YAML configuration file into a dictionary. Arguments: filename {string} -- The location of the YAML configuration file.] Returns: Dictionary -- The contents of the configuration file. An empty dictionary is returned on error. """ wit...
e0d8c6c32919cf5c226bdf09eccea78bfa911b14
93,422
def has_experience(experience_string): """returns whether the current player has experience or not based on the string yes/no""" if experience_string == 'YES': return True else: return False
d6d870ce8713875f59399beadc3a4e61f5158914
341,128
def calc_saturated_fraction(unsatStore, unsatStore_max, alpha): """ Calculate the saturated fraction of the unsaturated zone Parameters ---------- unsatStore : int or float Storage in the unsaturated zone [mm] unsatStore_max : int or float Maximum storage in the unsaturated zone [mm...
125dcf56764b7f8dca89f798194822593fd0e78d
251,008
def to_name_key_dict(data, name_key): """ Iterates a list of dictionaries where each dictionary has a `name_key` value that is used to return a single dictionary indexed by those values. Returns: dict: Dictionary keyed by `name_key` values having the information contained in the...
ce5c2938b29bf42d0835f0a375ee01ba052d8585
497,647
import fnmatch def _is_excluded(name, exclude): """ Return true if given name matches the exclude list. """ if not exclude: return False return any((fnmatch.fnmatchcase(name, i) for i in exclude))
7cfe2422bd6ed6d7e6ab50569646be04c1858e29
140,421
def daisy_chain_from_acquisitions(acquisitions): """Given a list of acquisiton dates, form the names of the interferograms that would create a simple daisy chain of ifgs. Inputs: acquisitions | list | list of acquistiion dates in form YYYYMMDD Returns: daisy_chain | list | names of daisy cha...
47fe3f15427ded06a463860aaddcfb20a5223f8b
313,443
def isfloat(s:str) -> bool: """ Functions to determine if the parameter s can be represented as a float Parameters: ----------- * s [str]: string which could be or not a float. Return: ------- * True: s can be represented as a float. * False: s cannot be represented as a floa...
5ba78309d10c1b0a42b2e6a14fa489b92fe3de01
542,645
def find_initial_start(pos,reference_sequence,min_length): """ Using an initial position, it finds the initial starting position which satisfies the minimum length :param pos: int :param reference_sequence: str :param min_length: int :return: int """ ref_len=len(reference_sequence) n...
14c805d03d3efb9c1a0f9b23d6d2f99d6c3251ce
296,890
from math import ceil, sqrt def chooseGridThread(n): """ Modify this function to change how we choose number of threads and blocks Args: n (int): number of datapoints Returns: (int, int): (nblocks, nthreads) """ nroot = sqrt(n) curr = 32 while curr + 32 < nroot an...
2d54f516f61d5fe8aa4193260f78de82a244e53f
341,065
def add_lat_lon(df): """Add lat and lon columns to dataframe in WGS84 coordinates Parameters ---------- df : GeoDataFrame Returns ------- GeoDataFrame with lat, lon columns added """ geo = df[["geometry"]].to_crs(epsg=4326) geo["lat"] = geo.geometry.y.astype("float32") geo[...
2264b865fbf8499c51728f858c863e675d00b021
381,241
def reddit_response_parser(results): """ :param results: JSON Object :return: List of dictionaries [ { "title": "title of the news", "link": "original link of the news source", "source":"your-api-name" },...
b4cd22a1e1a549cb4e668eb543a61b12733d9a19
358,465
def _check_no_collapsed_axes(fig): """ Check that no axes have collapsed to zero size. """ for panel in fig.subfigs: ok = _check_no_collapsed_axes(panel) if not ok: return False for ax in fig.axes: if hasattr(ax, 'get_subplotspec'): gs = ax.get_subplo...
2ecbc6a3e17f73ab4c09f606c4638ad7748ee59a
656,103
def mixed_radix_to_base_10(x, b): """Convert the `mixed radix`_ integer with digits `x` and bases `b` to base 10. Args: x (list): a list of digits ordered by increasing place values b (list): a list of bases corresponding to the digits Examples: Generally, the base 10 representatio...
a821ca5ee4a720a9c445c98b2bcd2905bd6d87cb
12,107
from pathlib import Path from typing import Tuple import re def parse_samtools_flagstat(p: Path) -> Tuple[int, int]: """Parse total and mapped number of reads from Samtools flagstat file""" total = 0 mapped = 0 with open(p) as fh: for line in fh: m = re.match(r'(\d+)', line) ...
60c6f9b227cefdea9877b05bb2fe66e4c82b4dd1
705,319
def clock_getres(clk_id): # real signature unknown; restored from __doc__ """ clock_getres(clk_id) -> floating point number Return the resolution (precision) of the specified clock clk_id. """ return 0.0
f51d80fda97e5a2c869818a0ef306be7936e6e82
265,407
from textwrap import dedent def dedent_multiline(text): """Dedent multiline text, stripping preceding and succeeding newlines. This is useful for specifying multiline strings in tests without having to compensate for the indentation. """ return dedent(text).strip()
dff53acfc698072f2eeae9281cf33b3144fe12a4
278,592
def _guessFileFormat(file, filename): """ Guess whether a file is PDB or PDBx/mmCIF based on its filename and contents. authored by pandegroup """ filename = filename.lower() if '.pdbx' in filename or '.cif' in filename: return 'pdbx' if '.pdb' in filename: return 'pdb' f...
ab04db18b05ee416315d8d2faa2381e469dda955
635,128
def index() -> str: """Root page of Flask API. Returns: A test message. """ return "What I think a REST API is supposed to be in flask (probably wrong)!"
bea6676bdbb95b359fd642073002d39ab9f60a9f
102,614
from typing import List def txt_to_list(txtfilename: str) -> List[str]: """ Reads in file, splits at newline and returns that list :param path: Path to dir the file is in :param txtfilename: Filename :return: List with lines of read text file as elements """ with open(txtfilename, "r", en...
01e04352000113a6a5f5d4491773fd5378bae583
461,247
import random def random_bytes(size=1024): """ Return size randomly selected bytes as a string. """ return ''.join([chr(random.randint(0, 255)) for i in range(size)])
bf09258ea7542b5f89c25100d1b19f95380bb8a0
180,680
def epoch_time(start_time, end_time): """ Computes the time for each epoch in minutes and seconds. :param start_time: start of the epoch :param end_time: end of the epoch :return: time in minutes and seconds """ elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) ...
8265cb78c26a96a83a1035c09a7dccb0edf8c4d0
14,189
def find_name_from_len(lmin, lens): """ reverse lookup, get name from dict >>> lens = {'chr1': 4, 'chr2': 5, 'chr3': 4} >>> find_name_from_len(5, lens) 'chr2' """ for fname, l in lens.iteritems(): if l == lmin: return fname raise Exception('name not found')
6e4dc740442243fea1ebd3c09645a7972b200db9
625,822
def date_format(date, format='%d %m %Y'): """ convert date to string in a given format """ return date.strftime(format)
1402e0490780f9dec45638bac22a2b6dbb0897ce
443,930
def weekDay (obj): """ return the weekDay from a obj with a datetime 'date' field weekDay 0 is monday """ return obj['date'].weekday()
f67d086076e99727e2b39f6a52608144ac24165d
26,342
def replace_at(string,old,new,indices): """Replace the substring "old" by "new" in a string at specific locations only. indices: starting indices of the occurences of "old" where to perform the replacement return value: string with replacements done""" if len(indices) == 0: return string ind...
a136b498a627aba3ebdf6ed3c339a272c88dd3e3
65,277
def remove_background(image, threshold): """Threshold an image and use as a mask to remove the background. Used for improved compression Parameters ---------- image : ndarray input image threshold : float intensity to threshold the input image Returns ------- filtered :...
b455f0e08bc13d54a046eeeaed5df8632d9bd41d
558,099
def V_tank_Reflux(Reflux_mass, tau, rho_Reflux_20, dzeta_reserve): """ Calculates the tank for waste. Parameters ---------- Reflux_mass : float The mass flowrate of Reflux, [kg/s] tau : float The time, [s] rho_Reflux_20 : float The destiny of waste for 20 degrees celc...
3e1adc446bbe2dd936663af895c59222cd000a48
7,419
def pretty_dict(dict): """ Returns a pretty string version of a dictionary. """ result = "" for key, value in dict.items(): key = str(key) value = str(value) if len(value) < 40: result += f'{key}: {value} \n' else: result += f'{key}: \n' \ ...
f21196e52ef7f0c5777c875d0b6a3669838a7eb5
450,226
def remove_duplicates(dict_of_lists): """Removes duplicates from a dictionary containing lists.""" return {key: list(set(value)) for (key, value) in dict_of_lists.items()}
a663df2f00700aac4a204dc8a25fa80ea0336294
322,818
def calc_DH_return(t_0, t_1): """ This function calculates the return temperature of the district heating network according to the minimum observed in all buildings connected to the grid. :param t_0: last minimum temperature :param t_1: current minimum temperature :return: ``tmax``, new minimum...
6c058a70148ce08b9044f63df7622beb9df24907
512,439
def contour_coords(contour, source='scikit'): """Extract x, y tuple of contour positions from contour data. Scikit has reversed x, y coordinates OpenCV has an unusual numpy array shape (npts, 1, 2) Parameters ---------- contour: contour data source: 'scikit' or 'opencv' Output ---...
971f269fab6c476aed1be0a047f843ff0372fe08
38,817
def extract_etymology(entry): """ extracts the etymology part of a given entry string """ state = 0 etymology = "" for ch in entry: if state == 0: if ch == "[": state = 1 elif ch == "]": raise Exception(f"unexpected ] in: {entry}") ...
def5c936f72bb937f7dd5ad168f8a595318d40ef
104,468
def search_name(needle, name, obj): """Match if needle is contained in name""" return name and needle in name
4cc81df1ed35f6aceaa5d9f82b6414f9ebfa7b5d
472,420
def return_data_side_effect(*args, **kwargs): """Side effect to return data from a miller array.""" return kwargs["i_obs"].data()
ca740eb5f61160130b64d2bfb9594ce8471c3dee
186,537
from typing import Mapping def merge(left, right): """ Merge two mappings objects together, combining overlapping Mappings, and favoring right-values left: The left Mapping object. right: The right (favored) Mapping object. NOTE: This is not commutative (merge(a,b) != merge(b,a)). """ ...
5cfeaf647eaf1377c181180f10484602e30f562e
494,385
def _set_custom_clusters(bspecs, clusters): """Given a list of custom clusters, set them to the custom clusters to add to bspecs Parameters ---------- bspecs : dict clusters : list of properly formatted clusters Returns ------- dict """ bspecs["orbit_specs"]=clusters ...
4182f0e251111d8ebf6835a5aaa779083285bcce
326,394
def config(config): """ A config containing a smaller exposure sequence. """ config["exposure_sequence"]["n_days"] = 1 config["exposure_sequence"]["n_cameras"] = 1 config["exposure_sequence"]["n_dark"] = 1 config["exposure_sequence"]["n_bias"] = 1 config["exposure_sequence"]["filters"] = ["g_ba...
f11381b7ad4e6bfce7521a843bd54856305ca246
444,536
import requests import time def call_crossref_api(doi): """ Calls the crossref works API for a given DOI. """ url = "http://api.crossref.org/works/{}".format(doi) headers = { "User-Agent": "JournalsDB/1.1 (https://journalsdb.org; mailto:team@ourresearch.org)" } r = requests.get(url...
ce4f60b5f25c64a2eb88dcefc7e7077118799b1f
578,578
def count_long_words(sentence, length): """Given a sentence, computes and returns the number of words equal to or longer than the provided threshold length Keyword arguments: sentence -- sentence or series of sentences length -- minimum length for a word to be counted """ long_words = 0 ...
7a827ebf0d36c3f6eb8f0beda4bae227efa34ada
206,858
from typing import List def mutate_sentences(sentence: str) -> List[str]: """ Given a sentence (sequence of words), return a list of all "similar" sentences. We define a sentence to be similar to the original sentence if - it as the same number of words, and - each pair of adjacent words i...
3d3915d6af6c30895199603f373ab492b45a81d8
564,482
def search(bs, arr): """ Binary search recursive function. :param bs: int What to search :param arr: array Array of ints where to search. Array must be sorted. :return: string Position of required element or "cannot found" string """ length = len(arr) check_item ...
c157d25414a5aaa746b9b26cb51cdb2472376ece
98,039
def int_from_bytes(b) -> int: """ int_from_bytes - converts bytes to int Args: b: bytes Returns: int: result """ return int.from_bytes(b, 'big')
086eb0b0568dd7b12186eb32f84e6a82e0998b63
553,789
def helper(n, order, current_max): """ This function help find the biggest digit. :param n: the input integer :param order: the number of digits :param current_max: the currently biggest digit :return: the biggest digit """ # +-(0~9) if order == 0: return int(current_max) # +-(10~99999) else: # Get digit...
88e363aa0933d9727d8be6aa2e4de7c3a9c0ff49
374,233
def issubclass_safe(x, klass): """return issubclass(x, klass) and return False on a TypeError""" try: return issubclass(x, klass) except TypeError: return False
0b5ade96aa4b5fd3c55969aa22a0501549600d6b
98,467
def pretty_org_name(org_name): """Convert e.g. "homo-sapiens" to "Homo sapiens" """ first_letter = org_name[0].upper() return first_letter + org_name[1:].replace("-", " ")
86afe1f48d6dd7b62435ef133a7079fb7b61ce8d
102,125
def crc16(data): """ Generate the crc-16 value for a byte string. >>> from binascii import unhexlify >>> c = crc16(unhexlify(b'8792ebfe26cc130030c20011c89f')) >>> hex(~c & 0xffff) '0xc823' >>> v = crc16(unhexlify(b'8792ebfe26cc130030c20011c89f23c8')) >>> hex(v) '0xf0b8' """ ...
119e067ba38604d699bf2fc222a7c871d2170a02
201,485
def accom_replace(df): """ replaces values of the variable "SettledAccommodationInd" from input dataset to the format used for analysis and visualisation Grouped in to 'in accommodation' or 'not in accommodation' Parameters ---------- df : main datatset Returns -------...
5ff54051f8c7333ca0217d15bc61a70c27e25f35
354,767
def is_git_sha(xs: str) -> bool: """Returns whether the given string looks like a valid git commit SHA.""" return len(xs) > 6 and len(xs) <= 40 and all( x.isdigit() or 'a' <= x.lower() <= 'f' for x in xs)
3da4f923d32ef94e234738e38a8f98e31756d2da
106,845
import math def _TValue(mean1, mean2, v1, v2, n1, n2): """Calculates a t-statistic value using the formula for Welch's t-test. The t value can be thought of as a signal-to-noise ratio; a higher t-value tells you that the groups are more different. Args: mean1: Mean of sample 1. mean2: Mean of sample...
6c3f7e9399b8d54f65a429c14a76c9b6795fe051
136,106
def calc_center_point(point_a, point_b): """ 已知两点坐标,计算中间点坐标 :param point_a: A点坐标 :param point_b: B点坐标 :return: 中心点坐标 """ return (point_a[0] + point_b[0]) // 2, \ (point_a[1] + point_b[1]) // 2
b7b7b4f1c3258b1159f0f1977ad0839c239f2d7f
120,421