content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import random
def generate_axiom(alphabet='FXY'):
""" Generate a random axiom, using a specific alphabet """
return random.choice(alphabet) | 7c50dd00afbcc85f81ce166fc2e4ba1247e3aa5e | 123,517 |
def get_slope (points, i):
"""
Returns the slope at a certain point in %
Parameters
----------
points: list of points
i: point no to calculate slope from
"""
if i == 0 or points[i].distance_3d(points[i-1]) == 0:
return 0
return 100 * (points[i].elevation - points[i - 1].elevation) / points[i].distance_3d(points[i - 1]) | 08f369d921d203a84fc34610ff0cae68d90132e9 | 123,518 |
def convert_to_numpy(value):
"""
Converts the given Tensor to a numpy.
Parameters
----------
value : object
An object whose type has a registered Tensor conversion function.
Returns
-------
A value based on tensor.
Examples
---------
>>> import tensorlayerx as tlx
>>> x = tlx.ops.ones(shape=(10, 10))
>>> y = tlx.ops.convert_to_numpy(x)
"""
return value.numpy() | 354252d08a7ba03fb5237e077e14edd07784a2c8 | 123,519 |
def track_identifiers(tracks):
"""List criteria that identify a track"""
return [
identifier
for identifier in ["Condition", "Sample", "Tissue", "Track_ID", "Source"]
if identifier in tracks.dropna(axis=1).columns
] | aecd75c538a59019699405a64833dd1a19c345fa | 123,525 |
def mean_riders_for_max_station(ridership):
"""
Fill in this function to find the station with the maximum riders on the
first day, then return the mean riders per day for that station. Also
return the mean ridership overall for comparison.
This is the same as a previous exercise, but this time the
input is a Pandas DataFrame rather than a 2D NumPy array.
"""
overall_mean = ridership.values.mean()
max_station = ridership.iloc[0].argmax()
mean_for_max = ridership[max_station].mean()
return overall_mean, mean_for_max | 0542ed3675ac3fb5723e8b1852b66fa9b94b5457 | 123,527 |
import string
def no_emojis(s):
"""Return string without all emojis."""
return "".join(filter(lambda x: x in string.printable, s)).strip() | 0c950924f98d62382baadb3d3c81815bc40f3a6f | 123,531 |
def KSA(key: bytes) -> list:
"""
Key Scheduling algorithm
is the first process in rc4. It
returns an 'extended' key which
has a higher enthropy then the
simple concatenation.
params:
key: IV + Wi-Fi password
returns:
list of bytes, 'extended' key
"""
table = list(range(256))
y = 0
for x in range(256):
y = (y + table[x] + key[x % len(key)]) % 256
table[x], table[y] = table[y], table[x]
return table | 027bd1f2e8577929c8f82fa1a48c8ba57d9fa63b | 123,536 |
def nospines(left=False, bottom=False, top=True, right=True, **kwargs):
"""
Hides the specified axis spines (by default, right and top spines)
"""
ax = kwargs['ax']
# assemble args into dict
disabled = dict(left=left, right=right, top=top, bottom=bottom)
# disable spines
for key in disabled:
if disabled[key]:
ax.spines[key].set_color('none')
# disable xticks
if disabled['top'] and disabled['bottom']:
ax.set_xticks([])
elif disabled['top']:
ax.xaxis.set_ticks_position('bottom')
elif disabled['bottom']:
ax.xaxis.set_ticks_position('top')
# disable yticks
if disabled['left'] and disabled['right']:
ax.set_yticks([])
elif disabled['left']:
ax.yaxis.set_ticks_position('right')
elif disabled['right']:
ax.yaxis.set_ticks_position('left')
return ax | cd97d915b20a537ea83aefc864f9b199a6526a09 | 123,538 |
import re
import string
def wc(file_path):
"""
Count statistics for provided file:
count of lines in file
count of words in file
count of letters in file only in scope of string.ascii_letters
Args:
file_path (str): path to file
Return:
lines, words, letters: tuple of int
"""
with open(file_path, mode='r', encoding='utf-8') as fd:
lines = 0
words = 0
characters = 0
for line in fd:
lines += 1
words += len(re.findall(r'\b(\d*[a-zA-Z\']+\d*\w*)\b', line))
for letter in line:
if letter in string.ascii_letters:
characters += 1
return lines, words, characters | b2961ba2310770e6a524d9fb5741eef64915b9f7 | 123,543 |
import torch
import math
def affine_transformation_rotation_3d_z(angle_radian: float) -> torch.Tensor:
"""
Rotation in 3D around the y axis
See Also:
https://en.wikipedia.org/wiki/Rotation_matrix
Args:
angle_radian:
Returns:
4x4 torch.Tensor
"""
rotation = torch.tensor([
[math.cos(angle_radian), -math.sin(angle_radian), 0, 0],
[math.sin(angle_radian), math.cos(angle_radian), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
], dtype=torch.float32)
return rotation | 0b7416556b5ebbbda747442e5c0b7f20cc9bef02 | 123,546 |
def first(iterable):
"""Helper function, returns the first element of an iterable or
raises `IndexError` if the iterable is empty"""
for elem in iterable:
return elem
raise IndexError | e759376c567375f3cd55f4ebb0f7ff050ae7b36c | 123,547 |
import base64
def unprotect(match):
"""
Reverses protect().
"""
return '[[' + base64.b64decode(match.group(1)).decode() + ']]' | d610924ffd964aecf8a5217f44b9a73f20bbfed3 | 123,552 |
import click
def call_client_method(method, *args):
"""
Given a API client method and its arguments try to call or exit program
:param method: API client method
:param args: Arguments for method
:return: object from method call
"""
try:
return method(*args)
except Exception as e:
click.echo(str(e), err=True)
exit(1) | f5b1afddbb1c1ca7d5b3ce1ac8615d9674a7147a | 123,554 |
def success_probability_to_polarization(s, n):
"""
Maps a success probablity s for an n-qubit circuit to
the polarization, defined by p = (s - 1/2^n)/(1 - 1/2^n)
"""
return (s - 1 / 2**n) / (1 - 1 / 2**n) | d968effc171d69f26466ae0ecfac57333c70a23d | 123,556 |
def get_epoch_max_val_acc(data):
"""Gets the epoch with the highest validation accuracy.
Args:
data: Panda dataframe in *the* format.
Returns:
Row with the maximum validatin accuracy.
"""
df_val = data[data['data'] == 'validation']
return df_val[df_val['acc'] == df_val['acc'].max()] | cfa53edd023a9e3d2ca3e14aba672fc8fcf69bc4 | 123,557 |
def Clamp(num, a, b):
"""
Returns ``a`` if ``num`` is smaller than
or equal to ``a``, ``b`` if ``num`` is
greater than or equal to ``b``, or ``num``
if it is between ``a`` and ``b``.
Parameters
----------
num : float
Input number
a : float
Lower bound
b : float
Upper bound
"""
return min(max(num, a), b) | 2b66d62f8f795ecb4907436cb5c09b150abe9438 | 123,560 |
def verify_changed(source, result):
"""
Verify that the source is either exactly equal to the result or
that the result has only changed by added or removed whitespace.
"""
output_lines = result.split("\n")
changed = False
for line_nr, line in enumerate(source.split("\n")):
if line != output_lines[line_nr]:
changed = True
if line.strip() != output_lines[line_nr].strip():
raise IndentationError("Non-whitespace changes detected. Core dumped.")
return changed | 9e5f81664ca346b8ec202624537ad535255cb93d | 123,561 |
def session_ended_request_handler(handler_input):
"""
Purpose:
Handler for ending the session
Args:
handler_input (Dict): Input data from the Alexa Skill
Return:
alexa_reponse (Dict): Reponse for Alexa Skill to handle
"""
return handler_input.response_builder.response | 0d5aa4ccaf17fdc8d99a98a5bde08468707accf8 | 123,567 |
import time
def wait_for(condition, max_tries=60):
"""Wait for a condition to be true up to a maximum number of tries
"""
while not condition() and max_tries > 1:
time.sleep(1)
max_tries -= 1
return condition() | 59085cdfd308102c6c063ed13b9bc75014863163 | 123,568 |
def convert_blocking(blocking):
"""Converts a multi-type blocking variable into its derivatives."""
timeout = None
if not isinstance(blocking, bool):
timeout = float(blocking)
blocking = True
return blocking, timeout | 2e90e9120e0717c6cc88b686c02e54b3c0c8f3e3 | 123,571 |
def obsah_kruhu(r=42):
"""Vrati obsah kruhu o polomeru r"""
pi = 3.14
return pi*r*r | 6fb91e3f3e8cf1510da52f772c8969781c12a743 | 123,573 |
def find_max_min(integers):
"""Finds maximum and minumum number and return both of them as a list,
if all elements in list are equal, return the length of list
:param integers:
:return: min_and_max:
"""
min_and_max = []
min_number = min(integers)
max_number = max(integers)
if max_number == min_number:
min_and_max.append(len(integers))
else:
min_and_max.append(min_number)
min_and_max.append(max_number)
return min_and_max | e25ae4becca76c964ff89fd7859364d53f51a21a | 123,574 |
def _parse_locale(lang_code):
"""Parses language string to babel locale.
Args:
lang_code: String - language code, for example 'en', 'en-US'.
BCP 47 is expected: https://tools.ietf.org/html/bcp47
Returns:
parsed locale
"""
return lang_code.lower().split('-')[0] | d288ce148df5eedbefbc15b35ebf3e503b70bb88 | 123,575 |
def mode(numbers):
"""
Calculate mode of a list numbers.
:param numbers: the numbers
:return: mode number of the numbers.
>>> mode([1, 2, 2, 3, 4, 7, 9])
2
"""
max_count = 1
mode_number = numbers[0]
for number in numbers:
count = 0
for temp in numbers:
if temp == number:
count += 1
if count > max_count:
max_count = count
mode_number = number
return mode_number | e9fef87878b9aa4c378f4100928d815a96352fb5 | 123,579 |
def enumer(value):
"""
Conversion routine for enumeration values. Accepts ints or
strings.
:param str value: The value to convert.
:returns: A value of an appropriate type.
"""
try:
# Convert as an integer
return int(value)
except ValueError:
# Return the string unchanged
return value | d667096946afe81b2bab8d73e802a8dab3fc1c93 | 123,582 |
def bfs(graph, start):
"""
Breadth first search
Args:
graph (dict): graph
start (node): some key of the graph
Time: O(|V| + |E|)
"""
seen = set()
path = []
queue = [start]
while queue:
current = queue.pop(0)
if current not in seen:
seen.add(current)
path.append(current)
queue.extend(graph[current])
return path | a743ee4505eee2b378c141789429aea5944589c2 | 123,583 |
def lerp(start, stop, amt):
"""
Return the interpolation factor (between 0 and 1) of a VALUE between START and STOP.
https://processing.org/reference/lerp_.html
"""
return float(amt-start) / float(stop-start) | 03e905d555e1a2a915849d293d2e3258d3fd6baf | 123,587 |
def parse_arxiv_url(url):
"""
examples is http://arxiv.org/abs/1512.08756v2
we want to extract the raw id and the version
"""
_, idversion = url.rsplit('/', 1)
pid, ver = idversion.rsplit('v', 1)
return pid, int(ver) | 1e77327e0ef4e04b3908bf33c18f91691895e34f | 123,589 |
def convert_byte_dict_to_str_dict(inp: dict) -> dict:
"""
Convert dictionaries with keys and values as bytes to strings
Args:
inp: Dictionary with key and values in bytes
Returns:
Dictionary with key and value as string
"""
new_dict = dict()
for k, v in inp.items():
new_dict[k.decode()] = str(v.decode())
return new_dict | 8f91945d108bb9cabd4ac1ba1bc109fd7b43f097 | 123,590 |
import math
def cphase(c):
"""cphase(c): returns complex phase: (-pi, +pi]."""
return math.atan2(c.imag, c.real) | 6ff8207819d377bc8279d9f5efbf2123999650e3 | 123,592 |
def get_dependencies(line):
"""
Returns dependencies (list) of a Depends: line in a control file.
Those separeted by | are returned as a separate list.
Parameters
line : str, current line
"""
deps = line[9:].split(",")
alt = []
ind = []
for n, d in enumerate(deps):
# check for alternative dependencies
if "|" in d:
alt.extend(d.split("|"))
ind.append(n)
else:
# split at space to remove version numbers
deps[n] = d.split()[0]
for n in sorted(ind, reverse=True):
del deps[n]
return alt, deps | 1a18a294560d6fe9bbaaa5e62f3be96b73a23c7c | 123,594 |
def mock_wikipedia_random_page(mocker):
"""Mocks wikipedia.random_page"""
return mocker.patch("src.hypermodern_python_practice.wikipedia.random_page") | fbf4707d8e31b85cadda86b9b60e2906a04ef6d7 | 123,601 |
def ask_yes_no(question, repeat=True):
"""
Asks a question with answer YES/NO. Returns True if YES, False otherwise.
:param question - question to ask
:param repeat - if True, will repeat a question until either positive or negative answer given,
if False - any non-positive answer is treated as negative (no need to input exact negative answer, e.g.
"NO" or "N", etc.)
"""
print(question + ' [Y/N]: ', end='')
while True:
answer = input()
answer = answer.strip().lower()
if answer in ['y', 'yes']:
return True
if not repeat:
return False
if answer in ['n', 'no']:
return False
print('Please, enter either Y or N: ', end='') | 3d386610fe4fdac51c665faa04b78a2e1137e57b | 123,603 |
def construct_session_manager_url(instance_id: str, region: str = "us-east-1") -> str:
"""Assemble the AWS console session manager url with the current instance id and region."""
session_manager_url = f"https://{region}.console.aws.amazon.com/systems-manager/session-manager/{instance_id}?region={region}" # noqa: E501
return session_manager_url | 3c6d4f14f99623984f7c9646c2649c38fd0928bc | 123,608 |
from typing import Any
def set_attribute(obj: Any, attr: str, new_value: Any) -> bool:
""" Set an attribute of an object to a specific value, if it wasn't that already.
Return True if the attribute was changed and False otherwise.
"""
if not hasattr(obj, attr):
setattr(obj, attr, new_value)
return True
if new_value != getattr(obj, attr):
setattr(obj, attr, new_value)
return True
return False | 672abacc8cfbeeceb3c8e2e8df08bc7984e6ad69 | 123,613 |
def sod(n):
"""
Sum of digits.
>>> sod(123) # 1 + 2 + 3
6
"""
s = 0
while n:
s += n % 10
n //= 10
return s | ff63a5cadc3d7e610d304985fee99b303ed7e9d8 | 123,614 |
def _is_redirect(status_code):
"""Check if status code is redirect."""
return 300 <= status_code < 400 | cfafac406e6c26b46346c626aa8dfe3828fa1f2c | 123,615 |
import torch
def calc_square_dist(point_feat_a, point_feat_b, norm=True):
"""Calculating square distance between a and b.
Args:
point_feat_a (Tensor): (B, N, C) Feature vector of each point.
point_feat_b (Tensor): (B, M, C) Feature vector of each point.
norm (Bool, optional): Whether to normalize the distance.
Default: True.
Returns:
Tensor: (B, N, M) Distance between each pair points.
"""
length_a = point_feat_a.shape[1]
length_b = point_feat_b.shape[1]
num_channel = point_feat_a.shape[-1]
# [bs, n, 1]
a_square = torch.sum(point_feat_a.unsqueeze(dim=2).pow(2), dim=-1)
# [bs, 1, m]
b_square = torch.sum(point_feat_b.unsqueeze(dim=1).pow(2), dim=-1)
a_square = a_square.repeat((1, 1, length_b)) # [bs, n, m]
b_square = b_square.repeat((1, length_a, 1)) # [bs, n, m]
coor = torch.matmul(point_feat_a, point_feat_b.transpose(1, 2))
dist = a_square + b_square - 2 * coor
if norm:
dist = torch.sqrt(dist) / num_channel
return dist | 5badc1634868ecdb072b4b31dc6bf638f4d309b4 | 123,618 |
def find_closest(arr, val):
"""Return the closest value to val and its index in a 1D array.
If the closest value occurs more than once in the array, the index
of the first occurrence is returned.
Usage: closest_val, ind = find_closest(arr, val)
"""
diff = abs(arr-val)
ind = int(diff.argmin())
closest_val = float(arr[ind])
return closest_val, ind | bd626194d15115b6572b1bf0f6a31722e2276965 | 123,622 |
def doprefix(site_url):
"""
Returns protocol prefix for url if needed.
"""
if site_url.startswith("http://") or site_url.startswith("https://"):
return ""
return "http://" | fc53d4f9f113be79b68becec8b7332c96d779127 | 123,624 |
def get_xml(zip_file, file_path):
"""Reads in an XML file as UTF-8 from a zip file."""
with zip_file.open(file_path) as fp:
return fp.read().decode("utf-8") | e2f8ee6d40ca8698aadcab977ee24c10f032e392 | 123,625 |
def compound_cotes(f, x, interval, n):
"""
复合柯特斯公式
:param f: 原函数
:param x: 变量
:param interval: 积分区间
:param n: 将积分区间等分成n段
:return: 近似的积分值
"""
bottom, top = interval
step = (top - bottom) / n # 步长
X1 = [bottom + step * k for k in range(n + 1)] # 等距节点
half_step = step / 2 # 半步长
X2 = [x_num + half_step for x_num in X1[: -1]] # x下标为 k + 1/2 的所有节点
qtr_step = half_step / 2 # 四分之一步长
X3 = [x_num + qtr_step for x_num in X1[: -1]] # x下标为 k + 1/4 的所有节点
X4 = [x_num + qtr_step for x_num in X2] # x下标为 k + 3/4 的所有节点
res = 14 * sum([f.limit(x, x_num) for x_num in X1[1:-1]])
res += 12 * sum([f.limit(x, x_num) for x_num in X2])
res += 32 * sum([f.limit(x, x_num) for x_num in X3])
res += 32 * sum([f.limit(x, x_num) for x_num in X4])
res += 7 * (f.limit(x, bottom) + f.limit(x, top))
res *= step / 90
return res | 84c7923b2ccb070194026e31e6732919ed458be4 | 123,629 |
def calculate_fibonacci_number(n : int) -> int:
"""
Calculate and return the `n` th fibonacci number.
Args:
n (int) : specify term.
Exceptions:
- TypeError: when the type of `n` is not int.
- ValueError: when `n` is negative.
Note:
This solution obtains the answer by tracing from the target term to the first term.
0 1 1 3 ... A(n - 2) A(n - 1) A(n)
↑ ↑ ↓
`--------⊥------
WARNING:
This implementation increases function calls exponentially.
And this recomputes Fibonacci numbers that have already computed.
"""
if type(n) != int:
raise TypeError("`n` MUST be int but {} was passed.".format(type(n)))
if n < 0:
raise ValueError("`n` MUST be a natural but a negative is passed.")
if n == 0:
return 0
elif n == 1:
return 1
else:
return (calculate_fibonacci_number(n - 2) + calculate_fibonacci_number(n - 1)) | ae812418079d8b4c9756269da3a8dc62a8818969 | 123,632 |
def boolean(value):
"""
Converts string into boolean
Returns:
bool: converted boolean value
"""
if value in ["false", "0"]:
return False
else:
return bool(value) | ce5d434ec58f002032460e99857f29a00db10795 | 123,633 |
def L_v(t_air):
"""
Calculate latent heat of vaporization at a given temperature.
Stull, pg. 641
Args:
t_air (float) : Air temperature [deg C]
Returns:
lv : Latent heat of vaporization at t_air [J kg^-1]
"""
lv = (2.501 - 0.00237 * t_air) * 1e6
return lv | 54e707596746f91f03510445d3a85b904ed43b01 | 123,634 |
from pathlib import Path
def lrglob(self: Path, pattern=".*"):
"""Like path.rglob, but returns a list rather than a generator"""
return list(self.rglob(pattern)) | 0662b0d10b891790eb7a9d40d5daa2d6e6234f85 | 123,644 |
def array_identical(u, v):
"""
compares whether all elements are equal between two numpy arrays.
"""
if u.shape != v.shape:
return False
for a, b in zip(u.flat, v.flat):
if a != b:
return False
return True | 5ecdafcbadf3f13c309dc4b5b45eccc202ad3174 | 123,645 |
def empty(n):
"""
:param n: Size of the matrix to return
:return: n by n matrix (2D array) filled with 0s
"""
return [[0 for i in range(n)] for j in range(n)] | ef1303585fbc855a6f02a726440520343b6532e8 | 123,646 |
def makeContentType (mime, charset=None):
""" Create value of Content-Type WARC header with optional charset """
s = [mime]
if charset:
s.extend (['; charset=', charset])
return ''.join (s) | b6bac75b09e1edeefc2c24a6b785a9ebc3549424 | 123,652 |
import mimetypes
def guess_mime_type(filename):
"""Guess mime type based of file extension."""
if not mimetypes.inited:
mimetypes.init()
return mimetypes.guess_type(filename)[0] | 25b0422f5caf24f16caf8095bb4f7ef6b60c4c89 | 123,659 |
def graphic_progress( progress, columns ):
"""graphic_progress( progress, columns ) -> string
progress is a tuple of ( value, max )
columns is length of string returned
returns a graphic representation of value vs. max"""
value, max = progress
f = float(value) / float(max)
if f > 1: f = 1
if f < 0: f = 0
filled = int(f*columns)
gfx = "#" * filled + "-" * (columns-filled)
return gfx | 31024a9e5b977c992189f435054ee66899628313 | 123,660 |
import typing
def is_path(obj: typing.Any) -> bool:
"""
Is given object 'obj' a file path?
:param obj: file path or something
:return: True if 'obj' is a file path
"""
return isinstance(obj, str) | 95b6bc179c7620f1bcfcff3d45772145d4d66de6 | 123,664 |
def get_location(well_name, char2num):
"""
calculates for a well's name its row and column indices in an array that represents the plate.
Parameters
----------
well_name: str
the name of the well in the form "B - 02" when 2 is the column and B is the row
char2num: dict
A dictionary indicating the order of the different rows from left to right in the plate
Returns
-------
row, col : int
indices (starting count from zero) of the well in an array that represents the plate
"""
row = char2num[well_name[0]]
col = int(well_name[4:]) - 1
return row, col | 25b308d03e4f8befcdf1786cc357ab2939b1d64b | 123,666 |
import json
def create_patch_command(app, patch):
"""
Parameters
----------
app : `str`
The app to patch.
patch : `dict`
The patch dictionary containing the targetRevision change.
Returns
-------
`list`
The patch command to run.
"""
cmd = [
"argocd",
"app",
"patch",
f"{app}",
"--patch",
f"{json.dumps(patch)}",
"--type",
"merge",
]
return cmd | dbd1169a07ca7349fa4e263603e704055154595a | 123,673 |
def last_nondigit_index(s):
"""Returns the index of s such that s[i:] is numeric, or None."""
for i in range(len(s)):
if s[i:].isdigit():
return i
#if we get here, there weren't any trailing digits
return None | a57ae5cae3ae56a300d6de25632f7496d24daeab | 123,684 |
def datetime_to_iso8601(date_time):
"""Converts a date/time to an ISO8601 date string"""
assert not date_time.utcoffset()
return date_time.strftime('%Y-%m-%dT%H:%M:%S.%f') + 'Z' | 31af70fa64c4c050628f5ef28c32556d2a7abfe9 | 123,686 |
def pubmlst_schemas(pubmlst_file):
"""Read the PubMLST mappings and return a dict."""
pubmlst = {}
with open(pubmlst_file, 'rt') as pubmlst_fh:
for line in pubmlst_fh:
line = line.rstrip()
if line and not line.startswith('ariba'):
ariba, species, schema = line.split('\t')
if species not in pubmlst:
pubmlst[species] = {}
pubmlst[species][schema] = ariba
return pubmlst | dce6cdc92d2feef79654f02b0a82cb799deb5986 | 123,687 |
def add_heat(heatmap, bbox_list):
"""
Filter the found windows to combine overlapping detection.
Parameters:
heatmap: A zero-like NumPy array with the size of the image.
bbox_list: A list of bounding boxes.
"""
for box in bbox_list:
heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1
return heatmap | 90b4272a3667a3b7bc7f5e3fef7b02af888054fe | 123,688 |
def cropBorderFraction(img, crop_left=.1, crop_right=.1, crop_top=.1, crop_bot=.1):
"""
Crop a fraction of the image at its borders.
For example, cropping 10% (.1) of a 100x100 image left border
would result in the leftmost 10px to be cropped.
The number of pixels to be cropped are computed based on the original
image size.
"""
w, h = img.shape[0], img.shape[1]
nleft = int(round(crop_left * w))
nright = int(round(crop_right * w))
ntop = int(round(crop_top * h))
nbot = int(round(crop_bot * h))
return img[ntop:-nbot, nleft:-nright] | a3cabd88834f949c24bbb32021afa12b0891051b | 123,691 |
def callfunc(tup):
""" Function to ensure compatibility with Pool.map
"""
(ob, fun, args, kwds) = tup
return getattr(ob, fun)(*args, **kwds) | e3fa6aa5600f91990a5770a14953fa3840cbb677 | 123,697 |
def _generate_end_sequence(leds: int) -> bytes:
"""
Generate a byte sequence, that, when sent to the APA102 leds, ends a
led update message.
:param leds: number of chained LEDs.
:return: terminating byte sequence.
"""
edges_required = ((leds - 1) if leds else 0)
bytes_required = 0
output = bytearray()
# Each byte provides 16 clock edges, each LED except the first requires
# one clock edge to latch in the newly sent data.
if edges_required:
bytes_required = (((edges_required // 16) + 1) if (edges_required % 16)
else edges_required // 16)
for i in range(bytes_required):
output.append(0x00)
return bytes(output) | e5054bfb928a281c660ecdd14450ce189e3b520d | 123,701 |
def getFlatBufData(input_file):
"""
Collect fbuf data from input file and return.
"""
data = ""
with open(input_file, 'r') as _file:
data = _file.read()
return data | 3d24b934a7e13410ee24980476eecc3e55987664 | 123,702 |
def parse_resume_step_from_filename(filename):
"""
Parse filenames of the form path/to/modelNNNNNN.pt, where NNNNNN is the
checkpoint's number of steps.
"""
split = filename.split("model")
if len(split) < 2:
return 0
split1 = split[-1].split(".")[0]
try:
return int(split1)
except ValueError:
return 0 | 6d3530e7adf80efc27a2c8d9c14c398f4353b1b8 | 123,703 |
from xml.dom import minidom
def prettify(elem):
"""prettify
Args:
elem (Element): Element to be prettified
Returns:
str: prettified xml element
"""
x = minidom.parseString(elem)
# pretty = '\n'.join(x.toprettyxml().splitlines()[1:])
return x.toprettyxml() | d43de5762324f358a369ab8f438ab624f19df390 | 123,704 |
def check_syllabus_visibility(course, term, update=False):
"""For a specific course, check that course is:
- in this term and published
- has a syllabus visible to the institution (public_syllabus_to_auth)
or is otherwise public
"""
if course.enrollment_term_id != term:
return 0
if course.workflow_state != 'available':
return 0
problem_tabs = [t for t in course.get_tabs() if t.id == 'syllabus' and hasattr(t, 'hidden') and t.hidden == True]
if len(problem_tabs) > 0:
print("***", course.name, "has syllabus page hidden")
if course.public_syllabus_to_auth or course.public_syllabus:
return 0
print("-->", course.name, course.workflow_state, course.enrollment_term_id)
if update:
if not (course.public_syllabus_to_auth or course.public_syllabus):
course.update(course={'public_syllabus_to_auth':True})
return 1 | 8a13aa6039c2d58eba6ae42e3fce206e4ac50e1f | 123,705 |
def f_coef(k, Fs, N):
"""STFT center frequency
Notebook: C8/C8S2_SalienceRepresentation.ipynb
Args:
k (int): Coefficient number
Fs (scalar): Sampling rate in Hz
N (int): Window length in samples
Returns:
freq (float): STFT center frequency
"""
return k * Fs / N | 767721ed2a1e7771590466f3533cdabf79c1d88d | 123,706 |
def getFullUrlForGoogleSheet(sheetId, sheetName='repositories'):
"""Returns spreadsheet csv export compatible export url."""
return f'https://docs.google.com/spreadsheets/d/{sheetId}/gviz/tq?tqx=out:csv&sheet={sheetName}' | 18c13432ee73668531b78487ff6229476c023c79 | 123,707 |
def get_first(d, key):
"""Return value for d[key][0] if d[key] is a list with elements, else return d[key].
Useful to retrieve values from solr index (e.g. `title` and `text` fields),
which are stored as lists.
"""
v = d.get(key)
if isinstance(v, list):
return v[0] if len(v) > 0 else None
return v | 3d72ab4f5705df1065ced8348389c2bdf855bbbb | 123,711 |
import math
def _dist(i_node, j_node, dist_type) -> float:
"""Returns the distance between two nodes.
dist_type is either 'manhattan' or 'euclidean'
"""
if dist_type == 'manhattan':
return (abs(float(i_node['cx']) - float(j_node['cx'])) +
abs(float(i_node['cy']) - float(j_node['cy'])))
# otherwise assume euclidean
return math.sqrt(
(float(i_node['cx']) - float(j_node['cx']))**2 +
(float(i_node['cy']) - float(j_node['cy']))**2) | 3cc03d68e0b22aa03ab089562124604287a9d087 | 123,713 |
def hex2bytes(data: str):
"""Parse hexstring to bytes."""
return bytes.fromhex(data) | 2aaf8d4e8ff9b2083283727893ee9dc1e5686b4a | 123,717 |
def chrome_options(chrome_options, config):
"""Set Chrome options."""
if config.HEADLESS:
chrome_options.add_argument("--headless")
if config.USER_AGENT:
chrome_options.add_argument(f"user-agent={config.USER_AGENT}")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--no-default-browser-check")
chrome_options.add_argument("--no-first-run")
chrome_options.add_argument("--disable-default-apps")
chrome_options.add_argument("--disable-dev-shm-usage")
return chrome_options | 935f05bef830a8fb4e3011085f2be1922d663afa | 123,720 |
from datetime import datetime
def parse_windows_timestamp(qword):
"""see http://integriography.wordpress.com/2010/01/16/using-phython-to-parse-and-present-windows-64-bit-timestamps"""
return datetime.utcfromtimestamp(float(qword) * 1e-7 - 11644473600) | de21a39f3000049f09b7560e4cddedea8e8a332f | 123,724 |
def _instance_overrides_method(base, instance, method_name):
"""
Returns True if instance overrides a method (method_name)
inherited from base.
"""
bound_method = getattr(instance.__class__, method_name)
unbound_method = getattr(base, method_name)
return unbound_method != bound_method | ead33ec0f7c46cbf2f518b1659785aabcfd2f752 | 123,734 |
def compare_using_equality(span1, span2):
"""
Compare two spans and return true, if lower words in those spans are equal (stop words excluded)
Parameters
----------
span1: Span
First span to compare.
span2: Span
Second span to compare.
Returns
-------
tuple
Tuple with a flag indicating equality, and tokens of both spans matching
"""
for first_token in [t for t in span1 if not t.is_stop]:
for second_token in [t for t in span2 if not t.is_stop]:
if first_token.lemma_.lower() == second_token.lemma_.lower():
return True, first_token, second_token
return False, None, None | 2056635ac50bcb21e7b189c65e90d75c9de6b6c7 | 123,735 |
def _invert_indices(arr, range_max):
"""calculate all indices from range(range_max) that are not in arr
Args:
arr (list-like): array.
Returns:
list: list of complementary indices.
"""
inv = []
for j in range(range_max):
if j not in arr:
inv.append(j)
return inv | a2e13bad9500cf5f4d8180b5c9638846ef476185 | 123,740 |
import re
def strands(alt_string):
"""Extract strand orientation from ALT column of vcf file.
Args:
alt_string: ALT column of vcf file
Returns:
str: length 2 string with strand information. Returns None if alt_string doesn't match VCF spec of SVs.
"""
pp_pattern = re.compile(r'\D\].+\]')
pm_pattern = re.compile(r'\D\[.+\[')
mp_pattern = re.compile(r'\].+\]\D')
mm_pattern = re.compile(r'\[.+\[\D')
if pp_pattern.match(alt_string): return "++"
elif pm_pattern.match(alt_string): return "+-"
elif mp_pattern.match(alt_string): return "-+"
elif mm_pattern.match(alt_string): return "--"
return None | 88581b7eb3f8d866651130f47fae8c3a60be5711 | 123,745 |
def prepare_validation(cutted_image, patch_size, overlap_stepsize):
"""Determine patches for validation."""
patch_ids = []
D, H, W, _ = cutted_image.shape
drange = list(range(0, D-patch_size+1, overlap_stepsize))
hrange = list(range(0, H-patch_size+1, overlap_stepsize))
wrange = list(range(0, W-patch_size+1, overlap_stepsize))
if (D-patch_size) % overlap_stepsize != 0:
drange.append(D-patch_size)
if (H-patch_size) % overlap_stepsize != 0:
hrange.append(H-patch_size)
if (W-patch_size) % overlap_stepsize != 0:
wrange.append(W-patch_size)
for d in drange:
for h in hrange:
for w in wrange:
patch_ids.append((d, h, w))
return patch_ids | 2ee8556fa8d3ea33f8da8190393707069854157f | 123,748 |
def keys_to_ints(d):
"""
Takes a dict and returns the same dict with all keys converted to ints
"""
return {int(k): v for k, v in d.items()} | 17088f54c5808e42c0d6589cea8829c6819ccc7e | 123,750 |
def tiempo_a_segundos(dias: int, horas: int, mins: int, seg: int) -> int:
""" Unidades de tiempo a segundos
Parámetros:
dias (int): Número de dias del periodo de tiempo
horas (int): Número de horas del periodo de tiempo
mins (int): Número de minutos del periodo de tiempo
seg (int): Número de segundos del periodo de tiempo
Retorno:
int: Número de segundos al que equivale el periodo de tiempo dado como parámetro
"""
dias_a_horas = dias * 24
horas_a_minutos = (dias_a_horas + horas) * 60
minutos_a_segundos = (horas_a_minutos + mins) * 60
segundos_totales = minutos_a_segundos + seg
return int(segundos_totales) | bba94ec8128638e6aae96e932003a019b8ce0b5f | 123,756 |
def list_caps(payload):
"""Transform a list of capabilities into a string."""
return ','.join([cap["name"] for cap in payload["request"]["capabilities"]]) | e112678ff52f220ee1ebf394af90397a47ce9d3c | 123,758 |
from typing import Iterable
from typing import Any
from typing import Iterator
import itertools
def grouper(iterable: Iterable, n: int, fillvalue: Any = None) -> Iterator[tuple]:
"""Collect data into fixed-length chunks or blocks.
Based on the `grouper()` recipe at
https://docs.python.org/3/library/itertools.html#itertools-recipes
"""
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
# pylint: disable=invalid-name
args = [iter(iterable)] * n
# pylint: enable=invalid-name
return itertools.zip_longest(*args, fillvalue=fillvalue) | ab520d96a19b0a4039575631bb40168234f966ea | 123,762 |
def get_name(filename):
"""
Return the name of the file.
Given naming convention '<name>_<type>.<ext>' where none of the variables contains '_'.
"""
return filename.split('.')[0].split('_')[0] | 82910f2699c05a51ed5f2e42e841bd6f11dbd4f7 | 123,764 |
def parse_input_list(input_list, flag=True):
"""
Given a string with several elements, converts them into a list by splitting the string by ' ', ', ', or ','.
Args:
input_list: a string with multiple elements separated by a space, a comma or a comma+space
flag:
Returns:
list with the elements from the input.
"""
input_list = input_list.strip()
if input_list.find(', ') != -1:
parsed_list = input_list.split(', ')
elif input_list.find('; ') != -1:
parsed_list = input_list.split('; ')
elif input_list.find(' ') != -1:
parsed_list = input_list.split(' ')
elif input_list.find(',') != -1 and flag:
parsed_list = input_list.split(',')
elif input_list.find(';') != -1:
parsed_list = input_list.split(';')
else:
parsed_list = [input_list]
return parsed_list | 2d8f23b1e042aced27fa0135f7df9e2929aaa9ed | 123,766 |
import re
def es_diptongo(s: str, n: int = 2) -> bool:
"""Determina si una cadena es un diptongo (n=2).
:param s: cadena de caracteres
:s type: str
:param n: longitud, por defecto 2 (diptongo)
:n type: int
:return: True si es diptongo (n=2), False si no lo es
"""
regex = n * "[aeiou]"
return re.search(regex, s) is not None | d47387209b22cb5ef8119ebc6fd6d1abddc4651d | 123,775 |
import re
def is_local_path(value):
"""
Check if a path is absolute or depends on user or any other
SSH variable
"""
if re.findall(r'%[uh]', value):
return True
if re.findall(r'^/', value):
return False
return True | 8ea3b3fa2185f9eb8e876d852a5959fc9db37a6b | 123,778 |
def filter(key: str, value: str, index: dict):
"""Filter index by key value pair"""
return [i for i in index if i.get(key) == value] | 7f8a782cdb282c7d5e7a3f51ab8d188632ede9c9 | 123,782 |
def _tracking_uri(tracking_uri):
"""Helper function for URI shorthands.
Parameters
----------
tracking_uri: str
"file" will translate to `None`,
"localhost" to "http://localhost:5000", and
"localhost-2" to "http://localhost:5002".
Returns
-------
str or None
"""
if tracking_uri == "file":
tracking_uri = None
elif tracking_uri is not None and tracking_uri.startswith("localhost"):
split = tracking_uri.split("-")
port = 5000
if len(split) > 1:
port += int(split[1])
tracking_uri = "http://localhost:{}".format(port)
else:
tracking_uri = tracking_uri
return tracking_uri | 1e8239032d130cd22abeecd6b7fcd0ad7be02aa4 | 123,783 |
def is_palindrome(word):
"""
Checks if the given word is a palindrome or not. A palindrome is string
that reads the same if reversed like "madam" or "anna".
Parameters
----------
word: str
The word to be checked if it's a palindrome or not.
Returns
-------
bool:
A boolean verifying if the given word is a palindrome. `True` indicates
the given word is a palindrome. `False` indicates it's not.
Raises
------
AssertionError:
If the given word isn't a `str` object.
Example
-------
>>> is_palindrome("madam")
True
>>> is_palindrome("anna")
True
>>> is_palindrome("apple")
False
>>> is_palindrome("")
True
"""
assert type(word) == str
for i in range(len(word) // 2):
if word[i] != word[len(word) - 1 - i]:
return False
return True | 3fb0f7f58db56a27de6ce6375c6d7b68a6d525dd | 123,788 |
import requests
def get_wikidata_id(article):
"""Find the Wikidata ID for a given Wikipedia article."""
query_string = "https://de.wikipedia.org/w/api.php?action=query&prop=pageprops&ppprop=wikibase_item&redirects=1&format=json&titles=" + article
ret = requests.get(query_string).json()
id = next(iter(ret["query"]["pages"]))
return ret["query"]["pages"][id]["pageprops"]["wikibase_item"] | d7f0ac06645598c7703363990e924632f6608cbf | 123,789 |
from typing import Dict
def parse_benchmark_commandline(commandline: str) -> Dict[str, str]:
""" Parse the benchmark example command-line string into a dictionary of command-line arguments
"""
# Separate the data type option from the example_args portion of the string
commandline = commandline.replace(",--type=", " --type=")
args = commandline.split()
# Discard program name
args = args[1:]
# Split into a list of (argument name, argument value)
args = map(lambda arg: arg.split("="), args)
def transform(_name):
# Strip '-'/"--" if it exists
_name = _name.lstrip("-")
return _name
return {transform(name): val for name, val in args} | 7987b3227a60751c4d30de56115af7f8daa4f660 | 123,790 |
from datetime import datetime
import time
def datetime2timestamp(datetime_=None):
"""
Convert local datetime to unix timestamp
"""
if datetime_ is None:
datetime_ = datetime.now()
if not isinstance(datetime_, datetime):
return 0
return datetime_ and int(time.mktime(datetime_.timetuple())) | 18860b0d231d54f5499b8b9aa463b1056976d912 | 123,793 |
import json
def to_json(objs):
"""
Convenience method for returning am object as JSON
:param objs: any python dictionary though meant for one generated
by YamlStratus
:rtype: string in JSON format
"""
return json.dumps(objs, sort_keys=True, indent=4, separators=(',', ': ')) | ec7450bebd78c32f922454b54fc53bf9686371ab | 123,794 |
def _create_subscript_in(atom, root):
""" Find / create and insert object defined by `atom` from list `root`
The `atom` has an index, defined in ``atom.obj_id``. If `root` is long
enough to contain this index, return the object at that index. Otherwise,
extend `root` with None elements to contain index ``atom.obj_id``, then
create a new object via ``atom.obj_type()``, insert at the end of the list,
and return this object.
Can therefore modify `root` in place.
"""
curr_n = len(root)
index = atom.obj_id
if curr_n > index:
return root[index]
obj = atom.obj_type()
root += [None] * (index - curr_n) + [obj]
return obj | b4a0dc9fc143dff89a77afd6c4de7bd12d9e64e9 | 123,795 |
import torch.nn.functional as F
import torch
def get_class_count(box_class, n_class=-1):
"""
Return a tensor where each element of the last dimension represent a class and its value is the number of
bounding boxes with given class.
:param box_class: A [*, d1] tensor
:param n_class: Total number of classes
:return: A [*, n_class] tensor
"""
class_one_hot = F.one_hot(box_class, num_classes=n_class)
class_one_hot = torch.transpose(class_one_hot, dim0=-1, dim1=-2)
return class_one_hot.sum(dim=-1) | 8b27be397d2be44cf2c89b7618eab85c4ecc7ffa | 123,796 |
import hashlib
def string_hash(obj):
"""Returns a SHA-1 hash of the object. Not used for security purposes."""
return hashlib.sha1(str(obj).encode('utf-8')).hexdigest() | 957958b1e2623c28cdb4b12ee0163fab43199ded | 123,797 |
def point_in_polygon(point, poly):
""" Determine if a point is inside a given polygon or not. Polygon is a list of (x,y) pairs.
Code adapted from a dials polygon clipping test algorithm"""
if len(poly) < 3: return False
inside = False
for i in range(len(poly)):
j = (i+1) % len(poly)
if (((poly[i][1] > point[1]) != (poly[j][1] > point[1])) and
(point[0] < (poly[j][0] - poly[i][0]) * (point[1] - poly[i][1]) /
(poly[j][1] - poly[i][1]) + poly[i][0])):
inside = not inside
return inside | f714f67d5f46a7fcea59c0a294910a9c13b8b42d | 123,800 |
def same_module(cls1: type, cls2: type) -> bool:
"""Return if two classes come from the same module via the ``__module__`` attribute."""
return cls1.__module__.split(".")[0] == cls2.__module__.split(".")[0] | fee2451b84b38d9a212c09edd49b83880a59909a | 123,807 |
def read_file(path, mode="r"):
"""Read the content of a file."""
with open(path, mode) as f:
return f.read() | f6e1a8df8dea8720fed050e80de8490e3d916f3d | 123,808 |
from datetime import datetime
from dateutil import tz
def utc_to_pst(timestamp_str, in_fmt, out_fmt):
"""Convert UTC timestamp to Local time (PST)."""
timestamp = datetime.strptime(timestamp_str, in_fmt)
utc_tz = tz.gettz('UTC')
pst_tz = tz.gettz('US/Pacific')
timestamp = timestamp.replace(tzinfo=utc_tz)
pst_timestamp = timestamp.astimezone(pst_tz)
return pst_timestamp.strftime(out_fmt) | 3ce58d5dee03c6468c8acdd2ea9d4bfbe4435bbf | 123,809 |
def _cnPnPoly(P, V):
"""
Crossing number test for a point in a polygon.
:param P: :class:`Point` object.
:param V: List of :class:`Point` objects that represent vertices of
the shape to be tested. Must be a closed set.
:returns: 0 if outside, 1 if inside the polygon.
Copyright 2001, softSurfer (www.softsurfer.com)
This code may be freely used and modified for any purpose
providing that this copyright notice is included with it.
SoftSurfer makes no warranty for this code, and cannot be held
liable for any real or imagined damage resulting from its use.
Users of this code must verify correctness for their application.
"""
cn = 0 # the crossing number counter
n = len(V) - 1
# loop through all edges of the polygon
for i in range(n): # edge from V[i] to V[i+1]
if (V[i].y <= P.y and V[i + 1].y > P.y) \
or (V[i].y > P.y and V[i + 1].y <= P.y): # a downward crossing
# compute the actual edge-ray intersect x-coordinate
vt = (P.y - V[i].y) / (V[i + 1].y - V[i].y)
if P.x < V[i].x + vt * (V[i + 1].x - V[i].x): # P.x < intersect
cn += 1 # a valid crossing of y=P.y right of P.x
return cn % 2 == 1 | f28a7b10c3ab26346bd6c03d8b97d57313b858c3 | 123,810 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.