content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def Vabrms_calc(va,vb):
"""Inverter terminal voltage - line to line RMS"""
return abs(va-vb)/math.sqrt(2) | aeb9b30990513f88d4a671c7de035d0a5cd64296 | 10,048 |
import re
def get_value(text, regex, value_type=float):
"""Dump a value from a file based on a regex passed in."""
pattern = re.compile(regex, re.MULTILINE)
results = pattern.search(text)
if results:
return value_type(results.group(1))
else:
print("Could not find the value {}, in t... | 6c4b9990dab2d8fe9f55c7a8f8c97011d3857b01 | 10,050 |
def numberofdupes(string, idx):
"""return the number of times in a row the letter at index idx is duplicated"""
# "abccdefgh", 2 returns 1
initial_idx = idx
last = string[idx]
while idx+1 < len(string) and string[idx+1] == last:
idx += 1
return idx-initial_idx | e5b9aa310c821683632dbec1ce3ab9a8bf8a08b7 | 10,051 |
def _decline(di, t, qoi, b):
"""Arp's equation for general decline in a well
- qoi: initial rate of production
- di: initial decline rate
- b: curvature (b=0 exponential)
"""
return qoi / ((1 + b * di * t) ** (1 / b)) | 86368cef4d7d24bff738d5fe4acde2a1a9fb8922 | 10,057 |
import hashlib
def gen_robohash(s, size=200):
"""Return URL for robohash pic for sha1 hash of string ``s``"""
h = hashlib.sha1(s).hexdigest()
return ('http://robohash.org/{0}.png?size={1}x{1}&bgset=bg2&set=set1'
.format(h, size)) | f4ac71b54801a3b86e3ec4e0cf60f25a9cae5990 | 10,058 |
from typing import Any
import attr
def validated() -> Any:
"""Decorate an entity to handle validation.
This will let ``attrs`` manage the class, using slots for fields, and forcing attributes to
be passed as named arguments (this allows to not have to defined all required fields first, then
optional ... | 6903d654e74b6bd6fc2d062755823043125c922a | 10,065 |
def keep_type(value):
"""
Keep hook returned value type
:param value: Value to be returned
:return: Any
"""
return value | f5048e2863aca6eced8c3be76a3623fd5f3a808e | 10,071 |
def find_nodes(graph, query, data=False):
""" Iterator over all nodes matching the data query.
"""
return ((v, graph.nodes[v]) if data else v
for v in graph if query(graph.nodes[v])) | e8f2e25f843133446c32ca7f012ac2aa1b80d2b9 | 10,076 |
def _SigninUIState(oobe):
"""Returns the signin ui state of the oobe. HIDDEN: 0, GAIA_SIGNIN: 1,
ACCOUNT_PICKER: 2, WRONG_HWID_WARNING: 3, MANAGED_USER_CREATION_FLOW: 4.
These values are in chrome/browser/resources/chromeos/login/display_manager.js
"""
return oobe.EvaluateJavaScript('''
loginHeader = docu... | 355b7ebbaf0010165109c27162ca70f5168abe05 | 10,077 |
import hmac
import hashlib
def generate_dendrite_mac(shared_secret: str, username: str, password: str, admin: bool) -> str:
"""
Generate a MAC for using in registering users with Dendrite.
"""
# From: https://github.com/matrix-org/dendrite/blob/master/clientapi/routing/register.go
mac = hmac.new(
... | bed29168d88db0d9b2bd0bf95f493a9d4b5e7a3f | 10,080 |
def _cmpPair2(a, b):
"""Auxiliary comparision for sorting lists of pairs. Sorting on the second member of the pair."""
(x, y), (z, w) = a, b
if y < w:
return -1
elif y > w:
return 1
elif x < z:
return -1
elif x > z:
return 1
else:
return 0 | 5567ddc006756e224dde545503c427a3524c3c90 | 10,084 |
def toExport8F8(op):
"""Converts number to exportable 8.8 signed fixed point number."""
return int(round(op * 256.0)) | 3364703913e1c87223ffb11bdaf3b622db7eef1c | 10,085 |
import math
def LogRegressNomalize(value):
"""Uses log regress to normalize (-inf, inf) to [0, 1]."""
value_exp = math.exp(value)
return value_exp / (value_exp + 1) | a5d30077df70b3795754d62c6534781e61482f13 | 10,086 |
def to_dict(conf):
"""Converts a Config object to a dictionary.
Args:
conf (Config): A Config object
Returns:
dict: A multi-level dictionary containing a representation ogf the configuration.
"""
return conf._xpipe_to_dict() | 6c709e04f1ffb88b5b5563defc2a03fabfafbb1e | 10,096 |
def valid_hex(value):
"""Check if the string is a valid hex number representation."""
try:
int(value, 16)
except Exception:
return False
return True | 4037b9103cd3308253f929d0a4cbbe3f37c1c219 | 10,099 |
def get_mapvars(mapfile):
"""Read the sugar .map file and return a dictionary
where the key is the variable name and the value is the (start,r0,r1)
where r0 is the first ordinal and r1 is the last. Sugar uses uniary encoding."""
mapvars = {}
with open(mapfile,"r") as f:
for line in f:
... | c149270a4f1a86707b7ee5e2ed437b5736a2a986 | 10,100 |
def is_in_period(month, period):
"""Return which months fall within a specified group of calendar months.
Parameters
----------
month : int or iterable of ints
One or a series of calendar month numbers [1..12].
period : tuple of ints
Group of calendar month numbers to match against.... | e973f1ec11ea4dc6b87834c75d6374bbbb152635 | 10,105 |
def once(f):
"""Decorator. Defer to f once and only once, caching the result forever.
Users with a functional background may recognize the concept of a `thunk`.
"""
unset = val = object()
def _helper(*args, **kwargs):
nonlocal val
if val is unset:
val = f(*args, **kwa... | 39e900779a6665155fe83770964e509ff88a12c4 | 10,106 |
import hashlib
def _hash_file(fpath, chunk_size=65535):
"""
Calculates the md5 hash of a file
:param fpath: path to the file being validated
:param chunk_size: Bytes to read at a time (leave unless large files)
:return: The file hash
"""
hasher = hashlib.md5()
with open(fpath, 'rb') ... | 9f17f13f487f95620ad705a6f2b23d57407e640e | 10,109 |
def midpoint(start, end):
"""Find the mid-point between two points."""
x0, y0 = start
x1, y1 = end
return (x0+x1)/2, (y0+y1)/2 | dab5a66b8af759998a295d64ba3711b6e99e4c27 | 10,110 |
import re
def replace_pair(pair, content):
"""
Uses regex to locate a pair.
First element of the tuple is the original error token.
Second element of the tuple is the replacement token.
"""
return re.sub(pair[0], ' {} '.format(pair[1]), content) | 022633d417393959a94629117a1e664709770571 | 10,113 |
from datetime import datetime
def extract_sitename_date(directory_path,
sitename_location,
datetime_location):
"""Extract sitename and datetime from directory path name.
Parameters
-----------
directory_path : string
A path to the directory ... | 86a2085ba68b234585ef9855da64fa1fdd5459ce | 10,115 |
def multi_dict_unpacking(lst):
"""
Receive a list of dictionaries, join them into one big dictionary
"""
result = {}
for d in lst:
for key, val in d.items():
result[key] = val
return result | 530947224d682cffb809e83f308a97a108002080 | 10,118 |
import math
def dist(a: list, b: list) -> float:
"""Calculate the distancie between 2 points
Args:
a (list): point a
b (list): point b
Returns:
float: Distance between a and b
"""
return math.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2) | 7ad6d2f36c0bccee106c7b54a4abebd246c4a3fa | 10,119 |
def get_middle_opt(string: str) -> str:
"""Get middle value of a string (efficient).
Examples:
>>> assert get_middle_opt('middle') == 'dd'
"""
return (
string[int(len(string) // 2) - 1 : int(len(string) // 2) + 1]
if not len(string) % 2
else string[int(len(string) // 2)]... | 1636f39e22bacc4f571de876dd71add690e940e6 | 10,121 |
def duration(duration):
"""Filter that converts a duration in seconds to something like 01:54:01
"""
if duration is None:
return ''
duration = int(duration)
seconds = duration % 60
minutes = (duration // 60) % 60
hours = (duration // 60) // 60
s = '%02d' % (seconds)
m = '%0... | 7cd89654a84c2e3e41d96cb1b13688833ee54387 | 10,122 |
import types
def name(function):
"""
Retrieve a pretty name for the function
:param function: function to get name from
:return: pretty name
"""
if isinstance(function, types.FunctionType):
return function.__name__
else:
return str(function) | 4002d7a945c3b3e3e4d957c0b10ff202f2cf0246 | 10,123 |
import requests
def get_response_json(url: str):
"""
Function get response json dictionary from url.
:param url: url address to get response json
:type url: str
:return: dictionary data
:rtype: json
:usage:
function calling
.. code:: python
get_response_json... | dd209b1dba7f4320cd91addb1e49fa98bab0ae2b | 10,124 |
import pickle
def dumps_content(content):
"""
pickle 序列化响应对象
:param content: 响应对象
:return: 序列化内容
"""
return pickle.dumps(content) | f88159b9d016a6e39744e7af09a76705c9f4e76f | 10,125 |
def split_data(data, ratio, shuffle=1):
"""Split dataset according to ratio, larger split is first return"""
n_exs = len(data[0])
split_pt = int(n_exs * ratio)
splits = [[], []]
for col in data:
splits[0].append(col[:split_pt])
splits[1].append(col[split_pt:])
return tuple(splits... | fc837dd9f721950dde18cee9ec33eab5e3e96f77 | 10,133 |
def delBlank(strs):
"""
Delete all blanks in the str.
"""
ans = ""
for e in strs:
if e != " ":
ans += e
return ans | a6155af200918819055533057f63b4b44c8dd508 | 10,139 |
import re
def splitn(s, n):
"""split string s into chunks no more than n characters long"""
parts = re.split("(.{%d,%d})" % (n, n), s)
map(parts.remove, [""] * parts.count(""))
return parts | 3f0f697f54515e26f98bc08b53cb4d39952ed128 | 10,140 |
import csv
def LoadMOS(mos_csv):
"""Load a csv file withMOS scores.
Args:
mos_csv: Path to a csv file that has degraded and MOS.
Returns:
Dictionary with filename keys and MOS values
"""
mos_dict = {}
with open(mos_csv, 'r') as csvfile:
mos_reader = csv.reader(csvfile)
for row in mos_rea... | e98cbf93e3bc889a31a98ff32a9f9189a850a55f | 10,142 |
import unicodedata
def url_is_invalid_unicode(url_string):
""" Check for unicode control characters in URL """
for x in str(url_string):
if unicodedata.category(x)[0] == "C":
return True
return False | d1a3974b24023c46a337c7e17718e00aa5916c7d | 10,143 |
import string
def escape_bytes(bytes_):
"""
Convert a bytes object to an escaped string.
Convert bytes to an ASCII string. Non-printable characters and a single
quote (') are escaped. This allows to format bytes in messages as
f"b'{utils.escape_bytes(bytes)}'".
"""
res = ""
for byte i... | c1a6c2875824d8576e7d9c349f19548e2c3313e8 | 10,147 |
def shrink_dimensions(width, height, max_dimension):
"""
Resize dimensions so max dimension is max_dimension. If dimensions are too small no resizing is done
Args:
width (int): The width
height (int): The height
max_dimension (int): The maximum size of a dimension
Returns:
... | 60d4a6ec9b310f7c22f341f1309b4677c3617fd2 | 10,148 |
import json
def get_id_set(id_set_path: str) -> dict:
"""
Parses the content of id_set_path and returns its content.
Args:
id_set_path: The path of the id_set file
Returns:
The parsed content of id_set
"""
with open(id_set_path, 'r') as id_set_file:
id_set = json.load(... | 244495603bf423324ef4b3ffe4b1fdc3ca7fdf74 | 10,152 |
def format_label_value(*values):
"""
Construct a label value.
If multiple value components are provided, they are joined by underscores.
"""
return '_'.join(values) | 46bb4e968577c95d5dd0df8b9687efbfdcc0568e | 10,154 |
def _get_timeout(value):
"""
Turn an input str or int into a float timeout value.
:param value: the input str or int
:type value: str or int
:raises ValueError:
:returns: float
"""
maximum_dbus_timeout_ms = 1073741823
# Ensure the input str is not a float
if isinstance(value, ... | b8205cb34b90b856b4dda2a028f801b4cd70d7b4 | 10,158 |
def getAnswer(x,input_string):
"""Iegūst mainīgajam x vērtību 1 vai 2, parādot tekstu input_string.
Ja ievadīta nepareiza vērtība, tad tiek paradīta kļūdas ziņa."""
while True:
try:
x = int(input(input_string))
if x < 1:
raise ValueError
elif x > 2:
r... | 66f8b1cccef5fb710713f1c6498248dd0f3517ea | 10,160 |
from typing import Optional
from typing import Union
import struct
def encode_key(
key: str, value: Optional[Union[int, float, str]] = None, value_type: str = "str"
) -> bytes:
"""Encode given header key to a bytes string.
Parameters
----------
key : str
header key
value : Optional[Un... | b38e04fdbd761bd121f0e08a9eee9dfb692f616c | 10,161 |
import json
def get_numeric_project_id(gcloud, project_id):
"""Get the numeric project ID."""
project_info = json.loads(
gcloud.run('projects', 'describe', project_id, '--format=json'))
return project_info['projectNumber'] | f9e3086ed1436d4ce075960c191ff4f64a76582b | 10,165 |
from functools import reduce
from operator import add
def fitness(individual,target):
"""
individual : the individual to evaluate (a list)
target : the target sum the individuals are aiming for
"""
sum = reduce(add,individual,0)
return abs(target-sum) | bcfb4d857be926df249149e224babbc98d358780 | 10,167 |
def create_schema(name: str) -> str:
"""Function for generating create schema statements
:param str name: The name of the schema
:return: Create statement
:rtype: str
"""
statement = f"CREATE SCHEMA {name}"
return statement | a82d392ec411e2c412ef3f1959ff7ab229130532 | 10,168 |
def courant(dx, dt, v_max, **kwargs):
"""
Calculate the Courant's number describing
stability of the numerical scheme.
Parameters
----------
dx : float
Size of the spatial grid cell [m].
dt : float
Time step [s].
v_max : float
Max. velocity of the model.
Returns
-------
C : flo... | 58b09b545c4679b845c3e2702af8bffe4262c599 | 10,169 |
import math
def standard_deviation(series):
"""
implements the sample standard deviation of a series from scratch
you may need a for loop and your average function
also the function math.sqrt
you should get the same result as calling .std() on your data
https://pandas.pydata.org/pandas-docs/st... | 01a488f4bc8168a92d4a0590daa88bad08032fed | 10,172 |
def unify_projection(dic):
"""Unifies names of projections.
Some projections are referred using different names like
'Universal Transverse Mercator' and 'Universe Transverse Mercator'.
This function replaces synonyms by a unified name.
Example of common typo in UTM replaced by correct spelling::
... | a3cdf4bb2a26ee0391281e8f8b0d3e7ea5c8a962 | 10,173 |
import requests
def api_request(url, api_key=None):
"""
This function takes a url and returns the parsed json object. If necessary, it submits the auth header
"""
if api_key:
return requests.get(url, headers={'Authorization': 'Token ' + api_key}).json()
else:
return requests.ge... | ea8572d761dffb952b970ab14e73307a02f67ee8 | 10,184 |
def getbitlen(bint):
"""
Returns the number of bits encoding an integer
"""
return bint.bit_length() | f6ae3253e767382959d372eb5e4612fb85c89ffc | 10,195 |
def calc_max_cpu(records):
""" Returns the CPU usage at the max temperature, ever
:param records: a list of records of min, max temp and associated CPU avg load
:return: a record with the highest recorded temperature, and the associated list of CPU loads
"""
max_temp = 0
cpu_loads = []
for ... | bee21fadb3fcf9cdbbce79f6281f48350b3ffceb | 10,198 |
from typing import List
def longest_substring_using_nested_for_loop(s: str) -> int:
"""
Given a string s, find the length of the longest substring without repeating characters.
https://leetcode.com/problems/longest-substring-without-repeating-characters/
3946 ms 14.2 MB
>>> longest_substring_usin... | 996ce5fcb956012cb75fef35c6bec8be6ecad461 | 10,202 |
import re
def isSane(filename):
"""Check whether a file name is sane, in the sense that it does not contain any "funny" characters"""
if filename == '':
return False
funnyCharRe = re.compile('[\t/ ;,$#]')
m = funnyCharRe.search(filename)
if m is not None:
return False
if filena... | d9e8bac7ebad1fd2af024f8880e255fcb40db68c | 10,203 |
import csv
import itertools
def csv_read_row(filename, n):
""" Read and return nth row of a csv file, counting from 1. """
with open(filename, 'r') as f:
reader = csv.reader(f)
return next(itertools.islice(reader, n-1, n)) | a95cf8ed35b61acff418a02bfa5f8285f589e6d6 | 10,205 |
def load_proto(fpath, proto_type):
"""Load the protobuf
Args:
fpath: The filepath for the protobuf
Returns:
protobuf: A protobuf of the model
"""
with open(fpath, "rb") as f:
return proto_type().FromString(f.read()) | 7b6bcf6d2e56f2ca4087a9ec769b16a986511c55 | 10,206 |
from typing import Union
from pathlib import Path
def _filename(path: Union[str, Path]) -> str:
"""Get filename and extension from the full path."""
if isinstance(path, str):
return Path(path).name
return path.name | 552655ff66ec6cd42b57ada6080df9dc34db1bd0 | 10,211 |
import time
def log_str(proc_str, start):
"""Create a preamble string for stdout."""
former = "[{:>4}".format(proc_str)
latter = "] {:.2f}".format(round(time.time() - start, 3))
return former + latter | 5f4f82e758cf87ff643a20928e5c0f7368ef537f | 10,218 |
def linear_kernel(X, Y=None):
"""Compute linear Gram matrix between X and Y (or X)
Parameters
----------
X: torch.Tensor of shape (n_samples_1, n_features)
First input on which Gram matrix is computed
Y: torch.Tensor of shape (n_samples_2, n_features), default None
Second input on whic... | b1389059e755fa19bb26c88cf8c9f6ab39d51aec | 10,219 |
def split_date(dates):
"""
Split datetime64 dates into year, month, day components.
"""
y = dates.astype("<M8[Y]").astype(int) + 1970
m = dates.astype("<M8[M]").astype(int) % 12 + 1
d = (dates - dates.astype("<M8[M]")).astype("<m8[D]").astype(int) + 1
return y, m, d | 7152dbdd1f839ef3c401de06631fb0a249c36642 | 10,220 |
def process_failed(returncode, stdout):
"""Return True if the process failed."""
if returncode != 0:
return True
if 'badly_formatted' in stdout:
return True
return False | 2d3c84872acf3bf6592316aa95c39e41a6da849e | 10,224 |
def evaluate_quadratic(J, g, s, diag=None):
"""Compute values of a quadratic function arising in least squares.
The function is 0.5 * s.T * (J.T * J + diag) * s + g.T * s.
"""
if s.dim() == 1:
Js = J.mv(s)
q = Js.dot(Js)
if diag is not None:
q += s.dot(s * diag)
e... | cde6067f22ef3a146b80fb5324c0c1a8ce2e65a4 | 10,225 |
def vdowham(eta, vel_entrain, e_eff, r_eff):
"""
Calculate the velocity parameter of the contact problem according to
Dowson-Hamrock.
Parameters
----------
eta: ndarray, scalar
The dynamic viscosity of the lubricant.
vel_entrain: ndarray, scalar
The entrainment velocity of ... | e8abfcc3d312ffce0c192a3b890fe8f3a6785e76 | 10,234 |
def compute_convergence(output, output_prev):
"""
Compute the convergence by comparing with the output from the previous
iteration.
The convergence is measured as the mean of a XOR operation on two vectors.
Parameters
----------
output, output_prev : np.ndarray
Current and previous... | 7ea1e931598ed8dcf8466fb4df327391943187c1 | 10,235 |
import json
def get_profile_name(host, network):
"""
Get the profile name from Docker
A profile is created in Docker for each Network object.
The profile name is a randomly generated string.
:param host: DockerHost object
:param network: Network object
:return: String: profile name
""... | 37128df21074c75e53e9567c51301c76578947f2 | 10,237 |
def _absolute_path(repo_root, path):
"""Converts path relative to the repo root into an absolute file path."""
return repo_root + "/" + path | bae7013db933e58343f0d6b3f90dfa100de74b7e | 10,240 |
def aic(L, k):
"""
Akaike information criterion.
:param L: maximized value of the negative log likelihood function
:param k: number of free parameters
:return: AIC
"""
return 2*(k + L) | 159a02cc19d2b4eab30dd13c1cd2b802777277ad | 10,242 |
def prepare_update_sql(list_columns, list_values, data_code=100):
"""
Creates a string for the update query
:param list_columns: columns that are in need of an update
:param list_values: values where the columns should be updated with
:param data_code: data code to add to the columns
:return: st... | cc3f3c548623bdeb4d2e4e12cc3205baf0a9e9ba | 10,245 |
def onBoard(top, left=0):
"""Simplifies a lot of logic to tell if the coords are within the board"""
return 0 <= top <= 9 and 0 <= left <= 9 | 2b2007ae2e3acdbb9c04c3df1397cffce97c6717 | 10,247 |
def name( path ):
"""Extracts the resource name."""
return path[1+path.rfind('/'):] | 7e8448e5b1c62c30e7ae28c80580731aa9f6f9fb | 10,250 |
def report_dfa(q_0, dfa, g):
"""
Give a complete description of the DFA as a string
"""
output = ""
output += "----------- DFA ----------- " + "Goal: " + g + " ----------- \n"
transitions = [(i,dfa[(i,sigma)],sigma) for i,sigma in dfa]
transitions.sort()
for i,j,sigma in transitions:
output += (f"delta({i},{s... | 99d86557b9e1aede93f46e1ef78ecb1fe6cdbf30 | 10,251 |
def shutting_down(globals=globals):
"""
Whether the interpreter is currently shutting down.
For use in finalizers, __del__ methods, and similar; it is advised
to early bind this function rather than look it up when calling it,
since at shutdown module globals may be cleared.
"""
# At shutdow... | 01f601b989611b06a438a3be3e15937eff389038 | 10,255 |
def add_xls_tag(file_name):
"""
Check the file_name to ensure it has ".xlsx" extension, if not add it
"""
if file_name[:-5] != ".xlsx":
return file_name + ".xlsx"
else:
return file_name | e053d9f7dad8e638122e93d05e49c5a06de3e664 | 10,258 |
def pedestal_ids_file(base_test_dir):
"""Mock pedestal ids file for testing."""
pedestal_ids_dir = base_test_dir / "auxiliary/PedestalFinder/20200117"
pedestal_ids_dir.mkdir(parents=True, exist_ok=True)
file = pedestal_ids_dir / "pedestal_ids_Run01808.0000.h5"
file.touch()
return file | edda4c192e577774e0cc4a38aaa7d838127e7dcd | 10,263 |
def get_fa_icon_class(app_config):
"""Return Font Awesome icon class to use for app."""
if hasattr(app_config, "fa_icon_class"):
return app_config.fa_icon_class
else:
return 'fa-circle' | 3766abb1f80b7ccea9e09a5edf011f1586e9b49e | 10,264 |
from typing import Any
def get_valid_ref(ref: Any) -> str:
"""Checks flow reference input for validity
:param ref: Flow reference to be checked
:return: Valid flow reference, either 't' or 's'
"""
if ref is None:
ref = 't'
else:
if not isinstance(ref, str):
raise ... | 16c66dc9e0568bcd33e1cc9956ed31b5ae47595e | 10,267 |
def cut_rod2(p, n, r={}):
"""Cut rod.
Same functionality as the original but implemented
as a top-down with memoization.
"""
q = r.get(n, None)
if q:
return q
else:
if n == 0:
return 0
else:
q = 0
for i in range(n):
... | 2fa1433dffb9099709e466025645c4981f289692 | 10,270 |
def monthly_file_name(var, model, rcp):
"""Function for creating file connections for different variables
scenarios and models. Preasently, ensemble member r1i1p1 is assumed, as
well as 200601-210012 dime span for the monthly data."""
# e.g. hfls_Amon_CNRM-CM5_rcp85_r1i1p1_200601-210012.nc
f = var + "_" + "Amon_... | 7aeea6d3724c470e076645ddb96877e9fa15843f | 10,276 |
def subset(part, whole):
"""Test whether `part` is a subset of `whole`.
Both must be iterable. Note consumable iterables will be consumed
by the test!
This is a convenience function.
Examples::
assert subset([1, 2, 3], [1, 2, 3, 4, 5])
assert subset({"cat"}, {"cat", "lynx"})
... | 4200ea95e0c9ff03d0b7589812d0313c5d13cfac | 10,279 |
from pathlib import Path
def stem(fname, include_suffix=False):
"""/blah/my_file.json.gz --> my_file"""
path = Path(fname)
stem = path.stem
# If a filename has multiple suffixes, take them all off.
stem = stem[: stem.index(".")] if "." in stem else stem
if include_suffix:
stem = stem... | 9e4c557dff8583f9129215f91f8e123f062ccf52 | 10,280 |
def atol(s, base=None): # real signature unknown; restored from __doc__
"""
atol(s [,base]) -> long
Return the long integer represented by the string s in the
given base, which defaults to 10. The string s must consist
of one or more digits, possibly preceded by a sign. If base
is 0, it i... | f39aa403cbad98c448a35305c97c595bc3a77c02 | 10,283 |
def tokens_to_sovatoms(tokens: float) -> int:
"""Convert tokens to sovatoms."""
return int(tokens * 100000000) | 23f4bc3a1afc4520b5e2416332702d0a594c5039 | 10,284 |
def flow_cell_mode(info_reads):
"""Return flow cell sequencing mode."""
res = ''
if info_reads:
read_lens = [
a['num_cycles'] for a in info_reads if not a['is_indexed_read']]
if len(read_lens) == 1:
res = '1x{}'.format(read_lens[0])
elif len(set(read_lens)) ==... | 0563d0c163c2bd42b05d07fb30940669a8ef3513 | 10,289 |
def sortKey(e):
"""
This sorts the chores based on their start time.
e[0] is the start time for all the chores in my array of chores.
"""
return int(e[0]) | 00d37751d23fe6210b406485cbd76906075b2578 | 10,290 |
def merge_into_dict(original, secondary):
"""Merge two dictionaries into the first and return it.
This is simply a conveinence wrapper around the dictionary update method. In
addition to the update it returns the original dict to allow for chaining.
Args:
original: The dict which will be updated.
seco... | 899d40396885f0775f2cbaa865702ed0e5706dba | 10,291 |
def normalize_obs(obs_dict, obs_normalization_stats):
"""
Normalize observations using the provided "mean" and "std" entries
for each observation key. The observation dictionary will be
modified in-place.
Args:
obs_dict (dict): dictionary mapping observation key to np.array or
... | c866b6d18df13b9e6903b7d96024d48cde99d2ff | 10,292 |
def get_bprop_l2_loss(self):
"""Grad definition for `L2Loss` operation."""
def bprop(x, out, dout):
dx = x * dout
return (dx,)
return bprop | 6f52c07d9133939f5a7dc6d12a2416169f32147e | 10,297 |
def extract_tracklist_begin_num(content):
"""Return list of track names extracted from messy web content.
The name of a track is defined as a line which begins with a number
(excluding whitespace).
"""
tracklist = []
for line in content.splitlines():
# Empty line
if not line:
... | 7d860fb0ea444ae0d9bd536a4644fa6b1c11a826 | 10,299 |
def net_solar_radiation(rs, albedo=0.23):
"""
Calculate the fraction of the solar radiation that is not reflected from
the surface (Allen et al. 1998).
Parameters
----------
rs : float
Solar radiation (MJ m-2 day-1).
albedo : float, optional
Albedo (-), default is 0.23 (valu... | 41a8930966db4a658d1c3ec31e754987bc9ed387 | 10,300 |
def text_color(message='{}', color_code='\033[0;37m'):
"""Set text to a color, default color is White"""
no_color = '\033[0m'
return f'{color_code}{message}{no_color}' | bede08b771b33ce26bbb0ee4fd42f3712d224cc1 | 10,301 |
def register_new_user(access, username, password):
""" Register a new user & handle duplicate detection """
if access.user_data(username) is not None:
raise ValueError("User '%s' already exists!" % username)
if username in access.pending_users():
raise ValueError("User '%s' has already regis... | 25b98c4def9da81d71176aed196f61b2e71d64c5 | 10,306 |
def get_not_constant_species(model):
"""
get species of the model that are not constant
@param model: libsbml.model
@type model: libsbml.model
@return: list of species
@rtype: list[libsbml.species]
"""
def not_const(s): return not( s.getConstant() or s.getBoundaryCondition() )
return... | abb376899405fa1623ec5ca646d0399e067fd5cc | 10,307 |
from math import floor
from typing import Tuple
from typing import Union
def conv_output_shape(
h_w: Tuple[int, int],
kernel_size: Union[int, Tuple[int, int]] = 1,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
) -> Tuple[int, int]:
"""
Calculates the output shape (height and width)... | ea757a413a3b38ea024b85dd6987beda8a3b9aeb | 10,310 |
def _path(from_object, to_object):
"""
Calculates the 'path' of objects starting from 'from_object'
to 'to_object', along with the index of the first common
ancestor in the tree.
Returns (index, list) tuple.
"""
if from_object._root != to_object._root:
raise ValueError('No connecti... | 0ccfe54d36832b8dce3c55168f02abb3c79261ef | 10,312 |
def PtknsToStr(path_tokens):
"""
There are three ways to store paths:
As a single string: '/Protein/Phe/Ca' <- the format entered by the user
As a list of tokens ['Protein', 'Phe', 'Ca'] <- split into tokens
As a list of nodes in a tree (pointers to nodes in a tree hierarchy)
This functio... | 8dd64e6213f8a49f5b20619261a4b3d8daa8d95d | 10,321 |
def traverse_grid(start_cell, direction, num_steps):
"""
Helper function that iterates over the cells
in a grid in a linear direction and returns
a list of their indices.
"""
indices = list()
for step in range(num_steps):
row = start_cell[0] + step * direction[0]
col = start_... | 0ce6f91759c36a63b103ebff2cddd8dd50ca837b | 10,322 |
import requests
def open_recipe_file(file, recipes_path=None, github_repo='bioconda/bioconda-recipes'):
"""
Open a file at a particular location and return contents as string
"""
if recipes_path:
return open(f'{recipes_path}/{file}').read()
else: # if no clone of the repo is available loc... | ce5fc3c054bc937203966459e9981a5befdae40b | 10,329 |
def confidence_interval(data, column_name, confidence_level):
"""
get a 95% confidence interval from a bootstrap dataframe column
Parameters
----------
data : pandas dataframe
the bootstrap dataframe generated by :py:func:`.bootstrapLE`
column_name : string
the statistic that y... | 69668a88030c0a2d6d90dbc1b834cbab76d0ec17 | 10,330 |
def pig_latin(wrd):
"""Returns the Pig Latin version of a word.
For words that begin with a consonant, take the consonant/consonant cluster
and move it to the end of the word, adding the suffix 'ay' to the end of the word.
For words that begin with a vowel, leave the word as is and add the
suffix ... | 2eba5f4aaff1391e60f4097e526539d5b486c9bd | 10,334 |
def parse_units(units_str):
"""
Extract and parse the units
Extract the bounds over which the expression is assumed to apply.
Parameters
----------
units_str
Returns
-------
Examples
--------
>>> parse_units('Widgets/Month [-10,10,1]')
('Widgets/Month', (-10,10,1))
... | 18f35a06aedfc9d026cfa70a1217b0b5b0420ca5 | 10,335 |
def seg_pixel_accuracy_nd(label_imask,
pred_imask,
vague_idx=-1,
use_vague=False,
macro_average=True,
empty_result=0.0):
"""
The segmentation pixel accuracy (for MXNet nd-arrays).
... | 7da093ef624dee07fd335021ae2317d53583e612 | 10,336 |
def extract_seed(path, key):
""" Scrape the 5-character seed from the path and return it as an integer.
:param path: path to the tsv file containing results
:param key: substring preceding the seed, "batch-train" for splits, seed-" for shuffles
"""
try:
i = path.find(key) + len(key)
... | c5073ad43e8a966aba5382894490aa6cbc871271 | 10,338 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.