content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def class_name(obj):
""" Returns the class name of an object"""
return obj.__class__.__name__ | daa37085e28d2a7676f0eeacb8d65d74a6986934 | 680,234 |
def Split(string,n):
"""Split a string into lines of length n with \n in between them"""
N =len(string)//n
return '\n'.join([string[i*n:(i+1)*n] for i in range(N)]+[string[N*n:]]) | 06902b208fe1118c4a36edfa57f614238436dc22 | 680,235 |
def molm2_to_molec_cm2(spc_array):
"""
Convert moles/m2 to molec/cm2
"""
avo_num = 6.0221409e23
molec_per_m2 = spc_array * avo_num
molec_per_cm2 = molec_per_m2 * 1e4
return molec_per_cm2 | 9a22c2b79f1de4cfce04f2a41e422ad2421adc2a | 680,236 |
def dms2dd(dms):
"""
DMS to decimal degrees.
Args:
dms (list). d must be negative for S and W.
Return:
float.
"""
d, m, s = dms
return d + m/60. + s/3600. | 26ce439d9a4acc8b8d384ccb88e5142581ddcc99 | 680,238 |
def br(value):
""" Replaces newlines with HTML-style <br>'s """
return value.replace("\n", "<br>") | 919daa33a479293a112692aa6e3548a1ed71d6c3 | 680,240 |
import math
def binary_entropy(p):
"""
Uses the binary entropy function denoted H(p) in information theory/statistics
Computes the entropy of a Bernoulli process with probability of success p
When p = .5, entropy is at its max value (unbiased bit, most common unit of information entropy)
@param ... | 671eb431c152970546993ecdc6b9de06a7451e99 | 680,242 |
def quantify(iterable, pred=bool):
"""Count how many times the predicate is true.
:param iterable: source of values
:param pred: the predicate whose result is to be quantified when applied to
all values in iterable. Defaults to bool()
"""
# quantify([2, 56, 3, 10, 85], lambda x: x... | a9c8b611bf7f38aaf6d4e0f1fbbb6bd0a1b32073 | 680,249 |
def ensure_all_tokens_exist(input_tokens, output_tokens, include_joiner_token,
joiner):
"""Adds all tokens in input_tokens to output_tokens if not already present.
Args:
input_tokens: set of strings (tokens) we want to include
output_tokens: string to int dictionary mappi... | bb73fd901eccab0109d27f5d9eb8ed4f881833e9 | 680,250 |
import asyncio
def async_return(result):
"""Mock a return from an async function."""
future = asyncio.Future()
future.set_result(result)
return future | 8dcf55b5fc1ded019c9bec668d17f919215b09c7 | 680,251 |
def get_ttylog_lines_from_file(ttylog):
"""Read from ttylog. If lines have '\r' at end, remove that '\r'. Return the read lines"""
ttylog_file = open(ttylog,'r',errors='ignore', newline='\n',encoding='utf-8')
ttylog_read_data = ttylog_file.read()
#Replace escaped double qoutes with qoutes
ttylog_rea... | 7c900d11f9d872ef2c23bb6932724ac5a4c3b501 | 680,252 |
from pathlib import Path
def read_input_file(input_file_path):
""" read the input file and convert the contents
to a list of ints """
p = Path(input_file_path)
with p.open() as f:
data = list(map(int, f.readlines()))
return data | 5b3352ff1bdd0ab895e69a43f20100b92ad86f35 | 680,254 |
def variable_to_jsonpath(p):
"""Converts a expression variable into a valid JSON path starting with $."""
# replace JSON_ with $ and _ with .
return p.var.replace('JSON_', '$').replace('_', '.') | 92466ade3d97b31471e8b2f78199bc5c8ae0f33b | 680,257 |
def remove_bottom(pnts, gt_box, bottom):
"""
Args:
* `pnts`: Lidar Points
* `gt_box`: The 3D bounding box of the object
* `bottom`: A height threshold, deciding which points to keep\n
Return:
`pnts` whose heights are larger than -dz/2 + bottom, where dz is from the `gt_box`.
... | 3f03276134db713e587c9e4145c21b85543f20c5 | 680,263 |
from datetime import datetime
def _convert_to_datetime(unix_timestamp):
"""
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
"""
try:
unix_timestamp = float(uni... | be5aa2d95729c0cc779c232db76acebbc03f8c95 | 680,267 |
def _extract_username(request):
"""
Look for the "username" in a request. If there is no valid username we
will simply be throttling on IP alone.
"""
return request.POST.get("username", "notfound").lower() | 79641a2d6721af21ce5eb1bbeafe0cc387616adb | 680,270 |
from typing import List
import time
def tmp_path(base: str, _time_stamp: List[int] = []) -> str:
"""Get a temporary path containing a time stamp."""
if not _time_stamp:
_time_stamp.append(int(time.time()))
return f"{base}{_time_stamp[0]}" | 26041b4c1377048e97a5587ff12c27e468ecd9cf | 680,274 |
def is_error_response(res):
"""
check the status code of http response
:param res: http response
:return: True if the status code less than 200 or larger than 299;
False if the status code is between 200 and 299
"""
if res is None:
return True
if res.status_code < 200 or... | fb4153acb3efac0ec93e01b6e8ef5a7c02d07218 | 680,277 |
def get_content(*filename:str) -> str:
""" Gets the content of a file or files and returns
it/them as a string
Parameters
----------
filename : (str)
Name of file or set of files to pull content from
(comma delimited)
Returns
-------
str:
Content from the fi... | 5d19f26bd14200d9a71d2f246014bf7a56f5c7a5 | 680,279 |
def get_index(fields, keys):
""" Get indices of *keys*, each of which is in list *fields* """
assert isinstance(keys, list)
assert isinstance(fields, list)
return [fields.index(k) for k in keys] | fcaab2a055c223b29689fe6175212de480861288 | 680,280 |
def lcm(num1, num2):
"""
Find the lowest common multiple of 2 numbers
num1:
The first number to find the lcm for
num2:
The second number to find the lcm for
"""
if num1 > num2:
bigger = num1
else:
bigger = num2
while True:
if bigger % num1 == 0 and bi... | a307e9fdb391dc46dbb1e82c1c88890562304cd1 | 680,291 |
import importlib
def find_type_object(type_name):
"""Try to find the type object given the name of the type.
Deals with cases such as `argparse.ArgumentParser` where a module needs to
be imported before we can find the correct type object. If the type object
cannot be found, a `NameError` is raised.
... | bdb748be96bb755de372343eb463f03c20f13bf8 | 680,297 |
def add(x, y):
"""Add two coordinate pairs."""
return (x[0] + y[0], x[1] + y[1]) | ab900b9d683bd9215a35879f8bc3425c0e94e956 | 680,298 |
import itertools
def get_permutations(a):
"""
get all permutations of list a
"""
p = []
for r in range(len(a)+1):
c = list(itertools.combinations(a,r))
for cc in c:
p += list(itertools.permutations(cc))
return p | 3e3b71eeff6d29b60de28b38a524b1b07655048d | 680,300 |
from datetime import datetime
def fm_string(dt_string, millisecond=False):
"""
Input a date string and returns a datetime object.
"""
if millisecond:
return datetime.strptime(
dt_string, '%Y/%m/%d %H:%M:%S.%f')
else:
return datetime.strptime(
dt_string, '%Y/... | 7d4856e86cf24088c4ca7193caca0b2f3956ec0f | 680,305 |
def _is_weekend(date):
"""Returns whether the date is a weekend."""
return date.isoweekday() in (6, 7) # Saturday, Sunday | 71074d8b7e7e0d1f9a8d8e7c3f608a0f1b91ed9b | 680,308 |
import math
def _selection_size_heuristic(num_samples):
"""Return size of mini-batch, given size of dataset."""
# Incrase size of mini-batch gradually as number of samples increases,
# with a soft cap (using log).
# But do not return size larger than number of samples
return min(num_samples,
... | 605694af4875ac295ae9dea63b1ebda4308c038a | 680,309 |
import hashlib
def generate_md5(unicode):
"""
Generate an MD5 hash
Args:
unicode (bytes): Unicode bytes representing the string you want to be hashed
Returns:
str: An MD5 hash (hex characters)
"""
hasher = hashlib.md5()
hasher.update(unicode)
return hasher.hexdigest() | ecee642ca54ddf87d27d0d495395770d78e8fd78 | 680,311 |
import math
def factors_of(x):
"""Returns a set of tuples of factors of x.
Examples
--------
>>> factors_of(12)
{(1, 12), (2, 6), (3, 4)}
>>> factors_of(20)
{(1, 20), (2, 10), (4,5)}
"""
factors = set()
sqrt_x = math.sqrt(x)
if sqrt_x == int(sqrt_x):
factors.add... | 1b00d8292193a0cb16616f34f16154361c5b0dfc | 680,313 |
import math
def uv(sped, drct2):
"""Convert to u,v components."""
dirr = drct2 * math.pi / 180.00
s = math.sin(dirr)
c = math.cos(dirr)
u = round(-sped * s, 2)
v = round(-sped * c, 2)
return u, v | 0e1bacf73ec88e58ee495a1932fe24f6df0993bd | 680,315 |
def getfmt(n,dtype ="d"):
"""
Generates the binary format n dtype
defualts to double
@param n: number of particles
@param dtype: data type
returns the format string used to decode the binary data
"""
fmt = ""
fmt += dtype
for i in range(n):
... | a81ad1dac80d01fdcf809588d032ed1208333b37 | 680,317 |
def clean_timestamp(timestamp, format=False):
"""
used to remove unwanted characters from the overly long timestamp in the json data of a tweet
eg: timestamp comes in as 'Thu Dec 17 13:44:24 +0000 2020' and for now we only want 'Thu Dec 17 13:44'
"""
cleaned_timestamp_list = str(timestamp).split(' ... | 5fc1846f411ea8379dccf45f0770b946c718002b | 680,318 |
import torch
def transform_tensor_by_dict(tensor, map_dict, device="cpu"):
"""
Given a tensor of any shape, map each of its value
to map_dict[value].
:param tensor: input tensor
:param map_dict: value mapping dict. Both key and value are numbers
:return: mapped tensor, type is FloatTensor
... | 2bc6db21c579dea88b2b0612f80697797ab3deeb | 680,319 |
def connection_callback(isolation_level=None,
read_only=None,
deferrable=None,
application_name=None,
inherit=None):
"""
Decorator for functions used in :meth:`IConnectionManager.open_and_call`.
When the functio... | 2e043fa57e139a098ed41c4a4b4a25d2d50a6bcb | 680,321 |
def _generate_variable_name(variable_counter):
"""
Generates a unique variable name.
"""
return "v{}".format(variable_counter.next()) | 667ff33cee4d6a42547e078737d265d9dd147dc6 | 680,324 |
def null_padded(string, length):
"""
Force a string to a given length by right-padding it with zero-bytes,
clipping the initial string if neccessary.
"""
return bytes(string[:length] + ('\0' * (length - len(string))), 'latin1') | f39bb45b1dac9f901ae1acb24903eb43759436cd | 680,325 |
from typing import Dict
def get_border_width(width: int) -> Dict[str, int]:
"""Replicates border_width parameter from Gtk3, by producing a dict equivalent margin parameters
Args:
width (int): the border width
Returns:
Dict[str, int]: the dict with margin parameters
"""
return dic... | b29dbbf0fcd49b6ac1abfa1439ba7a81c8651ca6 | 680,328 |
def filter_dataframe(df, column, value):
"""Filter DataFrame for a column and a value or a list of value
Parameters
----------
df: DataFrame
DataFrame to filter
column: str
column name
value: list or 1dim value
values
Returns
-------
DataFrame: filtered Data... | e94d2d0be3d02bee999fdc9e5665785c862a19a8 | 680,335 |
def phi(T):
"""
:param T: [°C] Temperatura
:return: Factor que cuantifica la rapidez de cambios en los canales iónicos debido a la temperatura (T).
"""
Q_10 = 3 # Radio de las tasas por un incremento de temperatura de 10 °C
T_base = 6.3 # Temperatura base [°C]
return Q_10 ** ((T -... | 6873b85986e11d3f88e05a0793f4e8de7d1a2292 | 680,338 |
def int_to_rgb(int_):
"""Integer to RGB conversion"""
red = (int_ >> 24) & 255
green = (int_ >> 16) & 255
blue = (int_ >> 8) & 255
return red, green, blue | 2b93f91e3050da7500152c2c5adddd0cc575597b | 680,341 |
def model_uname(value):
"""Returns a model name such as 'baking_oils'"""
words = value._meta.verbose_name.lower().replace("&", "").split()
return "_".join(words) | 91ae8e36ea38eb559551c6a7d0f1cc44ffbbb08d | 680,342 |
import re
def chunk_paf(paf_record):
""" Takes a PafRecord object or a full cs string and returns a list of fields from its cs string """
if type(paf_record) == str:
cs = paf_record
else:
cs = paf_record.tags["cs"]
separable_cs = re.sub(r'(?<!\A)([-:*+])', r',\1', cs)
return separa... | 227ab6b995850ac27c0cd1c0ad3bc70a6e7e2a4d | 680,344 |
def heatmap_figsize(nrow, ncol=None):
"""Generate size tuple for heatmap based on number of rows and columns"""
if ncol is None:
ncol = nrow
return ncol * 0.3 + 3, nrow * 0.3 | 5bbe753368e14f388e140fc0e1866503e3b9673d | 680,345 |
def getBit(val, idx: int) -> int:
"""Gets a bit."""
return 1&(val>>idx) | 330c64f5e3ddb50608ded76a21dc52e56ca5485c | 680,352 |
def flatten_list(nested_list):
"""
Given a list of lists, it flattens it to a single list.
:param nested_list: list of lists
:return: Single list containing flattened list.
"""
return [item for sub_list in nested_list for item in sub_list] | c0f7bedb4cf776ca1b57c99eec37fc49d5334026 | 680,358 |
def rn_sub(a, b):
"""
a - b
uses rn_sum and rn_neg to get the difference like a + (-b)
:param a: RN object
:param b: RN object
:return: difference array
"""
return a + (-b) | 483bdcaab4121139f967057082c362e89409093a | 680,363 |
def split_sig(params):
"""
Split a list of parameters/types by commas,
whilst respecting brackets.
For example:
String arg0, int arg2 = 1, List<int> arg3 = [1, 2, 3]
=> ['String arg0', 'int arg2 = 1', 'List<int> arg3 = [1, 2, 3]']
"""
result = []
current = ''
level = 0
f... | 054e339410978d055a3873ee240b08b0c388fa21 | 680,367 |
def sum_factorial_digits(x):
"""
Returns the sum of the factorials of the digits of x
"""
factorials = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
sum_factorial_digits_ = 0
for i in str(x):
sum_factorial_digits_ += factorials[int(i)]
return(sum_factorial_digits_) | 421dcd734224ee691054bcb032c296bb0006d189 | 680,371 |
import random
import time
def retry(initial_delay,
max_delay,
factor=2.0,
jitter=0.25,
is_retriable=None):
"""Simple decorator for wrapping retriable functions.
Args:
initial_delay: the initial delay.
factor: each subsequent retry, the delay is multiplied by this v... | 4c62282671d46e1eb1d1720a84f6792380c21995 | 680,376 |
def fixup_acl(acl: str) -> str:
"""
Replace standard ip/mask entries with "none" and "any" if present
"""
if acl is None:
acl = "none"
if acl == '':
acl = "none"
if acl == "255.255.255.255/32":
acl = "none"
if acl == "0.0.0.0/0":
acl = "any"
return acl | a9c983ba5e76089d90d1fa551043615d1f449a45 | 680,377 |
import aiohttp
import base64
async def render(eqn: str, **kwargs) -> bytes:
"""
Render LaTeX using Matthew Mirvish's "TeX renderer slave microservice thing".
Returns raw image data or raises ValueError if an error occurred.
"""
kwargs["source"] = eqn
async with aiohttp.request("POST", "http:/... | c53a8cd5639f854301fafea72902f11427ca6dab | 680,379 |
import re
def sanitize(s):
""" Remove escape codes and non ASCII characters from output
"""
ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
s = ansi_escape.sub('', s)
mpa = dict.fromkeys(range(32))
return s.translate(mpa).strip().replace(' ', '') | 515057bba7eb1edc8066c9a9b1bf77589ad058cd | 680,381 |
def get_max_region(regions, field='area'):
"""Return the region from the list that maximizes the field."""
max_region = regions[0]
for i in range(1, len(regions)):
if regions[i][field] > max_region[field]:
max_region = regions[i]
return max_region | 69bcaface96b455fe411c578952c8dff251f291e | 680,382 |
def get_bucket_config(config, bucket_name):
"""
Pulls correct bucket config from application config based on name/alias.
Args:
config(dict)
bucket_name(string): bucket name or bucket reference name
Returns:
dict | None: config for bucket or None if not f... | fd742cd7c7484c51b3bb7a15003528834046fea7 | 680,383 |
def _has_dns_message_content_type(flow):
"""
Check if HTTP request has a DNS-looking 'Content-Type' header
:param flow: mitmproxy flow
:return: True if 'Content-Type' header is DNS-looking, False otherwise
"""
doh_content_types = ['application/dns-message']
if 'Content-Type' in flow.request... | 67bf9d5c4c1106961114459b750c87a2b496a7c5 | 680,384 |
def cast_to_str(labels, nested=False):
""" Convert every label to str format.
If nested is set to True, a flattened version of the input
list is also returned.
Args:
labels: list
Input labels
nested: bool
Indicate if the input list ... | 7e5b74a137ca3dfa06c50b1c3d680befd29a617d | 680,385 |
def binary_string_to_int(s):
"""
Convert a string of a binary representation to a number
:param s: a binary representation as a string
:return: an integer
"""
return int(s,2) | 5aeebf045ce25164369b92c98020f6db5c200e32 | 680,386 |
def optimal_merge_pattern(files: list) -> float:
"""Function to merge all the files with optimum cost
Args:
files [list]: A list of sizes of different files to be merged
Returns:
optimal_merge_cost [int]: Optimal cost to merge all those files
Examples:
>>> optimal_merge_pattern([2... | 724e9a380df3967e127c6e4d389a2aaedd3c4ae3 | 680,387 |
def total_mass(particles):
"""
Returns the total mass of the particles set.
>>> from amuse.datamodel import Particles
>>> particles = Particles(3)
>>> particles.mass = [1.0, 2.0, 3.0] | units.kg
>>> particles.total_mass()
quantity<6.0 kg>
"""
return particles.mass.sum() | 2865105a8813eeaa3e77da6056051e8605a6e32d | 680,393 |
def _str_to_int(_str):
"""Convert the input str to an int if possible
:param _str: input string
:return: integer if text is a digit, else string
"""
return int(_str) if _str.isdigit() else _str | 07fc15199455ed611fa678efe51d94d35791b8b2 | 680,396 |
def proto_to_bytes(proto):
""" Converts a proto object to a bytes array """
return proto.SerializeToString() | 2e4b00727851131eb367385e9dec69fd2427cc96 | 680,398 |
def gen_key_i(i, kappa, K):
"""
Create key value where key equals kappa, except:
key_(i mod n) = kappa_(i mod n) XOR K_(i mod n)
Parameters:
i -- integer in [0,n-1]
kappa -- string
K -- string
Return:
key -- list of bool
"""
# Transform string into list of booleans
kappa = list(kappa)
kappa = [boo... | 93b69742cc2476b93d2d568ab21bb0f4af276e95 | 680,406 |
def get_intent_queries(infold, intent_names, mode):
""" Get list of queries with their corresponding intent number. """
intent_queries = ['sentence\tlabel\n']
for index, intent in enumerate(intent_names):
queries = open(f'{infold}/{mode}set/{intent}.csv', 'r').readlines()
for query in queri... | f4fa21859874f68adfcadbe20b5dea925556c56a | 680,411 |
from typing import Tuple
def irot(x: int, y: int, deg: int, origin: Tuple[int, int] = (0, 0)) -> Tuple[int, int]:
"""
Rotate an integer point by `deg` around the `origin`. Only works when deg % 90 == 0.
"""
transformed_x = x - origin[0]
transformed_y = y - origin[1]
assert deg % 90 == 0
fo... | 49b47e7ffc70c08d72f4af1189b16f28038f300d | 680,412 |
def lsearch(l,pattern):
""" Search for items in list l that have substring match to pattern. """
rvals = []
for v in l:
if not v.find(pattern) == -1:
rvals.append(v)
return rvals | e49d5cbf17d2e7c7b6e5bdf0c1c66e481760db82 | 680,413 |
def parse_to_short_cmd(command):
"""Takes any MAPDL command and returns the first 4 characters of
the command
Examples
--------
>>> parse_to_short_cmd('K,,1,0,0,')
'K'
>>> parse_to_short_cmd('VPLOT, ALL')
'VPLO'
"""
try:
short_cmd = command.split(',')[0]
return ... | 6f1b69d6c3b642265fb13e72bf8b207123a24788 | 680,415 |
import hashlib
def md5sum(path):
"""Return the MD5 hash of the file contents.
"""
BUF_SIZE = 1024 * 64
buf = bytearray(BUF_SIZE)
mv = memoryview(buf)
md5 = hashlib.md5()
with open(path, 'rb') as fh:
while True:
num_bytes = fh.readinto(buf)
md5.update(mv[:num... | 6ac92d7074f650d1caa6246e18908ff9de032beb | 680,416 |
def allowed_file(filename, extensions):
"""
chceck if file extension is in allowed extensions
:param filename: name of file
:param extensions: allowed files extensions
:return: True if extension is correct else False
"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in extens... | 447c7cafebf501d69f45ec123589d25ac06cb2c0 | 680,417 |
def parse_bool(val):
"""
Parse bool value from cli.
Must be represented by integer number 0 or 1.
Return: (bool) True/False
"""
try:
val = int(val)
assert val == 0 or val == 1, 'Wrong value: {}'.format(val)
except:
raise ValueError('Cannot parse flag {}. It must an ... | 5faf07c03264ec94febff293b6503821fe824977 | 680,420 |
def is_list_or_tuple(x):
"""Return True if list or tuple."""
return isinstance(x, tuple) or isinstance(x, list) | 0857f275f9daf5535145feb29cf360e98d912fdd | 680,422 |
import torch
def get_box_attribute(probability):
"""
Return the argmax on `probability` tensor.
"""
return torch.argmax(probability, dim=-1) | 1edca219b316e1e6d53378c492f471691227fe1f | 680,426 |
def parse_arg_array(arguments):
"""
Parses array of arguments in key=value format into array
where keys and values are values of the resulting array
:param arguments: Arguments in key=value format
:type arguments: list(str)
:returns Arguments exploded by =
:rtype list(str)
"""
resu... | 7158b1b2cfb754a19cbf430cd2287027c882d986 | 680,427 |
def get_json_data(json_dict):
"""
Parameters
----------
json_dict : :obj:`dict`
QCJSON dictionary.
Returns
-------
:obj:`list` [:obj:`int`]
Atomic numbers of all atoms
:obj:`list` [:obj:`float`]
Cartesian coordinates.
:obj:`float`
Total energy of the... | 52b93f4a709213bcfd1c40f982abb14dd2c8eaf1 | 680,430 |
def get_total(shopping_list, prices):
"""
Getting shopping list and prices for goods in it,
returns total cost of available products.
>>> goods = {'Apple': 2.5, 'Pear': 1, 'Pumpkin': 1.5}
>>> prices = {'Apple': 9.50, 'Pear': 23.80, 'Pumpkin': 4.50}
>>> get_total(goods, prices)
54.3
If... | 1232ee95ee924efc3226d56cce49bbc13e4ccab0 | 680,433 |
def create_index_query(node_type, indexed_property):
""" Create the query for the index statement. See:
https://neo4j.com/docs/cypher-manual/current/indexes-for-search-performance/
"""
print(f'CREATE INDEX ON :{node_type}({indexed_property});')
return f'CREATE INDEX ON :{node_type}({indexed_property... | 2f73b64cd1fc00ad1dcdffa155b444923d304169 | 680,439 |
def get_indexes(dfobj, value):
"""Get a list with location index of a value or string in the
DataFrame requested.
Parameters
----------
dfobj : pandas.DataFrame
Data frame where the value will be searched.
value : str, int, float
String, integer or float to be searched.
Ret... | 1b149bec6e5188609ace2eadd6e35aad833f4306 | 680,441 |
import inspect
def unwrap_fullargspec(func):
"""recursively searches through wrapped function to get the args"""
func_dict = func.__dict__
if "__wrapped__" in func_dict:
return unwrap_fullargspec(func_dict["__wrapped__"])
else:
return inspect.getfullargspec(func) | e96c5e7f439c5f1ebb95631edec7de20de5320d0 | 680,442 |
def squared_error(prediction, observation):
"""
Calculates the squared error.
Args:
prediction - the prediction from our linear regression model
observation - the observed data point
Returns:
The squared error
"""
return (observation - prediction) ** 2 | ed527984eeb79c485ab3bb81def8f1aaa45363ac | 680,448 |
from typing import Counter
def recover_message(messages, least_frequent=False):
"""For each position in the recovered message,
find the most- (least-) frequently-occurring
character in the same position in the set of
raw messages.
"""
i = len(messages) if least_frequent else 1
return ''.jo... | 90349dc430602b683994c05ce917e3ff0ba3140e | 680,449 |
def strip_leading_zeros(version: str) -> str:
"""
Strips leading zeros from version number.
This converts 1974.04.03 to 1974.4.3 as the format with leading month and day zeros is not accepted
by PIP versioning.
:param version: version number in CALVER format (potentially with leading 0s in date an... | 4e4381d558d932dfd7644d2689b0d089cde82359 | 680,453 |
def tie_account_to_order(AccountKey, order):
"""tie_account_to_order - inject the AccountKey in the orderbody.
An order specification is 'anonymous'. To apply it to an account it needs
the AccountKey of the account.
Parameters
----------
AccountKey: string (required)
the accountkey
... | 5046a7cb0d8f6dac27c413be9011c214fcc110cf | 680,457 |
def renamefromto(row, renaming):
"""Rename keys in a dictionary.
For each (oldname, newname) in renaming.items(): rename row[oldname] to
row[newname].
"""
if not renaming:
return row
for old, new in renaming.items():
row[new] = row[old]
del row[old] | 5da935a61b929408269f7e47ab3ea0c3e8009bce | 680,458 |
import json
def is_bootstrap(event):
"""
Determines if the message sent in was for an bootstrap action -
Bootstrap (success) events are always just strings so loading it as json should
raise a ValueError
"""
try:
message = json.loads(event['Records'][0]['Sns']['Message'])
if is... | 40d66c461428c018420f7a2873dce2b08a60bbb3 | 680,459 |
from typing import Any
import yaml
def to_yaml_str(val: Any) -> str:
"""
:param val: value to get yaml str value of
:return: direct str cast of val if it is an int, float, or bool, otherwise
the stripped output of yaml.dump
"""
if isinstance(val, (str, int, float, bool)):
return st... | 4d8079c953e74da04041569d84880abeadeb59db | 680,462 |
def remove_comments(line):
"""
Remove all comments from the line
:param line: assembly source line
:return: line without comments (; ....)
"""
comment = line.find(';')
if comment >= 0:
line = line[0:comment]
return line | 92a19ac6d1e3eb2114800b961ea41e6d94d6c7f2 | 680,463 |
import re
def like(matchlist: list, array: list, andop=False):
"""Returns a list of matches in the given array by doing a comparison of each object with the values given to the matchlist parameter.
Examples:
>>> subdir_list = ['get_random.py',
... 'day6_15_payload-by-port.py',
... '... | b7cf450cdd06bd8e0e3bc6d35c3a6f8ba0cfa457 | 680,465 |
def colvec(vec):
""" Convert to column vector """
return vec.reshape(-1, 1) | 479de34100ca13ecda09b4c7fc012763737197ea | 680,473 |
def parse_genes(gene_file):
"""Select gene to exclude: where sgt column is not 'yes'
input: csv file with genes
return: set of genes which should be exluded"""
to_exlude = set()
with open(gene_file) as lines:
next(lines)
for line in lines:
gene, _, _, sgt = line.split('\... | 91e236e18ee0da44567cdd3c6888e0036b88394d | 680,474 |
def intervals_to_list(data):
"""Transform list of pybedtools.Intervals to list of lists."""
return [interval.fields for interval in data] | d8ca9ffbc138fb277a329c0a538e3318680b8181 | 680,477 |
def consume(queue_name):
"""
Decorate a function to signal it is a WCraaS consumer and provide its queue name.
>>> @consume("awesome_queue")
... def func(): pass
...
>>> func.is_consume
True
>>> func.consume_queue
'awesome_queue'
"""
def decorator(fn):
fn.is_consume ... | 55f20c98860fab686e3c11c72663007b81716f44 | 680,482 |
def presale_investor_4(accounts) -> str:
"""Test account planted in fake_seed_investor_data.csv"""
return accounts[9] | 21e5c64974ccfc00622b3ec39e4815e3dd9c0077 | 680,484 |
import numbers
def is_numeric(value):
"""Return True if value is really numeric (int, float, whatever).
>>> is_numeric(+53.4)
True
>>> is_numeric('53.4')
False
"""
return isinstance(value, numbers.Number) | 9fec44333b3f4da7ac33f3a7d970c0cc494ce908 | 680,489 |
def RIGHT(string, num_chars=1):
"""
Returns a substring of length num_chars from the end of a specified string. If num_chars is
omitted, it is assumed to be 1. Same as `string[-num_chars:]`.
>>> RIGHT("Sale Price", 5)
'Price'
>>> RIGHT('Stock Number')
'r'
>>> RIGHT('Text', 100)
'Text'
>>> RIGHT('Te... | d45021b3d9f89d2cc5ad8533d194a8c6ead87d17 | 680,490 |
import math
def degrees(d):
"""Convert degrees to radians.
Arguments:
d -- Angle in degrees.
"""
return d / 180 * math.pi | 27ca9cab77c874af6272731a361f2e6755523f6d | 680,494 |
def gasoline_cost_sek(dist, sekpl=20.0, kmpl=9.4):
"""Gets cost of commute via car in Swedish Krona.
Input
dist: distance in kilometers (numeric)
sekpl: Swedish Krona (SEK) per liter (L). Obtained from gasoline_price() function.
kmpl: Kilometers (km) per liter (L). (Fuel efficiency)
... | 197609d19e7ec3c03cf85e10ef4cbb9aec3d2795 | 680,497 |
def reverse_array_2(arr, start, end):
"""
A method to reverse an array within the given start and end ranges
Space complexity = O(1)
Time complexity = O(n)/2
:param arr: The array to reverse
:param start: The start index within array to reverse
:param end: The end index within array to rev... | 40a7f1848fbc73f67af8e451823ef140ebc5fc6a | 680,499 |
import typing
def trace_lines_model_checking_mode(stdout) -> typing.List[typing.List[str]]:
"""
Returns list of lists. Each sublist is a list of lines
that make a trace.
Args:
stdout : stdout of TLC execution run in model checking mode
"""
ret = []
lines = stdout.split("\n")
h... | 26b57ee29370a764b51961d672c5969050dccb85 | 680,500 |
from typing import List
from typing import Any
def pad_list(l: List[Any], length: int, item: Any) -> List[Any]: # noqa: E741
"""Pads a list to the specified length.
Note that if the input list is longer than the specified length it is not
truncated.
Args:
l: The input list.
length: ... | 97b2a11a3e88598ad7f456133b7c7e2779295a96 | 680,501 |
def get_user_id(flickr, user):
"""Get the user_id from the username."""
user_data = flickr.people.findByUsername(username=user)
return user_data['user']['id'] | 26a4d45cb04b6599c9bb6b519806ebb6e3263b8f | 680,506 |
import math
def angle_to_pixel(angle, fov, num_pixels):
"""
angle: object angle
fov: field of view of the camera
num_pixels: number of pixels along the dimension that fov was measured
"""
if angle > 90.0 or angle < -90.0:
raise ValueError
x = math.tan(math.radians(angle))
limi... | 498e867ad678aba82815af6d54f35be68a14ade7 | 680,509 |
def create_data_dict(data):
"""
Function to convert data to dictionary format
Args:
-----------
data: train/dev data as a list
Returns:
--------
a dictionary containing dev/train data
"""
train = {}
train['para'] = []
train['answer'] = []
train['question'] = []
... | adf57e19186b2bf4f28a58b50851bb19782cef8c | 680,514 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.