content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_duration_and_elevation(table):
""""Return an array of duration and elevation gain from an html table"""
try:
hiking_duration = str(table.contents[0].text.strip()) #av.note: want this to be numeric
except:
hiking_duration = ""
try:
elevation_gain_ft = str(
ta... | d52ca3c6e5d75ff936e44b452b05790db931dc6e | 3,646,828 |
def show_comparison(model, X_test, y_test, A_test, protected_features, prostprocess_preds):
"""
Returns Dashboard to show comparison of models based on the trade off of the disparity and accuracy
"""
FairlearnDashboard(sensitive_features=A_test, sensitive_feature_names=protected_features,
... | bc92c90c67f16c53c8c847556779d1ad923dc56c | 3,646,829 |
def my_edge(bw, threshold):
"""
2018.11.26
检测图像边缘
返回检测到的边缘二值图像
阈值用于消去检测到的噪声
时间复杂度:
Args:
bw: a grey-scale image with 8-bit depth
threshold: a decimal between 0 and 1
Returns:
bw_edge_binary: 二值化的边缘图像
Raises:
"""
m, n = bw.shape
bw0 = bw.astype(... | ea5ffd4869f0b5636ff73691761bac88316aad34 | 3,646,830 |
def csc_matvec(csc, x):
"""
Matrix vector multiplication
using csc format
"""
if not sparse.isspmatrix_csc(csc):
raise Exception("Matrix must be in csc format")
nrow, ncol = csc.shape
nnz = csc.data.shape[0]
if x.size != ncol:
print(x.size, ncol)
raise Value... | fa04c4e208333327ce6e4073a27b43f17ffb7dea | 3,646,831 |
def encode_base58(s) -> bytes:
"""
Encodes/converts any bytes to Base58 to transmit public key
"""
count = 0
for c in s:
if c == 0:
count += 1
else:
break
num = int.from_bytes(s, 'big')
prefix = '1' * count
result = ''
while num > 0:
... | 064867d9185a06f26c8f033ab04ac38621c48869 | 3,646,833 |
def save_chapter(
body,
source_lang,
target_lang,
title,
public=False,
user=None):
"""Save chapter to database
Parameters:
body (string): input text
source_lang (string): source language
target_lang (string): target language
title (string): title of the chapter
publi... | 9d85acb0a08d8e44bac86f7d3c5bec24b67a3cc1 | 3,646,836 |
def frequency(g, k, h):
"""
Computes the frequency for a given wave number and water depth
(linear dispersion relationship)
:param k: the wave number
:param g: -- gravitational acceleration
:param h: -- the water depth
:returns omega: -- wave frequency
"""
return np.sqrt(g * k * n... | c81b6721ea874506937d245bd886f129f01b69e2 | 3,646,837 |
def primitive_name(method_name):
"""Given a method_name, returns the corresponding Phylanx primitive.
This primarily used for mapping NumPy mapped_methods to Phylanx primitives,
but there are also other functions in python that would map to primitives
with different name in Phylanx, e.g., `print` is ma... | d6b1cc670503a8e8bade585f0a875b7bde4f743a | 3,646,838 |
import math
def _split_pandas_data_with_ratios(data, ratios, seed=SEED, shuffle=False):
"""Helper function to split pandas DataFrame with given ratios
Note:
Implementation referenced from `this source
<https://stackoverflow.com/questions/38250710/how-to-split-data-into-3-sets-train-validation... | 19b2ddd97a803042d1ac27df47a56b5157fd4e96 | 3,646,839 |
import requests
from datetime import datetime
def get_stock_information(stock, country, as_json=False):
"""
This function retrieves fundamental financial information from the specified stock. The retrieved
information from the stock can be valuable as it is additional information that can be used combined... | bfe70fd27c76d743f107056023a127283a76d8c4 | 3,646,840 |
from datetime import datetime
def check_export_start_date(export_start_dates, export_end_dates,
export_day_range):
"""
Update export_start_date according to the export_end_date so that it could be export_end_date - EXPORT_DAY_RANGE.
Parameters:
export_start_date: dict
... | ab2466db1107b980506d34de71c5b1849851fd10 | 3,646,841 |
def reformat_adata(
adata: AnnData, brain_region: str, num_seq_lanes: int, transgenes_list: str
):
"""
script that takes in user specified inputs in the data_reformat script
transforms dataframe input to usable AnnData output with group cell count labels,
df_obs
it also makes genes in the index... | 9f6e92b7dac8c8e84987676e7c2435a2e34f32e0 | 3,646,844 |
def chunks(list_, num_items):
"""break list_ into n-sized chunks..."""
results = []
for i in range(0, len(list_), num_items):
results.append(list_[i:i+num_items])
return results | 83da5c19c357cc996fc7585533303986bea83689 | 3,646,845 |
def form_requires_input(form):
"""
Returns True if the form has at least one question that requires input
"""
for question in form.get_questions([]):
if question["tag"] not in ("trigger", "label", "hidden"):
return True
return False | 97072a9edc494afa731312aebd1f23dc15bf9f47 | 3,646,846 |
import zlib
import json
def on_same_fs(request):
"""
Accept a POST request to check access to a FS available by a client.
:param request:
`django.http.HttpRequest` object, containing mandatory parameters
filename and checksum.
"""
filename = request.POST['filename']
checksum_i... | 2b19fe8d6a69db9cfeeea740cdcf70003e0c9ed1 | 3,646,848 |
from datetime import datetime
def get_memo(expense_group: ExpenseGroup, payment_type: str=None) -> str:
"""
Get the memo from the description of the expense group.
:param expense_group: The expense group to get the memo from.
:param payment_type: The payment type to use in the memo.
:return: The m... | 2402d7f0ff89ed7b06300f58f8bfb54c06d67f3f | 3,646,849 |
def get_prefix_for_google_proxy_groups():
"""
Return a string prefix for Google proxy groups based on configuration.
Returns:
str: prefix for proxy groups
"""
prefix = config.get("GOOGLE_GROUP_PREFIX")
if not prefix:
raise NotSupported(
"GOOGLE_GROUP_PREFIX must be s... | c81d3ede2ba1ad6b8ce716633abbc8e8f91f9a2b | 3,646,850 |
def client(tmpdir):
"""Test client for the API."""
tmpdir.chdir()
views.app.catchall = False
return webtest.TestApp(views.app) | 516230e96dff76afccc8f8a3a9dc3942c6341797 | 3,646,851 |
def list_extract(items, arg):
"""Extract items from a list of containers
Uses Django template lookup rules: tries list index / dict key lookup first, then
tries to getattr. If the result is callable, calls with no arguments and uses the return
value..
Usage: {{ list_of_lists|list_extract:1 }} (get... | 23fb863a7032f37d029e8b8a86b883dbfb4d5e7b | 3,646,852 |
from bs4 import BeautifulSoup
def get_links(url):
"""Scan the text for http URLs and return a set
of URLs found, without duplicates"""
# look for any http URL in the page
links = set()
text = get_page(url)
soup = BeautifulSoup(text, "lxml")
for link in soup.find_all('a'):
if 'hr... | 70746ba8d28244cf712655fd82a38d358a30779a | 3,646,853 |
from typing import Tuple
def get_merkle_root(*leaves: Tuple[str]) -> MerkleNode:
"""Builds a Merkle tree and returns the root given some leaf values."""
if len(leaves) % 2 == 1:
leaves = leaves + (leaves[-1],)
def find_root(nodes):
newlevel = [
MerkleNode(sha256d(i1.val + i2.v... | d0fae08918b042f87ef955be436f1e3d84a66e8a | 3,646,854 |
import torch
import copyreg
def BeginBlock(layer_to_call: torch.nn.Module,
user_id: str = None,
ipu_id: int = None) -> torch.nn.Module:
"""
Define a block by modifying an existing PyTorch module.
You can use this with an existing PyTorch module instance, as follows:
>>>... | a43c0d198fcf1f100cbec5bc3d916aeb05fd36d0 | 3,646,855 |
import torch
def unbatch_nested_tensor(nested_tensor):
"""Squeeze the first (batch) dimension of each entry in ``nested_tensor``."""
return map_structure(lambda x: torch.squeeze(x, dim=0), nested_tensor) | 0691cb1bb851c609747cde9d45b24ca6310fa022 | 3,646,856 |
def row2dict(cursor, row):
""" タプル型の行データを辞書型に変換
@param cursor: カーソルオブジェクト
@param row: 行データ(tuple)
@return: 行データ(dict)
@see: http://docs.python.jp/3.3/library/sqlite3.html
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | 60e0ebed21c35a65784fe94fe5781f61fbe0c97d | 3,646,857 |
def merge(left, right):
"""this is used for merging two halves """
# print('inside Merge ')
result = [];
leftIndex = 0;
rightIndex = 0;
while leftIndex < len(left) and rightIndex < len(right):
if left[leftIndex] < right[rightIndex]:
result.append(left[leftIndex])
... | 5b0012e102d72a93cf3ce47f9600b7dcef758a3b | 3,646,858 |
import re
def parse_query(query):
"""Parse the given query, returning a tuple of strings list (include, exclude)."""
exclude = re.compile(r'(?<=-")[^"]+?(?=")|(?<=-)\w+').findall(query)
for w in sorted(exclude, key=lambda i: len(i), reverse=True):
query = query.replace(w, '')
query = " " + que... | 4fe6aac76935af6e5acaa3aedad40d6bc635d4ff | 3,646,859 |
def _m_verify_mg(state, method_name, multigoal, depth, verbose=0):
"""
Pyhop 2 uses this method to check whether a multigoal-method has achieved
the multigoal that it promised to achieve.
"""
goal_dict = _goals_not_achieved(state,multigoal)
if goal_dict:
raise Exception(f"depth {depth}: ... | 262ae05ab34e37867d5fa83ff86ecbd01391dbe1 | 3,646,860 |
def eggs_attribute_decorator(eggs_style):
"""Applies the eggs style attribute to the function"""
def decorator(f):
f.eggs = eggs_style
@wraps(f)
def decorated_function(*args, **kwargs):
return f(*args, **kwargs)
return decorated_function
return decorator | 3fe6d6b65b29176cf9fb997697c1b70f01f041bf | 3,646,861 |
def byte_size(num, suffix='B'):
"""
Return a formatted string indicating the size in bytes, with the proper
unit, e.g. KB, MB, GB, TB, etc.
:arg num: The number of byte
:arg suffix: An arbitrary suffix, like `Bytes`
:rtype: float
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
... | 830d4ed401df90bc3a176c52124ed93c53c25c80 | 3,646,862 |
def cdsCoverage(genome_coverage, dict_cds, datatype, coverage):
"""Return Mean Coverage or Raw Counts for each CDS, or their promotor regions for tss and chip"""
genome_coverage = [map(int, genome_coverage[0]), map(int, genome_coverage[1])]
# CDS coverage is calculated from genome coverage on the entire gen... | 637d76347dbe09c3826e496f7c8f5ec0a79f3dbd | 3,646,863 |
def div88():
"""
Returns the divider ZZZZZZZZZZZZ
:return: divider88
"""
return divider88 | a2ae79f96ed7530fd2a1f266404ee3b21614a5a9 | 3,646,864 |
def laplace_noise(epsilon, shape, dtype, args):
"""
Similar to foolbox but batched version.
:param epsilon: strength of the noise
:param bounds: min max for images
:param shape: the output shape
:param dtype: the output type
:return: the noise for images
"""
scale = epsilon / np.sqrt... | 3016db9cebffe47c62f57e05d30442b9786636e8 | 3,646,865 |
def grid_convergence(lat, lon, radians=False):
"""
Given the latitude and longitude of a position, calculate the grid convergence
Args:
lat: latitude (degrees or radians)
lon: longitude (degrees or radians)
radians: true if lat/lon in radians
Returns: gamma, the grid convergence... | dc60c8325f66fdc2db9b72d2bdc099823f913d26 | 3,646,867 |
import uuid
import json
def _make_index_item(resource_type):
""" """
id_prefix = "2c1|"
uuid_ = uuid.uuid4().hex
tpl = {
"access_roles": [
"guillotina.Reader",
"guillotina.Reviewer",
"guillotina.Owner",
"guillotina.Editor",
"guillot... | 5c11bb14016e42ff36b12ca81fd83e81b71dea9d | 3,646,868 |
import torch
def mol_to_graph(mol):
"""
Converts Mol object to a graph compatible with Pytorch-Geometric
Args:
mol (Mol): RDKit Mol object
Returns:
node_feats (LongTensor): features for each node, one-hot encoded by element
edge_feats (LongTensor): features for each node, one... | 5a3e5169b7a84afae31254e71152fb6cb300bf64 | 3,646,869 |
from typing import List
import random
def _tournament(evaluated_population: List[Eval], tournament_size: int = 5,
previous_winner: Chromosome = None) -> Chromosome:
"""Selects tournament_size number of chromosomes to 'compete' against each other. The chromosome with the highest
fitness score '... | 29db4c9c4a5332c3e70760f57312b845e29b7a36 | 3,646,870 |
def interpolate_drift_table(table, start=0, skip=0, smooth=10):
"""
Smooth and interpolate a table
:param table: fxyz (nm) array
:param start: in case of renumbering needed : first frame
:param skip: how many frame were skipped
:param smooth: gaussian smoothing sigma
:return: interpolated ta... | d2296e6eb1b55cf5416d2ab933ef430eb0ace964 | 3,646,871 |
def on_mrsim_config_change():
"""Update the mrsim.config dict. Only includes density, volume, and #sidebands"""
existing_data = ctx.states["local-mrsim-data.data"]
fields = ["integration_density", "integration_volume", "number_of_sidebands"]
# if existing_data is not None:
print(existing_data["conf... | cea2f60ca0de5e8b383a7363adfeea19473b1662 | 3,646,872 |
import base64
def decrypt(encrypted, passphrase):
"""takes encrypted message in base64 and key, returns decrypted string without spaces on the left
IMPORTANT: key must be a multiple of 16.
Finaly, the strip function is used to remove the spaces from the left of the message"""
aes = AES.new(passphrase... | 90e10c3e6e07934bc2171fa09febd223db200d70 | 3,646,873 |
async def total_conversations(request: HistoryQuery = HistoryQuery(month=6),
collection: str = Depends(Authentication.authenticate_and_get_collection)):
"""Fetches the counts of conversations of the bot for previous months."""
range_value, message = HistoryProcessor.total_convers... | bc6a292b7ddc598d43c609272f6f45e87842bf21 | 3,646,876 |
import pandas
def intersect(table_dfs, col_key):
""" intsc tables by column
"""
col_key_vals = list(unique_everseen(chain(*(
table_df[col_key] for table_df in table_dfs))))
lookup_dcts = [lookup_dictionary(table_df, col_key)
for table_df in table_dfs]
intscd_rows = []
... | 9ca1035d4cd614ae4080c8e9dc9174c7423c28dc | 3,646,878 |
import socket
import json
def ask_peer(peer_addr, req_type, body_dict, return_json=True):
"""
Makes request to peer, sending request_msg
:param peer_addr: (IP, port) of peer
:param req_type: type of request for request header
:param body_dict: dictionary of body
:param return_json: determines ... | 44c8750ef4af487402a5cf5f789bf2a3d8d3fdb7 | 3,646,879 |
def describe_instances_header():
"""generate output header"""
return misc.format_line((
"Account",
"Region",
"VpcId",
"ec2Id",
"Type",
"State",
"ec2Name",
"PrivateIPAddress",
"PublicIPAddress",
"KeyPair... | 6939b8e47c15e098733e70fe17392c18cfff9636 | 3,646,880 |
def ordered_scaffold_split(dataset, lengths, chirality=True):
"""
Split a dataset into new datasets with non-overlapping scaffolds and sorted w.r.t. number of each scaffold.
Parameters:
dataset (Dataset): dataset to split
lengths (list of int): expected length for each split.
No... | 8a3e0ab5c4cf23dcdcb075fc9363452e06c7d22f | 3,646,881 |
import struct
def read_plain_byte_array(file_obj, count):
"""Read `count` byte arrays using the plain encoding."""
return [file_obj.read(struct.unpack(b"<i", file_obj.read(4))[0]) for i in range(count)] | f300d205fda9b1b92ebd505f676b1f76122f994d | 3,646,882 |
import imp
def find_django_migrations_module(module_name):
""" Tries to locate <module_name>.migrations_django (without actually importing it).
Appends either ".migrations_django" or ".migrations" to module_name.
For details why:
https://docs.djangoproject.com/en/1.7/topics/migrations/#libraries-thi... | fdae121b1341355bc1911d2b4ce9501eb80cf8f3 | 3,646,883 |
def big_number(int_in):
"""Converts a potentially big number into a lisible string.
Example:
- big_number(10000000) returns '10 000 000'.
"""
s = str(int_in)
position = len(s)
counter = 0
out = ''
while position != 0:
counter += 1
position -= 1
out = s[posit... | 7db0dce8ffa1cbea736537efbf2fdd4d8a87c20d | 3,646,884 |
def action_list_to_string(action_list):
"""Util function for turning an action list into pretty string"""
action_list_string = ""
for idx, action in enumerate(action_list):
action_list_string += f"{action['name']} ({action['action']['class_name']})"
if idx == len(action_list) - 1:
... | 5e291dd1dbf7b8d8149505a0efc157cbcc22af3b | 3,646,885 |
def test_pandigital_9(*args):
"""
Test if args together contain the digits 1 through 9 uniquely
"""
digits = set()
digit_count = 0
for a in args:
while a > 0:
digits.add(a % 10)
digit_count += 1
a //= 10
return digit_count == 9 and len(digits) == ... | ad5a738400f7b8a9bea001a13a76798633b9ac61 | 3,646,887 |
def volume_attached(context, volume_id, instance_id, mountpoint):
"""Ensure that a volume is set as attached."""
return IMPL.volume_attached(context, volume_id, instance_id, mountpoint) | 3bfd057dee24bf9a4b51ef6503dd46bacc64210d | 3,646,889 |
def _startswith(
self: str | ir.StringValue, start: str | ir.StringValue
) -> ir.BooleanValue:
"""Determine whether `self` starts with `end`.
Parameters
----------
self
String expression
start
prefix to check for
Examples
--------
>>> import ibis
>>> text = ibis... | dabc7a1e07b38fc99c1f31bb285fc895c890301d | 3,646,891 |
def _get_all_scopes(blocks):
"""Get all block-local scopes from an IR.
"""
all_scopes = []
for label, block in blocks.items():
if not (block.scope in all_scopes):
all_scopes.append(block.scope)
return all_scopes | daa13a20629dd419d08c9c6026972f666c3f9291 | 3,646,893 |
from datetime import datetime
def get_equinox_type(date):
"""Returns a string representing the type of equinox based on what month
the equinox occurs on. It is assumed the date being passed has been
confirmed to be a equinox.
Keyword arguments:
date -- a YYYY-MM-DD string.
"""
month = da... | 06b65a54a0ccf681d9f9b57193f5e9d83578f0eb | 3,646,894 |
def mcs_worker(k, mols, n_atms):
"""Get per-molecule MCS distance vector."""
dists_k = []
n_incomp = 0 # Number of searches terminated before timeout
for l in range(k + 1, len(mols)):
# Set timeout to halt exhaustive search, which could take minutes
result = FindMCS([mols[k], mols[l]], ... | 013958a41813181478b3133e107efed5d0370fa6 | 3,646,895 |
def get_tally_sort_key(code, status):
"""
Get a tally sort key
The sort key can be used to sort candidates and other tabulation
categories, for example the status and tally collections returned by
rcv.Tabulation().tabulate().
The sort codes will sort candidates before other tabulation
categories; electe... | bd7d643300997903b84b1827174dd1f5ac515156 | 3,646,896 |
def get_lidar_point_cloud(sample_name, frame_calib, velo_dir, intensity=False):
"""Gets the lidar point cloud in cam0 frame.
Args:
sample_name: Sample name
frame_calib: FrameCalib
velo_dir: Velodyne directory
Returns:
(3, N) point_cloud in the form [[x,...][y,...][z,...]]
... | f1deb8896a2c11d82d6a312f0a8f353a73a1b40d | 3,646,898 |
def make_mlp(dim_list, activation_list, batch_norm=False, dropout=0):
"""
Generates MLP network:
Parameters
----------
dim_list : list, list of number for each layer
activation_list : list, list containing activation function for each layer
batch_norm : boolean, use batchnorm at each layer,... | dc2677ccd1291942f474eb6fe7719103731f4cfc | 3,646,900 |
def load_and_prep_image(filename):
"""
Reads an image from filename, turns it into a tensor
and reshapes it to (img_shape, img_shape, colour_channel).
"""
image = cv2.imread(filename)
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(haarcascade)
fa... | cbf3b1a840ecc931adf0dd7f84cff68e83180efe | 3,646,902 |
def DoH(im, canvas, max_sigma=30, threshold=0.1, display=True):
""" Difference of Hessian blob detector
:param im: grayscale image
:param max_sigma: maximum sigma of Gaussian kernel
:param threshold: absolute lower bound Local maxima smaller than threshold ignore
"""
blobs = blob_doh... | 965ce92cdba24514fa9802a9e8891a96d97f1cf5 | 3,646,903 |
def _parse_class(s):
"""
Parse a key, value pair, separated by '='
On the command line (argparse) a declaration will typically look like:
foo=hello
or
foo="hello world"
"""
items = s.split('=')
key = items[0].strip() # we remove blanks around keys, as is logical
if len(... | db517a277e21448eb83ba25244a8bfa3892f18a4 | 3,646,904 |
import difflib
def getStringSimilarity(string1:str,string2:str):
"""
This function will return a similarity of two strings.
"""
return difflib.SequenceMatcher(None,string1,string2).quick_ratio() | 292f552449569206ee83ce862c2fb49f6063dc9e | 3,646,905 |
def calc_simcoef_distr(patfeats, labels, id_dict, simcoef):
"""
Calculates the score distributions
Inputs:
- simcoef: simcoef the values are calculated with (string)
- labels: list of strings with the scores to be calculated (e.g.: ['cited', 'random'])
- id_dict: dictionary containing the pa... | 897bcb2e30e0587173557772c17589fe43841e60 | 3,646,907 |
def fft(signal, sampling_rate, plot=False, show_grid=True, fig_size=(10, 5)):
"""
Perform FFT on signal.
Compute 1D Discrete Fourier Transform using Fast Fourier Transform.
Optionally, plot the power spectrum of the frequency domain.
Parameters
----------
signal : ndarray
Input arr... | 70296c900e8ad7342be3c6ee18ff8b34e481ac0e | 3,646,908 |
def pattern_count(data, **params):
"""
Count occurrences of a given pattern.
Args:
data (list): values.
params (kwargs):
pattern (str or list): the pattern to be sought in data (obligatory)
metric (str): 'identity' counts identical positions,
... | 0c943554b4c5b7739a6ca16aa739b3cd614ab79d | 3,646,909 |
import requests
import signal
def do(hostname):
"""
Performs a GET request.
Parameters
----------
hostname : str
Target request
Return
------
The request results
"""
try:
return requests.get(hostname, timeout=10)
except TimeoutException:
print("\... | 7e300e4be98beecad29e28594b76230e6c19382d | 3,646,911 |
def getAssignmentReport(assignment):
"""
Produces an ABET assignment report (as a markdown-formatted string)
for the given assignment (which is expected to be a codepost API
object) by pulling all relevant data as well as source
code files (and grader comments) for randomly selected A, B and C samples
"""
... | fd2a49c8fa8e3a15a878e06d29ec9598912034c6 | 3,646,912 |
def start_game():
"""
Method to start
:return: Choice selection for new game or load game
"""
maximize_console()
print_title()
print('Do you want to start a new game (enter 1) or resume an ongoing game (enter 2)?')
choice = input('||> ')
print()
return choice | 5780468f4239a8a519538a18feb12a0956dd4170 | 3,646,913 |
def get_inception_score(images, batch_size, splits=10):
"""
the function is to calculate the inception score of the generated images
image is a numpy array with values should be in the range[0, 255]
images 299x299x3
"""
assert(type(images) == np.ndarray)
inception_model = inception_v3
... | 9e14691a5c885b6b95e6ff9ecff014db0cca119e | 3,646,916 |
def generate_audio_testing(raw_gain, raw_freq, raw_dampings, modal_fir, reverb, impulse_profile,
gains, frequencies, dampings, modal_response,
noise, acceleration_scale, revc, audio_sample_rate, example_secs, scratch='controls'):
"""Generate DiffImpact's estimat... | 1b7932c165c9615096b79b5d0c19859bc6dd113d | 3,646,917 |
def dice_coef_multilabel(y_true, y_pred, numLabels=4, channel='channel_first'):
"""
calculate channel-wise dice similarity coefficient
:param y_true: the ground truth
:param y_pred: the prediction
:param numLabels: the number of classes
:param channel: 'channel_first' or 'channel_last'
:retu... | 16af1961d900add04f0f277335524ba1568feb12 | 3,646,918 |
def gaussian(sigma, fs, t=None):
""" return a gaussian smoothing filter
Args:
sigma: standard deviation of a Gaussian envelope
fs: sampling frequency of input signals
t: time scale
Return:
a Gaussian filter and corresponding time scale
"""
if... | aba5d419bb22cd0bfe0a702346dd77735b7f0d4c | 3,646,919 |
def score_sent(sent):
"""Returns a score btw -1 and 1"""
sent = [e.lower() for e in sent if e.isalnum()]
total = len(sent)
pos = len([e for e in sent if e in positive_wds_with_negation])
neg = len([e for e in sent if e in negative_wds_with_negation])
if total > 0:
return (pos - neg) / to... | cc70d035e932513ae27743bbca66ae8d870fcc91 | 3,646,920 |
import torch
def flipud(tensor):
"""
Flips a given tensor along the first dimension (up to down)
Parameters
----------
tensor
a tensor at least two-dimensional
Returns
-------
Tensor
the flipped tensor
"""
return torch.flip(tensor, dims=[0]) | b0fd62172b0055d9539b554a8c967c058e46b397 | 3,646,921 |
def connect():
"""Function to connect to database on Amazon Web Services"""
try:
engine = create_engine('mysql+mysqlconnector://dublinbikesadmin:dublinbikes2018@dublinbikes.cglcinwmtg3w.eu-west-1.rds.amazonaws.com/dublinbikes')
port=3306
connection = engine.connect()
Sessio... | 81da870305a853b621f374b521bb680e435d852b | 3,646,922 |
def get_file_type(filepath):
"""Returns the extension of a given filepath or url."""
return filepath.split(".")[-1] | 070a1b22508eef7ff6e6778498ba764c1858cccb | 3,646,923 |
def calcB1grad(B2grad,W2,A2):
"""
Calculates the gradient of the cost with respect to B1 using the chain rule
INPUT: B2grad, [layer3Len,1] ; W2, [layer2Len, layer3Len] ;
A2, [layer2len, 1]
OUTPUT: B1grad, [layer2Len, 1]
"""
temp1 = np.dot(W2,B2grad) #layer2Len * 1 vector
sigmGra... | e214f79be1377b4fc0f36690accf6072fee27884 | 3,646,924 |
def plot_3d(x, y, z, title, labels):
"""
Returns a matplotlib figure containing the 3D T-SNE plot.
Args:
x, y, z: arrays
title: string with name of the plot
labels: list of strings with label names: [x, y, z]
"""
plt.rcParams.update({'font.size': 30, 'legend.fontsize': 2... | 624a62f9dc941d6b7cfed06e10250fae8c8defa9 | 3,646,925 |
def is_rating_col_name(col:str)->bool:
"""
Checks to see if the name matches the naming convention for a rating
column of data, i.e. A wrt B
:param col: The name of the column
:return: T/F
"""
if col is None:
return False
elif isinstance(col, (float, int)) and np.isnan(col):
... | 57802e888f5a75cdc521a08115ad3b74a56da43d | 3,646,926 |
def _make_buildifier_command():
"""Returns a list starting with the buildifier executable, followed by any
required default arguments."""
return [
find_data(_BUILDIFIER),
"-add_tables={}".format(find_data(_TABLES))] | ab480ff1bc7b21685a4dd95bbc12ae5ee223bdc0 | 3,646,927 |
from typing import Union
def infer_path_type(path: str) -> Union[XPath, JSONPath]:
"""
Infers the type of a path (XPath or JSONPath) based on its syntax.
It performs some basic sanity checks to differentiate a JSONPath from an XPath.
:param path: A valid XPath or JSONPath string.
:return: An insta... | abeed8003b05dd5b66ada1367d0a5acf39102d60 | 3,646,928 |
def get_proximity_angles():
"""Get the angles used for the proximity sensors."""
angles = []
# Left-side of the agent
angles.append(3 * pi / 4) # 135° (counter-clockwise)
for i in range(5): # 90° until 10° with hops of 20° (total of 5 sensors)
angles.append(pi / 2 - i * pi / 9)
... | 29c093d1aef0d10d24968af8bee06e6d050e9119 | 3,646,929 |
def delete(request, scenario_id):
"""
Delete the scenario
"""
# Retrieve the scenario
session = SessionMaker()
scenario = session.query(ManagementScenario).filter(ManagementScenario.id == scenario_id).one()
# Delete the current scenario
session.delete(scenario)
session.commit()
... | 4d9c7090d66f8cd3bd055c6f383870b4648a3828 | 3,646,930 |
def angle(p1, p2, p3):
"""Returns an angle from a series of 3 points (point #2 is centroid).
Angle is returned in degrees.
Parameters
----------
p1,p2,p3 : numpy arrays, shape = [n_points, n_dimensions]
Triplets of points in n-dimensional space, aligned in rows.
Returns
-------
... | 3e57121a20f18f2ee5728eeb1ea2ffb39500db40 | 3,646,932 |
def transformer_parsing_base():
"""HParams for parsing on WSJ only."""
hparams = transformer_base()
hparams.attention_dropout = 0.2
hparams.layer_prepostprocess_dropout = 0.2
hparams.max_length = 512
hparams.learning_rate_warmup_steps = 16000
hparams.hidden_size = 1024
hparams.learning_rate = 0.05
hpa... | f86b3fe446866ff3de51f02278c2d2c9d7f1b126 | 3,646,933 |
def split_protocol(urlpath):
"""Return protocol, path pair"""
urlpath = stringify_path(urlpath)
if "://" in urlpath:
protocol, path = urlpath.split("://", 1)
if len(protocol) > 1:
# excludes Windows paths
return protocol, path
return None, urlpath | e9b006d976847daa9a94eb46a9a1c2f53cd9800f | 3,646,934 |
import pprint
def createParPythonMapJob(info):
"""
Create map job json for IGRA matchup.
Example:
job = {
'type': 'test_map_parpython',
'params': {
'year': 2010,
'month': 7
},
'localize_urls': [
]
}... | 142afc4b4be0d77b4921e57c358494dbfc43c6ab | 3,646,935 |
def calc_lampam_from_delta_lp_matrix(stack, constraints, delta_lampams):
"""
returns the lamination parameters of a laminate
INPUTS
- ss: laminate stacking sequences
- constraints: design and manufacturing guidelines
- delta_lampams: ply partial lamination parameters
"""
lampam = np.ze... | a1d179f441368f2ebef8dc4be4e2a364d41cf84e | 3,646,936 |
def perp(i):
"""Calculates the perpetuity to present worth factor.
:param i: The interest rate.
:return: The calculated factor.
"""
return 1 / i | 2fe59a039ac5ecb295eb6c443143b15e41fdfddb | 3,646,937 |
def chebyshev(x, y):
"""chebyshev distance.
Args:
x: pd.Series, sample feature value.
y: pd.Series, sample feature value.
Returns:
chebyshev distance value.
"""
return np.max(x-y) | 876f0d441c48a7ab4a89b1826eb76459426ad9a3 | 3,646,938 |
def soda_url_helper(*, build_url, config, year, **_):
"""
This helper function uses the "build_url" input from flowbyactivity.py,
which is a base url for data imports that requires parts of the url text
string to be replaced with info specific to the data year. This function
does not parse the data,... | b4e0f8c781a966d0291dad7d897eba02dc7a4e09 | 3,646,939 |
from typing import Optional
from datetime import datetime
from typing import List
def search(
submitted_before: Optional[datetime] = None,
submitted_after: Optional[datetime] = None,
awaiting_service: Optional[str] = None,
url:Optional[str] = None,
token:Optional[str] = None,
... | a2ce0d86fde2792365f27cf386e7c9ef0d4a0fa1 | 3,646,941 |
from typing import List
from typing import Pattern
import re
from typing import Optional
from typing import Match
def _target_js_variable_is_used(
*, var_name: str, exp_lines: List[str]) -> bool:
"""
Get a boolean value whether target variable is used in
js expression or not.
Parameters
-... | be07cb1628676717b2a02723ae7c01a7ba7364d6 | 3,646,942 |
def rnn_temporal(x, h0, Wx, Wh, b):
"""
Run a vanilla RNN forward on an entire sequence of data. We assume an input
sequence composed of T vectors, each of dimension D. The RNN uses a hidden
size of H, and we work over a minibatch containing N sequences. After running
the RNN forward, we return the ... | 794fed02ef96c97d9b4ccb6a7278fc72b81eea33 | 3,646,943 |
from typing import Union
def rejection_fixed_lag_stitch(fixed_particle: np.ndarray,
last_edge_fixed: np.ndarray,
last_edge_fixed_length: float,
new_particles: MMParticles,
adjusted_weights: np.n... | aeec4fc1956c7a63f15812988a38d54b63234de4 | 3,646,944 |
def zip_equalize_lists(a, b):
"""
A zip implementation which will not stop when reaching the end of the
smallest list, but will append None's to the smaller list to fill the gap
"""
a = list(a)
b = list(b)
a_len = len(a)
b_len = len(b)
diff = abs(a_len - b_len)
if a_len < b_len:... | 1cf5b9cadf4b75f6dab6c42578583585ea7abdfc | 3,646,945 |
def cover_line(line):
"""
This function takes a string containing a line that should
potentially have an execution count and returns a version
of that line that does have an execution count if deemed
appropriate by the rules in validate_line().
Basically, if there is currently no number where t... | 612cd295b78ce9a0d960b902027827c03733f609 | 3,646,946 |
def find_period(samples_second):
""" # Find Period
Args:
samples_second (int): number of samples per second
Returns:
float: samples per period divided by samples per second
"""
samples_period = 4
return samples_period / samples_second | c4a53e1d16be9e0724275034459639183d01eeb3 | 3,646,947 |
def sqrt(x: int) -> int:
"""
Babylonian Square root implementation
"""
z = (x + 1) // 2
y = x
while z < y:
y = z
z = ( (x // z) + z) // 2
return y | 1a91d35e5783a4984f2aca5a9b2a164296803317 | 3,646,948 |
def is_consecutive_list(list_of_integers):
"""
# ========================================================================
IS CONSECUTIVE LIST
PURPOSE
-------
Reports if elments in a list increase in a consecutive order.
INPUT
-----
[[List]] [list_of_integers]
- A list ... | 3b165eb8d50cc9e0f3a13b6e4d47b7a8155736b9 | 3,646,949 |
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):
"""
See https://gist.github.com/syrte/592a062c562cd2a98a83
Make a scatter plot of circles.
Similar to plt.scatter, but the size of circles are in data scale.
Parameters
----------
x, y : scalar or array_like, shape (n, )
... | cb3b2c4316ec573aa29cf5d500f50fbcd64f47b5 | 3,646,950 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.