content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def textarea_to_list(text: str): """Converts a textarea into a list of strings, assuming each line is an item. This is meant to be the inverse of `list_to_textarea`. """ res = [x.strip() for x in text.split("\n")] res = [x for x in res if len(x) > 0] return res
be2c1e7bb7c506b197804f7bfd6e78fff324e9ef
679,483
from pathlib import Path def iterdir(path): """Return directory listing as generator""" return Path(path).iterdir()
54e370f7a9a99f267b5a91a85219ce90f1e6dafd
679,484
import re def count_ops_in_hlo_proto(hlo_proto, ops_regex): """Counts specific ops in hlo proto, whose names match the provided pattern. Args: hlo_proto: an HloModuleProto object. ops_regex: a string regex to filter ops with matching names. Returns: Count of matching ops...
0e1a933a85e738e505f1b229625023f88e4c2d33
679,489
def list_diff(l1: list, l2: list): """ Return a list of elements that are present in l1 or in l2 but not in both l1 & l2. IE: list_diff([1, 2, 3, 4], [2,4]) => [1, 3] """ return [i for i in l1 + l2 if i not in l1 or i not in l2]
dd5c2ebecddec8b3a95cde30dae28cac6b996c51
679,494
def get_list_sig_variants(file_name): """ Parses through the significant variants file and creates a dictionary of variants and their information for later parsing : Param file_name: Name of file being parsed : Return sig_variants_dict: A dictionary of significant results """ ...
3b9551d512295f73e74c8a2ccc391ac93ff0664c
679,495
def attack_successful(prediction, target, targeted): """ See whether the underlying attack is successful. """ if targeted: return prediction == target else: return prediction != target
6cd17a7852268d97243bbc8c68938eb4a68727ac
679,496
def merge(elements): """Merge Sort algorithm Uses merge sort recursively to sort a list of elements Parameters elements: List of elements to be sorted Returns list of sorted elements """ def list_merge(a, b): """Actual "merge" of two lists Compares every member of a l...
3b896f5b3b1c88064d64dbaef9dc656448fecb78
679,497
def map_structure(func, structure, args=(), kwargs={}): """apply func to each element in structure Args: func (callable): The function structure (dict, tuple, list): the structure to be mapped. Kwargs: args (tuple,list): The args to the function. kwargs (dict): The kwargs t...
46d13e18c14940c6f0d59c754ad10cdd6d27d913
679,498
def is_a_monitoring_request(request): """Returns True it the input request is for monitoring or health check purposes """ # does the request begin with /health? return request.get_full_path()[:7] == '/health'
ce475eadeaacf67cadca1a3a254a5b5632d59fd5
679,500
def num2songrandom(num: str) -> int: """ 将用户输入的随机歌曲范围参数转为发送给 API 的数字 Algorithm: (ratingNumber * 2) + (ratingPlus ? 1 : 0) Example: '9+' -> 19 """ return int(num.rstrip('+')) * 2 + (1 if num.endswith('+') else 0)
ec1a21cacc08c57340d0796b8ddf2e2144e4638b
679,501
def pad(size, padding): """Apply padding to width and height. :param size: two-tuple of width and height :param padding: padding to apply to width and height :returns: two-tuple of width and height with padding applied """ width = size[0] + padding.left + padding.right height = size[1] + p...
9e1021ec6dac2598e58779db440eae853418cbc4
679,502
def _parse_input_list(input_list: str) -> list[str]: """ Converts a CSV list of assets IDs into a list of parsed IDs (but not Asset objects) """ return [fqn_id for fqn_id in input_list.split(",") if fqn_id != "" and fqn_id != ":"]
280bb0e110be0f1230533acfa0f8ae4f3f2ac7af
679,503
def count_where(predicate, iterable): """ Count the number of items in iterable that satisfy the predicate """ return sum(1 for x in iterable if predicate(x))
460e9fe3b515eb568bb3587947d3cef99b500be1
679,504
def add_default_value_to(description, default_value): """Adds the given default value to the given option description.""" # All descriptions end with a period, so do not add another period. return '{} Default: {}.'.format(description, default_value if default_value else '...
e33c1a6212cea712b826701cc77f2a1cf46abea6
679,505
def derive_order_id(user_uid: str, cl_order_id: str, ts: int, order_src='a') -> str: """ Server order generator based on user info and input. :param user_uid: user uid :param cl_order_id: user random digital and number id :param ts: order timestamp in milliseconds :param order_src: 'a' for rest ...
662199714e303ccd4a438e1aac97c92bbd266d96
679,509
def get_edge(source, target, interaction): """ Get the edge information in JSON format. :param source: the id or name of source node. :param target: the id or name of target node. :param interaction: the interaction of edge. :return : the JSON value about edge. """ if interaction is No...
d1018257fa7a1007369a482fc58713c18c44d4d0
679,510
def is_invocation(event): """Return whether the event is an invocation.""" attachments = event.get("attachments") if attachments is None or len(attachments) < 1: return False footer = attachments[0].get("footer", "") if footer.startswith("Posted using /giphy"): return True retu...
8c8af01611526376ae44f12fbdf521552e4cca56
679,513
def calc_prof(ability, profs, prof_bonus): """ Determine if proficiency modifier needs to be applied. If character has expertise in selected skill, double the proficiency bonus. If character has proficiency in selected skill/ability/save, prof_mod = prof_bonus (multiply by 1). If character h...
56a6cb2df4ce1e023641bea9b6b400787d6c0607
679,517
def inexact(pa, pb, pc, pd): """Tests whether pd is in circle defined by the 3 points pa, pb and pc """ adx = pa[0] - pd[0] bdx = pb[0] - pd[0] cdx = pc[0] - pd[0] ady = pa[1] - pd[1] bdy = pb[1] - pd[1] cdy = pc[1] - pd[1] bdxcdy = bdx * cdy cdxbdy = cdx * bdy alift = adx * ...
3e4e72147a97942ed6f392cd8559d5f6c3dd708b
679,519
def oef_port() -> int: """Port of the connection to the OEF Node to use during the tests.""" return 10000
62fbd90a3745abba1fdfe01327e5399c5fd7bc98
679,520
def get_input(filename): """returns list of inputs from data file. File should have integer values, one per line. Args: filename: the name of the file with the input data. Returns: a list of integers read from the file """ text_file = open(filename, "r") input_strs = text_...
1b39d031e8928ee7ec75ba7b05e6093b4c9000e9
679,521
def tuple_for_testing(model, val, replace_i): """this function creates a tuple by changing only one parameter from a list Positionnal arguments : model -- a list of valid arguments to pass to the object to test val -- the value you want to put in the list replace_i -- the index of t...
bc42ab1538d81f22777b8bf724c4754262155247
679,522
def all_entities_on_same_layout(entities): """ Check if all entities are on the same layout (model space or any paper layout but not block). """ owners = set(entity.dxf.owner for entity in entities) return len(owners) < 2
e49b797800ce12bb9f5eabe6d2f2af7fa61f0ac6
679,527
def merge_dicts(dicts_a, dicts_b): """Merges two lists of dictionaries by key attribute. Example: da = [{'key': 'a', 'value': 1}, {'key': 'b', 'value': 2}] db = [{'key': 'b', 'value': 3, 'color':'pink'}, {'key': 'c', 'value': 4}] merge_dicts(da, db) = [{'key': 'a', 'value': 1}, {'key': ...
cd1bf5611c414cf5e728baa3bb74cc1ceb477823
679,530
def parenthesize(s): """ >>> parenthesize('1') '1' >>> parenthesize('1 + 2') '(1 + 2)' """ if ' ' in s: return '(%s)' % s else: return s
d1463e5e366d818c6fd86b39024549075e356a62
679,531
def _PiecewiseConcat(*args): """Concatenates strings inside lists, elementwise. Given ['a', 's'] and ['d', 'f'], returns ['ad', 'sf'] """ return map(''.join, zip(*args))
d279e4140e28aadd3cac3c40a24055ba9e703d0d
679,537
def brute_force(s: str) -> int: """ Finds the length of the longest substring in s without repeating characters. Parameters ---------- s : str Given string. Returns: int Length of the longest substring in s without repeating characters. Speed Analysis: O(n), no ma...
62f9d18266b7dc335b5c9a896d5bb5b7528fc070
679,538
def get_box(mol, padding=1.0): """ Given a molecule, find a minimum orthorhombic box containing it. Size is calculated using min and max x, y, and z values. For best results, call oriented_molecule first. Args: mol: a pymatgen Molecule object padding: the extra space to be added...
896505ad0f776a3d7fe0ea4103b1c8ac517bf8d0
679,541
def is_maximum_local(index, relative_angles, radius): """ Determine if a point at index is a maximum local in radius range of relative_angles function :param index: index of the point to check in relative_angles list :param relative_angles: list of angles :param radius: radius used ...
c5f108889a3da9aaacbde5e50549fcef7a89147a
679,548
def get_clean_name(name, char='-'): """ Return a string that is lowercase and all whitespaces are replaced by a specified character. Args: name: The string to be cleaned up. char: The character to replace all whitespaces. The default character is "-" (hyphen). Returns: ...
0f825b0a3e29d432c71f44ea685238d06ab9600c
679,549
def decrement(field): """ Decrement a given field in the element. """ def transform(element): element[field] -= 1 return transform
2e392e7ed3f18dfce176b698de25c81e9081b333
679,551
def read_list_of_filepaths(list_filepath): """ Reads a .txt file of line seperated filepaths and returns them as a list. """ return [line.rstrip() for line in open(list_filepath, 'r')]
f6bc0219b1d1c7ea9b1df87d70a0cae5be94d8f9
679,553
def gatherKeys(data): """Gather all the possible keys in a list of dicts. (Note that voids in a particular row aren't too bad.) >>> from shared.tools.examples import complexListDict >>> gatherKeys(complexListDict) ['date', 'double', 'int', 'string'] """ keys = set() for row in data: keys.update(row) return...
3d49f0a9b5e8315b2af99d10ff0d383a45a0d210
679,556
def read_file(path): """Reads file""" with open(path) as file: return file.readlines()
e4759b5dce7ad4a332b4554229073e5f32973d04
679,560
import torch def sigmoid(z): """Applies sigmoid to z.""" return 1/(1 + torch.exp(-z))
572c4fc234401d05b05108ee477540399824f7d8
679,562
import base64 def decode64(string): """ Decode a string from base64 """ return base64.b64decode(string)
116da563b2d4e97672322e44f0732b988352dcb3
679,564
import threading import time def rate_limited(num_calls=1, every=1.0): """Rate limit a function on how often it can be called Source: https://github.com/tomasbasham/ratelimit/tree/0ca5a616fa6d184fa180b9ad0b6fd0cf54c46936 # noqa E501 Args: num_calls (float, optional): Maximum method invocations w...
1783ac412d7b7dcb0cc8adb3af4f94ae02808a6a
679,567
def throttling_mod_func(d, e): """Perform the modular function from the throttling array functions. In the javascript, the modular operation is as follows: e = (e % d.length + d.length) % d.length We simply translate this to python here. """ return (e % len(d) + len(d)) % len(d)
60e0bc5902623b02cb9d8faf969ccbc094f968f8
679,569
import math def dimension_of_bounding_square(number): """Find the smallest binding square, e.g. 1x1, 3x3, 5x5 Approach is to assume that the number is the largest that the bounding square can contain. Hence taking the square root will find the length of the side of the bounding square. The...
58d4acf078c33df69904ffba855f7c41656fd66c
679,570
def key_has_granted_prefix(key, prefixes): """ Check that the requested s3 key starts with one of the granted file prefixes """ granted = False for prefix in prefixes: if key.startswith(prefix): granted = True return granted
80720ef8e1160d73aa8701653781fb3b30334e63
679,571
def add_key(rec, idx): """Add a key value to the character records.""" rec["_key"] = idx return rec
0270ba0084b2c513a7b30a51ec57ebf31c8e7a7d
679,573
def unpack_twist_msg(msg, stamped=False): """ Get linear and angular velocity from a Twist(Stamped) message. """ if stamped: v = msg.twist.linear w = msg.twist.angular else: v = msg.linear w = msg.angular return (v.x, v.y, v.z), (w.x, w.y, w.z)
1182a9c5c9aff25cb2df261a32409d0b7df8d08d
679,576
import requests from bs4 import BeautifulSoup def get_soup(url): """Gets soup object for given URL.""" r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') return soup
6bb402dac489a7e1a49af6cc55f1dc823ac389bf
679,579
def generate_fake_ping_data(random_state, size): """ Generate random ping values (in milliseconds) between 5 and 20, some of them will be assigned randomly to a low latency between 100 and 200 with direct close values between 40 and 80 """ values = random_state.random_integers(low=5, high=20, si...
991b180f76f13e3c5107fc6a578a5259297c1b57
679,581
def split_cols_with_dot(column: str) -> str: """Split column name in data frame columns whenever there is a dot between 2 words. E.g. price.availableSupply -> priceAvailableSupply. Parameters ---------- column: str Pandas dataframe column value Returns ------- str: Valu...
7cb82a2e15afa41f58fabcd019739731af00c214
679,582
def parse_stat(stat): """Parses the stat html text to get rank, code, and count""" stat_clean = stat.replace('\n', ' ').replace('.', '').strip() stat_list = stat_clean.split(' ') rank = stat_list[0] code = code_orig = ' '.join(stat_list[1:-1]) # remove xx and dd from the end of the code so we c...
a9dea9b642dc34dcc4717d1f5458952274bfae93
679,584
from typing import Dict import torch from typing import List def collect_flow_outputs_by_suffix( output_dict: Dict[str, torch.Tensor], suffix: str ) -> List[torch.Tensor]: """Return output_dict outputs specified by suffix, ordered by sorted flow_name.""" return [ output_dict[flow_name] for...
5706a1645ca4d2e9cd263f699a21ed00d140de94
679,585
from typing import Counter def _counterSubset(list1, list2): """ Check if all the elements of list1 are contained in list2. It counts the quantity of each element (i.e. 3-letter amino acid code) in the list1 (e.g. two 'HIS' and one 'ASP') and checks if the list2 contains at least that quant...
a1420117f259351cdc86182f278e2b285efc56a1
679,586
def clean_url(address): """Remove unwanted data and provide a default value (127.0.0.1)""" if address == "": return '127.0.0.1' address = address.replace("http://", "") address = address.replace("https://", "") address = address.split(":")[0] return address
94cd8067f4142d4e97e5ad5119a7ac3a8447e786
679,587
def string_encode(key): """Encodes ``key`` with UTF-8 encoding.""" if isinstance(key, str): return key.encode("UTF-8") else: return key
e143e32135c17a066dbacc4e1ce21461c1c2ceae
679,590
def hasanno(node, key, field_name='__anno'): """Returns whether AST node has an annotation.""" return hasattr(node, field_name) and key in getattr(node, field_name)
257f8fb3b2295ab0dbe112fe9379b9b713a36931
679,591
def scale_reader_decrease(provision_decrease_scale, current_value): """ :type provision_decrease_scale: dict :param provision_decrease_scale: dictionary with key being the scaling threshold and value being scaling amount :type current_value: float :param current_value: the current consumed ...
255af14433efdecfa257df5df4c545b0e476c9d8
679,596
import logging def compareFuzzies(known_fuzz, comparison_fuzz): """ The compareFuzzies function compares Fuzzy Hashes :param known_fuzz: list of hashes from the known file :param comparison_fuzz: list of hashes from the comparison file :return: dictionary of formatted results for output """ ...
0421a10c70e3cc89022619b07d1621d93efaa4c8
679,597
import typing def _rounded(d: typing.SupportsFloat) -> float: """Rounds argument to 2 decimal places""" return round(float(d), 2)
88f85627c447a568c792059ac31c0efa29b9cb5a
679,598
def ping_parser(line): """When Twitch pings, the server ,ust pong back or be dropped.""" if line == 'PING :tmi.twitch.tv': return 'PONG :tmi.twitch.tv' return None
59221051bfb84fab841fb18b561ab259b5b1fd52
679,599
def _in_matched_range(start_idx, end_idx, matched_ranges): """Return True if provided indices overlap any spans in matched_ranges.""" for range_start_idx, range_end_idx in matched_ranges: if not (end_idx <= range_start_idx or start_idx >= range_end_idx): return True return False
6419a3039d251ae1e23cf8f6414e60b9710f584e
679,600
def isSubList(largerList, smallerList): """returns 1 if smallerList is a sub list of largerList >>> isSubList([1,2,4,3,2,3], [2,3]) 1 >>> isSubList([1,2,3,2,2,2,2], [2]) 1 >>> isSubList([1,2,3,2], [2,4]) """ if not smallerList: raise ValueError("isSubList: smallerList is empty: %s"% smallerList) ...
533fe07e3b3b3687cf7d708dcc6b0d7c3677d262
679,603
def merge_sort(arr): """ Merge sort repeatedly divides the arr then recombines the parts in sorted order """ l = len(arr) if l > 1: mid = l//2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < le...
0db88996a16e2d7a40604395a43a18b5bc985a02
679,604
import re def is_file_pattern(text): """ >>> is_file_pattern('file.java') True >>> is_file_pattern('.gitignore') True >>> is_file_pattern('file') False >>> is_file_pattern('java') False >>> is_file_pattern('*.java') True >>> is_file_pattern('docs/Makefile') True ...
8b7592ebb58cbb57b793dcbed41f71980ad0e887
679,612
def gc_percent(seq): """ Calculate fraction of GC bases within sequence. Args: seq (str): Nucleotide sequence Examples: >>> sequtils.gc_percent('AGGATAAG') 0.375 """ counts = [seq.upper().count(i) for i in 'ACGTN'] total = sum(counts) if total == 0: retu...
c74fe809ca74952456b815f345c13a5f52ca51a5
679,613
def build_superblock(chanjo_db, block_group): """Create a new superblock and add it to the current session. Args: chanjo_db (Store): Chanjo store connected to an existing database block_group (list): group of related database blocks Returns: object: new database block """ superblock_id, some_blo...
6f06c99a971e944ec23e3205e6bc1108a05e1acf
679,614
def prune_small_terms(hpo_counts, min_samples): """ Drop HPO terms with too few samples """ filtered_counts = {} for term, count in hpo_counts.items(): if count >= min_samples: filtered_counts[term] = count return filtered_counts
53edbe05ef91aa7b63aa5dade2ae48c721821956
679,618
import jinja2 def get_jinja_parser(path): """ Create the jinja2 parser """ return jinja2.Environment(loader=jinja2.FileSystemLoader(path))
18f0a673035592f26690c50e28426221aee0925c
679,619
def debian_number(major='0', minor='0', patch='0', build='0'): """Generate a Debian package version number from components.""" return "{}.{}.{}-{}".format(major, minor, patch, build)
2aa9471d0ebed91d8ab45ed8db4208e4220f94c5
679,620
import logging def get_request_data(request): """ Retrieve request data from the request object. Parameters ---------- request: object the request object instance Returns ------- Dictionary the request data from the request object. Raises ------ Exception: ...
90fb5c4be02e975ec27162b4033d14f839dc2c30
679,621
def get_prospective_location(location, velocity, time): """Calculate the final location and velocity based on the one at time 0""" return [l + v * time for l, v in zip(location, velocity)]
1c67fe7c81edb440727b4d41f1ae15a5d961fd67
679,623
import json def pretty_jsonify(data): """Returns a prettier JSON output for an object than Flask's default tojson filter""" return json.dumps(data, indent=2)
b36d2579b16c622f4b050ab86cf7cf1a153877d1
679,624
def _check_pixel(tup): """Check if a pixel is black, supports RGBA""" return tup[0] == 0 and tup[1] == 0 and tup[2] == 0
a12b1a8ce51a59e37326ef8f7bc80a5e5a907a1a
679,629
def deprecated_argument_lookup(new_name, new_value, old_name, old_value): """Looks up deprecated argument name and ensures both are not used. Args: new_name: new name of argument new_value: value of new argument (or None if not used) old_name: old name of argument old_value: value of old argument (...
5702e58179daf18bca5504fc3fffdab73e993b44
679,630
import torch def total_variation(x): """ Total Variation Loss. """ return torch.sum(torch.abs(x[:, :, :, :-1] - x[:, :, :, 1:]) ) + torch.sum(torch.abs(x[:, :, :-1, :] - x[:, :, 1:, :]))
057e2635ea9c7c78d89b8c0de134044140f2ee5a
679,633
def match_asset(asset_name, goos, goarch): """ Compate asset name with GOOS and GOARCH. Return True if matched. """ asset_name = asset_name.lower() goarch = { "386": ["386"], "amd64": ["amd64", "x86_64"] }[goarch] match_goos = goos in asset_name match_goarch = any([wo...
1d058237e0c903f7a8542975b862165f98e75f46
679,634
def create_fill_row_string(slot1: str, slot2: str, gap_space: int): """ creates a gap with variable spaces according to the length of the slot string """ return '|' + slot1 + (' ' * (gap_space-(2 + len(slot1) + len(slot2)))) + slot2 + '|'
04e3b394fc7351e209f3ddac8ed67479b0173853
679,639
from typing import List from typing import Any def list_union(a: List[Any], b: List[Any]) -> List[Any]: """Return union of two lists maintaining order of the first list.""" return a + [x for x in b if x not in a]
f2c085a42276bdc4c11f1df172a997db2c87916c
679,641
def sum_two(num_1, num_2): """ This function returns the sum of two numbers """ return num_1 + num_2
7af9e7abe366441c8e6e25686b81124e5967bddf
679,648
def equation_quad(x, a, b, c, d=0, e=0): """Equation form for quad """ return a + b*x + c*x*x
a51ac7aef82026e2cb2de73d62dc99357c860652
679,649
def fix_config_list(config_list): """ transforms a list of the form ['a, b'] to ['a', 'b'] """ if not config_list: return [] t = config_list item = t[0] list_items = item.split(',') return [nr.strip() for nr in list_items]
a514302578b9edebbdc929836eaef08046f8a69c
679,650
def collabel_2_index(label): """Convert a column label into a column index (based at 0), e.g., 'A'-> 1, 'B' -> 2, ..., 'AA' -> 27, etc. Returns -1 if the given labe is not composed only of upper case letters A-Z. Parameters ---------- label : string Column label (expected to be composed...
929d4b26dc9ec58bc55f397c2e67158ed0176a1d
679,651
def calculate_total_votes(poll): """Calculate the total number of votes of a poll.""" total = 0 for vote in poll.votes: total += vote.vote_count return total
4a6314a0a4ffb1a80c8e5a927631ceb5fa646a4b
679,652
def __none_mult(x, y): """PRIVATE FUNCTION, If x or y is None return None, else return x * y""" if x is not None and y is not None: return x * y return None
88cd9fca1fbb3f2ab10dec22a73e792201b20578
679,653
def get_rescale_ratio(image, target): """Gets the required ratio to rescale an image to a target resolution :param image: An image to resize. :param target: The target resolution to resize to. :type image: Image :type target: int :return: The min of the ratio between the target resolution and t...
d3a27b9cfb787bc586a0a97a58578e593ad1d66e
679,654
def option_name(path, delimiter="--"): """ Returns a cli option name from attribute path **Arguments** - path (`list`): attribute path - delimiter (`str`): delimiter for nested attributes **Returns** cli option name (`str`) """ return "--{}".format(delimiter.join(path).replace("...
0beab1b60f5ec479e70a4e12af799ca5efe0230a
679,656
def ledaLines(lines): """Filter sequence of lines to keep only the relevant ones for LEDA.GRAPH""" def relevant(line): return line and not line.startswith('#') return filter(relevant, lines)
1b1e67f59f6fb262795dc9f550e3bcc5d32f5de2
679,659
import colorsys def rgb_to_hls(r, g ,b): """Convert R(0-255) G(0-255) B(0-255) to H(0-360) L(0-255) S(0-255). """ rgb = [x / 255.0 for x in (r, g, b)] h, s, v = colorsys.rgb_to_hls(*rgb) return (h * 360, s * 255, v * 255)
4f20041e55e0d9bdb7f4200afaa3e609cd300169
679,661
def int_or_float(x): """Return `x` as `int` if possible, or as `float` otherwise.""" x = float(x) if x.is_integer(): return int(x) return x
eacef4f2f88351f0d0a8832afcbebb12be305b26
679,662
def aggregate_group(df, aggregate_me, name="aggregated_group"): """ Aggregates several rows into one row. df: str aggregate_me: list. One or more values from the new_var column may be given as a list. This function takes those values (rows), aggregates them, and returns one ro...
e819dea3b2903256ac5c430a6d8c07b1c5265daf
679,664
import re def remove_relative_imports(source) -> str: """ Remove all the relative imports from the source code :param source: :return: """ return re.sub(r"^#include \"(.+)\"$", "", source, flags=re.MULTILINE)
06c126b7fe3fe347256d75f2241893f2fb88b926
679,668
def get_table_names(connection): """ Gets all table names in the specified database file. :param connection: Connection to the DB file. :return: List of table names """ connection.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = [] for table in connection.fetchall(...
0be8aff053b4aef6d4d7deef2ea965471b081f01
679,671
import itertools def binary_cartesian_product(nb_bits: int): """ Compute binary possibilities of an nb_bits variable. """ ranges = [range(0, 2) for i in range(nb_bits)] # In possibilities, we compute the nb_bits cartesian product of set([0, 1]} possibilities = list() for xs in itertools.pr...
21333911eb19550c2cf8de895e27619c8ebdcf15
679,675
from typing import List def brute_force(num_lst: List[int], pivot: int) -> List[int]: """ Given a list and a pivot, sort so that all elements to the left of the pivot(s) are less than the pivot and all elements to the right of the pivot(s) are greater than the pivot. Runs in O(3n) but not constant storage...
b11fdc8ef5e5a10b3756380881daecdcdfba05b2
679,680
def degree(a): """ returns the degree of the atom """ return a.GetDegree()
778f15474582f9a2673b5d91ef9e1123ad986a60
679,684
import decimal def format_value(value): """Returns the given value rounded to one decimal place if it is a decimal, or integer if it is an integer. """ value = decimal.Decimal(str(value)) if int(value) == value: return int(value) # On Python 3, an explicit cast to float is required ...
cfc3bb57897d4004afd9f7c6d95efdb0ba1e6d33
679,686
import copy def exclude_meta(src_obj): """return copy of src_obj, without path, img, full_path, and objects keys""" obj = copy.copy(src_obj) for key in ['path', 'img', 'full_path', 'objects']: if key in obj: del obj[key] return obj
ca4ad46a6cf7cf0385ed8b33ce971f7841632fcc
679,687
def part1(input_lines): """ The captcha requires you to review a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list. For example: - 1122 produces...
dfc5387d08f146a71c2dbe72ec4d074de331c6bd
679,689
import importlib def import_and_get_task(task_path): """ Given a modular path to a function, import that module and return the function. """ module, function = task_path.rsplit(".", 1) app_module = importlib.import_module(module) app_function = getattr(app_module, function) return app_...
6e628eb0d24a94aafa22107b2ac70ece355f17d9
679,690
def MDD(series): """Maximum Drawdown (MDD) is an indicator of downside risk over a specified time period. MDD = (TroughValue – PeakValue) ÷ PeakValue """ trough = min(series) peak = max(series) mdd = (peak - trough) / peak return round(mdd, 3)
71ef94e58345b24c3a64311f3652b24c8f1eeafc
679,692
def named_value(dictionary): """ Gets the name and value of a dict with a single key (for example SenzaInfo parameters or Senza Components) """ return next(iter(dictionary.items()))
30ed1c6bcf6b0178b0705492b795646257a62fbd
679,693
def _get_conjuncts(tok): """ Return conjunct dependents of the leftmost conjunct in a coordinated phrase, e.g. "Burton, [Dan], and [Josh] ...". """ return [right for right in tok.rights if right.dep_ == 'conj']
8962050ab17d2c9991e6af7bf0d73cb178698a08
679,696
def last_common_item(xs, ys): """Search for index of last common item in two lists.""" max_i = min(len(xs), len(ys)) - 1 for i, (x, y) in enumerate(zip(xs, ys)): if x == y and (i == max_i or xs[i+1] != ys[i+1]): return i return -1
76baebee425dda29c08af32659a4418bef83e9bb
679,702
def gen_anytext(*args): """ Convenience function to create bag of words for anytext property """ bag = [] for term in args: if term is not None: if isinstance(term, list): for term2 in term: if term2 is not None: bag.a...
54749b40142465c03a8ac19cb7a1175b7e7ee0e7
679,704
def bool_on_off(value): """Convert True/False to on/off correspondingly.""" return 'on' if value else 'off'
387cee885ccc47a5415d810d1064f2d66bca6131
679,718