content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def cases():
"""
Loads all filenames of the pre-calculated test cases.
"""
case_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'cases'
)
cases = []
for dir_path, _, files in os.walk(case_dir):
cases = cases + [os.path.join(dir_path, f) fo... | 1e8cbf1001cb52ab5875b38714f1edca664f867c | 3,645,400 |
def axisAligned(angle, tol=None, axis=None):
""" Determine if a line (represented by its angle) is aligned with an axis.
Parameters
----------
angle : float
The line's angle of inclination (in radians)
tol : float
Maximum distance from `axis` for which `angle` is still considered to... | 9198f1d1e8b3755696f5ccf01b9df112d18bd363 | 3,645,401 |
def make_results_dict(
mesh_data,key_descriptor,
key_transformation=None,
verbose=False
):
"""Load mesh data into dictionary, using specified parameter tuple as
key.
Example key descriptor:
(("Nsigmamax",int),("Nmax",int),("hw",float))
Example:
>>> KEY_DESCRI... | cfc0e56751090fd3aea32ed42659652caf6c25ae | 3,645,402 |
def plot_1d(x_test, mean, var):
"""
Description
----------
Function to plot one dimensional gaussian process regressor mean and
variance.
Parameters
----------
x_test: array_like
Array containing one dimensional inputs of the gaussian process
model.
Mean: array_like
... | f53ca71b2546d6c849cdcb52c16ec77125a4c0a6 | 3,645,403 |
def sentence_to_windows(sentence, min_window, max_window):
"""
Create window size chunks from a sentence, always starting with a word
"""
windows = []
words = sentence.split(" ")
curr_window = ""
for idx, word in enumerate(words):
curr_window += (" " + word)
curr_window = cur... | 867240f310c9e7bc3f887a2592485a02ab646870 | 3,645,404 |
def get_master_name(els):
"""Function: get_master_name
Description: Return name of the master node in a Elasticsearch cluster.
Arguments:
(input) els -> ElasticSearch instance.
(output) Name of master node in ElasticSearch cluster.
"""
return els.cat.master().strip().split(" "... | 0371dac1fdf0fd6b906646e1882e9089d9dfa12c | 3,645,405 |
from typing import Sequence
import random
def flop_turn_river(dead: Sequence[str]) -> Sequence[str]:
"""
Get flop turn and river cards.
Args:
dead: Dead cards.
Returns:
5 cards.
"""
dead_concat = "".join(dead)
deck = [card for card in DECK if card not in dead_concat]
... | cea8289a5deb03dd74a9b20b99899d908e3f38e3 | 3,645,406 |
def smith_gassmann(kstar, k0, kfl2, phi):
"""
Applies the Gassmann equation.
Returns Ksat2.
"""
a = (1 - kstar/k0)**2.0
b = phi/kfl2 + (1-phi)/k0 - (kstar/k0**2.0)
ksat2 = kstar + (a/b)
return ksat2 | ae413d7ed55862927e5f8d06d4aff5bfc0e91167 | 3,645,407 |
import json
async def _preflight_cors(request):
"""Respond to preflight CORS requests and load parameters."""
if request.method == "OPTIONS":
return textify("ok", headers=generate_cors_headers(request))
request['args'] = {}
if request.form:
for key in request.form:
key_lowe... | 91f6057fc4d624d576b7a8ae45cd202264fde7c1 | 3,645,408 |
def login_teacher():
""" Login User and redirect to index page. """
# forget any user
session.clear()
# if user reached via route POST
if request.method == "POST":
# check user credentials
email_id = request.form.get("email_id")
passw = request.form.get("password")
... | 04982b664b18c3c10d1d5dadabe101de97f4383d | 3,645,409 |
import os
import tempfile
import json
def upload_file():
"""Upload files"""
print("UPLOADED FILES", len(request.files))
if not os.path.exists(FILE_START_PATH):
os.makedirs(FILE_START_PATH)
# Set the upload folder for this user if it hasn't been set yet
# pylint: disable=consider-using-wit... | 26071b9b6e8c6915994a0ddc049002e9f2e2ad8e | 3,645,410 |
import base64
def mult_to_bytes(obj: object) -> bytes:
"""Convert given {array of bits, bytes, int, str, b64} to bytes"""
if isinstance(obj, list):
i = int("".join(["{:01b}".format(x) for x in obj]), 2)
res = i.to_bytes(bytes_needed(i), byteorder="big")
elif isinstance(obj, int):
... | 7e86caf56f8187215c6ecbea63b259e627dde0ad | 3,645,411 |
import six
def get_barrier(loopy_opts, local_memory=True, **loopy_kwds):
"""
Returns the correct barrier type depending on the vectorization type / presence
of atomics
Parameters
----------
loopy_opts: :class:`loopy_utils.loopy_opts`
The loopy options used to create this kernel.
l... | 6f45099827f93ebe41e399b6c75aa7a1b85779fb | 3,645,412 |
def monthly_rain(year, from_month, x_months, bound):
"""
This function downloaded the data embedded tif files from the SILO Longpaddock Dataset
and creates a cumulative annual total by stacking the xarrays. This function is embedded
in the get_rainfall function or can be used separately
Paramet... | 951ac32a8afcc5b0fd6f0c1b6616f3cc4d162540 | 3,645,413 |
def organize_by_chromosome(genes, transcripts):
""" Iterate through genes and transcripts and group them by chromosome """
gene_dict = {}
transcript_dict = {}
for ID in genes:
gene = genes[ID]
chromosome = gene.chromosome
if chromosome not in gene_dict:
chrom_genes =... | 2f55d29a75f5c28fbf3c79882b8b2ac18590cdb2 | 3,645,414 |
from itertools import product
import pandas as pd
def get_synth_stations(settings, wiggle=0):
""" Compute synthetic station locations.
Values for mode "grid" and "uniform" and currently for tests on global Earth geometry.
TODO: incorporate into settings.yml
:param settings: dict holding all inf... | 962fa23773ebc297fedec6b79ac27718780a8699 | 3,645,415 |
def test_show_chromosome_labels(dash_threaded):
"""Test the display/hiding of chromosomes labels."""
prop_type = 'bool'
def assert_callback(prop_value, nclicks, input_value):
answer = ''
if nclicks is not None:
answer = FAIL
if PROP_TYPES[prop_type](input_value) == ... | da3003e54c681b689703f7226b3a5f7a13756944 | 3,645,416 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
name = entry.data.get(CONF_NAME)
ha = get_ha(hass, name)
if ha is not None:
await ha.async_remove()
clear_ha(hass, name)
return True | 1783c518e919eb60b2a40603322aa2a04dbc4000 | 3,645,417 |
def relay_state(pin):
"""Take in pin, return string state of the relay"""
logger.debug("relay_state() for pin %s", pin)
disabled = GPIO.digitalRead(pin)
logger.debug("Pin %s disabled: %s", pin, disabled)
state = "off"
if not disabled:
state = "on"
logger.debug("Relay state for pin %s... | eae5ce94baa8ffe114ffeed811c7a8733dfb5cc5 | 3,645,418 |
def calc_fn(grid, size, coefficients=(-0.005, 10)):
""" Apply the FitzHugh-Nagumo equations to a given grid"""
a, b, *_ = coefficients
out = np.zeros(size)
out[0] = grid[0] - grid[0] ** 3 - grid[1] + a
out[1] = b * (grid[0] - grid[1])
return out | 47a46f75a56ffb3d034a689034fa04f7593c485f | 3,645,419 |
def destr(screenString):
"""
should return a valid screen object
as defined by input string
(think depickling)
"""
#print "making screen from this received string: %s" % screenString
rowList = []
curRow = []
curAsciiStr = ""
curStr = ""
for ch in screenString:
if ch == '\n':
# then we are done with... | 38f540b3e8f6a16d2dbe7519ea5a43cbf2432b55 | 3,645,420 |
def analytical_solution_with_penalty(train_X, train_Y, lam, poly_degree):
"""
加惩罚项的数值解法
:param poly_degree: 多项式次数
:param train_X: 训练集的X矩阵
:param train_Y: 训练集的Y向量
:param lam: 惩罚项系数
:return: 解向量
"""
X, Y = normalization(train_X, train_Y, poly_degree)
matrix = np.linalg.inv(X.T.dot(... | 30f81cd74622889df64d6e67f023f67b3149504a | 3,645,421 |
def formule_haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""
Description:
Calcule la distance entre deux points par la formule de Haversine.
Paramètres:
lat1: {float} -- Latitude du premier point.
lon1: {float} -- Longitude du premier point.
la... | 03ac0c191aa17b9f20944a7de56febba77db1edc | 3,645,422 |
def get_word_combinations(word):
"""
'one-two-three'
=>
['one', 'two', 'three', 'onetwo', 'twothree', 'onetwothree']
"""
permutations = []
parts = [part for part in word.split(u'-') if part]
for count in range(1, len(parts) + 1):
for index in range(len(parts) - count + 1):
... | 5a4c042cc0f3dedb297e2513bf638eac4278e0a6 | 3,645,423 |
import tempfile
def env_to_file(env_variables, destination_path=None, posix=True):
"""
Write environment variables to a file.
:param env_variables: environment variables
:param destination_path: destination path of a file where the
environment variables will be stored. t... | c242ff4d6956922b2ccceecaef5b95640116e75a | 3,645,424 |
def _phase_norm(signal, reference_channel=0):
"""Unit normalization.
Args:
signal: STFT signal with shape (..., T, D).
Returns:
Normalized STFT signal with same shape.
"""
angles = np.angle(signal[..., [reference_channel]])
return signal * np.exp(-1j * angles) | f4e9021f8942bebf97d35e529068792b7f956425 | 3,645,425 |
def maintenance_():
"""Render a maintenance page while on maintenance mode."""
return render_template("maintenance/maintenance.html") | 61b95cdeb1a16f216a60330d7501e5270e1342ba | 3,645,426 |
def CanEditHotlist(effective_ids, hotlist):
"""Return True if a user is editor(add/remove issues and change rankings)."""
return any([user_id in (hotlist.owner_ids + hotlist.editor_ids)
for user_id in effective_ids]) | dc29c74e2628930faffb12b6772046564ffb8218 | 3,645,427 |
from desimodel.io import load_fiberpos, load_target_info
def model_density_of_sky_fibers(margin=1.5):
"""Use desihub products to find required density of sky fibers for DESI.
Parameters
----------
margin : :class:`float`, optional, defaults to 1.5
Factor of extra sky positions to generate. So... | a50111f51c2ce081c3379e2b5506912326fafb55 | 3,645,428 |
def dice_counts(dice):
"""Make a dictionary of how many of each value are in the dice """
return {x: dice.count(x) for x in range(1, 7)} | 427703283b5c0cb621e25f16a1c1f2436642fa9f | 3,645,429 |
def SynthesizeData(phase, total_gen):
""" Phase ranges from 0 to 24 with increments of 0.2. """
x_list = [phase]
y_list = []
while len(x_list) < total_gen or len(y_list) < total_gen:
x = x_list[-1]
y = sine_function(x=x, amp=amp, per=per, shift_h=shift_h, shift_v=shift_v)
x_lis... | e656767f7ebf13575571b5eb0592a0e11cbbfcf7 | 3,645,430 |
from pathlib import Path
import difflib
from datetime import datetime
def compare():
""" Eats two file names, returns a comparison of the two files.
Both files must be csv files containing
<a word>;<doc ID>;<pageNr>;<line ID>;<index of the word>
They may also contain lines with addit... | f6aa0421e84cf9d97a211904e64bd793ff7e989e | 3,645,431 |
def draw_transform(dim_steps, filetype="png", dpi=150):
"""create image from variable transormation steps
Args:
dim_steps(OrderedDict): dimension -> steps
* each element contains steps for a dimension
* dimensions are all dimensions in source and target domain
* each step i... | 4738f9512065a9d0d6e33879954581cbf0940a11 | 3,645,432 |
import statistics
def get_ei_border_ratio_from_exon_id(exon_id, regid2nc_dic,
exid2eibrs_dic=None,
ratio_mode=1,
last_exon_dic=None,
last_exon_ratio=2.5,
... | fd5239fabb81d328d644dbb8b56608eda15e78ce | 3,645,433 |
def events(*_events):
""" A class decorator. Adds auxiliary methods for callback based event
notification of multiple watchers.
"""
def add_events(cls):
# Maintain total event list of both inherited events and events added
# using nested decorations.
try:
all_events = cl... | 601f7d55ff4d05dd0aca552213dcd911f15c91b6 | 3,645,434 |
def _find_nearest(array, value):
"""Find the nearest numerical match to value in an array.
Args:
array (np.ndarray): An array of numbers to match with.
value (float): Single value to find an entry in array that is close.
Returns:
np.array: The entry in array that is closest to valu... | 7440447c4079563722b91771f07fcd3c3f5e0c3b | 3,645,435 |
import requests
from bs4 import BeautifulSoup
def download_document(url):
"""Downloads document using BeautifulSoup, extracts the subject and all
text stored in paragraph tags
"""
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
title = soup.find('title').get_text()
document = ' '.join([p.get_... | 8bb9055b40dd5554185ddec1d3218157a016bfd8 | 3,645,436 |
def rz_gate(phi: float = 0):
"""Functional for the single-qubit Pauli-Z rotation-gate.
Parameters
----------
phi : float
Rotation angle (in radians)
Returns
-------
rz : (2, 2) np.ndarray
"""
arg = 1j * phi / 2
return np.array([[np.exp(-arg), 0], [0, np.exp(arg)]]) | c148a03f3525698c44e5f8aa14085bfeb29c72ef | 3,645,437 |
from typing import List
def dict_to_kvp(dictionary: dict) -> List[tuple]:
"""
Converts a dictionary to a list of tuples where each tuple has the key and value
of each dictionary item
:param dictionary: Dictionary to convert
:return: List of Key-Value Pairs
"""
return [(k, v) for k, v in d... | 2b856ebb218884a4975d316bebe27546070f2083 | 3,645,438 |
def convert_and_remove_punctuation(text):
"""
remove punctuation that are not allowed, e.g. / \
convert Chinese punctuation into English punctuation, e.g. from「 to "
"""
# removal
text = text.replace("\\", "")
text = text.replace("\\", "")
text = text.replace("[", "")
text = text.re... | 2de1f930ca76da7fec3467469f98b0e0858e54a0 | 3,645,439 |
def create_random_context(dialog,rng,minimum_context_length=2,max_context_length=20):
"""
Samples random context from a dialog. Contexts are uniformly sampled from the whole dialog.
:param dialog:
:param rng:
:return: context, index of next utterance that follows the context
"""
# sample dia... | d66ee8f185380801735644a7ce4528f398385e60 | 3,645,440 |
def dev_test_new_schema_version(dbname, sqldb_dpath, sqldb_fname,
version_current, version_next=None):
"""
hacky function to ensure that only developer sees the development schema
and only on test databases
"""
TESTING_NEW_SQL_VERSION = version_current != version_next... | ec57d6ccb39d76159ab80c6fdfe094b486d00777 | 3,645,441 |
def _get_distance_euclidian(row1: np.array, row2: np.array):
"""
_get_distance
returns the distance between 2 rows
(euclidian distance between vectors)
takes into account all columns of data given
"""
distance = 0.
for i, _ in enumerate(row1):
distance += (row1[i] - row2[i]) ** 2... | 13a3944becf717222eb6fc997ceb937ad37b30ab | 3,645,442 |
import re
def _get_ip_from_response(response):
"""
Filter ipv4 addresses from string.
Parameters
----------
response: str
String with ipv4 addresses.
Returns
-------
list: list with ip4 addresses.
"""
ip = re.findall(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)... | ac36a3b729b0ce4ba13a6db550a71276319cbd70 | 3,645,443 |
from typing import Optional
from typing import List
import logging
def create_processor(
options: options_pb2.ConvertorOptions,
theorem_database: Optional[proof_assistant_pb2.TheoremDatabase] = None,
tactics: Optional[List[deephol_pb2.Tactic]] = None) -> ProofLogToTFExample:
"""Factory function for Proo... | 898a72372a80546f4de277c5f3e3573c7f8edff6 | 3,645,444 |
def EscapeShellArgument(s):
"""Quotes an argument so that it will be interpreted literally by a POSIX
shell. Taken from
http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python
"""
return "'" + s.replace("'", "'\\''") + "'" | 132a3b1bb8a0e7b3c92ac15e2d68337eeef19042 | 3,645,445 |
def login_invalid(request, error_type):
""" Displays the index with an error message. """
# TODO - encode authentification error message in URI
try:
message = INVALID_LOGIN_MESSAGE[error_type]
except KeyError:
message = "Erreur inconnue"
context = {'form': LoginForm(), 'message': m... | e9d901a052f696c69b00f6499da87fa6b5b3419d | 3,645,446 |
def lsh(B_BANDS, docIdList, sig):
""" Applies the LSH algorithm. This function first divides the signature matrix into bands and hashes each column onto buckets.
:param B_BANDS: Number of bands in signature matrix
:param docIdList: List of document ids
:param sig: signature matrix
:return: List of ... | ad6071e52d2c442764e57bb68e2f1e2d4c5a7c2e | 3,645,447 |
def langevin_coefficients(
temperature,
dt,
friction,
masses):
"""
Compute coefficients for langevin dynamics
Parameters
----------
temperature: float
units of Kelvin
dt: float
units of picoseconds
friction: float
frequency in picoseconds
masse... | 680d5c8898ecb7c0627232c8c993bb0f64a2e9d3 | 3,645,448 |
def waitpid_handle_exceptions(pid, deadline):
"""Wrapper around os.waitpid()/waitpid_with_timeout(), which waits until
either a child process exits or the deadline elapses, and retries if certain
exceptions occur.
Args:
pid: Process ID to wait for, or -1 to wait for any child process.
deadline: If non-... | 2d15594c9b066b3e1000a6394503a9b8a88e5420 | 3,645,449 |
import subprocess
def tedor_ideal(t_mix, a, dist, t2, j_cc, obs='C13', pulsed='N15', vr=14000, return_t=False):
"""
Makes a SpinEvolution input file from template file "tedor_ideal_template", calls SpinEvolution, parses the output,
and applies phenomenological scaling and exponential relaxation.
The ... | 646d4d3a811c8fc7ad2521a1aca921d2ceb2e8a6 | 3,645,450 |
def preprocess(image, image_size):
"""
Preprocess
pre-process the image by to adaptive_treshold, perspectiv_transform,
erode, diletate, resize
:param image: image of display from cv2.read
:return out_image: output image after preprocessing
"""
# blurr
blurred = cv2.GaussianBlur(im... | 497d3d1a32be643486903d44621ff203503b726e | 3,645,451 |
import urllib
import json
import time
def download(distributor: Distributor, max_try:int = 4) -> list[TrainInformation]|None:
"""Download train information from distributor.
If response status code was 500-599, this function retries up to max_try times.
Parameters
----------
distributor : Distri... | 1288e50807465164dd4aa2e082b4136abe81636c | 3,645,452 |
def add_payloads(prev_layer, input_spikes):
"""Get payloads from previous layer."""
# Get only payloads of those pre-synaptic neurons that spiked
payloads = tf.where(tf.equal(input_spikes, 0.),
tf.zeros_like(input_spikes), prev_layer.payloads)
print("Using spikes with payloads f... | 4f7bd805e8659ddea0da63fd542edb6d52073569 | 3,645,453 |
def read_csv_to_data(path: str, delimiter: str = ",", headers: list = []):
"""A zero-dependancy helper method to read a csv file
Given the path to a csv file, read data row-wise. This data may be later converted to a dict of lists if needed (column-wise).
Args:
path (str): Path to csv file
... | f60e163e770680efd1f8944becd79a0dd7ceaa08 | 3,645,454 |
def main_menu(update, context):
"""Handling the main menu
:param update: Update of the sent message
:param context: Context of the sent message
:return: Status for main menu
"""
keyboard = [['Eintragen'],
['Analyse']]
update.message.reply_text(
'Was möchtest du mach... | bafc092ec662286f417a9a5d2c47a675336c4825 | 3,645,455 |
def build_model(inputs, num_classes, is_training, hparams):
"""Constructs the vision model being trained/evaled.
Args:
inputs: input features/images being fed to the image model build built.
num_classes: number of output classes being predicted.
is_training: is the model training or not.
... | 0ad57496d77e4406c5081982a2c02f2111cb5b57 | 3,645,456 |
import flask_monitoringdashboard
def get_test_app_for_status_code_testing(schedule=False):
"""
:return: Flask Test Application with the right settings
"""
app = Flask(__name__)
@app.route('/return-a-simple-string')
def return_a_simple_string():
return 'Hello, world'
@app.route('... | 69951350c8b14cf02b1327773665d9080b0eeb48 | 3,645,457 |
import os
def current_user():
"""Returns the value of the USER environment variable"""
return os.environ['USER'] | 75d588d801a5afcd2037a05c7dc5e990532eb114 | 3,645,458 |
def run_multiple_cases(x, y, z, door_height, door_width, t_amb,
HoC, time_ramp, hrr_ramp, num, door, wall,
simulation_time, dt_data):
"""
Generate multiple CFAST input files and calls other functions
"""
resulting_temps = np.array([])
for i in range(le... | 1c056b4c991889b81324857788cda416f90a8cdc | 3,645,459 |
def get_all():
"""
Obtiene todas las tuplas de la relación Estudiantes
:returns: Todas las tuplas de la relación.
:rtype: list
"""
try:
conn = helpers.get_connection()
cur = conn.cursor()
cur.execute(ESTUDIANTE_QUERY_ALL)
result = cur.fetchall()
... | 8b2248f09b02bf8fb4198bd36e743a5d052dd9f3 | 3,645,460 |
import warnings
def load_fgong(filename, fmt='ivers', return_comment=False,
return_object=True, G=None):
"""Given an FGONG file, returns NumPy arrays ``glob`` and ``var`` that
correspond to the scalar and point-wise variables, as specified
in the `FGONG format`_.
.. _FGONG format: http... | 17fcac5511a588351701f921dc8449d81a603fb6 | 3,645,461 |
import os
import numpy
import time
def hla_saturation_flags(drizzled_image, flt_list, catalog_name, catalog_data, proc_type, param_dict, plate_scale,
column_titles, diagnostic_mode):
"""Identifies and flags saturated sources.
Parameters
----------
drizzled_image : string
... | 9ccd478331ec1e22068fb344d7a2d63eb4a40533 | 3,645,462 |
import ctypes
def dskb02(handle, dladsc):
"""
Return bookkeeping data from a DSK type 2 segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskb02_c.html
:param handle: DSK file handle
:type handle: int
:param dladsc: DLA descriptor
:type dladsc: spiceypy.utils.support_types... | b08eed84bd518d35166ee28df8f87c06b08220c4 | 3,645,463 |
from sys import version
def mt_sec(package, db):
"""
Multithreaded function for security check of packages
:param package: package name
:param db: vuln db
:return:
"""
all_rep = {}
all_rep[package] = {}
error_message = None
try:
_, status, rep = control_vulnerability(pa... | 46e6b3bc0725e88d443b418faf9fc1622e9210cf | 3,645,464 |
def train_node2vec(graph, dim, p, q):
"""Obtains node embeddings using Node2vec."""
emb = n2v.Node2Vec(
graph=graph,
dimensions=dim,
workers=mp.cpu_count(),
p=p,
q=q,
quiet=True,
).fit()
emb = {
node_id: emb.wv[str(node_id)]
for node_id in... | 7cea146b2971e973de2ecd365ad25c7f4fd57289 | 3,645,465 |
def approx_match_dictionary():
"""Maps abbreviations to the part of the expanded form that is common beween all forms of the word"""
k=["%","bls","gr","hv","hæstv","kl","klst","km","kr","málsl",\
"málsgr","mgr","millj","nr","tölul","umr","þm","þskj","þús"]
v=['prósent','blaðsíð',\
'grein','hát... | 021c7de862b2559b55051bc7267113d77132e195 | 3,645,466 |
def matrix2array(M):
"""
1xN matrix to array.
In other words:
[[1,2,3]] => [1,2,3]
"""
if isspmatrix(M):
M = M.todense()
return np.squeeze(np.asarray(M)) | 731317458f6ec7c068c1a9450447eba39e1423f9 | 3,645,467 |
def expected(data):
"""Computes the expected agreement, Pr(e), between annotators."""
total = float(np.sum(data))
annotators = range(len(data.shape))
percentages = ((data.sum(axis=i) / total) for i in annotators)
percent_expected = np.dot(*percentages)
return percent_expected | 86562fec2b17df35401b8d8b7eafd759a13715e3 | 3,645,468 |
import numpy
def maximization_step(num_words, stanzas, schemes, probs):
"""
Update latent variables t_table, rprobs
"""
t_table = numpy.zeros((num_words, num_words + 1))
rprobs = numpy.ones(schemes.num_schemes)
for i, stanza in enumerate(stanzas):
scheme_indices = schemes.get_schemes_f... | a0e23367d6dff50d79bb828a0af8a82b640400c8 | 3,645,469 |
import json
def account_export_mydata_content(account_id=None):
"""
Export ServiceLinks
:param account_id:
:return: List of dicts
"""
if account_id is None:
raise AttributeError("Provide account_id as parameter")
# Get table names
logger.info("ServiceLinkRecord")
db_entry_... | d61dd638319479572ecea5335f0a9a7fc7156410 | 3,645,470 |
from typing import List
def indicator_entity(indicator_types: List[str] = None) -> type:
"""Return custom model for Indicator Entity."""
class CustomIndicatorEntity(IndicatorEntity):
"""Indicator Entity Field (Model) Type"""
@validator('type', allow_reuse=True)
def is_empty(cls, valu... | f6c77ffd3b8415e07e0e64ab8120a084aab3e2c8 | 3,645,471 |
def z_to_t(z_values, dof):
"""
Convert z-statistics to t-statistics.
An inversion of the t_to_z implementation of [1]_ from Vanessa Sochat's
TtoZ package [2]_.
Parameters
----------
z_values : array_like
Z-statistics
dof : int
Degrees of freedom
Returns
-------... | 4700f52263519169a4610daee8c0940489b2731e | 3,645,472 |
def getInputShape(model):
"""
Gets the shape when there is a single input.
Return:
Numeric dimensions, omits dimensions that have no value. eg batch
size.
"""
s = []
for dim in model.input.shape:
if dim.value:
s.append(dim.value)
... | 628f61a995784b9be79816a5bbcde2f8204640be | 3,645,473 |
import os
def get_latest_file(file_paths, only_return_one_match=True):
"""
Returns the latest created file from a list of file paths
:param file_paths: list(str)
:param only_return_one_match: bool
:return: list(str) or str
"""
last_time = 0
times = dict()
for file_path in file_pat... | 895e11ddd1e46228233b880afd5df8a2772e7f44 | 3,645,474 |
def get_node_depths(tree):
"""
Get the node depths of the decision tree
>>> d = DecisionTreeClassifier()
>>> d.fit([[1,2,3],[4,5,6],[7,8,9]], [1,2,3])
>>> get_node_depths(d.tree_)
array([0, 1, 1, 2, 2])
"""
def get_node_depths_(current_node, current_depth, l, r, depths):
depths ... | 4a5a001600c0cb6b1b545be003708088bbd2d060 | 3,645,475 |
import attr
from typing import Tuple
def homo_tuple_typed_attrs(draw, defaults=None, legacy_types_only=False, kw_only=None):
"""
Generate a tuple of an attribute and a strategy that yields homogenous
tuples for that attribute. The tuples contain strings.
"""
default = attr.NOTHING
val_strat = ... | 398e47ea6fb65ba0fab1e633ea27dc3cac30ed28 | 3,645,476 |
from typing import Dict
from typing import Any
from typing import Callable
from typing import Union
from typing import Tuple
from typing import Optional
def flatland_env_factory(
evaluation: bool = False,
env_config: Dict[str, Any] = {},
preprocessor: Callable[
[Any], Union[np.ndarray, Tuple[np.nd... | a2076ef15964e60b7a5e4cf885e5b92da594f0ac | 3,645,477 |
import six
def industry(code, market="cn"):
"""获取某个行业的股票列表。目前支持的行业列表具体可以查询以下网址:
https://www.ricequant.com/api/research/chn#research-API-industry
:param code: 行业代码,如 A01, 或者 industry_code.A01
:param market: 地区代码, 如'cn' (Default value = "cn")
:returns: 行业全部股票列表
"""
if not isinstance(code, ... | bf5606b93e17d5b5125f6afd133e86b5ded9a03d | 3,645,478 |
def kewley_agn_oi(log_oi_ha):
"""Seyfert/LINER classification line for log([OI]/Ha)."""
return 1.18 * log_oi_ha + 1.30 | 5e6b71742bec307ad609d855cced80ae08e5c35c | 3,645,479 |
def XGMMLReader(graph_file):
"""
Arguments:
- `file`:
"""
parser = XGMMLParserHelper()
parser.parseFile(graph_file)
return parser.graph() | ef9c1cb101b22f3302cf93db7447431fb1f5cfa8 | 3,645,480 |
def pt_encode(index):
"""pt: Toggle light."""
return MessageEncode(f"09pt{index_to_housecode(index)}00", None) | 1e2143d7c356736082d4dc25b459630e8c97fe7a | 3,645,481 |
def normalize_inputspace(
x,
vmax=1,
vmin=0,
mean=PYTORCH_IMAGENET_MEAN,
std=PYTORCH_IMAGENET_STD,
each=True,
img_format="CHW",
):
"""
Args:
x: numpy.ndarray
format is CHW or BCHW
each: bool
if x has dimension B
then apply each inpu... | d616213457722eb183b7c9b64e9b4778e56aa5be | 3,645,482 |
from typing import Tuple
import os
def get_load_average() -> Tuple[float, float, float]:
"""Get load average"""
return os.getloadavg() | 48942b9dbd5c1c38e0c9e13566521d96e980b7a7 | 3,645,483 |
from qtpy.QtCore import QUrl
from qtpy.QtGui import QDesktopServices
def start_file(filename):
"""
Generalized os.startfile for all platforms supported by Qt
This function is simply wrapping QDesktopServices.openUrl
Returns True if successfull, otherwise returns False.
"""
# We need to use ... | 269704fdd5bbf4e3d3e35bec6e9862fe36602f22 | 3,645,484 |
def require_context(f):
"""Decorator to require *any* user or admin context.
This does no authorization for user or project access matching, see
:py:func:`authorize_project_context` and
:py:func:`authorize_user_context`.
The first argument to the wrapped function must be the context.
"""
d... | 7a052ddf20b9afff055daed09dbe0963269d46f4 | 3,645,485 |
def failsafe_hull(coords):
"""
Wrapper of ConvexHull which returns None if hull cannot be computed for given points (e.g. all colinear or too few)
"""
coords = np.array(coords)
if coords.shape[0] > 3:
try:
return ConvexHull(coords)
except QhullError as e:
if '... | dca4d35d98032f9c77da38a860c2209758babfda | 3,645,486 |
def list_closed_poll_sessions(request_ctx, **request_kwargs):
"""
Lists all closed poll sessions available to the current user.
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:return: List closed poll sessions
:rtype: requests.Response (with voi... | 90c2d660a18ed9fa9f10f092a415e5f94148eba1 | 3,645,487 |
from typing import List
import struct
def _wrap_apdu(command: bytes) -> List[bytes]:
"""Return a list of packet to be sent to the device"""
packets = []
header = struct.pack(">H", len(command))
command = header + command
chunks = [command[i : i + _PacketData.FREE] for i in range(0, len(command), ... | 828521642b43758cf0c43f2c8af171d3463cacf5 | 3,645,488 |
from pathlib import Path
def build_dtree(bins):
"""
Build the directory tree out of what's under `user/`. The `dtree` is a
dict of:
string name -> 2-list [inumber, element]
, where element could be:
- Raw bytes for regular file
- A `dict` for directory, which recurses on
"""... | 66248226318a6225ea17d82d535012447b33f7e5 | 3,645,489 |
def _compose_image(digit, background):
"""Difference-blend a digit and a random patch from a background image."""
w, h, _ = background.shape
dw, dh, _ = digit.shape
x = np.random.randint(0, w - dw)
y = np.random.randint(0, h - dh)
bg = background[x:x+dw, y:y+dh]
return np.abs(bg - digit).as... | 956e06623f0534bea93b446e9a742ae78aada69f | 3,645,490 |
def permissions_vsr(func):
"""
:param func:
:return:
"""
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper | a7e01f7711cab6bc46c004c4d062930c2a656eee | 3,645,491 |
import scipy
def tri_interpolate_zcoords(points: np.ndarray, triangles: np.ndarray, mesh_points: np.ndarray,
is_mesh_edge: np.ndarray, num_search_tris: int=10):
"""
Interpolate z-coordinates to a set of 2D points using 3D point coordinates and a triangular mesh.
If point is alo... | 0a1702407c8a5b175b8fa8314eede203ac5a86ca | 3,645,492 |
from typing import List
def getServiceTypes(**kwargs) -> List:
"""List types of services.
Returns:
List of distinct service types.
"""
services = getServices.__wrapped__()
types = [s['type'] for s in services]
uniq_types = [dict(t) for t in {tuple(sorted(d.items())) for d in types}]
... | 23bd7730b43c1d942450fc57c2a3c6f83f7c578c | 3,645,493 |
from keras.callbacks import EarlyStopping, ModelCheckpoint
import pylab as plt
def train_model(train_data, test_data, model, model_name, optimizer, loss='mse', scale_factor=1000., batch_size=128, max_epochs=200, early_stop=True, plot_history=True):
""" Code to train a given model and save out to the designated pa... | 3d74e765065b8514dd43d0a0ba6f83542bc47b11 | 3,645,494 |
def get_pipeline_storage_es_client(session, *, index_date):
"""
Returns an Elasticsearch client for the pipeline-storage cluster.
"""
secret_prefix = f"elasticsearch/pipeline_storage_{index_date}"
host = get_secret_string(session, secret_id=f"{secret_prefix}/public_host")
port = get_secret_stri... | 8b759f1c2b6fa2b525a0a20653bd1ff99441e893 | 3,645,495 |
def cqcc_resample(s, fs_orig, fs_new, axis=0):
"""implement the resample operation of CQCC
Parameters
----------
s : ``np.ndarray``
the input spectrogram.
fs_orig : ``int``
origin sample rate
fs_new : ``int``
new sample rate
axis : ``int``
the resample axis
... | d252fdc2587c48d15d7f41224df3bfcd9e17693c | 3,645,496 |
def weights_init():
"""
Gaussian init.
"""
def init_fun(m):
classname = m.__class__.__name__
if (classname.find("Conv") == 0 or classname.find("Linear") == 0) and hasattr(m, "weight"):
nn.init.normal_(m.weight, 0.0, 0.02)
if hasattr(m, "bias") and m.bias is not... | f56aa9c988b93d30c6a78769bc0f2c86f0209cd8 | 3,645,497 |
def named(name):
"""
This function is used to decorate middleware functions in order
for their before and after sections to show up during a verbose run.
For examples see documentation to this module and tests.
"""
def new_annotate(mware):
def new_middleware(handler):
new_h... | 0f1cef0788eae16bf557b5f7cb01bd52e913203d | 3,645,498 |
def concatFile(file_list):
""" To combine files in file list.
"""
config = getConfig()
print('[load]concating...')
df_list = []
for f in file_list:
print(f)
tmp = pd.read_csv(config['dir_raw']+f, index_col=None, header=0)
df_list.append(tmp)
df = pd.concat(df_list, axis=0, ignore_index=True)
return df | c289db2e1a995f3b536f2d472eed550843980635 | 3,645,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.