content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
|---|---|---|
def find_key_values_in_dict(d, key):
"""
Searches a dictionary (with nested lists and dictionaries)
for all the values matching to the provided key.
"""
values = []
for k, v in d.iteritems():
if k == key:
values.append(v)
elif isinstance(v, dict):
results = find_key_values_in_dict(v, key)
for result in results:
values.append(result)
elif isinstance(v, list):
for item in v:
if isinstance(item, dict):
more_results = find_key_values_in_dict(item, key)
for another_result in more_results:
values.append(another_result)
return values
|
f620261daa864b66de9b9794b52a54dff0f70e35
| 57,330
|
def win_path_dirname(path: str) -> str:
"""Retrieve only the directory part of a Windows file path"""
dirname = '\\'.join(path.rstrip('\\').split('\\')[:-1])
return 'c:\\' if dirname == 'c:' else dirname
|
5040c4e1f6b5968798498b24f1840fecfd9ae22e
| 57,336
|
def dict_with(base_dict, **kwargs):
""" Return a copy of the dictionary with the added elements. """
full_dict = dict(base_dict)
full_dict.update(**kwargs)
return full_dict
|
540873562dae83be08408fedbbdfac7efbbfe445
| 57,338
|
from typing import List
def path_to_nodes(path: str) -> List[int]:
"""
Maps from a path string to a list of indices where each index represents the corresponding level in the path.
"""
path = path.replace(' ', '')
if not set(path).issubset(set('m1234567890/')):
raise ValueError(f"Invalid path {path}")
indices = path.split('/')
if indices[0] != 'm':
raise ValueError(f"The first character of path should be `m`. Got {indices[0]}.")
indices.pop(0)
return [int(index) for index in indices]
|
0d4291e129ef9671d04c1ccdfe9b1e448c1e934a
| 57,339
|
import math
def tan(x):
"""Return tan of x (x is in radians)"""
return math.tan(x)
|
a6f733f72591eb91d8c5707c8644deac68ce20e0
| 57,342
|
def _get_username(member):
"""
Resolve the username from the member object returned from a group query
Returns:
str: The username converted to domain\\username format
"""
return member.ADSPath.replace("WinNT://", "").replace("/", "\\")
|
0cfcc9b53478311ca88e2a7b193e8150baa189c8
| 57,344
|
def filter_month(string, month):
"""
Filter month.
Keyword arguments:
string -- the string to perform the filtration on
month -- the month used as the filter
"""
if month in string:
return True
else:
return False
|
9f806747b4462e255cb84fd395899ad87ea6e39c
| 57,349
|
def strip_end(h, s):
"""
If string h ends with s, strip it off; return the result
"""
if h.endswith(s):
h = h[:-len(s)]
return h
|
5a12fdcbc0c54af41e0609061ab9be9b6869e2e2
| 57,353
|
from typing import Tuple
import re
def _match_line_offset(m: 're.Match') -> Tuple[int, int, str]:
""" Convert a match position into a lineno, offset, and line """
pos = m.span()[0]
lines = m.string.split('\n')
for line_i, line in enumerate(lines, 1):
new_pos = pos - len(line) - 1
if new_pos < 0:
return line_i, pos + 1, line
pos = new_pos
assert False
|
7cb2d3381ab54057c89f690c58f97aa57b180d2b
| 57,354
|
def bbox_to_extent(bbox):
"""Helper function to reorder a list of coordinates from [W,S,E,N] to [W,E,S,N]
args:
bbox (list[float]): list (or tuple) or coordinates in the order of [W,S,E,N]
returns:
extent (tuple[float]): tuple of coordinates in the order of [W,E,S,N]
"""
return (bbox[0], bbox[2], bbox[1], bbox[3])
|
0280fba1c4b4169a5bd7f32ce68e2dfa0fe52bf2
| 57,355
|
def __det3x3__(a):
""" compute the 3x3 determinant of an array
Hard coded equations are 8 times faster than np.linalg.det for a matrix 3x3
Parameters
----------
a: ndarray, shape=(3,3), dtype=float
array matrix
Returns
-------
val: float
determinant of a
"""
val = +a[0] * (a[4] * a[8] - a[7] * a[5])
val += -a[1] * (a[3] * a[8] - a[6] * a[5])
val += +a[2] * (a[3] * a[7] - a[6] * a[4])
return val
|
bd233a2282ea5b41dad9ae82f7972fc1c75beaf2
| 57,357
|
def merge_dictionaries_summing(first_dict, second_dict):
"""Merge two dictionaries summing values with the same key.
Args:
first_dict (defaultdict): A defaultdict dictionary.
second_dict (defaultdict): A defaultdict dictionary.
Returns:
The enriched version of the first dictionary (it works in place). The
returned object is of type `defaultdict`.
Note:
This only works only with two input objects for the moment. Later
improvements could be made, if needed.
"""
for k, v in second_dict.items():
first_dict[k] += v
return first_dict
|
0b3e29877f35663cd7d278165cf925af225aa25f
| 57,358
|
def get_bill_to_address(user):
"""
Create an address appropriate to pass to billTo on the CyberSource API
Args:
user (User): the user whose address to use
Returns:
dict:
User's legal_address in the appropriate data structure
"""
legal_address = user.legal_address
# minimally require fields
billing_address = {
"firstName": legal_address.first_name,
"lastName": legal_address.last_name,
"email": user.email,
"street1": legal_address.street_address_1,
"street2": legal_address.street_address_2,
"street3": legal_address.street_address_3,
"street4": legal_address.street_address_4,
"city": legal_address.city,
"country": legal_address.country,
}
# these are required for certain countries, we presume here that data was validated before it was written
if legal_address.state_or_territory:
# State is in US-MA format and we want that send part
billing_address["state"] = legal_address.state_or_territory.split("-")[1]
if legal_address.postal_code:
billing_address["postalCode"] = legal_address.postal_code
return billing_address
|
8558a4e2185d4f634695bf4d8248b744c17cc557
| 57,360
|
def calculate_mileage(distance_matrix, route):
"""Calculate total mileage travelled using the given route.
:param distance_matrix: distance matrix, i.e. a matrix M such that M[i,j]
is a distance between i-th and j-th location. It is assumed that this matrix
is symmetric.
:type distance_matrix: numpy.ndarray
:param route: sequence of locations visited in TSP solution. For instance,
if the solution is to start in 1, then go to 0, go to 2 and come back to 1,
this parameter should be [1, 0, 2].
:type route: sequence of ints
:returns: mileage of the route, i.e. total distance travelled, in whatever units
distance_matrix is specified.
:rtype: number
"""
mileage = 0
for i in range(len(route)-1):
mileage += distance_matrix[route[i], route[i+1]]
return mileage
|
a8daf642cd95f8cc9b5b7397c7876d24d4b59da9
| 57,362
|
def _len(x):
"""Implement `len`."""
return len(x)
|
f8012b274efe84ff0fd932d4364f2de3b163b503
| 57,364
|
import csv
def load_phrase_database(f_abbreviations):
"""
Load the dictionary of abbreviated steps created in the "import_data" step
Args:
f_abbreviations (str): Filename of the abbreviation dictionary
Returns:
A dictionary of abbreviations.
"""
P = {}
with open(f_abbreviations, "r") as FIN:
CSV = csv.DictReader(FIN)
for row in CSV:
key = (tuple(row["phrase"].split()), row["abbr"])
val = int(row["count"])
P[key] = val
return P
|
fb2440189282170a8690f3e8d6cf44013b8f80c1
| 57,366
|
def repeat(text: str, n: int) -> str:
"""Repeat each character in a string n times."""
return "".join([letter * n for letter in text])
|
7445a6b87776c3676c1cd6e7030d3f8ca1c9e225
| 57,370
|
def encrypt_letter(letter, shift):
"""
>>> assert(encrypt_letter('a', 0) == 'a')
>>> assert(encrypt_letter('a', 3) == 'd')
>>> assert(encrypt_letter('z', 3) == 'c')
>>> assert(encrypt_letter('a', 26) == 'a')
>>> assert(encrypt_letter('b', 26) == 'b')
>>> assert(encrypt_letter('A', 0) == 'A')
>>> assert(encrypt_letter(' ', 123) == ' ')
"""
val = ord(letter)
if 64 < val < 91:
return chr(65 + (val - 65 + shift) % 26)
elif 96 < val < 123:
return chr(97 + (val - 97 + shift) % 26)
else:
return letter
|
91ff3bee0ad6494aec0df9c6d3645177aa36ed81
| 57,377
|
def mean(array):
"""
Calculates the mean of the absolute values in a list of numbers
Args:
array (list): array which we want to calculate the mean
Returns:
float: mean of the absolute values of the elements of the array
"""
sum = 0
for element in array:
sum += abs(element)
return sum / len(array)
|
c93de842f8fa84b62766a6543d8ec120ef397022
| 57,380
|
def isatty(file):
"""
Returns `True` if `file` is a tty.
Most built-in Python file-like objects have an `isatty` member,
but some user-defined types may not, so this assumes those are not
ttys.
"""
if hasattr(file, 'isatty'):
return file.isatty()
return False
|
199a8c4352d4be6e28509dbf492848e2d9f1dbea
| 57,381
|
def clean_ensembl_id(identifier):
"""
Formats an ensembl gene identifier to drop the version number.
E.g., ENSG00000002822.15 -> ENSG00000002822
Args:
identifier (str)
Returns:
identifier (str)
"""
return identifier.split('.')[0].upper()
|
abaef14f4bedd33bd9714c9e7df3504652a9899c
| 57,387
|
def updater(old, new):
"""Recursively update a dict. """
for k, v in new.items():
if type(v) == dict:
old[k] = updater(old.get(k, {}), v)
else:
old[k] = v
return old
|
bf8735f3e7b9722a7717fec30dfa57343c876490
| 57,391
|
import itertools
def sgroupby(items, kfn, kfn2=None):
"""
itertools.groupby + sorted
:param items: Iterable object, e.g. a list, a tuple, etc.
:param kfn: Key function to sort `items` and group it
:param kfn2: Key function to sort each group in result
:return: A generator to yield items in `items` grouped by `kf`
>>> from operator import itemgetter
>>> items = [(1, 2, 10), (3, 4, 2), (3, 2, 1), (1, 10, 5)]
>>> list(sgroupby(items, itemgetter(0)))
[[(1, 2, 10), (1, 10, 5)], [(3, 4, 2), (3, 2, 1)]]
>>> list(sgroupby(items, itemgetter(0), itemgetter(2)))
[[(1, 10, 5), (1, 2, 10)], [(3, 2, 1), (3, 4, 2)]]
"""
return (list(g) if kfn2 is None else sorted(g, key=kfn2) for _k, g
in itertools.groupby(sorted(items, key=kfn), kfn))
|
955a27901d605915d22eee415684e6c0196e7e9d
| 57,400
|
def choice_of_c_constants(prev_c, **optional_args):
"""Function that returns the new constants that will be used in the iteration knowing the previous ones.
The returned values for the two constants should be such that there are enough models to find enough parents and
also should be bounded in ...
Args:
prev_c ([type]): [description]
Returns:
int, int: The two contants with the smaller one before and the bigger one after
"""
c_1 = prev_c - 1 if not(prev_c == 1) else prev_c
c_2 = prev_c + 1 if not(prev_c == 3) else prev_c
return c_1, c_2
|
d9b61421433a52d062a27ea5210953a29cbf9436
| 57,402
|
import struct
def read_until_null(filebuffer, maxbytes=1024):
"""Reads a file until a null character
Args:
filebuffer (obj): a file that was opened with open()
maxbytes (int): number of bytes that will be read if no null byte is found
Avoids infinite loops.
Returns:
str: string concatenation of the bytes read
int: how many bytes were read
"""
current_string = b''
current_byte = filebuffer.read(1)
bytes_read = 1
while current_byte != b'\x00':
current_string += current_byte
# print('current byte: {}'.format(current_byte))
bytes_read += 1
current_byte = struct.unpack('c', filebuffer.read(1))[0]
if bytes_read > maxbytes:
print('exiting due to infinite loop')
break
return current_string, bytes_read
|
c2c4095df221d78a7459dea4929fd113c8aec10f
| 57,405
|
from datetime import datetime
def ingame_formatted(dt: datetime) -> str:
"""Returns formatted ingame timedate(text)."""
return dt.strftime("%Y - %B")
|
6cecb13c9b40c6b740ad353e8b87cb80069fc078
| 57,406
|
def _strip(tag):
"""
Tag renaming function to remove whitespace, depending on the csv format
column heading items can pick up some extra whitespace when read into Pandas
"""
return tag.strip()
|
2af1489902c03b3b177d92a937b7c36b3fe140da
| 57,407
|
def _rgb2hsl(rgb):
"""Create HSL from an RGB integer"""
r = ((rgb >> 16) & 0xFF) / 255
g = ((rgb >> 8) & 0xFF) / 255
b = (rgb & 0xFF) / 255
min_c = min(r, g, b)
max_c = max(r, g, b)
delta_c = max_c - min_c
l = min_c + (delta_c / 2)
h = 0
s = 0
if max_c != min_c:
if l > 0.5:
s = delta_c / (2 - max_c - min_c)
else:
s = delta_c / (max_c + min_c)
if max_c == r:
h = (g - b) / delta_c
if g < b:
h += 6
elif max_c == g:
h = ((b - r) / delta_c) + 2
else:
h = ((r - g) / delta_c) + 4
h /= 6
return (h, s, l)
|
6b9fe14435f836bb9fbb92a82f954869dd9a7819
| 57,408
|
import time
def compute_average(n):
"""Perform n appends to an empty list and return average time elapsed."""
data = []
start = time.time()
for k in range(n):
data.append(None)
end = time.time()
return (end - start) / n
|
4d7d55e87189d30af23961cbdde41720dc912431
| 57,416
|
import six
def _objectToDict(obj):
"""
Convert an object to a dictionary. Any non-private attribute that is an
integer, float, or string is returned in the dictionary.
:param obj: a python object or class.
:returns: a dictionary of values for the object.
"""
return {key: getattr(obj, key) for key in dir(obj) if
not key.startswith('_') and
isinstance(getattr(obj, key),
tuple([float, tuple] + list(six.string_types) +
list(six.integer_types)))}
|
b65303a667b36ee0bab9110556392a85ec902c3c
| 57,422
|
def get_SQL_type(config, datatype):
"""Given the config structure and the name of a datatype, climb the datatype tree (as required),
and return the first 'SQL type' found."""
if "datatype" not in config:
raise Exception("Missing datatypes in config")
if datatype not in config["datatype"]:
return None
if config["datatype"][datatype]["SQL type"]:
return config["datatype"][datatype]["SQL type"]
return get_SQL_type(config, config["datatype"][datatype]["parent"])
|
83550c166c35e83e8d553e9b2c99ccffc7a7e27a
| 57,429
|
def image_id_from_path(image_path):
"""Given a path to an image, return its id.
Parameters
----------
image_path : str
Path to image, e.g.: coco_train2014/COCO_train2014/000000123456.jpg
Returns
-------
int
Corresponding image id (123456)
"""
return int(image_path.split("/")[-1][-16:-4])
|
98efcc5cc4eb94ed5ea495fcc8a0af64408153af
| 57,431
|
def ij_2_ind(coordinates, shape):
"""
Return the index of ij coordinates
"""
return [ij[0] * shape[1] + ij[1] for ij in coordinates]
|
9a0aa2ebc361a45817a1d341bc9dc0c8005f74ec
| 57,433
|
def default_link_info_gen(default_link_delay, default_link_loss, default_link_bw):
"""Generate the default link information
Args:
default_link_delay (float): Default delay for the link.
default_link_loss (float): Default loss for the link.
default_link_bw (float): Default bandwidth for the link.
Returns:
str: Default link infomation.
Examples:
The return can be "default_link_info: 1000, 5ms, 0, N/A, N/A"
"""
return "default_link_info: {}, {}ms, {}, N/A, N/A".format(default_link_bw, default_link_delay, default_link_loss)
|
970e40fc3571557355a9093e331efa565fd9e88d
| 57,435
|
def get_node_type(node):
"""Simply gets the type of an ast node
Args:
**node (:obj:)**: ast node
Returns:
The type of an ast node
"""
return type(node)
|
5be836005b2b27e7395e87b235efcbe8cf188327
| 57,438
|
def isgoodipv4(ip_addr):
"""
Method to check if the give ip address is a valid ipv4
:param ip_addr: ipv4 address
:return: Boolean
"""
pieces = ip_addr.split('.')
if len(pieces) != 4:
return False
try:
return all(0 <= int(p) < 256 for p in pieces)
except ValueError:
return False
|
d124fbaae8751c6badd4d3279ee40c2366268b18
| 57,440
|
def atom_information(xyz_file):
"""
extract information about system: number of atoms and atom numbers
"""
atom_numbers = []
with open(xyz_file, 'r') as _file:
line = _file.readline()
n_atoms = int(line.split()[0])
_file.readline()
for i in range(n_atoms):
line = _file.readline().split()
atom_number = line[0]
atom_numbers.append(atom_number)
return n_atoms, atom_numbers
|
610ce3054a1da20e9daf206d7f742abbf650685c
| 57,445
|
def ang2pix(val, pixel_scale):
"""Transform an angle from angular units into pixels."""
return val / pixel_scale
|
2aa8f648d93af1d0ddd198aa1a9fe937319827de
| 57,447
|
import pickle
def load_source_coordinates(fname):
"""
Load source coordinates dictionary from pickle-file.
:return:
Dictionary with keys - source names and values - instances of
``astropy.coordinates.SkyCoord``.
"""
with open(fname, 'rb') as fo:
source_coordinates = pickle.load(fo)
return source_coordinates
|
095cd681631687ac38412d42773dcb0e5b5c5d5c
| 57,449
|
from functools import reduce
def rgetattr(obj, attr):
"""A "recursive" version of getattr that can handle nested objects.
Args:
obj (object): Parent object
attr (string): Address of desired attribute with '.' between child
objects.
Returns:
The attribute of obj referred to."""
return reduce(getattr, [obj] + attr.split('.'))
|
478a547b19401a837c6dbeec99cc03c911e4779c
| 57,452
|
def lmap_call(func, args_seq):
"""map every func call and return list result
>>> from operator import add
>>> lmap_call(add, [(1, 2), (3, 4)])
[3, 7]
"""
result = []
for args in args_seq:
result.append(func(*args))
return result
|
b8cff2ee8df16ac538212dc6f3d8b0cfd1aaf1e5
| 57,456
|
def mbar2inHg (mbar):
"""
Convert millibars to inches of mercury.
:param mbar: (`float`)
The pressure in millibars.
:return:
- **inHg** (`float`) -- The pressure in inches of mercury.
"""
inHg = 0.029530 * mbar
return inHg
|
3a0dfe04128394643e2f251a1d55a98af1b23e69
| 57,459
|
def normalized_msgpack(value):
"""Recursively convert int to str if the int "overflows".
Args:
value (list, dict, int, float, str, bool or None): value to be normalized
If `value` is a list, then all elements in the list are (recursively)
normalized.
If `value` is a dictionary, then all the dictionary keys and values are
(recursively) normalized.
If `value` is an integer, and outside the range ``-(1 << 63)`` to
``(1 << 64)``, then it is converted to a string.
Otherwise, `value` is returned unchanged.
Returns:
Normalized value
"""
if isinstance(value, (list, tuple)):
return [normalized_msgpack(v) for v in value]
elif isinstance(value, dict):
return dict(
[(normalized_msgpack(k), normalized_msgpack(v)) for (k, v) in value.items()]
)
if isinstance(value, int):
if -(1 << 63) < value < (1 << 64):
return value
else:
return str(value)
else:
return value
|
a5da3528113fdd25fbe86283904a93c018e88fed
| 57,464
|
def fiscal_to_academic(fiscal):
"""Converts fiscal year to academic year.
Args:
fiscal (str): Fiscal year value.
Returns:
str: Academic year value.
"""
fiscal_int = int(fiscal)
fiscal_str = str(fiscal)
return f'{fiscal_int - 1}/{fiscal_str[-2:]}'
|
03e5376f1d94f214183d02a5a932a64796c370c3
| 57,468
|
def parse_threshold(value):
"""Extract threshold value from the param for validation.
:param value: Input threshold value.
:return: A Float between 0 and 1, otherwise ``None``.
"""
try:
threshold = float(value)
if 0 <= threshold <= 1:
return threshold
except Exception:
return None
return None
|
48a8d69180661fc3b29eaf666e3baa59be95ab93
| 57,470
|
import binascii
def hstr_to_ascii(hstr):
"""Convert hex byte string into ascii string."""
return binascii.unhexlify(hstr)
|
c4cda179389fddaf30d03dc30dff38ebd0c02c54
| 57,472
|
def clamp(a, min_value, max_value):
"""
Clamp a between two values.
"""
return max(min(a, max_value), min_value)
|
69bd813171c6f365ac434d60a0e7fa0fd8474967
| 57,473
|
import re
def set_methods_ado_links(text: str) -> str:
"""
Add links to the markdown text compatible with Azure DevOps
Parameters
----------
text : str
[description]
Returns
-------
str
[description]
"""
text_links = text
links = set(re.findall(r"\(#(.*)\)", text))
for link in links:
text_links = text_links.replace("(#{})".format(link), "(#module-`{}`)".format(link))
return text_links
|
6bf97f9f69bb2f0816c33366a5c8317ec5a89075
| 57,474
|
def Identity(x):
"""Returns the object given to it"""
return x
|
6372893d482c9a430e890610ce48f385785d09d2
| 57,480
|
def read_nbytes(buffer: bytearray, length: int) -> bytes:
""" Read the given number of bytes, read bytes are consumed.
"""
array = bytes(buffer[:length])
del buffer[:length]
return array
|
19aaabf90b71714c2464ac8be200b9cb502dc633
| 57,481
|
def lookup(dictionary, key):
"""
Get a dictionary value by key within a template.
"""
return dictionary.get(key)
|
fa41ec3a9732d29a271bc61c67cc33e64f7001eb
| 57,486
|
import warnings
def _turn_off_warning(func):
"""Decorator to turn off warning temporarily."""
def wrapper(*args, **kwargs):
warnings.filterwarnings("ignore")
r = func(*args, **kwargs)
warnings.filterwarnings("once", category=DeprecationWarning)
return r
return wrapper
|
fff90ecf85f38233055905d0bb5cfb0e5949152d
| 57,488
|
def detectar_vocal(letra):
"""
Función para validar si el caracter introducido es una vocal, y mostrarlo.
Args: Un caracter.
Salida: True (si es una vocal), False si no es una vocal.
"""
vocal=('a','e','i','o','u')
for index in vocal:
if index==letra:
return ('True: El caracter introducido es una vocal.')
else:
return ('False: El caracter introducido NO es una vocal.')
|
07ccc3925052b74d910688bb905c90087fda07ec
| 57,496
|
def dissect_versions(versions):
""" Dissects version JSON returned by the API """
version_tokens = versions.get('version', '').split('.')
if len(version_tokens) > 1:
(major, minor, rev) = version_tokens
else:
major = 0
minor = 0
rev = 0
apiver_tokens = versions.get('apiversion', '').split('.')
if len(apiver_tokens) > 1:
(api_major, api_minor) = apiver_tokens
else:
api_major = 0
api_minor = 0
return {
'daemon': {
'major': major,
'minor': minor,
'rev': rev,
},
'api': {
'major': api_major,
'minor': api_minor,
}
}
|
afc6a462adf6ef8e4418813f1ffba452f0851821
| 57,499
|
def args_to_argline(prm, filters=[], underscore_to_dash=True,
bool_argparse=True):
"""Naive transformation of dictionary into argument line
Parameters
----------
prm : dict
desired pair of key-val. Keys must corresponds to argument line options
filters : list, optional
string in keys to avoid
underscore_to_dash : bool, optional
Replace underscore for dash for keys
bool_argparse : bool, optional
use --no-{key} if False, --key if True.
Returns
-------
argline : str
argument line string
"""
argline = ''
for k, v in prm.items():
# Filter keys
remove = 0
for f in filters:
if f in k:
remove += 1
break
if remove:
continue
if underscore_to_dash:
k = k.replace('_', '-')
if isinstance(v, str):
v = '"{}"'.format(v)
elif isinstance(v, list):
v = ' '.join(map(str, v))
elif isinstance(v, bool) and bool_argparse:
if not v:
k = 'no-' + k
v = ''
# Add keys
argline += '--{} {} '.format(k, str(v))
return argline
|
bc23e571d98503deab3540ef60a70964889d0309
| 57,504
|
def _build_robovac_command(mode, command):
""" Compile the given mode and command into the bytes data sent to the RoboVac. """
mcu_ota_header_0xa5 = 0xA5
cmd_data = (mode.value + command.value)
return bytes([mcu_ota_header_0xa5, mode.value, command.value, cmd_data, 0xFA])
|
6dc6d00faaa3d6b19a2b2b4b8ca245ee83f18603
| 57,510
|
def expand_cube(cube,j):
"""expands a cube along the jth direction by putting in a '-' there """
res=''
for i in range(len(cube)):
if i == j:
res = res + '-'
else:
res = res+cube[i]
return res
|
de1dd7466b56b5f1fd257c39e8cfc20acf05ccfd
| 57,512
|
def get_package(module_name, is_package):
"""Returns a string representing the package to which the file belongs."""
if is_package:
return module_name
else:
return '.'.join(module_name.split('.')[:-1])
|
b181f71b11828a40b8a9f186c86892785007c2b5
| 57,513
|
def line_to_unit_vector(line):
"""
Converts a line to a unit vector.
:param line: ((x0, y0), (x1, y1))
:return: ((a, b), (x0, y0))
"""
# unpack line
p0, p1 = line
x0, y0 = p0
x1, y1 = p1
# get vector components
a = x1 - x0
b = y1 - y0
# get vector magnitude
mag = (a ^ 2.0 + b ^ 2.0) ^ 0.5
# make vector tuple as listed at beginning
vec = ((a / mag, b / mag), p0)
# return vector
return vec
|
517705cf0474b4d724724e2fd308754314b823aa
| 57,516
|
import random
def pickfirst_prob(l, p=0.5):
"""Select the first item in a list with the specified probability,
else select an item, with equal probability, from the rest of the list."""
if len(l)>1 and random.random() >= p:
return random.choice(l[1:])
return l[0]
|
3e5c5c6c3e71c1aa7f7fcb39dd714b529b1d0aec
| 57,520
|
import requests
def get_cached(SERVER_URL, max_number=5):
"""
It asks for the server for X amount of data cached on the server.
:param SERVER_URL: string
A string that contains the server address.
:param max_number: int
The amount of information the user desire from cached data.
:return: json
It returns a JSON containing the last X amount of data.
"""
return requests.get(f'{SERVER_URL}/weather?max={max_number}').json()
|
66d4e7a463b10e5370d89eb61a40c648d5651c99
| 57,523
|
def funpack(fpack):
"""
Execute a function, packed arguments pair.
"""
return fpack[0](*fpack[1],**fpack[2])
|
e7b4d72cceac75f85a47cc5dba6752d07750b4c6
| 57,533
|
def generate_csd_link(refcode: str) -> str:
"""Take a refocde string and make a link to WebCSD"""
return '<a href="https://www.ccdc.cam.ac.uk/structures/Search?Ccdcid={}&DatabaseToSearch=Published">{}</a>'.format(
refcode, refcode
)
|
18d36329efd3ba799d4220708450323b3762739e
| 57,537
|
def split_area(bbox, pixel_width, max_size):
"""
Splits a square polygon in smaller squares.
Arguments:
-----------
bbox: list
list of coordinates (lon, lat) of the 4 bounding box summits - must be in
the order: [[x_min, y_max],[x_max, y_max],[x_max, y_min],[x_min, y_min]]
pixel_width: int
width of the bbox, in pixels
max_size: int
maximum authorized pixel width
Returns:
-----------
small_boxes: list
list of smaller boxes (with coordinates in the same format as the original)
"""
# get coordinates of the original bbox
x_min = bbox[0][0]
y_max = bbox[0][1]
x_max = bbox[2][0]
y_min = bbox[2][1]
# compute size of each small box
small_boxes = []
nb_breaks = int(pixel_width // max_size)
x_step = (x_max - x_min) / (nb_breaks+1)
y_step = (y_max - y_min) / (nb_breaks+1)
# compute coordinates of each small box
for i in range(nb_breaks+1):
x_min_i = x_min + i*x_step
x_max_i = x_max - (nb_breaks-i)*x_step
for j in range(nb_breaks+1):
y_min_i = y_min + j*y_step
y_max_i = y_max - (nb_breaks-j)*y_step
box_i = [[x_min_i, y_max_i],[x_max_i, y_max_i],[x_max_i, y_min_i],[x_min_i, y_min_i]]
small_boxes.append(box_i)
return small_boxes
|
826806bb95d609f4e468874cdf99869ba17e0e50
| 57,539
|
def get_host_environ(repository_ctx, name):
"""Returns the value of an environment variable on the host platform.
The host platform is the machine that Bazel runs on.
Args:
repository_ctx: the repository_ctx
name: the name of environment variable
Returns:
The value of the environment variable 'name' on the host platform.
"""
return repository_ctx.os.environ.get(name)
|
19251bf68394c289db9ec40100e89f05c6559f48
| 57,540
|
def add_ome_axes_single_plane(image_np):
"""
Reshapes np.ndarray image to match OME-zarr standard
Parameters
----------
image_np:np.ndarray
image to which additional axes are added to meet OME-zarr standard
Returns
-------
image_np:np.ndarray
reshaped image array
"""
return image_np.reshape((1,) * (3) + image_np.shape)
|
5eaa48aa415166eb04226f3d0e0eb99e6c94c7d2
| 57,541
|
def _pd(shape):
""" Returns the product of all element of shape except shape[0]. """
s = 1
for dim in shape[1:]:
s *= dim
return s
|
4ae044bc30fe30b2d6398270570686f99d3fe8ce
| 57,543
|
def n_digits(figure):
"""Return the number of decimals of the given figure."""
n = 0
for ch in figure:
if ch == "e":
return n
elif ch in "0123456789":
n += 1
return n
|
aec5a47fd3be1741fd3a9171dba49fc0eacd881b
| 57,554
|
import math
def F15(x):
"""Bird function """
s = (x[0]-x[1])**2+math.cos(x[1])*math.exp((1-math.sin(x[0]))**2)
return s
|
d4b945f3b0dcf28bf9e773e8138d8d3ff52209b9
| 57,561
|
from datetime import datetime
def datetime_to_iso_str(value: datetime) -> str:
"""
Converts ``datetime`` object into Airtable compatible ISO 8601 string
e.g. "2014-09-05T12:34:56.000Z"
Args:
value: datetime object
"""
return value.isoformat(timespec="milliseconds") + "Z"
|
d7f9cc8b834ee3ea665a0adf263789ae57c93b72
| 57,564
|
def race_iter_h(r):
"""Return a census race iteration code for a PUMS records, for just
the Non-hispanic White / Hispanic distinction"""
is_hisp = r.HISP != 1
if r.RAC1P == 1 and not is_hisp:
return 'h' # non hispanic white
elif is_hisp:
return 'i'
else:
return None
|
d02145b205bf1b44a03fea8bce1b432a2dc35de5
| 57,565
|
def smash_candies(total_candies, friend_count=3):
"""
Function for Candy-sharing friends Alice, Bob and Carol. They have some candies which they plan to split evenly
among themselves. For the sake of their friendship, any candies left over would be smashed. For example, if they
collectively bring home 91 candies, they'll take 30 each and smash 1.
Also will calculate the number of candies to smash for *any* number of total candies. Modifying it so that it
optionally takes a second argument representing the number of friends the candies are being split between. If no
second argument is provided, it should assume 3 friends, as before.
-End of Doc String for the function-
"""
return total_candies % friend_count
|
685521e615374bfc629b4764b013bc9f89fe80ce
| 57,566
|
def fibo_generate(number):
"""
Generate fibonnaci numbers.
Arguments:
number -- how many numbers to generate
Returns:
fibo -- a list of fibonnaci numbers.
"""
fibo = [1, 1]
for i in range(0, number - 2):
fibo.append(fibo[i] + fibo[i+1])
return fibo
|
9bf1d8af0a294bae97597c4c2f3ce83e4d87ffbd
| 57,571
|
def get_outputportid(port):
""" Get the output port ID corresponding to the port letter """
portid = {
'a': 1,
'b': 2,
'c': 4,
'd': 8
}
port = port.lower()
if type(port) is not str:
raise NameError('Invalid output port.')
if port not in list(portid.keys()):
raise NameError('Invalid output port.')
return portid[port]
|
b337b6f539f98382e6711fbd8ffbf1752aece860
| 57,572
|
def dot(a, b):
"""Calculate the dot product of two lists.
Raises:
AttributeError: Length of first list does not match length of second.
Example:
>>> l1 = [1, 2, 3]
>>> l2 = [3, 4, 6]
>>> product = dot(l1, l2)
>>> print(product)
29
Args:
a(*iterables): first list
b(*iterables): second list
Return:
mixed
"""
if len(a) != len(b):
raise AttributeError('Length of first iterables does not match length of second.')
return sum(i * j for i, j in zip(a, b))
|
48e05204c3ccb9cd810e38706a833dbb23a07e8c
| 57,577
|
def identity_decorator(func):
"""
identy for decorators: take a function and return that same function
Arguments:
- func: function
Returns:
- wrapper_identity_decorator: function
"""
def wrapper_identity_decorator(*args, **kvargs):
return func(*args, **kvargs)
return wrapper_identity_decorator
|
619ee98cf93f107c4a2b6e554146a592f0274c45
| 57,578
|
def repeat(character: str) -> str:
"""Repeat returns character repeated 5 times."""
word = ""
for _ in range(5):
word = word + character
return word
|
19bdda35ffafa97d22200f74f1e078958e193962
| 57,579
|
import pickle
def Read_Data_From_Pickle(file_name):
"""
This function read data from a pickle
Input:
file_name: pickle file name
Return:
Sampes, lables
"""
with open(file_name, mode='rb') as f:
train = pickle.load(f)
return train['features'], train['labels']
|
d7bfbb69dbb8cf02832a0df500fadf8c9c225a33
| 57,583
|
def diff_dates(date1, date2, verbose=True):
"""Return the difference between date1 and date2 in number of days"""
result = date2 - date1
if verbose:
print('%s to %s: %d day(s)' % (date1, date2, result))
else:
print(result)
return result
|
d8a0f5c3afbfc9132fcdadee835541ac6f54ed2c
| 57,588
|
def extract_processor_name_with_recipe_identifier(processor_name):
"""Returns a tuple of (processor_name, identifier), given a Processor
name. This is to handle a processor name that may include a recipe
identifier, in the format:
com.github.autopkg.recipes.somerecipe/ProcessorName
identifier will be None if one was not extracted."""
identifier, delim, processor_name = processor_name.partition("/")
if not delim:
# if no '/' was found, the first item in the tuple will be the
# full string, the processor name
processor_name = identifier
identifier = None
return (processor_name, identifier)
|
de5dd58fc06f527b0173485baf697cdd5ae6b65f
| 57,589
|
def encode(value):
"""Encode string value to utf-8.
Args:
value: String to encode
Returns:
result: encoded value
"""
# Initialize key variables
result = value
# Start decode
if value is not None:
if isinstance(value, str) is True:
result = value.encode()
# Return
return result
|
63da0c8c30df40d93130f8c5261aa74d471b4ecd
| 57,594
|
def get_unique_combinations(combinations_per_row):
"""Performs set.union on a list of sets
Parameters
----------
combinations_per_row : List[Set[Tuple[int]]]
list of combination assignments per row
Returns
-------
Set[Tuple[int]]
all unique label combinations
"""
return set.union(*combinations_per_row)
|
f8e8acae910b436efffb238dd6aa830fc40df54f
| 57,597
|
def get_exptime(header):
"""Tries a couple of keywords to find the exposure time in a FITS header"""
for exptime_key in ("EXPTIME", "LEXPTIME", "SEXPTIME"):
if exptime_key in header:
exptime = float(header[exptime_key])
return exptime
|
1301f3dd7163eda691dd8c3066c638079120de4d
| 57,599
|
def exchange_rate_format(data):
"""Return a dict with the exchange rate data formatted for serialization"""
return {
'provider_1': {
'name': 'dof',
'rate': data.dof_rate,
'date': data.dof_date,
'last_updated': data.dof_last_updated,
},
'provider_2': {
'name': 'fixer',
'rate': data.fixer_rate,
'date': data.fixer_date,
'last_updated': data.fixer_last_updated,
},
'provider_3': {
'name': 'banxico',
'rate': data.banxico_rate,
'date': data.banxico_date,
'last_updated': data.banxico_last_updated,
},
'created': data.created,
}
|
47dbc58bf1c49d14372333cb38ef4fc8ea624490
| 57,600
|
def prints(monkeypatch):
"""Capture prints into a list."""
prints = []
def save_print(*args, **kw):
prints.append((args, kw))
if hasattr(__builtins__, 'get'):
monkeypatch.setitem(__builtins__, 'print', save_print)
else:
# For pypy we need to monkeypatch differently.
monkeypatch.setattr(__builtins__, 'print', save_print)
return prints
|
bc1b8b2443977b193712dab8986cde12cde6cc95
| 57,603
|
def get_data_from_concentration(df, concentration):
"""
Gets a numpy array of the data given the concentration and a df.
"""
data_df = df[df['Tubulin Concentration (uM)'] == concentration]
return data_df['Time to Catastrophe (s)'].values
|
eaca02fdb339a6b7901d4d8b07fb1533332dc974
| 57,608
|
import torch
def _compute_tensor_center(size, device, dtype):
"""
Computes the center of tensor plane for (H, W), (C, H, W) and (B, C, H, W).
"""
height, width = size
center_x = float(width - 1) / 2
center_y = float(height - 1) / 2
center = torch.tensor([center_x, center_y], device=device, dtype=dtype)
return center
|
6821243fe34d82504abf305af8c33605e4a4c442
| 57,612
|
import json
def json_true(json_line):
""" Checks JSON command is valid and will run.
Parameters:
json_line (str):
Returns:
Bool: True if line passes.
"""
try:
json_object = json.loads(json_line)
except ValueError:
return False
return True
|
a33ee39b546c511c3740578094ce6dcce9d4218b
| 57,613
|
import json
def json_to_dict(json_file):
"""
Reads dict from a JSON file.
:param json_file: A JSON file created by Sample.to_json()
:return: a dictionary (input to dict_to_sample())
"""
with open(json_file) as f:
dict_ = json.load(f)
return dict_
|
076f0217ba3ea43339cb86e87189de06ea2fe088
| 57,616
|
def lagrange(x_values, y_values, nth_term):
"""
If a polynomial has degree k, then it can be uniquely identified if it's values are known in k+1 distinct points
:param x_values: X values of the polynomial
:param y_values: Y values of the polynomial
:param nth_term: nth_term of the polynomial
:return: evaluates and returns the nth_term of the polynomial in O(k^2), given at least k+1 unique values were provided
"""
if len(x_values) != len(y_values):
raise ValueError('The X and Y values should be of the same length')
res = 0
for i in range(len(x_values)):
x, y = 1, 1
for j in range(len(x_values)):
if i != j:
x *= (nth_term - x_values[j])
y *= (x_values[i] - x_values[j])
res += (x * y_values[i] // y)
return res
|
b7f2b44eaa70dee7984ac4ad73ccfb4316cf93ed
| 57,619
|
import string
def get_deliver_from_class(class_name):
"""
Create deliver name from Class Name
Examples:
>>> get_deliver_from_class('DemoApp')
'_demo_app'
"""
split_text = []
last_position = 0
for i in range(1, len(class_name)):
if class_name[i] in string.ascii_uppercase:
split_text.append(class_name[last_position:i].lower())
last_position = i
split_text.append(class_name[last_position:len(class_name)].lower())
return '_' + '_'.join(split_text)
|
be2cbc25814475c10e5a3b139e5a6fb4d65ba6ae
| 57,624
|
from typing import List
def get_metaworld_single_benchmark_names() -> List[str]:
""" Returns a list of Metaworld single-task benchmark names. """
return ["MT1", "ML1_train", "ML1_test"]
|
60aff0adcf05ad2df4cb2582c6d6325a178ecc74
| 57,629
|
from typing import Union
def round_number(n: float) -> Union[int, float]:
"""Round a number based on its size."""
abs_n = abs(n)
if abs_n >= 10000:
return round(n)
elif abs_n >= 100:
return round(n, 1)
elif abs_n >= 1:
return round(n, 2)
else:
return round(n, 3)
|
3defa8439e7c4475780f8483ab805a55c533e43b
| 57,633
|
import torch
def _(points: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
"""Computes batched tour distance.
points should have dims (tour_len, batch, 2)
indices should have dims (tour_len + 1, batch)
"""
batch_arange = torch.arange(points.shape[1], device=points.device)
# NOTE: indices are 1-indexed
curr = points[indices[:-1] - 1, batch_arange]
next_ = points[indices[1:] - 1, batch_arange]
return torch.sum(torch.sqrt(torch.sum((next_ - curr) ** 2, dim=2)), dim=0)
|
fbe9a1f02b7775ae7246181405c44c1c9eb86cef
| 57,634
|
def matrix_to_pic(matrix: list) -> None:
"""Matrix to picture
Converts a matrix of lists with one-character values into `ASCII Art`_.
Args:
matrix: List with lists containing one-character elements.
Returns:
None. Prints the contents of the lists as `ASCII Art`_
.. _ASCII Art:
https://en.wikipedia.org/wiki/ASCII_art
"""
new_matrix = zip(*matrix) #: Convert rows to columns in new matrix
for item in new_matrix:
print(''.join(item))
return None
|
fd1c8395a4f3b33d8a21073d2198cc95f8fd9cec
| 57,635
|
import pwd
def get_uname(uid):
"""Get the user name from the user ID."""
try:
return pwd.getpwuid(uid).pw_name
except KeyError:
return None
|
e39ee84aa7a7ffff0fd6e27901a75aee590668b0
| 57,639
|
def utf8_bytes(text):
"""
Ensures that text becomes utf-8 bytes.
:param text: strings or bytes.
:return: a bytes object.
"""
if not isinstance(text, bytes):
return text.encode('utf-8')
return text
|
0528e3b11af5c01ad7f76fa9051ce950eb46d09a
| 57,642
|
import re
def get_decontracted_form(text):
"""
Function to expand words like won't, can't etc.
"""
text = re.sub(r"won[\']t", "will not", text)
text = re.sub(r"can[\']t", "can not", text)
text = re.sub(r"shan[\']t", "shall not", text)
text = re.sub(r"she ain[\']t", "she is not", text)
text = re.sub(r"he ain[\']t", "he is not", text)
text = re.sub(r"you ain[\']t", "you are not", text)
text = re.sub(r"it ain[\']t", "it is not", text)
text = re.sub(r"they ain[\']t", "they are not", text)
text = re.sub(r"we ain[\']t", "we are not", text)
text = re.sub(r"i ain[\']t", "i am not", text)
text = re.sub(r"n[\']t", " not", text)
text = re.sub(r"[\']re", " are", text)
text = re.sub(r"[\']ll", " will", text)
text = re.sub(r"[\']t", " it ", text)
text = re.sub(r"[\']ve", " have", text)
text = re.sub(r"[\']m", " am", text)
text = re.sub(r"[\']em", " them", text)
text = re.sub(r"[\']s", " is", text)
return text
|
03c1c8a00344b5206ef7b3dff976218c7887ed59
| 57,646
|
def zeros(shape: tuple) -> list:
"""
Return a metrics that all elements are
zero with the specified shape.
"""
return [shape[1] * [0] for _ in range(shape[0])]
|
d51f0d3794a65298ae92a137b9468b3ab7bb0226
| 57,654
|
import random
def block_design(randomize=None, seed=None, **kwargs):
""" Generate a Block Design
Arguments:
randomize: (optional) A boolean indicating if the runs should be in a
random order. The default is false.
seed: (optional) The seed for the RNG.
**kwargs: A list of factors for each nuisance factor
Returns:
dict: The dictionary has two components: a list of names that is the
names of the factors in the order they appear in the lists and a
list of lists where each list represents a run.
"""
factor_names = []
factor_levels = []
total_levels = 1
# Sort the keywords to ensure reproducibiltiy
factors = sorted(kwargs.items())
print(factors)
for factor, levels in factors:
factor_names.append(factor)
if not isinstance(levels, list):
raise ValueError('Each factor must have a list of levels.')
factor_levels.append(len(levels))
total_levels *= len(levels)
n_factors = len(factor_names)
# design = [[0] * n_factors] * total_levels
design = []
current_level = [0] * n_factors
for run in range(total_levels):
design.append(current_level[:])
current_level[n_factors - 1] += 1
for factor in range(n_factors - 1, 0, -1):
if current_level[factor] > factor_levels[factor] - 1:
current_level[factor] = 0
current_level[factor - 1] += 1
for run in range(total_levels):
for factor in range(n_factors):
design[run][factor] = factors[factor][1][design[run][factor]]
if randomize:
random.seed(seed)
random.shuffle(design)
res = {
'names': factor_names,
'design': design
}
return res
|
e51f1c4aa64f1a8abb645aea1862116414d1415b
| 57,655
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.