content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def vertices_from_bbox(box_min_x, box_min_y, box_min_z,
box_max_x, box_max_y, box_max_z):
"""
Return a tuple with
1 - a list with 8 tuples representing the vertices of the box that the
given bounding box min and max values represent
2 - the faces of that box
"""
v0 = (... | 4c83e6c03e7179869f0aab66a65e3feea77becd1 | 566,983 |
def add_list_member_operation(var_attribute_list_name, var_attribute_list_member):
"""Return request string for a single operation to add a list member to an attribute of type array/list."""
return '{"op":"AddListMember","attributeListName":"' + var_attribute_list_name + '", "newMember":"' + var_attribute_list... | 1eca3fa0129a0b71cff737fb1798b7523f15758e | 566,986 |
def tex_sub(obj, subscript) -> str:
"""Return obj_subscript in latex."""
return f"{obj}_{subscript}" if len(str(subscript)) == 1 else f"{obj}_{{{subscript}}}" | 4014087101b9b77b010d6e15a0803c7e261b45c2 | 566,987 |
import random
def get_random_ints(N):
"""Generate a random integer with cardinality N"""
lower = 10**(N-1)
upper = 10**N - 1
return random.randint(lower,upper) | ec9c4bc06c99059d396d72eb7b807d33a4535903 | 566,988 |
def make_text_to_translate(source_lines, translation_types):
""" Returns only lines that need to be translated according to translation_types
"""
filtered_lines = ''
l_orig = len(source_lines)
for i, line in enumerate(source_lines):
if translation_types[i] > 0:
filtered_lines += ... | 8eac6799ed0369b9bcf18292b915d6ded923a2c9 | 566,990 |
def get_subclasses(cls):
"""Get all subclasses (even indirect) of the given class."""
subclasses = []
for c in cls.__subclasses__():
subclasses.append(c)
subclasses.extend(get_subclasses(c))
return subclasses | 2668b9e18ab01bb4610af773a2495118e1a031f7 | 566,993 |
def get_id_map(database: dict) -> dict:
"""Make a Name to ID mapping from the database."""
mapping = {}
for _id in database:
name = database[_id]['name']
if _id in mapping.values():
raise ValueError(f'Duplicate tag ID: {_id}')
if name in mapping.keys():
raise ... | 71cf4356d4f72751ff5f5e58aa92f388fde9c265 | 566,995 |
def chars_to_bin(string):
"""
Convert characters of a string to a 7 bits long binary format
"""
#return ['{:b}'.format(ord(character)) for character in string]
list_of_7bits_items = ['{:b}'.format(ord(character)) for character in string]
if len(list_of_7bits_items)<8:
for i in range (8... | 7ef3da0676656eb7ec05cd10a4ecefaa143ff533 | 566,996 |
def replace_with_ids(tokens, vocab):
"""Takes in a list of tokens and returns a list of word ids. <unk> must be included in vocabulary!
Args:
tokens: List of tokens.
vocab: A dictionary from word -> word_id. MUST INCLUDE THE TERM <unk>.
Returns:
List of word ids.
"""
return ... | c0f2684a9a9c0edf92c8e9a902c26dfe87492200 | 566,999 |
def validate_country_codes(parser, arg):
"""Check that the supplied 2 country code is correct."""
country_codes = ["us", "de"]
if arg.strip().lower() not in country_codes:
parser.error("Invalid country code. Available codes are: %s" %
", ".join(country_codes))
else:
return ar... | b7e074e97e93a5f938c048a04339383130cd2c7e | 567,000 |
def _infinite_strings(key=None):
"""Returns a function which returns a float: either 'inf' for a
(base)string, or the float(value) for the argument. Intended for
sorting numbers before strings. Accepts a 'key' argument as for
sorting algorithms.
"""
def _sort_func(value):
if key is not N... | cdcbceb6fd9da15cc8c97d859f7dc4e900de6767 | 567,002 |
def get_change_set_status(cf, cfn_stack_name, cfn_change_set_name):
"""Returns change set status
:param cf: cfn client
:param cfn_stack_name: stack name
:param cfn_change_set_name: chenge set name
:return: status
"""
details = cf.describe_change_set(ChangeSetName=cfn_change_set_name, StackN... | fd6d79a6cffe62be713c5ed4aca20da8a0fcc7c9 | 567,003 |
def p_html(text: str) -> str:
"""Embed text in paragraph tag."""
return "<p>{}</p>".format(text) | 26174186ca45c6d2a23906ae86e58fe3eab9eafd | 567,009 |
import random
def gen_knn_mix_batch(batch,train_dataset,sent_id_knn_array,knn_mix_ratio,train_size):
"""
we want to generate the mix bathc for knn data.
Inputs:
batch: the main training batch. a list of features. batch[5]: all_sent_id, a tensor of each sent's id
train_dataset: the whole tra... | 86d65fd0c5d2d0afd846dab60a7de70936d28e44 | 567,015 |
def create_sim_props(k, phase):
"""Create simulation properties for planet.
Parameters
----------
k : integer
The Radial Velocity semiamplitude.
phase : list
Orbital phase of the object orbiting the star.
Returns
-------
dictionary
Dictionary containing RV Semi.... | bf341f0eb2836a579a8518e5bd6cfde16ff349dd | 567,016 |
def color_from_dim(dataarray, dim_name):
"""Return colors and color mapping of a DataArray using coord values as color code.
Parameters
----------
dataarray : xarray.DataArray
dim_name : str
dimension whose coordinates will be used as color code.
Returns
-------
colors : array of f... | f822252d9aae8975f3877e94e935afff6dc89357 | 567,020 |
def make_image_key(video_id, timestamp):
"""Returns a unique identifier for a video id & timestamp."""
return "%s,%04d" % (video_id, int(timestamp)) | c338f544b6c0e8064c4d42d442227064764918e0 | 567,021 |
def pt_2_seg_dist(pt, seg):
"""
Desc: 计算点pt到线段seg的距离
Args:
pt : Point object
seg : Segment object
Returns:
float, distance
Raises:
None
"""
return pt.point().distance(seg.linestring()) | 5631fde91687ca3762084e75760f20413161312b | 567,022 |
def get_host_representation(fqdn, ip_address=None):
"""
Creates an object that contains information of the host on which tests will be run.
:param fqdn: The fqdn of the machine. localhost in case of config master
:param ip_address: The ip address of the machine. 127.0.0.1 in case of config master
:r... | 6bd122b699307ca6a0b39cca919b7d2e9c048040 | 567,027 |
import pathlib
import inspect
def _get_caller_folder(stack_level: int = 1) -> pathlib.Path:
"""Determine folder in which the caller module of a function is located."""
frame_info = inspect.getouterframes(inspect.currentframe())[stack_level]
caller_path = frame_info[1] # frame_info.filename
here = pa... | dd30bee6ae1721a7cf629ef087bd773884e35444 | 567,032 |
def _dict_fix_dates(my_dict):
"""Convert values of keys 'start_date' and 'end_date' to proper ISO
date format."""
for key, val in my_dict.items():
if key in ['start_date', 'end_date']:
my_dict[key] = val.isoformat()
return my_dict | c077600fbe95a0b64d2f34a62ec099f1586eddaa | 567,038 |
from datetime import datetime
def to_datetime(milliseconds):
"""Convert a timestamp in milliseconds to a datetime"""
return datetime.fromtimestamp(milliseconds // 1000) | 2d48795f0dbf7ce8b846345bad34da15d337e9d0 | 567,039 |
import base64
def encode(s):
"""encode string with base64 algorithm
Arguments:
s (string) : the string will be encoded
Returns:
bytes : the encoded bytes
"""
if isinstance(s, str):
b = s.encode()
else:
b = s
return base64.b64encode(b) | 6c2a04b91384ef2ffc919cb194344272fc4ac127 | 567,042 |
async def twitter_follower_count(client, bearer_token, username):
"""Find out the follower count of *username* on Twitter."""
# https://developer.twitter.com/en/docs/authentication/oauth-2-0
headers = {"authorization": f"Bearer {bearer_token}"}
# https://developer.twitter.com/en/docs/twitter-api/users/l... | 699bba45b1fe29c6d2d0cf4f84cb06a5c51b8311 | 567,045 |
def get(response):
"""Retrieve the 'response' portion of the json object."""
return response.json()['response'] | 59456fb49cb21993caf1f606dfe67b781db45295 | 567,047 |
import requests
def check_url(url):
"""Send HEAD request to the url and return the HTTP status code
:param url: URL to check
:type url: str
:return: HTTP status code
:rtype: int
"""
try:
response = requests.head(url)
except requests.exceptions.ConnectionError:
return N... | 9567d7b7427db6831ff10392c1c506c1e94120c1 | 567,051 |
def _write_a_tikz_coordinate(name, xy, num_fmt):
"""Write a TikZ coordinate definition.
Parameters
----------
name : str
TikZ coordinate identified / name.
xy : list or tuple of floats
(x, y)-coordinates.
num_fmt : str
Specification of the numbers format, e.g. '.4f'.
... | 5917bbe0fd97ff632a3ff8376f20b43ebdccbd5b | 567,052 |
def convert_words2ids(words, vocab, unk, max_value, sos=None, eos=None):
""" convert string sequence into word id sequence
Args:
words (list): word sequence
vocab (dict): word-id mapping
unk (int): id of unkown word "<unk>"
sos (int): id of start-of-sentence s... | 50dc62ac0a43e93c6f32887d3ebc8337ea36a19f | 567,053 |
from typing import Set
from typing import Tuple
def countActive3DCubesAfterXCycles(activeSet: Set[Tuple[int, int, int]], cycles: int) -> int:
"""
Runs X cycles of the process according to the below rules, and outputs num active 3D cubes:
- If a cube is active and exactly 2 or 3 of its neighbors are also acti... | 65e5e82e37d19d702b862da971efe88bc816439a | 567,055 |
def _is_retryable_err(http_error):
"""
Return whether `http_error` is an error response for which we can re-try
the request.
"""
if http_error.resp.status >= 500:
# Always retry for server errors
return True
if http_error.resp.status == 429:
# Since there is no daily quo... | 11dd6a629a78aba2c1fc92f8bce515a21ed9aac4 | 567,059 |
from pathlib import Path
def read_pid(path: Path) -> int:
""" Read content of file into number """
return int(path.read_text()) | 6f48dbdb38f474b93a13751bdfa422ed828e9839 | 567,063 |
async def generate_settings_message(config):
"""
Generate JSON message to send current settings to client.
Args:
config (dict): Global settings object
Returns:
dict: JSON-style message for clients
"""
message = {}
message["settings"] = config["settings"]
message["warp_f... | 02f005b3512aac0c6cd1873923ce4541b5b007c0 | 567,067 |
def get_node_string(node_formatter, node):
"""
Returns a string for the specified node and its children, converted
with the specified formatter. Based on
serifxml.SerifSynNodeTheory._treebank_str.
"""
# Terminal nodes just get formatted
if len(node) == 0:
return node_formatter(node)... | d6d014cf79f25bb09cabbb072e7781f63be84cfa | 567,068 |
def has_these_keys(dict_, required=None):
"""Checks `dict_` for presence of all keys passed as strings in iterable
`required`. Useful for binding with `partial`.
"""
if not required:
return True
for reqd_key in required:
if reqd_key in dict_:
continue
else:
... | 7ec5a5896304d6278eeba9a9ef0098abc32e5648 | 567,072 |
def create_study_meta_file(
study_identifier: str,
type_of_cancer: str,
name: str,
description: str,
groups: str,
short_name: str,
) -> dict:
"""Create study metadata file
Args:
study_identifier (str): A string used to uniquely identify this cancer study
... | a79be34eafdcd670aadc71d23cb59b15b4ec8e61 | 567,077 |
def count_covered_examples(matrix, vocabulary_size):
"""Returns the number of examples whose added phrases are in the vocabulary.
This assumes the vocabulary is created simply by selecting the
`vocabulary_size` most frequent phrases.
Args:
matrix: Phrase occurrence matrix with the most frequent phrases on... | c0fa756e255af8f203079a5d63b24c5b4a6f479a | 567,079 |
def combine_result(old_results, new_result):
"""Adds a new result to the results JSON list; filters for duplicate entries and saves the best performing one"""
# Loops over all existing results to test for already existing entries with these parameters
for old_result in old_results:
# Verify whethe... | b3688e6b7507201cec31e3e36d8d1ecac49727d5 | 567,080 |
def get_neighbours(p_ref, ref_array):
"""
Given a reference point p_ref = (i,j) (array cell) and the 2D array it is part of
return the list of its neighbours (bu providing their rows and columns)
:param p_ref: Tuple giving a row and column of the reference point p_ref
:param ref_array: The 2D array ... | 216436bc062a6107ba071bf4fef64df52ea6de0b | 567,082 |
def get_keys(dct, keys, default=None, raise_error=False):
"""retrieve the leaf of a key path from a dictionary
:param dct: the dict to search
:param keys: key path
:param default: default value to return
:param raise_error: whether to raise an error if the path isn't found
:return:
"""
... | 19b0656c9b7efb5637cbc4de162f56d2af1c935d | 567,086 |
import math
def calc_skycell_dist(x, y, x_ref, y_ref):
"""Calculate distance from one skyframe to another
Parameters
----------
x : int
skyframe x index
y : int
skyframe y index
x_ref : int
reference x index
y_ref : int
reference y index
Returns
... | 1bdc4f1e24b043c61fffd21c66d06f12050c4f83 | 567,087 |
def get_tweets(query, n, api):
"""
Provided with authentication tweety searches twitter using search terms provided by query
:param query: search terms
:param api: twitter authentication
:param n: number of tweets to get
:returns: search results
"""
try:
# using query to search f... | 68cf38c80c37d5e65b7c951f9679292c11149818 | 567,088 |
def integer_to_base(number, base_string):
"""
Converts base10 integer to baseX integer (where X is the length of base_string, say X for '0123' is 4),
for example: 2645608968347327576478451524936 (Which is 'Hello, world!') to 21646C726F77202C6F6C6C6548 (base16),
does not account for negative numbers
... | d762fe28eceef79d35f4cc829ea8a00d3404de52 | 567,089 |
def overlap_between(pair1, pair2):
""" checks whether there is an overlap between two start/stop position pairs """
# ensure that start < stop position
pair1.sort()
start1, stop1 = pair1
pair2.sort()
start2, stop2 = pair2
if stop1 < start2: return 0
elif stop2 < start1: return 0
else: return 1 | 006037d746ccdfb77cca260c351ac07ef781f6bf | 567,091 |
from typing import List
from typing import Set
from typing import Dict
def get_samples_in_studies(samples: List[str],
studies: Set[str],
sample_to_study: Dict[str, str]) -> List[str]:
"""
Find which samples from the list were generated by the given studies... | 2990853024b9006df27b002d98705db55e94ed30 | 567,092 |
def api_frame_checksum(data: bytes) -> bytes:
"""
Calculates the 8-bit checksum of the given data, returned as a byte array object of length 1.
"""
checksum: int = 0
for c in data:
checksum += c # Add all bytes
checksum &= 0xFF # Keep only the lowest 8 bits.
chec... | d3bd59e7306008993f2404372e163123d087dae1 | 567,094 |
def summarize_return_num(return_nums):
"""
Gets the number of returns by return number.
:param return_nums: A :class:`pandas.Series` of return number that describes the return number of each point.
:return: A :class:`pandas.Series` of return number counts by return number.
"""
return return_nu... | 61d5a5e63eb37362d249cfc17b1206b4df504da3 | 567,096 |
def input_combo(request):
"""
Simply return the current combination of params as a dictionary for use in
tests or other parameterized fixtures.
"""
parameters = dict(zip(("graph_file", "max_iter", "tol"), request.param))
return parameters | 2677ccf8a4f60bbdef5a859b6129f376261e8964 | 567,098 |
import csv
def csv_to_dict_list(filename):
"""Open a CSV file and return a list of dict objects."""
with open(filename) as f:
values = list(csv.DictReader(f))
return values | 8d2f81d5b3d3f58f6b7764adf8796d16f745b40a | 567,099 |
import multiprocessing
def make_pool_with_counter(n_threads):
"""Create a new Process pool with a shared progress counter.
:param n_threads: number of processes
:type n_threads: int
:return: (Process pool, progress counter, lock)
:rtype: (multiprocessing.Pool, multiprocessing.Value, multiprocess... | c16212d9b418253ef04cc7fe995abead12303c73 | 567,101 |
def _struct_has_path(struct, path):
"""Returns True if struct has a value at field path."""
for p in path:
f = struct.fields.get(p)
if f is None:
return False
struct = f.struct_value
return True | 3fbc6ec8e19be2f7705ac2e049d0abe422fea72b | 567,102 |
def get_subdirs(folder):
"""
Gets all subdirectories of a folder
:param folder: pathlib.Path object
"""
return [f for f in folder.iterdir() if f.is_dir()] | 49bd9d7c8b37d4b0b9945c862939af818c946ab7 | 567,105 |
def walk(tree_el):
"""
Given an ast element (list), walk it in a dfs to get every el (list) out of it
:param tree_el ast:
:rtype: list[ast]
"""
if not tree_el:
return []
ret = [tree_el]
for el in tree_el:
if isinstance(el, list):
ret += walk(el)
return r... | 939b2544307f90b65672301c249dcdbc984561ad | 567,106 |
def rename_keys(d, keys):
"""Rename keys from `d` that are present as a key in `keys` by the
corresponding value in `keys`.
Arguments:
d {dict} -- [a dict whose certain keys need to be updated]
keys {dict} -- [a dict that map old key to new key]
Returns:
[dict] -- [an updated d... | a5ebc44e708a20cbc4d96f74866704f43196defc | 567,107 |
def modular_inverse(a: int, N: int) -> int:
"""Return the inverse of `a` modulo `N`.
Args:
a: The number to invert.
N: The modulus. Must be > 1.
Returns:
The inverse of `a` modulo `N`.
Raises:
ValueError: if `N` <= 1 or the inverse does not exist.
"""
if not N ... | a9353e5e6956dca1493f4de98ef0592e0612e2d8 | 567,109 |
def splitBy(s1, s2):
"""Split sequence s1 by sequence s2.
Returns True and prefix + postfix, or just False and None None
"""
if len(s2) == 0:
return True, s1, ()
for i in range(len(s1) - len(s2)+1):
if s1[i:i+len(s2)] == s2:
return True, s1[:i], s1[i+len(s2):]
re... | 3a0ae88c0fc3d376d4452b6216d66fb51a56946f | 567,114 |
def num_tests(cases):
"""
Returns the number of test cases in `cases`
"""
sum = 0
for k, v in cases.items():
sum += len(v)
return sum | 722357edeb177c02e6e6f21c880eeb4b123f1b2d | 567,115 |
def mark(l, h, idx):
"""Produce markers based on argument positions
:param l: sentence position of first word in argument
:param h: sentence position of last word in argument
:param idx: argument index (1 or 2)
"""
return [(l, "{}{}".format('~~[[', idx)), (h+1, "{}{}".format(idx, ']]~~'))] | 39b9eeec1a8aee6e4607821e944d558b34b3b67f | 567,118 |
def CustomSearch(start_token, func, end_func=None, distance=None,
reverse=False):
"""Returns the first token where func is True within distance of this token.
Args:
start_token: The token to start searching from
func: The function to call to test a token for applicability
end_func: The... | fcef9136bcbc38a7126e47fef277c0965e392266 | 567,119 |
def float_metric_value(metric):
"""Gets the value of a float-value keras metric."""
return metric.result().numpy().astype(float) | d5b170b01603e837703e44c7dbceef90089b9cbc | 567,120 |
def generate_train_test(fold, df, save_path=""):
"""
Divide the data in train and test in a subject-wise 5-CV way. The division is generated before running the training
of each fold.
:param fold:[int] Fold to create the train and test sets [ranging from 0 - 4]
:param df:[DataFrame] Dataframe with t... | 52b51449c555eeff63f0804aa7eca102ee4aa299 | 567,125 |
def asner2014_acd(top_of_canopy_height: float) -> float:
"""
Convert `top_of_canopy_height` (tch) to biomass according to
the general ACD formula in Asner & Mascaro 2014.
Source:
https://www.sciencedirect.com/science/article/pii/S003442571300360X
Args:
top_of_canopy_height (float):... | 5376338d32dde3f868857dc9adda1c8c57f4eacb | 567,126 |
def roc(df, price, roc, n):
"""
The Rate-of-Change (ROC) indicator, which is also referred to as simply
Momentum, is a pure momentum oscillator that measures the percent change in
price from one period to the next.
Parameters:
df (pd.DataFrame): DataFrame which contain the asset information... | 37990a793eb91deef7570a7873f4078b8cc594bf | 567,129 |
async def async_to_list(aiter):
"""
Convert an asynchronous generator to a simple list.
"""
# Can't do this until Python3.6 ...
# https://www.python.org/dev/peps/pep-0530/
# return [i async for i in aiter]
res = []
async for i in aiter:
res.append(i)
return res | 852a93332c49b96bf3ffa73f780f13c5d86ff0ed | 567,132 |
def _new_value_pb(entity_pb, name):
"""Add (by name) a new ``Value`` protobuf to an entity protobuf.
:type entity_pb: :class:`gcloud.datastore._generated.entity_pb2.Entity`
:param entity_pb: An entity protobuf to add a new property to.
:type name: string
:param name: The name of the new property.
... | 4db8dd48eb0ac27c941c1a968b7f12ceb4c04b0c | 567,133 |
def read_wien2k_fermi(filename):
"""
Read the Wien2K .scf file and return the Fermi energy in units of Rydberg
The Fermi energy is given on lines starting with ":FER :". The .scf file
may contain multiple of such lines. We want to keep the last one and
extract the Fermi energy from that.
"""
... | c97518fb9c96f819812cd7696aa820eb42e83017 | 567,139 |
def makeGoodbyeUpdate(client_id):
"""
A default goodbye message to publish to the Pulsar topic
in case a client disconnection is detected
"""
return {
'messageType': 'player',
'playerID': client_id,
'payload': {
'x': None,
'y': None,
'h': F... | aa623abc3e5ee7a2890b3c492c29464b18536284 | 567,143 |
def get_accuracy_score(y_test, y_predict):
"""Get the accuracy score of the prediction
Args:
y_test ([type]): true values
y_predict ([type]): predicted values
Returns:
[float]: accuracy score
"""
assert(len(y_test) == len(y_predict))
n = len(y_test)
c = 0
for i,... | 9d81468763aae4d08b453407f5d4fc00183f1d21 | 567,147 |
def get_pairs(str):
"""Gets list of pairs from the string"""
pairs = []
for i in range(len(str) - 1):
pairs.append(str[i:i+2])
return pairs | 2e06a42a3ca0363cfdcafd0f9836ca6595316af0 | 567,149 |
from typing import Dict
def sets_to_lists(input_object: Dict):
"""
Converts sets to lists from a dictionary
"""
for attrib in input_object.keys():
if isinstance(input_object[attrib], set):
input_object[attrib] = list(input_object[attrib])
return input_object | f5b4ca10550bd6f46d9d620171b0c4e3c81e18be | 567,150 |
def assert_number_of_revolutions_not_negative(M):
"""
Checks if the number of revolutions is zero or positive, that is, it does
not have a negative value.
Parameters
----------
M: int
Number of revolutions
"""
if M < 0:
raise ValueError("Number of revolutions must be e... | 1cb64ad10a97bbaffe2f39d3aa9346db5af97001 | 567,157 |
def extend_unique(seq, more):
"""Return a new sequence containing the items in `seq` plus any items in
`more` that aren't already in `seq`, preserving the order of both.
"""
seen = set(seq)
new = []
for item in more:
if item not in seen:
seen.add(item)
new.append(... | a3151d41cf1d643b393e27f368841095631fac60 | 567,159 |
def moz_to_unix_timestamp(ts):
"""Convert Mozilla timestamp to Unix timestamp."""
try:
return ts // 1000000
except TypeError:
return 0 | e11558a7051885a19e168a446a869aa8ef9d8943 | 567,161 |
from typing import Dict
def dict_intersect(dict1: Dict, dict2: Dict) -> Dict:
"""takes two dictionaries as argument
and returns a dictionary that contains only the key/value pairs
found in both of the original dictionaries
>>> a = {'a': 1, 'b': 2, 'c': 3};
>>> b = {'b': 2, 'c': 5, 'd': 6, 'e': 7};... | d7faa8490ac020c293dc113c3747c06f83cef9bc | 567,162 |
def _t2n(x):
"""Convert torch tensor to a numpy array."""
return x.detach().cpu().numpy() | 22f4b26e889b93f442ae823abd38c1ff087c2816 | 567,167 |
import re
def gcs_join(path_segments, include_protocol=False):
"""Build a path using GCS path separators
Args:
path_segments - list of string path segments. May include file name.
include_protocol - if True, prepend 'gs://' protocol to path.
"""
if not path_segments:
raise ValueE... | c5ce356b6479784a14c1c05c2ad0fc5e5654d581 | 567,170 |
def encode(s: str) -> str:
"""
Turns all astral characters (code points U+10000 and bigger)
in string ``s`` into surrogate pairs:
a high surrogate (code points U+D800 to U+DBFF)
followed by a low surrogate (code points U+DC00 to U+DFFF).
"""
if not isinstance(s, str):
raise TypeError... | fae259acfb53d8e59858f8e7c4af72ce4ea49611 | 567,173 |
from typing import List
def are_qbits_adjacent(qbit_indices: List[int]) -> bool:
"""
Checks if qbit indices are adjacent.
:param qbit_indices: list of qbit indices.
:return: true if adjacent, false otherwise.
"""
if len(qbit_indices) == 1:
# Trivially true
return True
if l... | b15d27d1d06da46a6bc15f565b5aeee62e5e3503 | 567,174 |
def parse_boolean(s):
"""Parse an environment variable string into a boolean.
Considers empty string, '0', 'no', or 'false' (case insensitive) to be
``False``; all other values are ``True``.
"""
return s.lower() not in {'', '0', 'no', 'false'} | 046b144498c2c5738ac33085677abab0ff24ed8f | 567,175 |
def _do_not_recurse(value):
"""Function symbol used for wrapping an unpickled object
(which should not be recursively expanded).
This is recognized and respected by the instantiation parser.
Implementationally, no-op (returns the value passed in as an
argument).
Parameters
----------
v... | 7a68483470ae742df1ae1d41a1017f66a8cd161c | 567,176 |
def protein_file_stats_filename(setname):
"""Return the name of the protein stat file."""
if setname is None:
return "protein_files.tsv"
return f"{setname}-protein_files.tsv" | 250fa69591ad6210ed3abed629ef211c24a8bee5 | 567,177 |
def _table_create_query_var(model):
"""Returns the name of the variable to hold the model's table creation query"""
return '{}_TABLE_CREATE'.format(model.get_table_name().upper()) | fa6c37ee711df16a2cb2cf20db9575ee614f8b5a | 567,178 |
import logging
def create_standard_library_root_logger(library_root_package: str) -> logging.Logger:
"""
Creates a root logger for libraries. This is a logger
with a single null handler attached to it so that libraries
can be used without logging set up.
:param library_root_package: The packag... | 321219236647f58a665d5a0bbd8d78f05fff9137 | 567,181 |
def clones_k(module, N):
"""
>>> d = Dense(input_shape=(d_model,), units=d_model)
>>> d_list = clones_k(d, 4)
Parameters
----------
module: layer to be copied
N: number of copy
Returns
-------
"""
# return [copy.deepcopy(module) for _ in range(N)] # probability not worki... | 4813962defc36e767c8ba4f242061f61a37f83ad | 567,185 |
def pprint_timing(value):
"""Pretty-print timing data"""
RANGES = [("h", 3600), ("m", 60), ("s", 1), ("ms", 0.001), ("μs", 1e-6), ("ns", 1e-9)]
value += 1e-9 # CHEAT
for postfix, limit in RANGES:
if abs(value) >= limit:
return "{:.2f}{}".format(float(value)/limit, postfix).replace("... | a219ab7272636780bd4e9b678663a2db0348268b | 567,187 |
def create_position_alignment(alignment):
"""
Given an alignment with multiple sequences, assign ascending numbers
to the nucleotides of each sequence representing their positions.
Positions with gaps are skipped and assigned 0.
"""
position_alignment = []
for record in alignm... | 546bc6ec4cb5d4d99304a5b589068acc5a406f27 | 567,188 |
import re
def get_test_methods(f):
"""
Fetches all of the methods annotated with @Test in the given file.
Params:
f: The file object of the test file.
Return:
[str]: List of @Test-annotated methods by name.
"""
file_str = f.read()
method_pattern = r'@Test[\r\n\t ]*.+ (\w+)\(.*\)'... | 19bc5dc095aa52bab3525c107dd8db17d67f2f9b | 567,190 |
def distinct_series(df, keep="first"):
"""Verb: select distinct values from Series
Parameters
-----------
keep : which instance to keep in case of duplicates (see :meth:`pandas.Series.duplicated`)
"""
duplicated = df.duplicated(keep)
return df[~duplicated] | 174c7eee3315d8b6e91704633351b3e124a4b273 | 567,193 |
def check_positive_integer(name, value):
"""Check a value is a positive integer.
Returns the value if so, raises ValueError otherwise.
"""
try:
value = int(value)
is_positive = value > 0
except ValueError:
raise ValueError("%s should be an integer; got %r" % (name, value))
... | ce04f7690ba0ecfc3bd7048e4335f4db6eba83fa | 567,194 |
import math
def human_readable_size(bytes):
"""
Converts a size in bytes to a string containing a
human-readable size in KB/MB/GB etc.
"""
exp = int(math.log(bytes) / math.log(1024))
units = "kMGTPE"
pre = units[exp-1]
return "%.1f %sB" % (bytes / (1024**exp), pre) | 3523fc4acdeca36ee63d87af7e55386b6f327ed1 | 567,195 |
def subnetToDict(prefix, subnet):
"""
Generate a dict from a subnet using the specified prefix.
"""
return {
"%s_subnet" % prefix: subnet.network,
"%s_subnet_cidr" % prefix: subnet.cidr,
"%s_subnet_mask" % prefix: subnet.netmask,
"%s_subnet_gateway" % prefix: subnet.gatew... | 1bf1753706bee4dbd93d4f5235329b9ff1ce117f | 567,196 |
import re
def git_patch_ish(patch: str) -> str:
"""
Massage patch to look like a Git-style patch, so that it can
be passed to 'git patch-id' in order to calculate a patch-id.
:param patch: Patch to transform.
:return: Transformed patch.
"""
# Prettend as if format is 'diff --git'
patt... | 05b071b2448a800d5dbc5415588dfb1c3c31b4b8 | 567,199 |
def find_data_start(filename, lookup="\n", encoding="ISO-8859-1"):
"""
This function reads a .txt file and returns where it finds the first
newline. It was built to scan Nivek's measurement outputs and figure
out where the data actually starts and ignore all the metadata
parameters
-----------
filename: str
... | 1c9541bc2ac08ed14cc07fb35e79fa021d98f22e | 567,200 |
def shorten_replication_tasks(replication_tasks):
"""Returns only relevent fields form replication_tasks object """
tasks = []
for task in replication_tasks:
t1 = {
"ReplicationTaskIdentifier": task['ReplicationTaskIdentifier'],
"Status": task['Status'],
"Replicat... | 7da21d7276ff3cf476821a610b3f1c0a8495c190 | 567,202 |
import threading
def timeout(func, args=(), timeout_duration=2, default=None, **kwargs):
"""This will spwan a thread and run the given function using the args, kwargs and
return the given default value if the timeout_duration is exceeded
"""
class InterruptableThread(threading.Thread):
def __... | 06d96b2cd27ddaabe796f9d4a6ef5883056099e7 | 567,204 |
import re
def numberOfTracksInCommand(strCmd):
"""
Every track have a --language option count
them to know the number of tracks
Args:
strCmd(str): command line
Returns:
int:
total number of tracks
"""
reLanguageEx = re.compile(r"\-\-language (.*?)\s")
matchL... | aa7913d2f23bba044ae6a53f27b3be7ded196d6e | 567,206 |
def J_kg2Btu_lb(x):
"""J/kg -> Btu/lb"""
return x/2326.0 | a4eb8d4c97006372330505afd6e264798b248f23 | 567,209 |
def _get_day_of_month(x):
"""From a datetime object, extract day of month."""
return int(x.strftime('%d')) | 530a2b76ea2a24c051833b8983f6e54182a7e6e8 | 567,210 |
def get_games_between_dates(date, date_end, sql_engine):
""" Get dataframe of all games in [date, date_end) (note exclusive of date_end) """
sql_query = """
SELECT * FROM game_data WHERE "Date">='{date}' AND "Date"<'{date_end}' ORDER BY "Date";
""".format(date=date, date_end=date_end)
retu... | 6b8d62a1cd6eeb2fefb2a630912ec75d0674daaa | 567,213 |
def dict_list_search(l, keys, value):
"""
Search a list of dictionaries of a common schema for a specific key/value pair.
For example:
l = [{'a': foo, 'b': 1, 'c': 2}, {'a': 'bar', 'b': 3, 'c': 4}]
If `keys='a'` and `value='foo'` then the first dict in the list would be returned.
"""
v... | 568f34602813276ed39dd9f2b2f73e30fa8bef26 | 567,214 |
from itertools import islice
from typing import Iterable
from typing import Optional
from typing import Any
def nth(it: Iterable, n: int, default: Optional[Any] = None) -> Any:
"""
Returns the nth item or a default value
>>> nth(range(10), 5)
5
"""
return next(islice(it, n, None), default) | 1a6d01e57d008b588e1a7c071847107ca88b54e3 | 567,221 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.