content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def to_snake_case(text: str):
"""
Convert string to snake_case.
Example:
'Hi there!' -> 'hi_there_'
"""
return re.sub("\W+", "-", str(text)).lower() | c6d6962d4b5fa34f1bbe3cd762c9871cf4a5e3bd | 128,480 |
def hamming_distance(v1, v2):
"""
Get Hamming distance between integers v1 and v2.
:param v1:
:param v2:
:return:
"""
return bin(v1 ^ v2).count("1") | 1cc8ba3238e19fa6c1d8edec84b3ce7e00437a88 | 128,481 |
def generate_flow_control_parameters(rng):
"""Generate parameters related to flow control and returns a dictionary."""
configs = {}
configs["enableFlowControl"] = rng.choice([True, False])
if not configs["enableFlowControl"]:
return configs
configs["flowControlTargetLagSeconds"] = rng.randint(1, 1000)
configs["flowControlThresholdLagPercentage"] = rng.random()
configs["flowControlMaxSamples"] = rng.randint(1, 1000 * 1000)
configs["flowControlSamplePeriod"] = rng.randint(1, 1000 * 1000)
configs["flowControlMinTicketsPerSecond"] = rng.randint(1, 10 * 1000)
return configs | 604decc20edb49bb866ab4349b4371cd6163f3e4 | 128,486 |
def class_name(obj):
"""
Get the name of an object, including the module name if available.
"""
name = obj.__name__
module = getattr(obj, '__module__')
if module:
name = f'{module}.{name}'
return name | c6c8fbb72e9c122e87adaf4af458c57577308e6e | 128,494 |
def __get_request_headers(api_key: str) -> dict[str, str]:
"""Creates request headers for GitHub API."""
return {"Authorization": f"token {api_key}"} | 1c01d00e424def8a6a2eabc66100db1fadba443f | 128,502 |
def quatToConfig(quat):
"""
Shape a pinocchio.Quaternion as a list
:param quat: A Quaternion object
:return: a list containing the quaternion values (x, y, z, w)
"""
return [quat.x, quat.y, quat.z, quat.w] | ca63fadabebdbae9d57c16f23b853799ddd681e5 | 128,505 |
def compare_sub(got, expected):
""" Check if got subdomain of expected, throw exception if different. """
if not expected.is_subdomain(got):
raise Exception("expected subdomain of '%s', got '%s'" % (expected, got))
return True | d8a5cf41ce608fce226fef8a79d2900323ce51dd | 128,506 |
def transfer_seg_data(seg, traverse_queue):
"""Transfer data to child segments.
Description
----------
Transfers object information from current segment to
child segments and updates visited parent list. If all
parents visited then add to build network queue.
Parameters
----------
seg: obj
StreamSegment object.
traverse_queue: list
Start list of objects to process.
Returns
----------
traverse_queue: list
Updated list of objects to process.
This may or may not be the same as the input.
Notes
----------
In addition to returning the queue, segment objects are updated.
In building upstream network, children would be downstream segments.
In building downstream network, children would be upstream segments.
"""
# For each child of segment
for child in seg.children:
# Add seg's all parent list and seg to childs all parent list
child.all_parents.update(seg.all_parents)
child.all_parents[seg.xstrm_id] = seg
# Increase child's visited-parent-count by one
child.visited_parent_cnt += 1
# If child's visited-parent-count equals the number segments
# in child' parent list all of child's parent segments
# have been visited and child is inserted into queue
if len(child.parents) == child.visited_parent_cnt:
traverse_queue.append(child)
return traverse_queue | 15a3a32c2e1d4c5b5a2eb78432e288cf725ce1a2 | 128,515 |
def get_menu(options):
"""Get the string representation of a menu from the specified options
Assumes options is an ordered dictionary that maps strings (option)
to strings (name)
assumes option length + name length + 2 < 20
Return a string along these lines
each option must appear in order
[--------------------]
[1] option
... ...
[--------------------]
"""
border = '[%s]' % ('-'*20)
menu = border
for option, name in options.items():
space = ' ' * (20 - (len(option) + 2) - len(name))
menu += '\n\n [%s]%s%s' % (option, space, name)
menu += '\n\n%s' % border
return menu | 581e2203981e03b802637774679d6fbd96b48fbb | 128,518 |
from typing import Dict
def key_extractor(obj: Dict, key: str):
""" Extract a specific key from a dictionary
:param obj: the source dictionary
:param key: the key to extract in a string dot delimited format : key1.key2.subItem
:return: A dict/list if the key exists
:raises KeyError if the key is not valid
"""
if key == "":
return obj
keys = key.split('.')
for k in keys:
if k in obj.keys():
obj = obj[k]
else:
raise KeyError(f"{key} was not found in object !!")
return obj | 4409f22661b9009be5f93f87522aeedacadc1bf4 | 128,525 |
import requests
from bs4 import BeautifulSoup
def get_home_soup(home_rel_url):
"""
Accepts the relative URL for an individual home listing and returns a BeautifulSoup object.
:param home_rel_url: str. Relative URL string that can be appended to the root 'https://www.redfin.com'.
E.g. '/CA/Oakland/9863-Lawlor-St-94605/home/1497266'
:return: BeautifulSoup object for an individual listing's website.
"""
url = 'https://www.redfin.com' + home_rel_url
hdr = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=hdr)
assert response.status_code == 200, "HTML status code isn't 200 for {}.".format(home_rel_url)
return BeautifulSoup(response.text, "lxml") | 314664dfd321bc9628f45e1ba24372cb4cd3d4d0 | 128,527 |
import logging
def get_null_logger() -> logging.Logger:
"""
Get a logger that does nothing.
Useful for writing library functions where logging is optional.
:return:
"""
logger = logging.getLogger('_null')
if len(logger.handlers) == 0:
logger.addHandler(logging.NullHandler())
logger.setLevel(logging.CRITICAL)
return logger | 12b6c7b39d21bbdfb4cfe297cc11fdb95bd7a192 | 128,528 |
import math
def snake(state):
"""
Returns the heuristic value of b
Snake refers to the "snake line pattern" (http://tinyurl.com/l9bstk6)
Here we only evaluate one direction; we award more points if high valued tiles
occur along this path. We penalize the board for not having
the highest valued tile in the lower left corner
"""
snake = []
for i in range(4):
snake.extend(reversed(state.grid[:, i]) if i % 2 == 0 else state.grid[:, i])
m = max(snake)
return sum(x / 10 ** n for n, x in enumerate(snake)) - \
math.pow((state.grid[3, 0] != m) * abs(state.grid[3, 0] - m), 2) | 7e01ef5ddd29ffe870afa33eb5a2ccf7c9ddc47e | 128,531 |
def _get_deployment_preferences_status(function):
"""
Takes a AWS::Serverless::Function resource and checks if resource have a deployment preferences applied
to it. If DeploymentPreference found then it returns its status if it is enabled or not.
"""
deployment_preference = function.get("Properties", {}).get("DeploymentPreference", None)
if not deployment_preference:
# Missing deployment preferences treated as not enabled.
return False
return deployment_preference.get("Enabled", True) | db4e027cfe916427d0a20e342711de597e721a03 | 128,535 |
import torch
def kl_loss(mu, logvar):
"""
KL-Divergence = 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
:param mu: the mean from the latent vector
:param logvar: log variance from the latent vector
"""
KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return KLD | 283ac494834a7d60d39a37cb54e938ef1f50a94a | 128,536 |
def clean_text(raw_text):
""" Clean text by removing extra spaces between words
Args:
raw texts
Returns:
Cleaned text
"""
token_words = raw_text.split()
cleaned_text = ' '.join(token_words)
return cleaned_text | 5f7a8e913ee9bb96e1c5fb46363df369f654fb00 | 128,537 |
def pull_rows(client, dref, table_name, start_index=0, count=40000):
"""
Query count rows starting at index from table_name in dataset of
established bigquery client
client: bigquery client connection
dref: bigquery dataset reference
table_name: bigquery dataset table name
start_index: starting index of query
count: how many rows to query
Returns a list of bigquery row instances
"""
table_ref = dref.table(table_name)
table = client.get_table(table_ref)
results = [x for x in client.list_rows(table, start_index=start_index, max_results=count)]
return results | 21ff6903a216e7ba56ec1221bb4eed6645214016 | 128,538 |
def to_word(word):
"""
Convert an underscored key name into a capitalised word
"""
return word.replace("_", " ").capitalize() | ada8199ebc6c9047d3a0db43553cedf70fc46fd0 | 128,540 |
def make_error_msg(msg, sequence_name, img_idx, det_idx):
"""
Make an error message for a particular detection, so that the particular problem can be identified.
:param msg: The raw error message
:param sequence_name: The name of the sequence containing the detection
:param img_idx: The index of the image the detection was made on
:param det_idx: The index of the detection within that image
:return:
"""
return "{0}, image index {1}, detection index {2} : {3}".format(sequence_name, img_idx, det_idx, msg) | b013295a5886461af50f4842d5c935e4ee30c670 | 128,544 |
def _convert_to_farenheit(x):
""" Converts Celsius to Fahrenheit
Parameters
----------
x : float
Temperature in Celsius
Returns
-------
float
"""
return 1.8 * x + 32 | a5362556c15e3c3254640174e23976bbbf0a8e6d | 128,545 |
def as_tokens(values, max_len=20):
"""Return values as a set of tokens
>>> sorted(list(as_tokens(['this is a test', 'other', 'tokentoolongtobecapturedasis'])))
['a', 'is', 'other', 'test', 'this', 'tokentoolongtobecapt']
"""
tokens = set([
t[:max_len] for v in values
for t in v.lower().split()
])
return tokens | dd236866b57ccfe0b84baea6cfaa3cce58ea4280 | 128,548 |
def mydummy_to_number(context, builder, fromty, toty, val):
"""
Implicit conversion from MyDummy to int.
"""
return context.get_constant(toty, 42) | b7133a3423f59953006f35bfd509b92646d86ea7 | 128,549 |
def _normalize(url):
"""
Ensure that its argument ends with a trailing / if it's nonempty.
"""
if url and not url.endswith("/"):
return url + "/"
else:
return url | f49e73eeb63280eb54b40aef06ae688e5fafacf3 | 128,557 |
def _is_freezer(name):
""" returns true if the given name matches the freezer name """
return name.strip().lower() == 'freezer' | 04afed951bbf4e36b4f3c27df104fb39efa1e49b | 128,562 |
def getIndexPositionsThatStartWith(listOfElements, item):
""" Returns the indexes of all occurrences of give element in
the list- listOfElements """
indexPosList = []
for index in range(0, len(listOfElements)):
if listOfElements[index].startswith(item):
indexPosList.insert(len(indexPosList), index)
return indexPosList | 7ea2f89f561ee717f8cdd60d8f30a7b8eea09b3f | 128,567 |
def outer_product(l):
"""Produces the outer product of a list of lists.
Example:
>>> l = [[1, 2], [3, 4]]
>>> outer_product(l) == [[1, 3], [1, 4], [2, 3], [2, 4]]
If the number of lists is fixed, it is better to use a list comprehension
>>> [(e1, e2) for e1 in l1 for e2 in l2]
"""
def _expand(l, pos, result):
"""Recurses on `l` and produces all combinations of elements from the lists."""
for e in l[pos]:
result.append(e)
if pos == len(l) - 1:
yield result[:]
else:
for r in _expand(l, pos + 1, result):
yield r
result.pop()
return _expand(l, 0, []) | 7adcf2cbbf393045dea05898fca8ae2aab0ac3c2 | 128,569 |
def findEmpty(grid):
"""[Find next 0 in grid]
Args:
grid ([2D Array]): 2D Matrix to represent sudoku grid
Returns:
(Y,X): positon of next 0 in grid
False: if no 0 found
"""
for i in range(9):
for j in range(9):
if grid[i][j] == 0:
return (i,j) # returns a tuple in (Y,X) format
return False | 8c0cace6b15500bbdb9e67869d7d06dffe3a0c75 | 128,579 |
def _encode_asn1_utf8_str(backend, string):
"""
Create an ASN1_UTF8STRING from a Python unicode string.
This object will be an ASN1_STRING with UTF8 type in OpenSSL and
can be decoded with ASN1_STRING_to_UTF8.
"""
s = backend._lib.ASN1_UTF8STRING_new()
res = backend._lib.ASN1_STRING_set(
s, string.encode("utf8"), len(string.encode("utf8"))
)
backend.openssl_assert(res == 1)
return s | 1dde36f1df1e85f865ae00fb3d9f89448ccb1ae0 | 128,580 |
def _merge_strides(
lhs,
rhs
):
"""Merge two sets of strides.
Args:
lhs: A tuple (x, y) where each element is either an integer or None.
rhs: A tuple (x, y) where each element is either an integer or None.
Returns:
A merged tuple (x, y). For example:
* merge((1, 1), (None, None)) = (1, 1)
* merge((None, None), (None, None)) = None
* merge((1, 1), (2, 2)) triggers an error, since the two strides
are incompatible.
"""
if lhs[0] is not None and rhs[0] is not None and lhs[0] != rhs[0]:
raise ValueError('Stride mismatch: {} vs {}'.format(lhs, rhs))
if lhs[1] is not None and rhs[1] is not None and lhs[1] != rhs[1]:
raise ValueError('Stride mismatch: {} vs {}'.format(lhs, rhs))
x = lhs[0] if lhs[0] is not None else rhs[0]
y = lhs[1] if lhs[1] is not None else rhs[1]
return (x, y) | 63cfd6130578c94be68e4de29fb66446d78918d7 | 128,582 |
import pathlib
def make_dir(path: str) -> str:
"""Make a directory, along with parent directories.
Does not return an error if the directory already exists.
Args:
path (str): path to make the directory.
Returns:
str: path of the new directory.
"""
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
return path | f1a756835493c0f2d7638f39166337c808a6be77 | 128,601 |
def cen_to_feet(cen):
"""Converts centimetre to feet"""
return cen * 0.03281 | 988bbbe33899a49a1c59b39e695b2b35255fa093 | 128,606 |
def adjacent_lines_indexes(indexes):
"""Given a sequence of vertices indexes, return the indexes to be used with
GL_LINES_ADJACENCY in order to draw lines between them in a strip.\n
Example:
(0, 1, 2, 3) ->
(
0, 0, 1, 2,
0, 1, 2, 3,
1, 2, 3, 3
)
"""
assert len(indexes) >= 2
indexes = (indexes[0], *indexes, indexes[-1])
lines_idx = []
for line_idx in zip(*(indexes[i:] for i in range(4))):
lines_idx += line_idx
return lines_idx | 5f3359858b621423dc92e4c669ed4803b1afdcda | 128,612 |
import torch
def clip_npy_labels_by_time_step(features, labels, time_step):
"""Clip features in npy file and labels by time step, for example:
npy_shape[1000, 14, 2], labels_shape[1000], time step:100, clip
to npy_shape[900, 100, 14, 2], labels_shape[10, 100]."""
features = torch.from_numpy(features).float()
labels = torch.Tensor(labels)
x, y = features.shape[-2:]
feature_size = features.shape[0]
assert feature_size == labels.shape[0], "length of feture must " \
"equal length of labels, but got {} and {}.".format(feature_size, labels.shape[0])
# this is for random start time
features_list = []
labels_list = []
for i in range(feature_size - time_step):
features_list.append(features[i:i+time_step])
labels_list.append(labels[i:i+time_step])
features = torch.cat(features_list, 0).view(-1, time_step, x, y)
labels = torch.cat(labels_list, 0).view(-1, time_step)
return features, labels | 00fb5a832c38211822789419cf38520c24b318f3 | 128,615 |
def vec_compose(vecs, f):
"""
Compose a sequence of vectors using the given mapping function
Parameters
----------
vecs: list[]
A sequence of vectors with equal dimensions
f: callable
A function that performs the mapping f:vecs->composite,
where 'composite' is the resulting vector. The function
f(v1[i],...,vn[i]) is applied to all elements of the
n vectors for each point.
Returns
-------
list[]
The composite vector
"""
return [*map(f, *vecs)] | ff634832fdf5306c5c4791f13938dcfe35adb5d5 | 128,623 |
def identity(amplitude_values):
"""Return the identity of the amplitude values."""
return amplitude_values | 7a3a1a53197c432c1a1ec78918cbf3a7568a40c3 | 128,624 |
import importlib
def importFromString(pyurl):
""" Imports python module from the string argument """
return importlib.import_module(pyurl) | 353ba1f424d3af3836f6e50ea28e2cd06de6ea9c | 128,625 |
def transaction_user_validator(transaction_user_pid):
"""Validate that the given transaction user PID is valid."""
return transaction_user_pid == "user_pid" | 2203616095c2939e3b91dafde6bdf2094b229fba | 128,626 |
def minute_to_decimal(degree, minute, second):
"""
Change degree minute second to decimal degree
"""
return degree + minute / 60 + second / 3600 | c0605c486e2769d4b2f42dad8d6d8fd4ea661998 | 128,628 |
def chaffify(val, chaff_val = 25978):
""" Add chaff to the given positive integer. """
return val * chaff_val | 0c831113c5c1ede554fcba3e5062ed4c187dc9f2 | 128,630 |
def ge_quotient(left, right):
"""
Returns whether the left quotient is greater than or equal than the right
quotient.
Only works for quotients that have positive numerator and denominator.
"""
(a, b) = left
(c, d) = right
return a * d >= b * c | e9008179acf46249172e8705ff183a38d88f5ed0 | 128,632 |
import collections
def _counts(data):
"""Return a count collection with the highest frequency.
>>> _counts([1, 1, 2, 3, 3, 3, 3, 4])
[(3, 4)]
>>> _counts([2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5])
[(1.25, 2)]
"""
table = collections.Counter(iter(data)).most_common()
if not table:
return table
maxfreq = table[0][1]
for i in range(1, len(table)):
if table[i][1] != maxfreq:
table = table[:i]
break
return table | 6d37d78e16d1b00a36120714aae68182ce225930 | 128,633 |
def VerificaEntrada(num):
"""
Retorna um booleano dizendo se a entrada é válida
ou não, tendo em vista o número de dígitos
True --> Entrada Válida
False --> Entrada Inválida
"""
if num < 1000 or num >= 10000:
return False
else:
return True | 6a7a24446e2b65ee44378fd7acb684ec359f13f2 | 128,639 |
import plistlib
def read_from_string(s: bytes):
"""Read property list"""
result: dict = plistlib.loads(s)
return result | c15dad7bbf3931fdfcc0b5da8ab954767847c964 | 128,643 |
import math
def cos(x):
"""
El coseno de un número.
El ángulo debe estar expresado en radianes.
.. math::
\cos(x)
Args:
x (float): Argumento.
Returns:
El coseno.
"""
return math.cos(x) | b4110e72d571001ffe8b8535eb57cef7bd989f56 | 128,646 |
def AND(*expressions):
"""
Evaluates one or more expressions and returns true if all of the expressions are true.
See https://docs.mongodb.com/manual/reference/operator/aggregation/and/
for more details
:param expressions: An array of expressions
:return: Aggregation operator
"""
return {'$and': list(expressions)} | 4dc87b995a7132207e35a68dee1569fbde400c2a | 128,647 |
import pkg_resources
def get_package_versions(model=None):
"""Get the package versions for SDV libraries.
Args:
model (object or None):
If model is not None, also store the SDV library versions relevant to this model.
Returns:
dict:
A mapping of library to current version.
"""
versions = {}
try:
versions['sdv'] = pkg_resources.get_distribution('sdv').version
versions['rdt'] = pkg_resources.get_distribution('rdt').version
except pkg_resources.ResolutionError:
pass
if model is not None:
if not isinstance(model, type):
model = model.__class__
model_name = model.__module__ + model.__name__
for lib in ['copulas', 'ctgan', 'deepecho']:
if lib in model_name or ('hma' in model_name and lib == 'copulas'):
try:
versions[lib] = pkg_resources.get_distribution(lib).version
except pkg_resources.ResolutionError:
pass
return versions | f6ad43b665fe38bddbf31b38f2535b5435d15bda | 128,649 |
def countIncreasingNumbers(numbers: list[int]) -> int:
"""Method to count the number of times a number, in a list, increases over the previous entry."""
count: int = 0
for i, n in enumerate(numbers[1:]):
if n > numbers[i]:
count += 1
return count | 7818d3b7db74d62a08aede1fbf1efab3ed8da3a3 | 128,650 |
def parse_season_period(season_period_string):
"""Returns the season and period value from an id
Argument
--------
season_period_string : str
A string representation of the season_period_id
Returns
-------
tuple
A tuple of ``(season, period)``
"""
season, period = season_period_string.split("_")
season = int(season)
period = int(period)
return (season, period) | eb71e20a23a6f5679c5e3c4149db6b6a15bb8e64 | 128,651 |
def add_one(x):
"""
Add one to the input argument
:param x: The parameter to add
:return: The result after adding one
"""
return x + 1 | 4278035dc154b32dcfb120ca63d7d5b62bf1ee9c | 128,652 |
from datetime import datetime
def get_time_str(time_in: datetime = datetime.now()) -> str:
"""
Get time in string format.
Args:
time_in: datetime object to transform to string
"""
return time_in.strftime("%Y%m%d_%H%M%S") | ef25773424f482f04569e675500997331bd3e30f | 128,654 |
def num_windows_of_length_M_on_buffers_of_length_N(M, N):
"""
For a window of length M rolling over a buffer of length N,
there are (N - M) + 1 legal windows.
Example:
If my array has N=4 rows, and I want windows of length M=2, there are
3 legal windows: data[0:2], data[1:3], and data[2:4].
"""
return N - M + 1 | fb21140fad9800c2e7515707a24b52a67d62d6fb | 128,658 |
from typing import List
from typing import Tuple
from typing import Dict
from typing import Any
def make_trie(autocorrections: List[Tuple[str, str]]) -> Dict[str, Any]:
"""Makes a trie from the the typos, writing in reverse.
Args:
autocorrections: List of (typo, correction) tuples.
Returns:
Dict of dict, representing the trie.
"""
trie = {}
for typo, correction in autocorrections:
node = trie
for letter in typo[::-1]:
node = node.setdefault(letter, {})
node['LEAF'] = (typo, correction)
return trie | 0c9bd117d3e4f38eea8b3abcd07824f57ca13b37 | 128,661 |
def get_node_type(node):
"""
Get type of node
:param node: node of h5file
:return: node type name or None
"""
if 'type' in node._v_attrs:
return node._v_attrs.type.decode('UTF-8')
return None | 81cada208a42ae91e841992cae1bc9ea790c38ec | 128,662 |
import json
def load_json(file_name):
"""
Load the json file given the file name
"""
with open(file_name) as f:
data = json.load(f)
return data | 43afaf3dd53ba0923bf75e5d44f1ff7c60a8c2e7 | 128,673 |
def get_min_max_landmarks(feature: list):
"""
Get minimum and maximum landmarks from training set
:param feature: list of features
:return: min/max landmarks
"""
return feature[-6:-3], feature[-3:] | 604c9b947d67795fe9cfec25159b410b6a0f3453 | 128,674 |
def sort_012(input_arr):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Time Complexity O(n)
Space Complexity O(n)
Where n is the array size.
Args:
input_arr(array): Array to be sorted
Returns:
sorted_arr(array): Sorted array
"""
# Test that input_arr consists of digits between 0 and 9
for element in input_arr:
if element < 0 or element > 2:
return (-1, -1)
bin_zeros = []
bin_ones = []
bin_twos = []
for element in input_arr:
if element == 0:
bin_zeros.append(element)
elif element == 1:
bin_ones.append(element)
elif element == 2:
bin_twos.append(element)
sorted_arr = bin_zeros + bin_ones + bin_twos
return sorted_arr | 90b530727f389a125341865fb38b2d8ef4362420 | 128,675 |
def convert_hex(string_number):
""" Convert a string representing a number in base 2 in a string representing the same number in the base 16 """
return "{0:x}".format(int(string_number, 2)).zfill(4) | 9d4ee3e9d504bbb46fcb0116025e558426ffefd6 | 128,676 |
def formula2components(formula):
"""Convert a glass/any composition formula to component dictionary.
Parameters
----------
formula : string
Glass/any composition for e.g. 50Na2O-50SiO2.
Returns
-------
dictionary
Dictionary where keys are components of glass/any composition and values are their ratio.
"""
dict1 = {}
parts = formula.split('-')
if len(parts)==1:
dict1[parts[0]] = 1.0
else:
for i in parts:
k = ''
p = ''
for ind, j in enumerate(i):
try:
float(j)
p += j
except:
if j == '.':
p += j
else:
k = i[ind:]
break
dict1[k] = float(p)
if sum(dict1.values())==100:
for k,v in dict1.items():
dict1[k] = dict1[k]/100
return dict1
elif sum(dict1.values())==1.0:
return dict1
else:
try:
raise Exception("Invalid Formula: {}.".format(formula))
except Exception as e:
print(e)
raise | b6931b9cd470c8d2e378635d287c8e7be9b91f6e | 128,681 |
def isactive(context, url, active='active', inactive='', exact=False):
"""
A ternary tag for whether a URL is 'active'. An active URL is defined as matching
the current request URL. The default behavior is to match the beginning of the URL.
For example, if `url` is '/some/path' and the current request URL is
'/some/path/subpath', then the URL is considered active. If `exact` is set to True,
then the URL's must match exactly.
Example::
{% url 'named-url' as named_url %}
<div class="{% isactive named_url 'active' 'inactive' %}">
</div>
"""
request_url = context['request'].path_info
if (request_url == url if exact else request_url.startswith(url)):
return active
return inactive | 26a2eec610a06e7dc8c63b96d8442bf572da5115 | 128,685 |
def character_tokenizer(text: str) -> list:
"""Tokenize by single characters, keeping whitespace.
Args:
text: The text to tokenize.
Returns:
list: A list of character tokens.
"""
return [char for char in text] | c6806b488e2d39e2516baf7956d09bebc948a25f | 128,688 |
def _rotate_byte(byte, rotations):
"""Rotate byte to the left by the specified number of rotations."""
return (byte << rotations | byte >> (8-rotations)) & 0xFF | b2195b0fedda1b6f1969e422f474294b36c41db0 | 128,689 |
def get_noncentral_m3(mean: float, cv: float, skew: float) -> float:
"""Compute non-central third moment if mean, CV and skew provided.
"""
m1 = mean
std = cv * mean
var = std**2
return skew * var * std + 3 * m1 * var + m1**3 | 23e308e22bbdb04709b4da600a057f6583d61637 | 128,690 |
import re
def verify_kr_inner(peptide_seq):
""" verify if K or R feature within the peptide sequence
(an indicator of missed cleaveges)
"""
kr_inner = bool(re.search('K', peptide_seq[:-1])) or bool(
re.search('R', peptide_seq[:-1]))
return kr_inner | 9850033c9d045c9a51c90224e29ed9b6ef64244a | 128,692 |
def nothing(json):
"""Pass value without doing anything."""
return json | c0295f9ef52f3235f47e627f769a43593146c07c | 128,696 |
def MinPositiveValue(data):
"""
This function determines the minimum positive value of a provided data list
Input:
- *data*
Output:
- *minimum positive value*
"""
return min([elem for elem in data if elem > 0]) | 845aa2ac786d987f470f829e36737e43334dddc0 | 128,705 |
import csv
def ReadCollectedKeyboards(stream):
"""Parses collected keyboard list (CSV).
Args:
stream: An input stream.
Returns:
A frozeset of tuples (base_name, major, minor, revision).
"""
result = set()
reader = csv.DictReader(stream)
for row in reader:
result.add((row['base_name'], row['major'], row['minor'], row['revision']))
return frozenset(result) | c8e2a5e24f4d15c33cbe57d9947d5d0e99ba9aee | 128,708 |
def quote_message(msg: str) -> str:
"""
Prefixes each line with a '>'.
In makrdown this symbol denotes a quote, so Slack will render the message
wrapped in a blockquote tag.
"""
return "> ".join(msg.splitlines(True)) | bc86b03852aa7a9dc512a4f930445acb8cb89024 | 128,709 |
def map_(input_layer, fn):
"""Maps the given function across this sequence.
To map an entire template across the sequence, use the `as_fn` method on the
template.
Args:
input_layer: The input tensor.
fn: A function of 1 argument that is applied to each item in the sequence.
Returns:
A new sequence Pretty Tensor.
Raises:
ValueError: If the input_layer does not hold a sequence.
"""
if not input_layer.is_sequence():
raise ValueError('Can only map a sequence.')
return [fn(x) for x in input_layer] | 106bf89d6d765e9de26038920012e2082b140728 | 128,710 |
import re
def is_author(author: str, text: str, blame: str) -> bool:
"""Determine if an author authored the given text."""
for line in blame.splitlines():
if re.match(f".*{author}.+{text}", line):
return True
return False | d228695e66e8416b1d973352a7eabcb998e41d4f | 128,712 |
def _julian_century(jd):
"""Caluclate the Julian Century from Julian Day or Julian Ephemeris Day"""
return (jd - 2451545.0) / 36525.0 | 477f07e9106c09a2a54a5f279248a221f3729b4e | 128,713 |
from typing import Dict
from typing import Any
def filter_path_parameters(parameters: Dict[str, Any]) -> bool:
"""Single "." chars are excluded from path by urllib3.
In this case one variable in the path template will be empty, which will lead to 404 in most of the cases.
Because of it this case doesn't bring much value and might lead to false positives results of Schemathesis runs.
"""
return not any(value == "." for value in parameters.values()) | 03623a04a26c7cafcad5637afb5832dd01fea9f2 | 128,714 |
def _prepend_comments_to_lines(content: str, num_symbols: int = 2) -> str:
"""Generate new string with one or more hashtags prepended to each line."""
prepend_str = f"{'#' * num_symbols} "
return "\n".join(f"{prepend_str}{line}" for line in content.splitlines()) | 4645d72ed95beb91bc3d09231af61d698c66b784 | 128,716 |
def get_snapshot_with_keys(snapshots, keys):
""" Return the first snapshot that with the given subset of keys"""
sk = set(keys)
for s in snapshots:
if (sk.issubset(set(s.keys()))):
return s
return None | 5cbdab17b3847c321f548b1f3ffec466d8d56c91 | 128,725 |
from typing import Any
from typing import Dict
def list_instances(compute: Any, tf_vars: Dict, filter_expr: str) -> Any:
"""Get list of instances for this deployment matching the given filter."""
result = (
compute.instances()
.list(project=tf_vars.get("project_id"), zone=tf_vars.get("zone"), filter=filter_expr)
.execute()
)
return result["items"] if "items" in result else [] | a368f59799d09a53398f7a3a94aa999440930cff | 128,727 |
def key_parse(keystring):
"""
parse the keystring/keycontent into type,key,comment
:param keystring: the content of a key in string format
"""
# comment section could have a space too
keysegments = keystring.split(" ", 2)
keystype = keysegments[0]
key = None
comment = None
if len(keysegments) > 1:
key = keysegments[1]
if len(keysegments) > 2:
comment = keysegments[2]
return (keystype, key, comment) | 6c0003ebcb4a2fcbef1ebfcbf655996ef37d40bd | 128,731 |
def truthy(value: object) -> bool:
"""Return :py:const:`True` for truthy objects."""
return bool(value) | cb6a36f252f7961ba5ccbf269b96b8396b6d4c49 | 128,733 |
def annuity(A, r, g, t):
"""
A = annual payment
r = discount rate
t = time periods
returns present value
"""
return((A/r) * (1 - 1/((1+r)**t))) | 269fa5c964e8b35e684d419a8c8f10dc706f4738 | 128,734 |
import hashlib
def get_file_sha256(src_path: str, block_size: int = 2 ** 20) -> str:
"""Calculate the (hex string) hash for a large file"""
with open(src_path, 'rb') as f:
shasum_256 = hashlib.sha256()
while True:
data = f.read(block_size)
if not data:
break
shasum_256.update(data)
return shasum_256.hexdigest() | de88d1c7462e06443c2ac9b54b5c71051a631bf5 | 128,735 |
import optparse
def SimpointPhaseGroup(parser):
"""Define the group for options which apply to Simponts."""
group = optparse.OptionGroup(
parser, "Simpoint parameter options",
"These options define parameters which are used in the Simpoint phase (--simpoint).")
return group | 339d0835b38c54e83d405fd316f2d099ad185970 | 128,738 |
def filter_aws_headers(response):
"""Removes the amz id, request-id and version-id from the response.
This can't be done in filter_headers.
"""
for key in ["x-amz-id-2", "x-amz-request-id", "x-amz-version-id"]:
if key in response["headers"]:
response["headers"][key] = [f"mock_{key}"]
return response | f9f7f72f6063c6540dfb634cfef0a6623f8b5379 | 128,741 |
def getKeyIdx(key, key2Idx):
"""Returns from the word2Idx table the word index for a given token"""
if key in key2Idx:
return key2Idx[key]
return key2Idx["UNKNOWN_TOKEN"] | 0638c7bd9bc03ca74fa2aff826cf80dac15e3bd0 | 128,744 |
import random
def generate_vote(candidate_chances):
"""
returns a list of vote choices, votes are picked based on each candidate's chances of being voted for.
[(1, 'candidate_id'), (2, 'candidate_id'), (2, 'candidate_id'), ...]
Votes are generated by determining how many candidates a voter wants to pick.
At least one pass is made through the candidate_chance list (possibly picking more candidates than chosen but never
more than are available)
for each candidate, it is randomly determined if they will be picked that round. Every candidate picked in
each round will have the same rank number.
For example; candidate chances are:
[(0.3103760707038792, 1), (0.3368433989455909, 0), (0.40308497270067967, 4), (0.6070980766930767, 2), (0.7710239099894114, 3)]
Voter is determined to pick 3 candidates.
In the first round each candidate is checked
0.3103760707038792 rolls 0.1 and is picked at rank 1 (first round) - 2 remaining picks
0.3368433989455909 rolls 0.9 and is not picked
0.40308497270067967 rolls 0.3 and is picked at rank 1 - 1 remaining pick
0.6070980766930767 rolls a 0.5 and is picked at rank 1 - 0 remaining picks but not all candidates have been checked
0.7710239099894114 rolls a 0.6 and is picked at rank 1
Vote returned is [(1, 1), (1, 4), (1, 2), (1,3)]
"""
# vote for at least 1
nr_to_vote_for = random.randint(1, len(candidate_chances))
votes = []
rank = 1
while nr_to_vote_for > 0:
for c in candidate_chances:
if random.random() < c[0]:
votes.append((rank, c[1]))
nr_to_vote_for -= 1
if rank > 1 and nr_to_vote_for == 0:
break
rank += 1
return votes | b9cfd1f3f21910166f12ff419b0d1219beaf362c | 128,747 |
def stringify_value(v):
"""Converts a value to string in a way that's meaningful for values read from Excel."""
return str(v) if v else "" | 752742aeafecd8f90a381aaf3987ea24efb88cf6 | 128,748 |
def format_alert_message(raised_error, message):
"""
Formats error in the desired format
:param raised_error: Error that was raised
:param message: Message accompanying the error
:return: Formatted f-string
"""
return f"{raised_error}: {message}" | c0fc1a437bb16c5d9cfc5f83f92606f3968b74e8 | 128,752 |
import json
def get_predictions(inference_output):
"""
Load inference output as a python list
"""
predictions = []
for line in inference_output:
data = json.loads(line)
prediction = {}
for key, value in data.items():
if key != "SageMakerOutput":
prediction[key] = value
else:
if not isinstance(value, dict):
print("Error: Expected dictionary inside SageMakerOutput.")
prediction.update(value)
predictions.append(prediction)
return predictions | 132fe6471de0ef34d2498bf164cb0c39a273b82e | 128,755 |
def load_module_from_entry_points(entry_points, name):
"""Load module found via metadata entry points.
Args:
entry_points (list): List of entry points
name (str): Entry point's name
Returns:
Loaded Python module
"""
for entry_point in entry_points:
if entry_point.name == name:
return entry_point.load()
return None | 29a86385f8c368e1e9a74412fe16ff6b4e2578f1 | 128,762 |
import json
def dict_to_json(summary_result):
"""Function converts python dictionary to json format"""
return json.dumps(
summary_result, sort_keys=True, indent=4, separators=(',', ': ')) | 14e418cd2ca38aec5daa0d0b6596d2f503aa208b | 128,766 |
def users_same_init(users):
"""
Return a list of users that have inits that are the same.
Args:
users: A list of TurnUsers.
Returns:
Returns a list of different TurnUsers with the same init.
"""
inits = [x.init for x in users]
for init in set(inits):
inits.remove(init)
inits = list(set(inits))
return [x for x in users if x.init in inits] | 552a5271b752e482f438e100104ab34e257b973e | 128,769 |
from typing import Optional
from typing import Callable
from typing import Tuple
from typing import Any
from typing import Dict
import functools
import warnings
def deprecated_parameter(
*,
deadline: str,
fix: str,
func_name: Optional[str] = None,
parameter_desc: str,
match: Callable[[Tuple[Any, ...], Dict[str, Any]], bool],
rewrite: Optional[
Callable[[Tuple[Any, ...], Dict[str, Any]],
Tuple[Tuple[Any, ...], Dict[str, Any]]]] = None,
) -> Callable[[Callable], Callable]:
"""Marks a function parameter as deprecated.
Also handles rewriting the deprecated parameter into the new signature.
Args:
deadline: The version where the parameter will be deleted (e.g. "v0.7").
fix: A complete sentence describing what the user should be using
instead of this particular function (e.g. "Use cos instead.")
func_name: How to refer to the function.
Defaults to `func.__qualname__`.
parameter_desc: The name and type of the parameter being deprecated,
e.g. "janky_count" or "janky_count keyword" or
"positional janky_count".
match: A lambda that takes args, kwargs and determines if the
deprecated parameter is present or not. This determines whether or
not the deprecation warning is printed, and also whether or not
rewrite is called.
rewrite: Returns new args/kwargs that don't use the deprecated
parameter. Defaults to making no changes.
Returns:
A decorator that decorates functions with a parameter deprecation
warning.
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def decorated_func(*args, **kwargs) -> Any:
if match(args, kwargs):
if rewrite is not None:
args, kwargs = rewrite(args, kwargs)
qualname = (func.__qualname__
if func_name is None else func_name)
warnings.warn(
f'The {parameter_desc} parameter of {qualname} was '
f'used but is deprecated.\n'
f'It will be removed in cirq {deadline}.\n'
f'{fix}\n',
DeprecationWarning,
stacklevel=2)
return func(*args, **kwargs)
return decorated_func
return decorator | 0c47795491c384c58d1cfcf8cc73ad73f3f6bbe5 | 128,770 |
def create_searching_by_message(searching_by: str):
"""
Creates a message informing the user how something is being searched
:param searching_by: A string saying how something is searched
:return:
A title cased string in the format of 'Searching: {searching_by}' minus
any `-` characters
"""
# remove any `-` characters and title case
formatted_string = searching_by.replace('-', '').title()
return f'Searching: {formatted_string}' | 6c695b491f3558f2bdddc8b880662aa706fb9395 | 128,771 |
def convert_date(dict, date_key):
"""Convert dates to int or "NA" if missing."""
try:
date = int(dict[date_key])
except:
date = "NA"
return date | 89a54c0ea074b17e9325fa7170c24bd4853d63de | 128,772 |
def no_resize(packing, cell):
"""Don't do any resizing"""
return packing, cell | 4d50c6c5219c37bd848905788060cb5c096041d8 | 128,775 |
import ctypes
def ct_voidp(ptr):
"""Convert a SIP void* type to a ctypes c_void_p"""
return ctypes.c_void_p(int(ptr)) | ef6ed3d8d33090bf735917c0af6b5ecf72a8dc2e | 128,781 |
import unicodedata
def isNumber(s):
"""
Determines if a unicode string (that may include commas) is a number.
:param s: Any unicode string.
:return: True if s represents a number, False otherwise.
"""
s = s.replace(',', '')
try:
float(s)
return True
except ValueError:
pass
try:
unicodedata.numeric(s)
return True
except (TypeError, ValueError) as e:
pass
return False | df43f7e83cab485c48b21bdb221cb8804e98596a | 128,785 |
def syd(c, s, l):
""" This accountancy function computes sum of the years
digits depreciation for an asset purchased for cash
with a known life span and salvage value. The depreciation
is returned as a list in python.
c = historcal cost or price paid
s = the expected salvage proceeds
l = expected useful life of the fixed asset
Example: syd(1000, 100, 5)
"""
return [(c-s) * (x/(l*(l+1)/2)) for x in range(l,0,-1)] | f7491f58ed05ee6fd7485bfefe4758c1aa9f7d10 | 128,791 |
from typing import Union
from typing import List
import torch
def sequence_accuracy(sequences: Union[List[str], torch.Tensor],
target_sequences: Union[List[str], torch.Tensor]) -> float:
"""
What percentage out of the given sequences match the target sequences:
1 if A == B else 0 with A and B being strings or list of tokens
:param sequences: list of strings or tensor
:param target_sequences: list of strings or tensor
:return: mean accuracy over all pairs
"""
if isinstance(sequences, torch.Tensor):
sequences = sequences.tolist()
if isinstance(target_sequences, torch.Tensor):
target_sequences = target_sequences.tolist()
equal = [
sequence == target_sequence
for sequence, target_sequence in zip(sequences, target_sequences)
]
return sum(equal) / max(len(equal), 1) | c2726a199fb87472767b1c731339f3903c7b0390 | 128,796 |
def constrain_touch(touch):
"""Constrain touch values from the MDRNN"""
touch[0] = min(max(touch[0], 0.0), 1.0) # x in [0,1]
touch[1] = min(max(touch[1], 0.0), 1.0) # y in [0,1]
touch[2] = max(touch[2], 0.001) # dt # define minimum time step
return touch | 2391330305e0b56a50e50e34fbe858ed9293683d | 128,799 |
def get_dict_from_blast(file_name, subject_index):
"""Generate a dictionary from tabular BLAST (one-one) output"""
blast_dict = {}
with open(file_name) as file:
for line in file:
split_line = line.split()
blast_dict[split_line[0]] = split_line[subject_index]
return blast_dict | 676dd56f7a34e4a0b221c066e28222d7a5fa7757 | 128,800 |
def replace_labels_with_temps(contents: str, labels: dict) -> str:
"""
Replaces all labels that we don't know the location for with temporary addresses ($00000000)
:param contents: The string to replace labels
:param labels: The labels
:return: The string with labels replaced
"""
for label in labels.items():
contents = contents.replace(label[0], '($00000000).L')
return contents | a4ca80aa21e977c5d964f16e7cc2a533549bbac8 | 128,805 |
import time
def format_expiration_time(expires):
"""Format expiration time in terms of days, hours, minutes, and seconds.
Args:
expires (int): Absolute UNIX time.
Returns:
str: Human-readable expiration time in terms of days, hours, minutes,
and seconds.
"""
delta = int(expires - time.time())
if delta < 0:
return "Expired at " + time.asctime(time.localtime(expires))
days, r = divmod(delta, 86400)
hours, r = divmod(r, 3600)
minutes, r = divmod(r, 60)
seconds = r
if days > 0:
return "{} days, {} hrs, {} min, {} sec".format(days, hours, minutes, seconds)
elif hours > 0:
return "{} hrs, {} min, {} sec".format(hours, minutes, seconds)
elif minutes > 0:
return "{} min, {} sec".format(minutes, seconds)
else:
return "{} sec".format(seconds) | aa2bde94f2c90d35f541000d1a2d748056feeaa0 | 128,806 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.