content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
from typing import Union
from typing import Tuple
from typing import List
def get_subdomain(
x: int, y: int, subdomains: Union[str, Tuple[str], List[str]] = "abc"
) -> str:
"""
Returns a subdomain based on the position.
Subdomains help supporting more simultaneous tile requests.
https://github.com/Leaflet/Leaflet/blob/37d2fd15ad6518c254fae3e033177e96c48b5012/src/layer/tile/TileLayer.js#L222
Args:
x (int): X coord in the XYZ system.
y (int): Y coord in the XYZ system.
subdomains: List of letters made available by the tiles supplier.
Example:
* a string: "abcd" for subdomains a, b, c, and d
* or a tuple/list: ("10", "100", "101", "102", "103", "104", "20")
Returns:
str: One of the subdomain letter.
"""
return subdomains[abs(x + y) % len(subdomains)] | e68046572c28c6bdf7f240772a11e37137890a44 | 235,286 |
def boxes_iou(box1, box2):
"""
Returns the IOU between box1 and box2 (i.e intersection area divided by union area)
"""
# Get the Width and Height of each bounding box
width_box1 = box1[2]
height_box1 = box1[3]
width_box2 = box2[2]
height_box2 = box2[3]
# Calculate the area of the each bounding box
area_box1 = width_box1 * height_box1
area_box2 = width_box2 * height_box2
# Find the vertical edges of the union of the two bounding boxes
mx = min(box1[0] - width_box1/2.0, box2[0] - width_box2/2.0)
Mx = max(box1[0] + width_box1/2.0, box2[0] + width_box2/2.0)
# Calculate the width of the union of the two bounding boxes
union_width = Mx - mx
# Find the horizontal edges of the union of the two bounding boxes
my = min(box1[1] - height_box1/2.0, box2[1] - height_box2/2.0)
My = max(box1[1] + height_box1/2.0, box2[1] + height_box2/2.0)
# Calculate the height of the union of the two bounding boxes
union_height = My - my
# Calculate the width and height of the area of intersection of the two bounding boxes
intersection_width = width_box1 + width_box2 - union_width
intersection_height = height_box1 + height_box2 - union_height
# If the the boxes don't overlap then their IOU is zero
if intersection_width <= 0 or intersection_height <= 0:
return 0.0
# Calculate the area of intersection of the two bounding boxes
intersection_area = intersection_width * intersection_height
# Calculate the area of the union of the two bounding boxes
union_area = area_box1 + area_box2 - intersection_area
# Calculate the IOU
iou = intersection_area/union_area
return iou | 22735591c906af9592ce13fb76d7baa0a243c673 | 333,758 |
def non_empty(title: str, value: str, join_with: str = " -> ", newline=True) -> str:
"""
Return a one-line formatted string of "title -> value" but only if value is a
non-empty string. Otherwise return an empty string
>>> non_empty(title="title", value="value")
'title -> value\\n'
>>> non_empty(title="title", value=None)
''
"""
if value:
s = f"{title}{join_with}{value}"
if newline:
s = f"{s}\n"
return s
else:
return "" | fa7b2c332d72acf1f8b2196152504448b574d384 | 658,690 |
import time
import random
def printer(message: str) -> str:
"""
Prints a string to the stdout.
"""
# Use a random sleep to force printing order to be random, unless seq() is used.
time.sleep(random.random())
print(message)
return message | 0fe3972819aeb8999383b420cc8ea5c4933b9e91 | 233,764 |
import json
def get_inputs(sat: str):
"""Extacts arguments past the first from a function string
def f(a: Dict[int, str], b=12):
test
"""
sat = sat.replace(" -> bool", "")
first_line = sat.split("\n")[0].strip()
if "#" in first_line:
first_line = first_line[:first_line.index("#")].strip()
if not (first_line.endswith("):") and first_line.startswith("def")):
print("Weird puzzle, cannot extract inputs", json.dumps(sat))
return ""
arg_str = first_line[first_line.index("("):-len("):")]
depth = 0
for i, c in enumerate(arg_str):
if c == "," and depth == 0:
return arg_str[i + 1:].strip()
elif c == "[":
depth += 1
elif c == "]":
depth -= 1
return "" | 5114e068aa69e2d444b58d08747ca55a5cfbc6d9 | 517,392 |
import json
def format_errors(errors: dict) -> str:
""" Flattens a django validation error dictionary into a json string. """
messages = []
for field, field_errs in errors.items():
messages.extend([err["message"] for err in field_errs])
return json.dumps({"errors": messages}) | 70101c6d0458824b612ba2cd16a439c7aa35861b | 542,261 |
import torch
def top_k_accuracy(output, target, k=3):
"""
Function to calculate the top k accuracy of the model output.
Parameters
----------
output : multiple
Output of the neural network model
target : multiple
Ground truth value
k : int
Number of probablities required for the accuracy to be considered
Returns
-------
accuracy : float
Top k accuracy of the model output
"""
with torch.no_grad():
predictedValue = torch.topk(output, k, dim=1)[1]
assert predictedValue.shape[0] == len(target)
correct = 0
for i in range(k):
correct += torch.sum(predictedValue[:,i] == target).item()
return (correct/len(target)) | e834d4f3d9576ea334f9564999a0bc3c1bc55df1 | 323,358 |
def extract_data(stdout):
"""Extract data from youtube-dl stdout.
Args:
stdout (string): String that contains the youtube-dl stdout.
Returns:
Python dictionary. For available keys check self._data under
YoutubeDLDownloader.__init__().
"""
data_dictionary = dict()
if not stdout:
return data_dictionary
stdout = [string for string in stdout.split(' ') if string != '']
stdout[0] = stdout[0].lstrip('\r')
if stdout[0] == '[download]':
data_dictionary['status'] = 'Downloading'
# Get filename
if stdout[1] == 'Destination:':
data_dictionary['filename'] = ' '.join(stdout[2:])
# Get progress info
if '%' in stdout[1]:
if stdout[1] == '100%':
data_dictionary['speed'] = ''
data_dictionary['eta'] = ''
else:
data_dictionary['percent'] = stdout[1]
data_dictionary['filesize'] = stdout[3]
data_dictionary['speed'] = stdout[5]
data_dictionary['eta'] = stdout[7]
# Get playlist info
if stdout[1] == 'Downloading' and stdout[2] == 'video':
data_dictionary['playlist_index'] = stdout[3]
data_dictionary['playlist_size'] = stdout[5]
# Get file already downloaded status
if stdout[-1] == 'downloaded':
data_dictionary['status'] = 'Already Downloaded'
# Get filesize abort status
if stdout[-1] == 'Aborting.':
data_dictionary['status'] = 'Filesize Abort'
elif stdout[0] == '[ffmpeg]':
data_dictionary['status'] = 'Post Processing'
else:
data_dictionary['status'] = 'Pre Processing'
return data_dictionary | f34475135b006d57a6e5dcdc88a1277eaa20b81e | 448,132 |
def bit_bitlist_to_str(ordlist):
"""Given a list of ordinals, convert them back to a string"""
return ''.join(map(chr, ordlist)) | 7e36a2f5fa4e28ddb4bb909ce11c47761312fa27 | 358,367 |
def findMissing(aList, aListMissingOne):
"""
Ex)
Given aList := [4,12,9,5,6] and aListMissingOne := [4,9,12,6]
Find the missing element
Return 5
IDEA:
Brute force! Examine all tuples.
Time: O(n*m) and Space: O(1)
Smarter: Use a hashMap, instead!
Time: O(n+m) and Space: O(m)
"""
assert len(aList)-len(aListMissingOne) == 1
# n = len(aList)
# m = len(aListMissingOne)
# for i in range(n):
# for j in range(m):
# if (aList[i] == aListMissingOne[j]): break
# if (j == m-1): return aList[i]
_dict = {}
for i in range(len(aListMissingOne)): # O(len(aListMissingOne) + len(aList))
_dict[aListMissingOne[i]] = aListMissingOne[i]
for j in range(len(aList)):
if (aList[j] not in _dict): return aList[j]
return 'lists are permutations of each other' | df9241d0595831ac00e617b3bde023f341d1ea84 | 521,843 |
def filter_by_suffix(l, ignore, filter_dotfiles=True):
"""
Returns elements in `l` that does not end with elements in `ignore`,
and filters dotfiles (files that start with '.').
:param l: List of strings to filter.
:type l: list
:param ignore: List of suffix to be ignored or filtered out.
:type ignore: list
:param filter_dotfiles: Filter dotfiles.
:type filter_dotfiles: boolean, default True
:returns: List of elements in `l` whose suffix is not in `ignore`.
**Examples**
>>> l = ['a.txt', 'b.json', 'c.txt']
>>> ignore = ['.txt']
>>> filter_by_suffix(l, ignore)
['b.json']
"""
filter_list = [e for e in l if not sum([e.endswith(s) for s in ignore])]
if filter_dotfiles:
filter_list = [e for e in filter_list if not e.startswith('.')]
return filter_list | 9455c2514df1a53ac71d44e357ca944b3aecd8e7 | 490,324 |
from typing import Dict
from typing import Iterable
from typing import Any
def check_dictionary_keys(dictionary: Dict, required_keys: Iterable[Any], verbose: int = 0) -> bool:
"""
Check a dictionary for keys given an iterable of keys to check
Parameters
----------
dictionary : dict
The dictionary to check
required_keys : Iterable
An iterable of keys to check
verbose : int
Optional verbose setting. If non-zero, will print out missing keys
Returns
-------
Boolean
Return True if all keys present in dictionary else False
Example
-------
test_dict = {
'A': [1, 1, 1],
'B': ['foo', 'bar', 'banana'],
'C': [99.0, 23.5, 68.9]
}
print(check_dictionary_keys(test_dict, ['A', 'C']))
> True
"""
missing_keys = []
for key in required_keys:
if key not in dictionary.keys():
missing_keys.append(key)
if missing_keys:
if verbose > 0:
print(
f'Missing keys {missing_keys} not found in dictionary with keys {dictionary.keys()}')
return False
else:
return True | 215dd9acc9c15d7fae7e862528de5917e5b08c0c | 306,463 |
def behavior_get_required_inputs(self):
"""Return all required Parameters of type input for this Behavior
Note: assumes that type is all either in or out
Returns
-------
Iterator over Parameters
"""
return (p for p in self.get_inputs() if p.property_value.lower_value.value > 0) | 13063f7708d518928aed7556ca9da7a851de6622 | 691,091 |
def is_unauthorized_response(response):
"""Checks if a response is unauthorized."""
if response.status_code == 401:
response_content = response.json()
message = 'Authorization has been denied for this request.'
if 'message' in response_content:
if response_content['message'] == message:
return True
return False | 89359b32fa276a3fc14f0565cc91d73b22602a2d | 416,752 |
def prev(n, r):
"""The player after n."""
return (n - 1) % r.nPlayers | bdd1e398f6901c80b43c7e0f86668ca8870490f0 | 577,034 |
def map_to_range(min_1:float, max_1:float, min_2:float, max_2:float, value:float):
"""
This function maps a number of one range to that of another range.
Arguments:
min_1 : float/int : The lowest value of the range you're converting from.
max_1 : float/int : The highest value of the range you're converting from.
min_2 : float/int : The lowest value of the range you're converting to.
max_2 : float/int : The highest value of the range you're converting to.
value : float/int : The value that will be converted.
Example:
mapping a RGB value between 0 - 255 to a RGB value between 0 - 1
map_to_range(0, 255, 0, 1, 127.5) -> will return 0.5
"""
binary_range = (value - min_1) / (max_1 - min_1)
return binary_range * (max_2 - min_2) + min_2 | a70a1149390b49443a75283e9bfaa65981712ab6 | 291,995 |
def subsample_fourier(x, k):
"""Subsampling in the Fourier domain
Subsampling in the temporal domain amounts to periodization in the Fourier
domain, so the input is periodized according to the subsampling factor.
Parameters
----------
x : tensor
Input tensor with at least 3 dimensions, where the next to last
corresponds to the frequency index in the standard PyTorch FFT
ordering. The length of this dimension should be a power of 2 to
avoid errors. The last dimension should represent the real and
imaginary parts of the Fourier transform.
k : int
The subsampling factor.
Returns
-------
res : tensor
The input tensor periodized along the next to last axis to yield a
tensor of size x.shape[-2] // k along that dimension.
"""
N = x.shape[-1]
res = x.reshape(x.shape[:-1] + (k, N // k)).mean(axis=(-2,))
return res | 54c4af979f3fe2f8e439fa425b94dac7763ba76f | 117,344 |
def count_matching_pairs(arr, k):
"""
given a unique sorted list, count the pairs of elements which sum to equal k.
an element cannot pair with itself, and each pair counts as only one match.
:param arr: a unique sorted list
:param k: the target sum value
:return: the number of elements which sum to equal k
"""
forward_index = 0
reverse_index = len(arr) - 1
count = 0
# if the array is empty or contains only one value, no matches are possible
if reverse_index < 1:
return 0
while forward_index < reverse_index:
test_sum = arr[forward_index] + arr[reverse_index]
# we found a match, advance both the forward and reverse indexes
if test_sum == k:
count += 1
forward_index += 1
reverse_index -= 1
# test sum is too low, we need bigger numbers. advance forward_index
elif test_sum < k:
forward_index += 1
# test sum is too high, we need smaller numbers. advance reverse_index
elif test_sum > k:
reverse_index -= 1
return count | 5a566fba6bb5544056a2769a1ad4ca94c4ec07de | 344,077 |
from typing import Union
import re
def regex_iterator(text: str, regexes: Union[tuple, list]):
"""
Check a text string against a set of regex values
Parameters
----------
- text (str): a string to test
- regexes (Union[tuple, list]): a tuple/list of regexes
"""
result = None
for regex in regexes:
result = re.search(regex, text)
if result:
result = result.groups()
return result | 93b62b1bf4343c701cfa05f72accd453c4d38d0a | 152,456 |
def get_first_syl(w):
"""
Given a word w, return the first syllable and the remaining suffix.
"""
assert len(w) > 0
a = w[0]
n = 0
while n < len(w) and w[n] == a:
n = n + 1
return ((a, n), w[n:]) | a84c033582f89d1b4ec06983981696e17bdbefa6 | 92,213 |
def to_str(text, session=None):
"""
Try to decode a bytestream to a python str, using encoding schemas from settings
or from Session. Will always return a str(), also if not given a str/bytes.
Args:
text (any): The text to encode to bytes. If a str, return it. If also not bytes, convert
to str using str() or repr() as a fallback.
session (Session, optional): A Session to get encoding info from. Will try this before
falling back to settings.ENCODINGS.
Returns:
decoded_text (str): The decoded text.
Note:
If `text` is already str, return it as is.
"""
if isinstance(text, str):
return text
if not isinstance(text, bytes):
# not a byte, convert directly to str
try:
return str(text)
except Exception:
return repr(text)
default_encoding = (
session.protocol_flags.get("ENCODING", "utf-8") if session else "utf-8"
)
try:
return text.decode(default_encoding)
except (LookupError, UnicodeDecodeError):
for encoding in ["utf-8", "latin-1", "ISO-8859-1"]:
try:
return text.decode(encoding)
except (LookupError, UnicodeDecodeError):
pass
# no valid encoding found. Replace unconvertable parts with ?
return text.decode(default_encoding, errors="replace") | 74bcec023a7a8afea69c24a3dc2d7ae41247f461 | 627,731 |
import itertools
def itail(iterable):
"""Returns an iterator for all elements excluding the first out of
an iterable.
:param iterable:
Iterable sequence.
:yields:
Iterator for all elements of the iterable sequence excluding
the first.
"""
return itertools.islice(iterable, 1, None, 1) | df7f0ddabc493a3c9ae84b13e82208d7d05ef2e3 | 590,200 |
def scale(val, src, dst):
"""
Scale the given value from the scale of src to the scale of dst.
"""
return int(((val - src[0]) / float(src[1] - src[0])) * (dst[1] - dst[0]) + dst[0]) | c80aebd6a1b0162546eebd409cccb3d4cd073d9f | 538,392 |
from typing import List
from typing import Type
def validate_objects(elements: List, element_class: Type) -> bool:
"""
Check if all the elements are instance of the element_class.
Args:
elements: List of objects that should be instance of element_class.
element_class: class of the objects.
Returns:
True if all the elements are instance of element_class.
Raises:
ValueError if one element is not an instance of element_class.
"""
for element in elements:
if not isinstance(element, element_class):
raise ValueError(f"{element} is not a {element_class}")
return True | cd913ef4005d5360f8c2053ae30a72173e41d886 | 36,381 |
import re
def GetBackgroundColorTypeTagForTableValue(Color, ColorType):
"""Setup color type tage for setting background of a table value."""
ColorTypeTag = "class" if re.match("^colorclass", ColorType, re.I) else "bgcolor"
return ColorTypeTag | 6df7cb31b66ff38a228e618ee914281eee2da5b7 | 95,606 |
def _retrieve_start_nodes(net, mc):
"""
retrieve nodes with in_degree == 0 as starting points for main path analysis
args:
net: a CitationNetwork object
mc: minimum citations
returns:
list of start nodes in net
"""
return [node for node in net.nodes if (net.in_degree(node) == 0 and net.out_degree(node) > mc)] | ff31c50a16a24efa37fbe53f0ba4b7bd9195cb0d | 51,167 |
def inventory(testdir):
"""
Create minimal ansible inventory file (such file contains just
single line ``localhost``).
"""
inventory = testdir.makefile(".ini", "localhost")
return inventory | 8544e81fd960fc400eee51fd07d6434fa4c16175 | 544,580 |
def get_primary_key(model):
"""
Return primary key name from a model. If the primary key consists of multiple columns,
return the corresponding tuple
:param model:
Model class
"""
mapper = model._sa_class_manager.mapper
pks = [mapper.get_property_by_column(c).key for c in mapper.primary_key]
if len(pks) == 1:
return pks[0]
elif len(pks) > 1:
return tuple(pks)
else:
return None | 54daa5cde947d27b9b223d2b57062d44aea8d444 | 125,075 |
def to_rational(s):
"""Convert a raw mpf to a rational number. Return integers (p, q)
such that s = p/q exactly."""
sign, man, exp, bc = s
if sign:
man = -man
if bc == -1:
raise ValueError("cannot convert %s to a rational number" % man)
if exp >= 0:
return man * (1<<exp), 1
else:
return man, 1<<(-exp) | 3dccd2acc324d8b748fe95290c49d961f1c636e1 | 28,957 |
def list_ids(txtfile: str) -> set[str]:
"""
Return a set containing the identifiers presented in a file,
line by line, starting with ">"
"""
identifiers = set()
with open(txtfile, 'r') as fi:
for line in fi:
line = line.strip()
identifiers.add(str(line).replace('>', '')) #record.id excludes ">"
return(identifiers) | 888ca238b57350c25c10e16880d1b8e9d9066788 | 499,573 |
from typing import Iterable
from typing import Union
from functools import reduce
from operator import mul
def get_product_of_iterable(
_iterable: Iterable[Union[float, int]]
) -> Union[float, int]:
"""Method to get the product of all the enteries in an iterable"""
return reduce(mul, _iterable, 1) | 73416ac38d503d66e1e2e6c5e6ab9cd6ab735549 | 261,689 |
def get_uncert_dict(res):
"""
Gets the row and column of missing values as a dict
Args:
res(np.array): missing mask
Returns: uncertain_dict (dict): dictionary with row and col of missingness
"""
uncertain_dict = {}
for mytuple in res:
row = mytuple[0]
col = mytuple[1]
if uncertain_dict.get(row):
uncertain_dict[row].append(col)
else:
uncertain_dict[row] = [col]
return uncertain_dict | 336eebcd2fc64294ffe70a03988906eb29fca78c | 690,911 |
def select_from_view(view, targets):
"""
Identify the fragments of the view that contain
at least one of the targets
Args:
view (dict): if present, identifies the fragments that contain the
relevant units
targets (list): list of the fragments to search in the view
Returns:
list: fragments to select
"""
reselect = []
for frag in targets:
for key, val in view.items():
if frag in val and key not in reselect:
reselect.append(key)
break
return reselect | bb870cd4e3f57c2d626f4878f374cfedef2bba48 | 547,130 |
def single_dimensional_fitness(individual):
"""A simple single-dimensional fitness function."""
return pow(individual, 2) | 08e1573f8e7bed1f11fffedfdcbc1d69afc2a776 | 238,394 |
def join_with_last(items, sep=',', last_sep=' and '):
"""Join a sequence using a different separator for the last two items."""
if not items:
return ''
if len(items) == 1:
return items[0]
return ''.join([sep.join(items[:-1]), last_sep, items[-1]]) | fb52e35882dd4845cfe09b508063056ed4ccbbe8 | 317,639 |
def constant(connector, value):
"""the constraint that connector=value"""
constraint = {}
connector["set_val"](constraint, value)
return constraint | 36ff5a5da9be907b56b00bb10fa8a0817893913f | 349,705 |
def inject(variables=None, elements=None):
"""
Used with elements that accept function callbacks.
:param variables: Variables that will be injected to the function arguments by name.
:param elements: Elements that will be injected to the function arguments by name.
"""
def wrapper(fn):
fn.inject = {
'variables': variables or [],
'elements': elements or []
}
return fn
return wrapper | 9b7ad2679acb4e1a3e01b0191d0af96fb88cc2de | 684,564 |
def char_to_float(c: int, f_min: float = -100., f_max: float = 50.) -> float:
"""Translates char number ``c`` from -128 to 127 to float from ``f_min`` to ``f_max``.
Parameters
----------
``c`` : int
value to translate
``f_min`` : float, optional
(default is -100)
``f_max`` : float, optional
(default is 50)
Returns
-------
float
"""
f = f_min + (f_max - f_min) * (c + 128.) / 255.
return f | 4db07af994a4819495a10e274343aa5a0ed24a06 | 409,044 |
def expectation_description(expect = None, expect_failure = None):
"""Turn expectation of result or error into a string."""
if expect_failure:
return "failure " + str(expect_failure)
else:
return "result " + repr(expect) | 0a6944cbe83fbc14723526fd145ab816b86d2f0a | 642,839 |
def _check_state(monomer, site, state):
""" Check a monomer site allows the specified state """
if state not in monomer.site_states[site]:
args = state, monomer.name, site, monomer.site_states[site]
template = "Invalid state choice '{}' in Monomer {}, site {}. Valid " \
"state choices: {}"
raise ValueError(template.format(*args))
return True | 8f61c91ddae5af378503d98377401446f69c37db | 695,914 |
def crop_size(height, width):
"""
Get the measures to crop the image
Output:
(Height_upper_boundary, Height_lower_boundary,
Width_left_boundary, Width_right_boundary)
"""
## Update these values to your liking.
return (1*height//3, height, width//4, 3*width//4) | 67e98e069585e6bc73beff47ae984861a850b89b | 421,481 |
def get_bounds(points):
"""
Returns the min and max lat and lon within an array of points
"""
min_lat = float("inf")
max_lat = float("-inf")
min_lon = float("inf")
max_lon = float("-inf")
for point in points:
min_lat = point["lat"] if point["lat"] < min_lat else min_lat
min_lon = point["lon"] if point["lon"] < min_lon else min_lon
max_lat = point["lat"] if point["lat"] > max_lat else max_lat
max_lon = point["lon"] if point["lon"] > max_lon else max_lon
return {
"min_lat": min_lat,
"min_lon": min_lon,
"max_lat": max_lat,
"max_lon": max_lon
} | 5689e401ec8d51c88a38b0c0a3cbc334b305392b | 165,272 |
def gaussian_pdf(x: str = 'x', mean: str = r'\mu', variance: str = r'\sigma^2') -> str:
"""
Returns a string representing the probability density function for a Gaussian distribution.
**Parameters**
- `x`: str
The random variable.
- `mean`: str, optional
The mean of the random variable.
- `variance`: str, optional
The variance of the random variable.
**Returns**
- `out`: str
TeX compatible string.
"""
return r'\frac{1}{\sqrt{2\pi ' + variance + r'}}e^{-\frac{(' + x + '-' + mean + r')^2}{2' + variance + r'}}' | f5da3be1ee4676fadb32e9da989ff83d1b8114ef | 87,110 |
import hashlib
def sha3_384(s):
"""Compute the SHA3 384 of a given string."""
return hashlib.sha3_384(s.encode("utf-8")).hexdigest() | 8ab13d08fd01d8377d0bd283af338ce1a93dc3f6 | 430,804 |
def getanmval(pvec, B, Y, W):
"""
Return the SHD for a single time-frequency bin
:param pvec: Vector containing M-channel STFTs of a single time-frequency bin
:param B: Response equalisation matrix
:param Y: SHD matrix
:param W: Cubature matrix
:return: SHD for a single time-frequency bin; (N+1)^2 by 1
"""
anm = B * Y * W * pvec
return anm | 3f00b26829a0d54fcec8b1d206ff2879625ba32f | 367,705 |
def fixBadHtml(source):
"""
Takes bad html lists and puts closing tags on the end of each line
with a list tag and no closing tag.
"""
# process each line on it's own
source = source.split('\n')
newSource = []
for line in source:
line = line.strip()
# check if its a relevant line
# we know that only entries are li's
if '<li>' in line:
if not '</li>' in line:
line += '</li>'
newSource.append(line)
newSource = '\n'.join(newSource)
return newSource | 90085bc27269ada821c30f5675f5a147c55e9539 | 351,679 |
def cyclomatic_complexity(control_flow_graph):
"""Computes the cyclomatic complexity of a function from its cfg."""
enter_block = next(control_flow_graph.get_enter_blocks())
new_blocks = []
seen_block_ids = set()
new_blocks.append(enter_block)
seen_block_ids.add(id(enter_block))
num_edges = 0
while new_blocks:
block = new_blocks.pop()
for next_block in block.exits_from_end:
num_edges += 1
if id(next_block) not in seen_block_ids:
new_blocks.append(next_block)
seen_block_ids.add(id(next_block))
num_nodes = len(seen_block_ids)
p = 1 # num_connected_components
e = num_edges
n = num_nodes
return e - n + 2 * p | 5620c6715cb867c84b42128b0a15bdf7b6e2c7a7 | 460,100 |
import re
def get_cv_params(std_text):
"""accepts stdout generated by cross-validate, returns the "Best Model" Objects
for each validated fold as a list of lists of ints
Example output for a cv with four folds and s=24 might be
[[2, 0, 3, 2, 1, 0, 24],
[2, 0, 1, 2, 1, 0, 24],
[3, 0, 3, 0, 1, 1, 24],
[1, 0, 0, 0, 1, 1, 24]]"""
# build a match pattern that matches a string that looks like
# this: 'Best model: ARIMA(1,0,0)(0,1,1)[24]' from full contents of stdout
# containing the ARIMA parameters from each fold in a cv search
mod_pattern = re.compile(r'Best.*24]')
# Match the pattern against stdout
pat_list = (re.findall(mod_pattern, std_text))
# Find all digits in each param in pat_list, save as list of params
params = [re.findall(r'\d', pat_list[j]) for j, _ in enumerate(pat_list)]
# this is a bit complicated: but does a fairly simple thing:
# converts params from a list of lists filled with digits as individual strings of len 1
# to a list of lists filled with digits as ints. since s=24 is specified in our AutoArima pipe
# the last two digits are always 2 and 4, we fix this by converting them both to 24 and
# removing the last digit, converting a list like ['2', '0', '3', '2', '1', '0', '2', '4']
# to for example [2, 0, 3, 2, 1, 0, 24], which we can feed as SARIMA params
params = [[int(param[p]) if (p < len(param) - 2) else 24 for p,
_ in enumerate(param)][:-1] for param in params]
return params | c2d89ca99621ee2ce02a9026eafe4926a97876b1 | 385,121 |
import json
def read_ij_intensity (file):
"""Read a file that was written by the save_background.py ImageJ script.
Args:
file (str): Full path to .json file written by save_background.py
Returns:
intensity_data (dict): All data stored in the data file
"""
with open(file) as data_file:
intensity_data = json.load(data_file)
return intensity_data | c7a9296dc97d5e0329d647bb184a68afe6298bfa | 179,772 |
def _load_alphabet(filename):
"""
Load a file containing the characters of the alphabet.
Every unique character contained in this file will be used as a symbol
in the alphabet.
"""
with open(filename, 'r') as f:
return list(set(f.read())) | c1088ffbb558bd2e244b145bcc4fa29fa96d6234 | 264,641 |
def comma_separated_arg(string):
""" Split a comma separated string """
return string.split(',') | 5e4626501e72efe0edaf33b81ef334ecc73dbc5f | 284,265 |
import json
def dumps_tree(tree, duplicate_action = 'list', **kwargs):
"""
Dumps a Tree as json.dumps.
First converts to_python using duplicate_action.
Additional kwargs are sent to json.dumps.
"""
obj = tree.to_python(duplicate_action = duplicate_action)
return json.dumps(obj, **kwargs) | 3419ef28cce2c77605ec9fedca173dcbc7ed6b8b | 629,433 |
def does_need_adjust(change, next_value, limit):
"""Check if change of the next_value will need adjust."""
return change and (next_value - 1 < 0 or next_value + 1 >= limit) | 07dccd9e7af67dda38043b57acc8c6923f5db1fa | 474,721 |
import random
def sample_without_replacement(mylist: list):
"""
Pick a random name from a list
return the name and the list without that name
Args:
mylist (list): list of items to pick from
Returns:
name (str): random item from the list
mylist_copy(list): mylist with name removed
"""
mylist_copy = mylist.copy()
if len(mylist_copy) == 0:
return None
name = random.choice(mylist_copy)
mylist_copy.remove(name)
return name, mylist_copy | 2651135632ce1e072bbba076ca96f172981dc0ad | 602,663 |
import hashlib
import yaml
def det_hash(x):
"""Deterministically takes sha256 of dict, list, int, or string."""
return hashlib.sha384(yaml.dump(x).encode()).digest()[0:32] | 103c9844c1f59e085ae2747da49c505e166416d5 | 472,309 |
def doc_key(locale, doc_slug):
"""The key for a document as stored in client-side's indexeddb.
The arguments to this function must be strings.
"""
return locale + '~' + doc_slug | 39e9a794c0b8239b946d4c2e461fbd4949a8d171 | 498,923 |
import importlib
def import_module(module, package=None):
"""Protected import of a module
"""
try:
ret = importlib.import_module(module, package=package)
except ModuleNotFoundError:
if package is not None:
raise ModuleNotFoundError("Requested module/package '{}/{}' not found.".format(module, package))
raise ModuleNotFoundError("Requested module '{}' not found.".format(module))
return ret | bfc215aed80575c5802759fcbce4b2d48b4a6505 | 573,820 |
def tmp_working_directory_path(tmp_path) -> str:
"""
Return a path to a temporary working directory (different path for each test).
"""
destination = tmp_path.joinpath("obfuscation_working_dir")
destination.mkdir()
return str(destination) | 44a155ebc3b0c3bfe36b951dcdfb84180f108b79 | 626,492 |
import re
def get_job_details(job):
"""Given a Nomad Job, as returned by the API, returns the type and volume id"""
# Surveyor jobs don't have ids and RAM, so handle them specially.
if job["ID"].startswith("SURVEYOR"):
return "SURVEYOR", False
# example SALMON_1_2323
name_match = re.match(r"(?P<type>\w+)_(?P<volume_id>\d+)_\d+$", job["ID"])
if not name_match:
return False, False
return name_match.group("type"), name_match.group("volume_id") | 21afd0ac3fcdc1c320eefd9a84ee05a8a1f56ee7 | 139,763 |
def map_coords_to_scaled_float(coords, orig_size, new_size):
"""
maps coordinates relative to the original 3-D image to coordinates corresponding to the
re-scaled 3-D image, given the coordinates and the shapes of the original and "new" scaled
images. Returns a floating-point coordinate center where the pixel at array coordinates
(0,0) has its center at (0.5, 0.5). Take the floor of the return value from this function
to get back to indices.
"""
if not all(
isinstance(arg, (tuple, list, set)) for arg in (coords, orig_size, new_size)
):
raise TypeError(
"`coords`, `orig_size` and `new_size` must be tuples corresponding to the image shape."
)
if not all(len(arg) == len(coords) for arg in (orig_size, new_size)):
raise TypeError(
"Number of dimensions in `coords` ({}), `orig_size` ({}), and `new_size` ({}) did not match.".format(
len(coords), len(orig_size), len(new_size)
)
)
ratio = lambda dim: float(new_size[dim]) / orig_size[dim]
center = lambda s, dim: s[dim] / 2.0
offset = lambda dim: (coords[dim] + 0.5) - center(orig_size, dim)
new_index = lambda dim: (center(new_size, dim) + ratio(dim) * offset(dim))
return tuple([new_index(dim) for dim in range(len(orig_size))]) | f5e1e1523366a9e1e37f9d1a304d9deea8d53e00 | 9,346 |
from typing import List
from typing import Dict
def _missing_required_keys(
required_keys: List[str], found_keys: List[str]
) -> Dict[str, str]:
"""Computes an error message indicating missing input keys.
Arguments:
required_keys: List of required keys.
found_keys: List of keys that were found in the input.
Returns:
A dictionary with a pre-formatted error message.
Raises:
TypeError if either argument is not a list.
ValueError if all the required keys are present.
"""
if not isinstance(required_keys, list) and not isinstance(
found_keys, list
):
raise TypeError("argument must be a list type")
missing_keys = [key for key in required_keys if key not in found_keys]
if not missing_keys:
raise ValueError("there were no missing keys")
return {
"msg": "Required field(s) not found",
"data": (
f"'{missing_keys}' field(s) not optional. "
f"Found: {found_keys}. Required: {required_keys}"
),
"level": "critical",
} | e62adfd5be46a41728b83e944b56ea8c37063c49 | 391,759 |
def filter_keys(d, key_whitelist):
"""
Removes keys from a dictionary that are not
in the provided whitelist.
Args:
d: The dictionary to update.
key_whitelist: The list of allowed keys.
Returns:
The updated dictionary.
"""
for key in d.keys():
if key not in key_whitelist:
d.pop(key)
return d | 60c7892bd9582aca0f753b0feb8c9e4a20cffd7b | 439,942 |
def check_diagonal_winner(input_list, size):
"""
Check the winner number in diagonal direction.
Arguments:
input_list -- a two dimensional list for checking.
size -- the length for winning.
Returns:
winner -- the winner player number, if no winner return None.
"""
for row_idx, line in enumerate(input_list):
winner = ' '
try:
list_for_check = []
for i in range(size):
list_for_check.append(input_list[row_idx+i][i])
if list_for_check.count(list_for_check[0]) == size:
if list_for_check[0] != ' ':
return list_for_check[0]
except IndexError:
winner = ' ' | 01e87dcf163f3705238d554f36f92631da2175d9 | 279,189 |
def global_max_pool2d_check(expr):
"""Check if the nn.global_max_pool2d can be executed in BNNS"""
attrs, args = expr.attrs, expr.args
data_typ = args[0].checked_type
rank = len(data_typ.shape)
if rank < 3 or rank > 4 or data_typ.dtype != "float32":
return False
if attrs.layout != "NCHW":
return False
return True | d418dbc98b5a01327f90bec63b5bface10951ed8 | 380,216 |
def comp_slope_value(qvec):
"""
Returns the fixed point increment per unit increase in binary number.
"""
frac_width = qvec[1]
return 2.**(-frac_width) | 99c3699a9ac47d41e389e5544c0b6f2355c54bb7 | 468,913 |
def bool_to_string(bool):
""" Converts True / False into 'Yes' / 'No'
Returns:
string: 'Yes' or 'No'
"""
return 'Yes' if bool else 'No' | bce695263aaeccf5123c0d059dbdad336023bd1e | 552,939 |
def __hash_combine(h1, h2):
"""
Combine two hash values to create a new hash value
:param h1: int
:param h2: int
:return: int
"""
h1 = h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h2 >> 2))
return h1 | c388d03c9cf6f70096331f3e74c38716f192d23a | 211,640 |
def get_media_stream(streams):
"""Returns the metadata for the media stream in an MXF file,
discarding data streams."""
found = None
for stream in streams:
# skip 'data' streams that provide info about related mxf files
if stream['codec_type'] == 'data':
continue
if found:
raise UserWarning('Expected only one media stream per MXF.')
found = stream
return found | 563ef35c2be3e9787340d7527e7fd0f27b6db036 | 694,879 |
def isolate_path_filename(uri):
"""Accept a url and return the isolated filename component
Accept a uri in the following format - http://site/folder/filename.ext and return the filename component.
Args:
uri (:py:class:`str`): The uri from which the filename should be returned
Returns:
file_component (:py:class:`str`): The isolated filename
"""
# Look for the last slash
url_parse = uri.rpartition('/')
# Take everything to the right of the last slash and seperate it on the '.' if it exists, otherwise return the
# string as is
if '.' in url_parse[2]:
file_parse = url_parse[2].rpartition('.')
file_component = file_parse[0]
else:
file_component = url_parse[2]
return file_component | 5b04e36bc8a1b47c8b7af3892d083f73528e7391 | 584,425 |
import torch
def make_one_hot(position: int, length: int) -> torch.Tensor:
"""
Makes a 1D one hot vector of length l with a one at index position, rest all zeroes
Arguments:
position (int): index at which the one hot vector would have one
l (int): length of the one hot vector
Returns:
torch.Tensor
Usage:
make_one_hot(position=3, l=5) -> torch.Tensor([0, 0, 0, 1, 0])
"""
one_hot_vec = torch.zeros(length)
one_hot_vec[position] = 1
return one_hot_vec | 84c38438df4310a4c0c5cb7bcc830a49c142c221 | 173,788 |
def check_ascii_compliance(plaintext):
"""Returns true if all the characters of plaintext are ASCII compliant (ie are in the ASCII table)."""
return all(c < 128 for c in plaintext) | b8c3328793387baf78b8ce5b9a00499d51a37c1e | 587,075 |
def get_elapsed(begin, end):
"""
Return the number of minutes that passed between the specified beginning
and end.
"""
return (end - begin).total_seconds() / 60 | 08bfa2e3d0bfa63fca62d693894b6021f9092755 | 187,894 |
def footer(id1, id2 = None):
"""
Build SMT formula footer
Args:
id1 (str): ID of policy 1 in SMT formula
id2 (str, optional): ID of policy 2 in SMT formula. Defaults to None.
Returns:
str: SMT footer
"""
smt = '(assert {}.allows)\n'.format(id1)
if id2:
smt += '(assert (or {0}.denies {0}.neutral))\n'.format(id2)
smt += '(check-sat)\n'
smt += '(get-model)\n'
return smt | c9af2ad7453282e1611e7b2010f4269ca8ac0bc0 | 46,252 |
def _convert_sensor_enabled_flag_11_2(byte):
"""Convert the old sensor enabled flags to the new one."""
conversion_map = {0x01: 0x02, 0x02: 0x10, 0x04: 0x08, 0x08: 0x80} # gyro # analog # baro # temperature
# always enable acc for old sessions:
out_byte = 0x01
# convert other sensors if enabled
for old, new in conversion_map.items():
if bool(byte & old) is True:
out_byte |= new
return out_byte | f2f01f8756fa3f6ec8c766f85373fa9f977bd7db | 461,614 |
import re
def escape_regex(regex):
"""
Escape regex metachars so user does not have to backslash them on command line
:param regex: The regular expression to backslash metachars in
:return: Properly backslashed regular expression metachars in regex
"""
# src: https://stackoverflow.com/questions/4202538/escape-regex-special-characters-in-a-python-string
regex = re.escape(regex) ## This works better but regex is ugly in -v output
# regex = re.sub(r'([\.\\\+\*\?\[\^\]\$\(\)\{\}\!\<\>\|\:\-])', r'\\\1', regex)
return regex | e5cd00fb7fe57c3c1343dc870f7c1ed24888839b | 463,849 |
from typing import Optional
from typing import List
def _check_str_input(var, input_name: str, valid_options: Optional[List[str]] = None) -> str:
"""
_check_str_input
Convenience function to check if an input is a string. If argument valid_options is given, this
function will also check that var is a valid option from the valid_options specified.
Parameters
----------
var
the input variable to check
input_name : str
the name of the variable to include if an error is raised
valid_options: List[str], optional
a list of valid options for var
Returns
-------
str
the input var after lowering ans stripping the string
"""
if not isinstance(var, str):
raise ValueError("Invalid input {0} for {1}. Input {1} must be a string.".format(
var, input_name))
var = var.strip().lower()
if valid_options is not None:
valid_options = [option.strip().lower() for option in valid_options]
if var not in valid_options:
raise ValueError("Invalid input {0} for {1}. Input {1} must be one of the following "
"options: {2}.".format(var, input_name, valid_options))
return var | 357a8516fe65dddb35b7799ddc68b892da75ea02 | 147 |
def get_chunks(lo, hi, size, overlap=500):
"""
Divides a range into chunks of maximum size size. Returns a list of
2-tuples (slice_range, process_range), each a 2-tuple (start, end).
process_range has zero overlap and should be given to process_chromosome
as-is, and slice_range is overlapped and should be used to slice the
data (using get_window) to be given to process_chromosome.
"""
chunks = []
for start_index in range(lo, hi, size):
process_start = start_index
# Don't go over upper bound
process_end = min(start_index + size, hi)
# Don't go under lower bound
slice_start = max(process_start - overlap, lo)
# Don't go over upper bound
slice_end = min(process_end + overlap, hi)
chunks.append(((slice_start, slice_end), (process_start, process_end)))
return chunks | 1a0ddf94eef86127e260d1985dc7bbada973da47 | 425,208 |
def parse_mode(mode_data):
""" Takes in a mode string and parses out which are to be added and which
are to be removed.
>>> mode_data = "+ocn-Ct"
>>> parse_mode(mode_data)
('ocn', 'Ct')
"""
add = remove = ""
directive = "+"
for char in mode_data:
if char in ("+", "-"):
directive = char
elif directive == "-":
remove += char
elif char == " ":
continue
else:
add += char
return (add, remove) | e1893c1293807f78acb4a45767f1f4f8564e932b | 348,149 |
def get_info_or_create(source_dict, key, default_value):
"""
This returns the value of the key if it exists
else it creates the key with the default value and returns it
"""
try:
info = source_dict[key]
return info
except KeyError:
info = source_dict[key] = default_value
return info | 78c2e1768afac425fa04b533697ad70fa95f737c | 426,305 |
def get_func_pos_args_as_kwargs(func, pos_arg_values):
"""Get the positional function arguments as keyword arguments given their values"""
pos_arg_names = func.__code__.co_varnames[
1 : func.__code__.co_argcount
] # without the `step` argument
kwargs = dict(zip(pos_arg_names, pos_arg_values))
return kwargs | e12b78f78715a54589fa6be366144e2e6980d118 | 243,704 |
from functools import reduce
def _bigint_bytes_to_int(x):
"""Convert big-endian bytes to integer"""
return reduce(lambda o, b: (o << 8) + b if isinstance(b, int) else ord(b), [0] + list(x)) | 83d1b34b4e40b5e8a084eb0685020900adba88da | 365,891 |
def merge_caption(marker_dict):
"""Treat first value as a caption to the rest."""
values = list(marker_dict.values())
if not values:
return ''
elif len(values) == 1:
return values[0]
else:
return '{}: {}'.format(values[0], ' '.join(values[1:])) | 9e471fe7e161f1a8ff0f8051bc06398758c7c40d | 156,519 |
def add(number_1: int, number_2: int) -> int:
"""Adds two numbers together."""
return number_1 + number_2 | 65e730a7dea68324e9ec7e2d56238d84ab93158d | 486,142 |
def cmyk2rgb(C, M, Y, K):
"""CMYK to RGB conversion
C,M,Y,K are given in percent.
The R,G,B values are returned in the range of 0..1.
"""
C, Y, M, K = C / 100., Y / 100., M / 100., K / 100.
# The red (R) color is calculated from the cyan (C) and black (K) colors:
R = (1.0 - C) * (1.0 - K)
# The green color (G) is calculated from the magenta (M) and black (K) colors:
G = (1. - M) * (1. - K)
# The blue color (B) is calculated from the yellow (Y) and black (K) colors:
B = (1. - Y) * (1. - K)
return (R, G, B) | 47d076f90578ed76fd5e153690f3042b0eba3bc7 | 180,972 |
def rgb2bgr(x):
"""
Convert clip frames from RGB mode to BRG mode.
Args:
x (Tensor): A tensor of the clip's RGB frames with shape:
(channel, time, height, width).
Returns:
x (Tensor): Converted tensor
"""
return x[[2, 1, 0], ...] | c5672fe1290d641fede5395184be7b8d86e08d8f | 224,116 |
def a_r(P,R,M,format='days'):
"""
function to convert period to scaled semi-major axis.
Parameters:
----------
P: Period of the planet.
R: Radius of the star in units of solar radii.
M: Mass of star in units of solar masses
format: Unit of P (str). Specify "days" or "years"
Returns
-------
a_r: Scaled semi-major axis.
"""
AU_factor=1.496e8/(R*695510)
if format=='days':
P=P/365.
return P**(2/3.)*M**(1/3.)*AU_factor | 880bf9d2da6908f599a906c547ede016100aa080 | 247,721 |
def _maybe_parse_as_library_copts(srcs):
"""Returns a list of compiler flags depending on whether a `main.swift` file is present.
Builds on Apple platforms typically don't use `swift_binary`; they use different linking logic
(https://github.com/bazelbuild/rules_apple) to produce fat binaries and bundles. This means
that all such application code will typically be in a `swift_library` target, and that
includes a possible custom main entry point. For this reason, we need to support the creation
of `swift_library` targets containing a `main.swift` file, which should *not* pass the
`-parse-as-library` flag to the compiler.
Args:
srcs: A list of source files to check for the presence of `main.swift`.
Returns:
An empty list if `main.swift` was present in `srcs`, or a list containing a single
element `"-parse-as-library"` if `main.swift` was not present.
"""
use_parse_as_library = True
for src in srcs:
if src.basename == "main.swift":
use_parse_as_library = False
break
return ["-parse-as-library"] if use_parse_as_library else [] | 02d96244f892b7a68731e8bc9c451727dfa1636b | 465,151 |
import ast
def replace_fields(node, **kwds):
"""
Return a node with several of its fields replaced by the given values.
"""
new_kwds = dict(ast.iter_fields(node))
for key, value in kwds.items():
if value is not new_kwds[key]:
break
else:
return node
new_kwds.update(kwds)
return type(node)(**new_kwds) | bc37c0a6b24ffc1d2a2bcbd055efe26234909466 | 657,720 |
def warn_config_absent(sections, argument, log_printer):
"""
Checks if the given argument is present somewhere in the sections and emits
a warning that code analysis can not be run without it.
:param sections: A dictionary of sections.
:param argument: The argument to check for, e.g. "files".
:param log_printer: A log printer to emit the warning to.
"""
if all(argument not in section for section in sections.values()):
log_printer.warn('coala will not run any analysis. Did you forget '
'to give the `--{}` argument?'.format(argument))
return True
return False | a0c65f455a03624f69b2fd1b026ba88933226501 | 342,932 |
def yes_no_checker(string):
"""Gets user input, if yes returns True,
else if no, returns false"""
yes_list = ['yes', 'y', '1']
no_list = ['no', 'n', '0']
while True:
try:
answer = input(string)
if answer.lower() not in yes_list and answer.lower() \
not in no_list:
print('Please enter yes or no!')
continue
elif answer.lower() in yes_list:
return True
else:
return False
except Exception as e:
print(e) | c6e0c221d354cfe6a93f8b9bd09a776b1aeb9b4b | 571,188 |
from io import StringIO
import tokenize
def should_quiet(source: str) -> bool:
"""
Should we suppress output?
Returns ``True`` if the last nonwhitespace character of ``code`` is a semicolon.
Examples
--------
>>> should_quiet('1 + 1')
False
>>> should_quiet('1 + 1 ;')
True
>>> should_quiet('1 + 1 # comment ;')
False
"""
# largely inspired from IPython:
# https://github.com/ipython/ipython/blob/86d24741188b0cedd78ab080d498e775ed0e5272/IPython/core/displayhook.py#L84
# We need to wrap tokens in a buffer because:
# "Tokenize requires one argument, readline, which must be
# a callable object which provides the same interface as the
# io.IOBase.readline() method of file objects"
source_io = StringIO(source)
tokens = list(tokenize.generate_tokens(source_io.readline))
for token in reversed(tokens):
if token.type in (
tokenize.ENDMARKER,
tokenize.NL, # ignoring empty lines (\n\n)
tokenize.NEWLINE,
tokenize.COMMENT,
):
continue
return (token.type == tokenize.OP) and (token.string == ";")
return False | b4070a293c1cee002743c3ee2b79ccf1fdda99fc | 166,098 |
import re
def parse_country(text: str) -> list:
"""
Get covid data of each countries in the world
:param text: text to be parsed
:return: (country_name, confirmed, suspected, cured, dead, timestamp)
"""
pattern = re.compile(
r',\"provinceName\":\".*?\",.*?'
r'\"confirmedCount\":(.*?),.*?'
r'\"suspectedCount":(.*?),'
r'\"curedCount\":(.*?),'
r'\"deadCount\":(.*?),.*?'
r'\"countryFullName\":\"(.*?)\",'
)
result = pattern.findall(text)
for i, res in enumerate(result):
res = list(res)
n = res.pop()
n = re.sub(r'\xa0', ' ', n)
res.insert(0, n)
result[i] = tuple(res)
return result | c2a66092b617def6e221a2dc09c987c22ef050e0 | 341,236 |
def built_before(building, timestamp, player):
"""Get list of buildings constructed before a given time."""
result = []
for item in player['build']:
if item['building'] == building and item['timestamp'] < timestamp:
result.append(item)
return result | 4d7dd2fce525ad79713034c458bf2ef78459a27e | 612,601 |
def _is_dunder(function_name: str) -> bool:
"""Checks if a function is a dunder function."""
return function_name.startswith("__") and function_name.endswith("__") | c61a8d47a2e66acaf2c9dd9660cb758ef5959720 | 440,868 |
def attrs(m, first=[], underscores=False):
"""
Given a mapping m, return a string listing its values in a
key=value format. Items with underscores are, by default, not
listed. If you want some things listed first, include them in
the list first.
"""
keys = first[:]
for k in m.keys():
if not underscores and k.startswith('_'):
continue
if k not in first:
keys.append(k)
return ', '.join(["{0}={1}".format(k, repr(m[k])) for k in keys]) | 6c37a33233730c10ada96c162885f1277d1e38e6 | 519,104 |
def parse_raw_intervals(str_list):
"""Decode serialized CCDS exons.
Accepts a formatted string of interval coordinates from the CCDS
row and turns it into a more manageable list of lists with
(start, end) coordinates for each interval (exon).
.. code-block:: python
>>> parse_raw_intervals('[11-18, 25-30, 32-35]')
[[11, 18], [25, 30], [32, 35]]
Args:
str_list (str): A CSV string of (start, end) pairs, wrapped in '[]'
Returns:
list: 2D list with the start ``int``, end ``int`` pairs
"""
# remove the "[]"
csv_intervals = str_list[1:-1].replace(' ', '')
# 1. split first into exons coordinates
# 2. split into start, end and parse int
intervals = [[int(pos) for pos in item.split('-')]
for item in csv_intervals.split(',')]
return intervals | 9172297ff177d29c08a18d56aff5b40bd6ba5b2c | 316,637 |
def parseUnits(value, units):
"""
Parses a value with a unit and returns it in the base unit.
:param value: str The value to parse
:param units: list of tuples of unit names and multipliers
:return: int
"""
n = len(value)
for i, c in enumerate(value):
if c.isalpha():
n = i
break
numberStr = value[:n]
number = float(numberStr)
unitStr = value[n:]
for unit, multiplier in units:
if unitStr == unit:
return int(multiplier * number)
raise ValueError('Unknown unit "%s"' % unitStr) | e920ac498231e05cb05e312a6b9746d26aeebe6f | 271,167 |
def atomic_mass(a):
""" Atomic mass of atom """
return a.GetMass() | 02e66d924ecfa6918562f839cf6549de13ce698c | 215,408 |
def filterResultsByRunsetFolder(runSets, form):
"""
Filters out results that don't have the specified runsetFolder name
"""
ret = []
for runset in runSets:
if runset.runsetFolder == form['runset'].value:
ret.append(runset)
return ret | a9416fa8f96aa2dc370c23260f65bfb53114e09a | 694,760 |
def total_heat_sum_error(spf_heat_data):
"""Total values for heating and overall heating spf.
Uses heating operational data. Calculate total heat extracted from
ground and absolute error. Also calculates spf and fractional error.
Parameters
----------
spf_heat_data : pd.Dateframe
Heatpump operational data during heating.
Returns
-------
total_ground_heat : float
Total heat from ground in kWh.
total_gh_error : float
Absolute error of total heat from ground in kWh.
total_heat_spf : float
Heating spf.
ah_e_spf : float
Heating fractional uncertainity of SPF.
"""
# total heat from ground (kWh)
total_ground_heat = spf_heat_data['hfg'].sum()
# total heat from ground absolute error
total_gh_error = spf_heat_data['E_Q'].sum()
# heating spf for data period
total_heat_spf = ((spf_heat_data['heat_provided'].sum())
/ (spf_heat_data['electricity_kWh'].sum()))
# fractional heating error
fhe = total_gh_error/(spf_heat_data['heat_provided'].sum())
# fractional electric error
fee = spf_heat_data['E_w'].sum()/spf_heat_data['electricity_kWh'].sum()
# heating fractional uncertainity of the SPF for data period
ah_e_spf = ((fhe**2)+(fee**2))**0.5
return total_ground_heat, total_gh_error, total_heat_spf, ah_e_spf | c15c07c984a11b2732ee7ed47c6263db18156e10 | 647,073 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.