content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def is_question_answer_yes(question: str) -> bool:
"""
Prompt a yes/no question to the user.
Parameters
----------
question : str
The question to print on stdout.
Returns
-------
bool
True if the user answers "yes", False otherwise.
"""
answer = input(question ... | 3b8564d0d984a315fcf46acc935db1759f148af5 | 50,328 |
import numpy
def multivariate_Gaussion(X, Mu, Sigma2):
"""Computes the probability density function of multivariate Gaussian distribution.
Args:
X (1D numpy.array (float)): n by 1 feature vector.
Mu (1D numpy.array (float)): n by 1 mean vector.
Sigma2 (1D numpy.array (float)): n by 1 ... | fdbc95219f2c0fd8a504f1b0e948f345c79ce115 | 50,329 |
def is_real_contact(p):
"""Returns true if this <p> element is an actual contact,
and not a blank <p>. False otherwise.
Arguments:
p {bs4.element.Tag} -- <p> element to inspect
Returns:
[bool] -- Whether this element represents a contact.
"""
return p.strong is not None | 3d00bc8a9409d1a9d1e0bbb1750f70d021282840 | 50,330 |
def _G(x,y):
"""Helper function.
returns True when the timestamps of x and y are within 5 seconds."""
return abs((x.timestamp - y.timestamp).total_seconds()) <= 5 | 8fc6bc08b8fd70438031878d6906e6e487166af9 | 50,331 |
def toStringDuration (duration):
"""Returns a description of the given duration in the most appropriate
units (e.g. seconds, ms, us, or ns).
"""
table = (
('%dms' , 1e-3, 1e3),
(u'%d\u03BCs', 1e-6, 1e6),
('%dns' , 1e-9, 1e9)
)
if duration > 1:
return '... | 2b000767563df5addaa4c2d7f98f44841d81130a | 50,332 |
def get_groups(data, scope, args):
"""Get groups."""
groups = {}
if scope == 'fed' or scope == 'local':
args["scope"] = scope
groups = data.client.list("group", "group", **args)
return groups | 754cfc75c62f9ce89c82db001b9e9c2597988193 | 50,334 |
def vararg_callback(option, opt_str, value, parser):
"""Callback for an option with variable arguments.
Manually collect arguments right of a callback-action
option (ie. with action="callback"), and add the resulting
list to the destination var.
Usage:
parser.add_option("-c", "--callback", dest... | 0d25d97e4702a83b46a20842e9dea1100de575da | 50,336 |
def assemble_haplotypes(snps):
"""Input phased SNPS data. Assemble haplotype strings for two chromosomes."""
h = {"A": {}, "B": {}}
for snp in snps:
if snp.gt == "1|0":
h["A"][snp.pos] = snp.alt
h["B"][snp.pos] = snp.ref
elif snp.gt == "0|1":
h["A"][snp.po... | 093dbe9739da74cce6d9bc434009a205b91ce5d8 | 50,337 |
def mrmmult(temp, covmat):
"""Matrix multiplication (MRM' or m'Rm)."""
return temp @ covmat @ temp.T | 65d7da0f4303a8414c884ed172d1123ca9033f34 | 50,339 |
def transitive_closure(graph, reflexive=False):
"""
Calculate the transitive closure of a directed graph,
optionally the reflexive transitive closure.
The algorithm is a slight modification of the "Marking Algorithm" of
Ioannidis & Ramakrishnan (1998) "Efficient Transitive Closure Algorithms".
... | 40126120eede6b0944794311ee828382f3bfd1aa | 50,340 |
def detect_cycle(ary:list) -> bool:
"""
フロイドの循環検出法 に従って、ループを雑に検出します。
aryにループがある場合はTrueを返却します。
Args:
ary list:
ループを検出したいリスト
Returns:
bool:
aryにループがある場合はTrue。それ以外はFalse
"""
hare_iter = iter(ary)
for tortoise in ary:
try:
hare ... | bf7599aade5060ba4d309a042e721974924a9b64 | 50,343 |
import math
def calibrated_fps(calibrate):
"""Calibration of the dynamic frames per second engine.
I've started with the equation y = log10(x + m) * k + n, where:
y is the desired fps, m and n are horizontal and vertical translation,
k is a calibration factor, computed from some user input c (see... | 8f51d14bc3b58a20e3a2e6775233569f65c0f511 | 50,344 |
def mut_pair_num(table):
"""
A function that calculates the number of pairs of codons one
mutation away from each other. Treats mutations with directionality. In
general, the number of mutational pairs is equal to the number of
codons in a table multiplied by the number of unique codons within one
... | ce44087d295ac2cf0860c364dbf18b4f2de500b1 | 50,346 |
def train_loop(model, optimizer, loss_fn, samples, labels,
batch_size, seq_len, device='cpu', pre_trained=False):
"""
Standard pytorch training loop, using our helper loss function above.
:param model: model to optimize
:param optimizer: optimizer
:param loss_fn: loss function
:pa... | d97ec345f6e1bb1e1951a699bf171e5accca362e | 50,347 |
import math
def closest_power2(x):
"""Get the closest power of 2 checking if the 2nd binary number is a 1."""
op = math.floor if bin(x)[3] != "1" else math.ceil
return 2**(op(math.log(x, 2))) | fa2d3025f83283b79d5c7e4c3babaacd873f3cb9 | 50,348 |
async def read_data(stream, length, decryptor=None) -> bytes:
"""Reads from the packet stream.
If the received data is not equal to the length, it will keep reading until it meets that length.
Args:
stream: The packet stream to read from.
length: The amount of bytes to read.
decrypt... | a43d1bd9c0128724922eb23d6aca84b7df9011ca | 50,351 |
import importlib
import json
def create_object(config):
"""
Creates an object from the specified configuration dictionary.
Its format is:
class: The fully qualified path name.
args: A list of positional arguments (optional).
kwargs: A dictionary of keyword arguments (optional).
... | 3f39a1f09a664602b4beeaf35590470dc96a1db2 | 50,353 |
import os
import subprocess
def bias_field_correction(t1_in):
"""corrects field bias using fast method from fsl.
It will save multiple nifti files in the directory (as described by FAST
https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FAST#Fast) where t1_in is
stored, however only the path to the biase... | b9947f2ef9d3e62c659cd1db4b9e2aaf1fb40984 | 50,354 |
from typing import Counter
def find_top_codes(df, col_name, n):
""" Find the top codes from a columns of strings
Returns a list of strings to make sure codes are treated as classes down the line """
string_total = df[col_name].str.cat(sep=' ')
counter_total = Counter(string_total.split(' '))
r... | 61a2a8c06f589ba2834bab58f34679aef96b2a2f | 50,355 |
def bollinger_band(df, base, upper_target, lower_target, period):
"""
Function to compute Bollinger Bands (BB)
This is a lagging indicator
df - the data frame
base - on which the indicator has to be calculated eg Close
upper_target - column name to store upper BB value
lower_target - column... | e9daecd68e6a41178a554acefbc460184855bca6 | 50,356 |
def boost_optimizer(bid_dict, boost_values, learning_rate):
"""
DOCUMENTATION
"""
boost_bid_dict = {}
for i in bid_dict:
if i in boost_values:
boost_bid_dict[i] = bid_dict[i] * boost_values[i]
else:
boost_bid_dict[i] = bid_dict[i]
second_high_bidder, high_... | e61bdb1a91b3dd46c704c041f9e42f1ce1d6e655 | 50,357 |
def UnicodeToCLiteral(s):
"""Converts a unicode string to a C-style escaped string (e.g. "\xe1\x84")."""
s = s.encode('utf8')
out = ['"']
for c in s:
if ord(c) > 127:
out.append(r'\x%.2x' % ord(c))
# To prevent the C++ compiler from interpreting subsequent characters as
# part of the hex c... | 40b991e02df77b8e043a353002a286080bfba61a | 50,358 |
def decode_topic_name(encoded: str) -> str:
"""
Reverses ``encode_topic_name``.
:param encoded: the encoded SNS topic name
:return: the decoded channel name
"""
decoded = encoded
decoded = decoded.replace("_WCD_", "*")
decoded = decoded.replace("_FWS_", "/")
decoded = decoded.replac... | d8af5240645b1286bc119fdf162cb7645d439e0c | 50,359 |
import torch
def _sort_edges(edges):
"""sort last dimension of edges of shape (E, 2)"""
with torch.no_grad():
order = (edges[:, 0] > edges[:, 1]).long()
order = order.unsqueeze(dim=1)
a = torch.gather(input=edges, index=order, dim=1)
b = torch.gather(input=edges, index=1 - ord... | 7024567c02a37626263b97ab4fcf3bea13e4ec83 | 50,361 |
import collections
def count_domLetters(word):
"""The acutal algorithm that does the counting of the dominant letters in the input.
Args:
word ([type]): The word whose dominant letters are being counted.
Returns:
[int]: Returns the frequency of the dominant letter.
"""
# https://... | 8b617b9256bbfb6b8e0fb0a2204e5688a71f5f0d | 50,362 |
import json
def download_options(dataset, node, entityids, api_key=None):
"""
The use of the download options request is to discover the different download
options for each scene. Some download options may exist but still be unavailable
due to disk usage and many other factors. If a download is unavai... | 2c82faab4f1a74dfa95bc3acc9049919c47be2c2 | 50,363 |
def jsfy(df, songID):
"""Takes a data frame and song ID and outputs a Plotly graph converted to JSON"""
features = [
'acousticness',
'danceability',
'energy',
'instrumentalness',
'liveness',
'speechiness']
find_id = df['track_id'] == songID
song_stats = d... | ca3199e936e7e3b1620a9352731bad91f6972e0c | 50,365 |
def scan_and_target_id_to_context_info(scan_id, target_id, all_scans_in_dict):
""" Get context information (e.g., same instance-class objects) of the object specified by the target_id in the
scene specified by the scene_id.
:param scan_id: (string) scene0010_00
:param target_id: (int) 36
:param... | bfcd36c0988a165405cf3f84a808f9fe43e3bc6c | 50,366 |
import shlex
def shlex_split(s, comments=False, posix=True):
"""
Splits a string using shell lexer, but returns any incomplete string as the
last component instead of erroring for unmatched quotations.
"""
lex = shlex.shlex(s, posix=posix)
lex.whitespace_split = True
if not comments:
... | 8708c423af6ffa9b69aacec0e05676879f7104c1 | 50,367 |
def get_summary_entry_template():
"""
Get a template to describe each line in an assembly summary
Keys have the following meanings:
- has_assembly: Does this line of the summary have assembly code.
- assembly: Information about the assembly in this summary line.
- assembly/info: The assembly l... | 63ab6a0df80150a74b60ec1e8094d938d9d15879 | 50,368 |
def bib_sublist(bibfile_data, val_type):
"""
Sublist of bibfile_data whos elements are val_type
This method examines each bib_dict element of a bibfile_data list and returns the subset which can be classified according to val_type.
:param list bibfile_data: List containing `RefFile`s.
:param type ... | 1865e5af22b873b5b43a1b1cde7982e92aa77226 | 50,370 |
def render(dot, desc_filename, suffix):
"""Outputs the graph."""
return dot.render(desc_filename + suffix) | 1e32d709624950be213fbadb21d67b55f1486392 | 50,372 |
import base64
def convert_image(filename: str) -> str:
"""Converts image to string.
Args:
filename: The name of the image to convert.
Returns:
The image converted to serializable string representation.
"""
with open(filename, 'rb') as file:
converted = base64.b64encode(fi... | 28d0341a76ee2323683225606a8fc4b80205cb28 | 50,373 |
def column_to_list(data:list, prop:str):
"""
Agrupa os valores de uma coluna de dados para uma lista
args:
data_list (list): Uma lista de dados (list/dict)
prop (str): Uma key ou index
return (list): Uma lista dos valores mapeados como 'prop' em cada item da lista i... | 18ddae43a15cee920d8f3789dc23fe019ef2b63f | 50,374 |
def get_colours(query, clusters):
"""Colour array for Plotly.js"""
colours = []
for clus in clusters:
if str(clus) == str(query):
colours.append('rgb(255,128,128)')
else:
colours.append('blue')
return colours | c06d07a7da8bf758c290c2b5ce80fbe0015bea4a | 50,375 |
def transform_box_coord(H, W, box_vertices, dataset_name, high_rez=False, scaling_factor=1):
"""
Transform box_vertices to match the coordinate system of the attributions
:param H: Desired height of image
:param W: Desired width of image
:param box_vertices:
:param dataset_name:
:param high_... | 5b4e915d4f42122a87c49cbc9cb5b93abfb1ce38 | 50,376 |
def transaction_to_itemset(T):
"""
Converts each record of a database in to a itemset format
"""
result = set()
for i in range(len(T)):
if T[i]!=0:
result.add(i+1)
return(result) | 42a6b812e9b8e2c14180cbc6fd8e74e2d32d10c7 | 50,377 |
def whoosh_url():
"""Return Whoosh URL."""
return 'whoosh:///home/search/whoosh_index' | 918567f21feee372c2b69a5867aca151554a6998 | 50,378 |
import subprocess
def run_cmd(cmd):
"""
run cmd on frontend machine
"""
return subprocess.check_output(cmd,shell=False) | d4a4f2d923734bc91b47cb05031faa5d4666e3ff | 50,379 |
def short_assets(S):
""" Create synthetic short assets. """
X = S / S.shift(1)
# shorting
X = 2 - X
X.iloc[0] = S.iloc[0]
# reconstruct original
return X.cumprod() | 0d575e26fcb3ada3a373666cc40de4af904aa101 | 50,380 |
import requests
def connect(url):
"""http request to corona API"""
try:
with requests.get(url, timeout=3) as requestapi:
if requestapi.status_code == 200:
return requestapi.json()
return False
except requests.exceptions.RequestException as requestapiexception:
... | ec7418766c66b50c8b2db6e1088146cabba3edce | 50,381 |
def tri(s) :
""" Renvoit le mot trié pour repérage anagramme """
return "".join(sorted(list(s))) | 4cfa0e226aef52e10927f086d0d840e387c61268 | 50,382 |
import os
import yaml
import click
def read_chart_data(app, verbose=None):
"""
# Read local chart data
"""
chart_file_path = os.path.join(app.config['ftl']['chart_data_path'])
chart_data = {}
with open(chart_file_path, 'r') as fh:
chart_data = yaml.safe_load(fh.read())
if verbo... | 4b674b1347b0839f23689f1bf07b02a75b7f4ea9 | 50,387 |
def GetChunks(data, size=None):
"""
Get chunks of the data.
"""
if size == None:
size = len(data)
start = 0
end = size
chunks = []
while start < len(data):
chunks.append(data[start:end])
start = end
end += size
if end > len(data):
en... | 51bdfe5334292a700c660def7e3306b6fa528398 | 50,389 |
def serchNotBlackPixel(image):
"""
Cerca il pixel non nero nell'immagine di coordinata y inferiore (dove la mascherina inizia)
:param image: matrice di pixel
:return: coordinate (i,j) del pixel individuato
"""
imgShape = image.shape
print("Size img : ", imgShape)
for i in range(imgShape[... | f75d434a79c5bb517f50f11707ab07ff9f9dee8f | 50,391 |
def remove_duplicate_words(text: str) -> str:
"""Remove duplicate words.
It is a general-purpose function, which can remove duplicate words next
to each other, and preserve only one of them.
Args:
text (str): Accepts only one element (i.e., scalar).
Returns:
A text variable of <cl... | 2f78193325266b47fd55b340989822c62fb6b6df | 50,395 |
def get_common_elements(element_list):
"""
:param element_list: list of list where each internal list contains values
:return: a sorted list of elements which are common in all the internal lists
"""
common_element_list = set(element_list[0])
index = 1
while index < len(element_list):
... | fa3233bb2945949837fd70db4d75f5803100e3ee | 50,396 |
def user_file(filename, username="master"):
"""Return json file for the user and given filename."""
assert username, "user_file: empty username."
if username == 'master':
return './library/' + filename + '.json'
else:
return './users/' + username + '/' + filename + '.json' | 89ec038990eae7b285428ff9e8c7e70609cb9de3 | 50,397 |
def ddpg(loss):
""" paper : https://arxiv.org/abs/1509.02971
+ effective to use with replay buffer
- using grads from critic not from actual pollicy ( harder to conv )
"""
grads = loss
return loss | 1ed110c0827dfe489bb32290cd1bb1fe799b5089 | 50,398 |
import torch
def compute_active_units(mu, delta):
"""Computes an estimate of the number of active units in the latent space.
Args:
mu(torch.FloatTensor): [n_samples, z_dim]. Batch of posterior means.
delta(float): variance threshold. Latent dimensions with a variance above this threshold are ... | cdbd24ba9735f48f5c92b3c028106d7824a2e3cf | 50,399 |
def decode_qwikcord(packet, channel=1):
"""Extract the qwikcord current measurements from val (CTavg, CTsum)."""
val = str(packet.get('val', ''))
if len(val) != 16:
return None
if channel == 1:
return int(val[6:12], 16) # CTavg
return int(val[12:], 16) | d0edf4244b5d62d892e5ce71c966145e82b5dc37 | 50,400 |
def is_odd(number: int) -> bool:
""" checks whether number is odd, returns boolean """
return bool(number & 1) | 003658703e9263bdfeed9c97e5270a30c4a5ade8 | 50,401 |
def has_afg_license(instr):
"""Returns True if the first license includes an AFG license"""
return "AFG" in instr.query("LIC:ITEM? 0").strip().split('"')[3].split(",") | 0b9b2d65b7f910d3a4e412f67c76c5333d4f7d7b | 50,403 |
def line_perpendicular(k,b,x):
"""
@param k: y=kx+b
@param b: y=kx+b
@param x: where the perpendicular has to intersect the line
"""
# y = k*x+b
k_perp = -1./k
b_perp = (k - k_perp) * x + b
return k_perp, b_perp | e72c8c65a5e11f1927f01548407687ad84837b89 | 50,404 |
import os
def key_name_from_path(path):
"""Convert a relative path into a key name."""
key_parts = []
while True:
head, tail = os.path.split(path)
if tail != '.':
key_parts.append(tail)
if head == '':
break
path = head
return '/'.join(reversed(k... | ffdfb84067144968530db540cd084c0e8f6d74d0 | 50,405 |
def resolve_set_to_value(value_set, default_value, error_message):
"""Resolve a set of values to a single value, falling back to
a default value if needed. If it is unresolvable, produce
an error message.
"""
if len(value_set) == 0:
return default_value
elif len(value_set) == 1:
... | f8d8cdf9dbbf73d7382fbf0fb37e217c975892f9 | 50,406 |
def ostr(string):
"""
Truncates to two decimal places. """
return '{:1.2e}'.format(string) | f4dc4fdf919f630d155b4be41ecb79abdc430c66 | 50,407 |
import torch
def batch_shuffle(batch: torch.Tensor):
"""Returns the shuffled batch and the indices to undo.
Examples:
>>> # forward pass through the momentum model with batch shuffling
>>> x1_shuffled, shuffle = batch_shuffle(x1)
>>> f1 = moco_momentum(x1)
>>> out0 = projectio... | 383aa4d51c1654fee1953242c14a193bda54e057 | 50,408 |
def pooled_prob(N_A, N_B, X_A, X_B):
"""Returns pooled probability for two samples"""
return (X_A + X_B) / (N_A + N_B) | 55beb8fc549fb0d71db16764738d7cdc9c570825 | 50,409 |
def compute_time(sign, FS):
"""Creates the signal correspondent time array.
"""
time = range(len(sign))
time = [float(x)/FS for x in time]
return time | 7d6bcc3a8f54d199a6bec9d46b0fe5bbdfeeb052 | 50,410 |
def __max_value_index(list):
"""
Find the idx of the max value in list
list -- numeric list
"""
max_val = max(list)
max_idx = list.index(max_val)
return max_idx | f94cc5629711000c6dcffb059ffe0c9bbdab62cf | 50,411 |
def get_sqr(sudoku, row, col):
"""zwraca kwadrat 3x3 zawierajacy pole (row,col)"""
return [sudoku[x][y] for x in range(9) if x//3 == row//3 for y in range(9) if y//3 == col//3] | 7cf2822ebedb6dcc502eea99d54d869f25741cc3 | 50,412 |
def isNA(string):
"""Filter #N/A from incoming tables."""
if string == "#N/A" or string == "NA":
return True
else:
return False | 51ae99a110c8555f31e9b62c3b6edc2852c107c0 | 50,413 |
def validDate(date: str) -> bool:
"""Return whether a string follows the format of ####-##-##."""
if len(date) == 10:
return date[0:4].isnumeric() and date[5:7].isnumeric() and date[8:10].isnumeric() and date[4] == "-" and date[7] == "-"
return False | 311eafdc794a97ff9b65c21b4ee79edd039c3027 | 50,414 |
def main(vault, keyname):
"""Return keyname entry from vault in plain text."""
return vault.require(keyname) | 0e4e0cd2bdf178073e226025b1febf3b2fc26f8e | 50,415 |
def topsoil():
"""
Properties of typical topsoils
Following main site type (1-4) classification
"""
topsoil = {
'mineral':{
'topsoil_id': 1,
'org_depth': 0.05,
'org_poros': 0.9,
'org_fc': 0.33,
'org_rw': 0.15
},
... | 6b4b986a09728cc148260571eea0309c13aa8890 | 50,416 |
import struct
def enc_float(val):
"""Encode a single float"""
return struct.pack("!f", val) | f4d6d3fff683c3b64dcebc97c48b4ab8e3815f91 | 50,417 |
def fizzbuzz(num):
"""Function returns fizzbuzz if divisible by 3 and 5, buzz if divisible by 5, fizz if divisible by 3, and returns num if none of those conditions met."""
arr = []
for i in range(1, num + 1):
if i % 3 == 0 and i % 5 == 0:
arr.append('FizzBuzz')
elif i % 5 == 0:
... | 4759e0d2ffc95dc61c6c0129bba2acb88a775d1c | 50,418 |
def _strip_list(list):
"""
strips all empty elements from a list, returns the stripped list
:param list: the list to be stripped
:return: the stripped list
"""
return [x for x in list if x] | e000a3335fbcab640981a825a698586e502f89b1 | 50,420 |
def join_fields(fields):
"""
Join a bunch of key/value pairs together.
"""
return ', '.join('%s="%s"' % pair for pair in fields.iteritems()) | 147a2add910046f48d403f404ec9333e4532ea56 | 50,421 |
def is_prime(n):
""" Check if n is a prime number.
Sample usage:
>>> is_prime(0)
False
>>> is_prime(1)
True
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(5)
True
"""
if n <= 0:
# This is only for numbers > 0.
return False
f... | 031948206a9b38ac12d6a0262eb749b8c5e18ca8 | 50,422 |
def find_ep_ix(eps, t):
"""Finds epoch during time t"""
for i, ep in enumerate(eps):
if t >= ep.t0:
try:
test = t < eps[i+1].t0
except IndexError:
test = t <= eps[i].t1
if test:
return i
else:
raise V... | c4c39a82a925aed5b44442246449d295b2a398c6 | 50,423 |
import random
def random_mac_address(local_admin=True):
"""
Generates and returns a random MAC address.
"""
# By default use a random address in VMWare's MAC address
# range used by VMWare VMs, which has a very slim chance of colliding
# with existing devices.
mac = [
0x00,
... | d72a702887c3e51f7917991af596a8dbdd1c3ab3 | 50,425 |
import pkg_resources
def package_details():
"""
Returns a dictionary with details of installed packages in the current environment
"""
details = {}
packages = pkg_resources.working_set
for package in packages: # pylint: disable=E1133
details[package.project_name] = package.version
... | 219140f54cadd58ac8dfea9b78081ad62ed76057 | 50,426 |
def crf_preprocess_candidates(candidates):
"""Receive annotated candidates and return features and labels list"""
features = []
labels = []
for candidate in candidates:
candidate_features = []
candidate_labels = []
for token_features, label in candidate:
candidate_fea... | 91c8f941a9334d26a8ac0623201c13ca560cfeb0 | 50,428 |
def _BasenameFromPath(path):
"""Extracts the basename of either a Unix- or Windows- style path,
assuming it contains either \\ or / but not both.
"""
short_path = path.split('\\')[-1]
short_path = short_path.split('/')[-1]
return short_path | 90dd65c95ef61e48132d7f0404a5c4d5bef685c1 | 50,429 |
import math
def distance_between(vec1, vec2):
"""
:param vec1: list of (x1,y1,z1) values
:param vec2: list of (x2,y2,z2) values
:return: list of (abs(x1-x2), abs(y1-y2), abs(z1-z2)) values
"""
if len(vec1) != len(vec2):
raise IndexError("vec1 and vec2 don't have the same number of elem... | 4ba5356d8cd70a9630283038c781304c248e0bda | 50,430 |
def has_case_updates(case_block_kwargs):
"""
Returns True if case_block_kwargs contains case changes.
>>> has_case_updates({"owner_id": "123456", "update": {}})
True
>>> has_case_updates({"update": {}})
False
"""
if case_block_kwargs.get("update"):
return True
if case_block... | e80ec5d38b7d7b05983d6672df681c2efb4d3d1d | 50,434 |
import torch
def mmd_neg_biased(X, Y, k):
"""
Calculates biased MMD^2 without the S_YY term, where S_X, S_XY and S_YY are the pairwise-XX, pairwise-XY, pairwise-YY
summation terms respectively.
:param X: array of shape (m, d)
:param Y: array of shape (n, d)
:param k: GPyTorch kernel
:retur... | fa45797415224f171c6ce900f5a83e8ce13e9ded | 50,435 |
import re
def normalize_text(text):
"""
标准化处理
转换为小写,并去除网址、数字以及特殊符号
"""
text = text.lower()
text = re.sub('((www\.[^\s]+)|(https?://[^\s]+)|(pic\.twitter\.com/[^\s]+))', '', text)
text = re.sub('@[^\s]+', '', text)
text = re.sub('#([^\s]+)', '', text)
text = re.sub('[:;>?<=*+()&,\-#... | 4c0ecf208eb78734a0263ac0fad0f368c931a6a5 | 50,436 |
import logging
def init_logger(
_logger: logging.RootLogger,
log_level: int,
log_file: str
) -> logging.RootLogger:
"""Initialise the logger.
:param logging.RootLogger _logger: Logger instance to initialise.
:param int log_level: Desidered logging level (e.g. ``logging.INFO``).
:param str... | 6bceb87729e66c0e037b7667d572d001b0ab981e | 50,438 |
from functools import reduce
import operator
def product(nums):
"""Returns the product of all values
Attributes:
nums (iterable) Iterator of intergers
"""
return reduce(operator.mul, nums, 1) | f1f25302014e024300220e575818dfd47c80f14a | 50,440 |
def Idetifiers():
"""
0th extension header keywords.
Used to select and pair FITS files.
"""
common = {'PROPOSID': 11853,
'SCLAMP': 'TUNGSTEN',
'OBSMODE': 'ACCUM',
'CCDAMP': 'D',
'CCDGAIN': 4}
clear = {'APERTURE': '50CCD',
'PR... | 82847dadc1297d4896b91a04a51385e02b4abb81 | 50,444 |
def sort_and_count_inversions(aList):
"""Return an inversion count and sorted list"""
inversionCount = 0
sortedList = []
n = len(aList)
# Check base case
if n <= 1:
# If the list has 1 or 0 elements, there are no inversions
# and nothing to sort
return 0, aList
#... | 89e014f3a6c732675eaa3ea73745d335c0dc4a0b | 50,448 |
def build_api_link(service_name, callback_url):
"""
Utility for building UDID.io API links
"""
api_link = 'https://get.udid.io/thirdparty/api/?callback=%(callback)s&service=%(service)s&schemeurl=0' % {
'callback': callback_url,
'service': service_name
}
return api_link | cd49d06201d70a7cb0d01bc8642cce06c47738af | 50,449 |
def get_version(server_id, version, client):
"""Requests a list of certain version of server with ID."""
return client.get_server_version(str(server_id), version) | 06319e8563e7075d246be73571cac51867c2a9bb | 50,452 |
def linux_notify(title: str, message: str) -> str:
"""Display notification for Linux systems"""
command = f'''notify-send "{title}" "{message}"'''
return command | ae702eed884e35fccaf974898de9cc0c12b686c2 | 50,453 |
def get_default_qm7_task_names():
"""Get that default qm7 task names and return measured expt"""
return ['u0_atom'] | fc64aac53bb34daac7fad436ea6f6ae256c71a79 | 50,454 |
def extractCoordinates(dataframe1,dataframe2,paired):
"""
Extracts coordinates of paired nodes in both scans
Parameters
----------
dataframe1 : pandas.DataFrame()
Dataframe containing data from the lower resolution scan
dataframe2 : pandas.DataFrame()
Dat... | 131661e0b95d04f8e76f1d9a45e9c32f7344e051 | 50,455 |
import typing
def handle_authentication() -> typing.Any:
"""
There is no need for authentication, as no files are created.
"""
return None | 0db5b4b2f97312658696554d9c669b30493b8cdb | 50,458 |
import yaml
import logging
def read_configuration_from_file(file: str) -> dict:
"""
Reads configuration from YAML file
"""
with open(file, "r") as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
logging.exception("Unable to parse configurations")
return {} | 07bb844650e7df5c84b5b415b146eafb739f4e86 | 50,459 |
from typing import List
def join_words_cat(words: List[str]) -> str:
"""Joins words using string concatenation"""
sentence = ""
for word in words:
sentence += word
return sentence | f47f2ea2f1e2fa9e53bb586283f6d8f2ba6af3cc | 50,460 |
def any():
"""
Can be used to match any value.
"""
class Any:
def __eq__(self, other):
return True
return Any() | 3ea8946406cf59b22371d55427effffd35f78427 | 50,461 |
def array_chunk_slice(array, size):
"""Return an array containing chunks of the specified array with the specified size, using "slice"."""
result = []
for i in range(0, len(array), size):
result.append(array[i: i + size])
return result | 1388bfd67bcd1689fb474b7a5b8495680915ed5b | 50,463 |
def gather_dictQPV(Dinit, Dmodified, index, D0, D1, D2):
"""
Gather the Thresholds dictionary to use it in Electre Tri
:param Dinit: Initial dictionary containing the form of the gathered dictionary.
:param Dmodified: Modified dictionary to be included in gathered dictionary
:param in... | 62c29b1b9f6430e0a1f43b2a64daf37d018a13e1 | 50,464 |
import os
def mydocuments():
""" get the path to the MyDocuments folder """
return os.path.expanduser('~/documents') | db8b0f3fe24160f971f8b1f3d33e5c0263401418 | 50,467 |
def create_biomarker_schema(schema: dict) -> dict:
"""
Factory method for creating a schema object.
Arguments:
schema {dict} -- Cerberus schema dictionary.
Returns:
dict -- EVE endpoint definition.
"""
base_dict = {
"public_methods": [],
"resource_methods": ["GE... | 6e534a7ecdb54c9c23d811430a89cf98bf3e9bdd | 50,469 |
def zigpy_zll_device(zigpy_device_mock):
"""ZLL device fixture."""
return zigpy_device_mock(
{1: {"in_clusters": [0x1000], "out_clusters": [], "device_type": 0x1234}},
"00:11:22:33:44:55:66:77",
"test manufacturer",
"test model",
) | b3a5a6773857edfc3d26e87e1c6a20052b80ec7f | 50,470 |
def unique_col(name, id_):
"""Ensure uniqueness of a header/data entry.
Simply apply this to both the entry in `headers` and the
dict keys in `rows` before passing them to one of the spreadsheet
functions.
:param name: The actual column name/title
:param id_: The id or whatever is needed to en... | a945e63e0e35f0407a2a235ec98cf45e92d5998b | 50,471 |
import re
def compile_terms(terms):
"""
Compile terms as regular expression,
for better matching.
"""
return [re.compile(re.escape(term), re.I | re.U)
for term in terms] | de614da9e9f35b2dee61b07f649ed7559757cc4c | 50,472 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.