content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
def get_generator_regulation_raise_term_3(data, trader_id, intervention) -> Union[float, None]:
"""Get R5RE term 3 in FCAS availability calculation"""
# Parameters
enablement_max = get_effective_enablement_max(data, trader_id, 'R5RE')
energy_target = lookup.get_trader_solutio... | f3c9316d7b5b9779bb01b301d6ccea5b3cb94bf4 | 3,601,615 |
from cblaster.extract_clusters import get_sorted_cluster_hierarchies
def binary(
session,
hide_headers=False,
delimiter=None,
key=len,
attr="identity",
decimals=4,
sort_clusters=False,
):
"""Generates a binary summary table from a Session object."""
# prevent a circular import
... | 3544af05a8f41a84e2d9147a8bdca81dc7da4cde | 3,601,616 |
def decode_entities(html):
"""
Convert all HTML entities into their unicode
representations.
This functions processes following entities:
* &XXX;
* &#XXX;
Example::
>>> print html.decode_entities('→ABC R©')
→ABC R©
"""
def process_entity(matc... | 70bf67af162d932f3200ce3b63fcc254826cd21d | 3,601,618 |
from typing import Container
def get_container() -> Container:
"""Returns container used for resolving and registering dependencies"""
return _CURRENT_CONTAINER.get() | 10ac514fbeaf9550d4e336f9b6be98e92bad5d8c | 3,601,619 |
import tqdm
def get_raw_downloads(in_file):
""" Gets raw download statistics for each node (file, URL, IP) """
raw_downloads = {}
with open(in_file, 'r') as f:
for line in tqdm(f):
line = line.rstrip()
values = line.split('\t')
if len(values) > 15:
... | 795c2ede7f34c2add0d8c049398db50d8e78a7e8 | 3,601,620 |
def callbacks(cbs):
"""Decorator that attaches callbacks to a function. Callbacks should be
defined as classes inheriting from abstract base class Callback that
implement on_begin and on_end methods. This allows us to store states
rather than just printing outputs or relying on global variables.
Pa... | 113e929fd6e34c17e16bad692ecae2bc0cbf71ea | 3,601,621 |
def update_simulation(n_clicks, *args):
"""
Simulates the model for the current slider values and updates the
subplots in the figure when the Run button is clicked.
Reset the app when the Reset button is clicked.
"""
ctx = dash.callback_context
if ctx.triggered:
input_id = ctx.trigge... | 8066682c4666a5264cc03b90756428ef8407de03 | 3,601,622 |
def get_itime_section_data(date, time):
"""
Get data for ITIME section
Parameters
----------
time : int
Time interval
Returns
-------
out : np.array
Array of items
See Also
--------
np.array
Examples
--------
>>> l = get_itime_section_data(5)
... | 6e2af095301bd8fce5b8f98d5b08351862d2b8f5 | 3,601,623 |
def delete_safe_member_command(
client: Client,
safe_name: str,
member_name: str,
) -> CommandResults:
"""Remove a specific member from a safe.
:param client: The client object with an access token
:param safe_name: Name of the safe to which the safe member belongs.
:param member... | 3e2a2e3e4977596d61addccdaa39ebdea566e72a | 3,601,624 |
def filter(datastream, src_field, pred):
"""
Filters out fields that yield a given criteria.
:param datastream: input datastream
:param src_field: field of list of fields to consider
:param pred: predicate function. If `src_field` is one field, than `pred` is a function of one argument returning boo... | aa1362cc57aebdc6cb93e3cf307d87d403bd5714 | 3,601,625 |
def get_imts_periods(imtls):
"""
Returns a list of IMT strings and a list of periods. There is an element
for each IMT of type Spectral Acceleration, including PGA which is
considered an alias for SA(0.0). The lists are sorted by period.
:param imtls: a set of intensity measure type strings
:re... | 5e0f9f5a3a3d416af04ac3f3f76c3d0bd793b495 | 3,601,626 |
def truedicts(all):
"""
Generates a pair of dictionairies containg all true tail and head completions.
:param all: A list of 3-tuples containing all known true triples
:return:
"""
heads, tails = {(p, o) : [] for _, p, o in all}, {(s, p) : [] for s, p, _ in all}
for s, p, o in all:
... | 03c126ff6cdc0cc14be1c64a91e8164e890c2f2d | 3,601,627 |
import math
def RotateXY(x, y, xc=0, yc=0, angle=0, units="DEGREES"):
"""Rotate an xy cooordinate about a specified origin
x,y xy coordinates
xc,yc center of rotation
angle angle
units "DEGREES" (default) or "RADIANS"
"""
x = x - xc
y = y - yc
# make angle clockwise (l... | 68d24bfd5b2cf436b1ea37c0d4124f6cfa357e9f | 3,601,628 |
def vectorize_tokens(tokens):
"""
Turns a file into a vector of indices (not a one-hot vector per token!).
Automatically inserts start and end tokens.
>>> from corpus import Token
>>> vectorize_tokens([Token(value='var', type='Keyword', loc=None)])
(0, 86, 99)
"""
def generate():
... | 9f310c5038fff925f63cd80e833d51964506c7a0 | 3,601,630 |
def _extract_gpcrdb_residue_html(txt):
"""
Extracts the relevant lines for all residues from a GPCRdb html entry.
Parameters
----------
txt : str
Content (html) of the website with the GPCRdb entry.
Returns
-------
residue_html : list
A list in which... | 4621848f27b9cd24017ed5c49683bfc4b8a180e8 | 3,601,631 |
def _vrsqrt_newton(num_to_vrsqrt):
"""Calculate vrsqrt(num_to_vrsqrt) with newton's method."""
start_value = topi.rsqrt(num_to_vrsqrt)
# use newton's method 3 times
newton_res_1 = _newton(start_value, num_to_vrsqrt)
newton_res_2 = _newton(newton_res_1, num_to_vrsqrt)
newton_res_3 = _newton(new... | ebd24e70b62058095c03cfaec1a61270e3b04868 | 3,601,632 |
def _random_customer(cust_dtls) -> tuple:
"""Return a random account number made of 12 characters."""
return choices(cust_dtls)[0] | 0e2732b9357ae5bae248a41d877ce2b12c3228f9 | 3,601,633 |
def getpassword(path):
"""Get password from an encoded file.
Input:
path -- source path.
Output:
passwd -- password.
"""
# Prepare cipher abs path
cipher_abs_path = get_abs_path(path)
# Read cipher
if exists(cipher_abs_path) and isfile(cipher_abs_path):
with ope... | 075fc6f01a7de23c51dbbfa109e10a2935e0fd35 | 3,601,635 |
def is_type_int16(*args):
"""
is_type_int16(t) -> bool
Does the type specify a 16-bit value? (signed or unsigned, see 'Basic
type: integer' )
@param t (C++: type_t)
"""
return _ida_typeinf.is_type_int16(*args) | 37b1ae865d31f3c362128975cef19d973bf325fb | 3,601,636 |
from typing import List
def convert_verse_ids_to_references(verse_ids: List[int]) -> List[NormalizedReference]:
"""
:param verse_ids:
:return: a list of normalized references
"""
references: List[NormalizedReference] = []
if verse_ids is None or not verse_ids:
return references
... | 6c1f33433d14af58be8adeeb39b1a19e81464ba6 | 3,601,637 |
import logging
import json
import time
def collect(type, **kwargs):
"""Collect result of a task of the given type."""
task_id = str(generate_uuid())
# Check if the task is in the local cache.
cache = load_cache()
if task_id in cache:
logging.info("Cached result found for {}".format(task_i... | 366b7fbb5d6623736b3eb2d968aae689ac25375b | 3,601,638 |
def reset_entry_registry(fn):
"""Decorator for tests using entry node registry
"""
def wrapper(*a, **kw):
root = get_root()
factories = set(root.factories.keys())
try:
fn(*a, **kw)
finally:
for key in set(root.factories.keys()).difference(factories):
... | 292bab2cd92f4b5eb67e1d3ed151f876f63a2bca | 3,601,639 |
def logsumexp(arr, axis=None):
"""Computes the sum of arr assuming arr is in the log domain.
Returns log(sum(exp(arr))) while minimizing the possibility of
over/underflow.
Examples
--------
>>> import numpy as np
>>> a = np.arange(10)
>>> np.log(np.sum(np.exp(a)))
9.45862974442671... | f32c7c7a295b548913057f8e78e77a934d290e03 | 3,601,640 |
def bezier2_h(t, hs):
""" evaluate quadratic bezier curve at t and project result """
x = bezier2(t, hs)
return la.proj(x) | a633e153e33850e45c2522824ca4ac00e961d816 | 3,601,641 |
import hashlib
def first_half():
"""
first half solver:
find MD5 hashes which, in hexadecimal, start with at least five zeroes.
iwrupvqb followed by a number in decimal.
To mine AdventCoins, you must find Santa the lowest positive number that produces such a hash.
"""
n = 1
while n:
... | 6c84da1dabd442cc1b28db4e09e1c67fb998a302 | 3,601,642 |
import math
def init_cv(dataset, fold=0, folds=8, validation=5, shuffle=False, seed=None):
"""
Initialize Cross-Validation
returns three indexes
"""
n_samples = len(dataset)
whole_range = np.arange(n_samples)
if shuffle:
_state = None
if seed is not None:
_s... | d9e5ddb8dfe6c52e71a328a4b983034121e30057 | 3,601,643 |
def seq2set(xs) :
"""
bijection from sequences to sets
"""
rs=[]
s = -1
for x in xs:
sx=x+1
s+=sx
rs.append(s)
return rs | b90ec731ce35539240c43d4c616889f71ca7c982 | 3,601,644 |
def strike_slip_from_rake_mag(rake, slip_mag = 1., input='degrees'):
"""
Calculates the strike slip magnitude from slip rake and magnitude.
Positive values indicate right-lateral slip. Rake is in Aki and Richards
convention (0 = right-lateral, 90 = reverse, 180/-180 = left-lateral,
-90 = normal).
... | 3ca70027dbfd7ce4df79587e2613b8dc0e087798 | 3,601,645 |
def calc_residual(coeff, pcs_arr, light_curve_flux, light_curve_err, map_dates_to_arr_index):
"""
function to calculate residual of the fit
Parameters
----------
coeff: np.array of shape [num_of_pcs]
current value of coefficients
pcs_arr: np.array of shape [num_pcs, num_prediction_point... | 2f7352a1eeffafe55f1cc85ec9e810e52fa7118c | 3,601,646 |
def preprocess_example(image, labels):
"""Map functions applied to image classification exampels / batches."""
image = tf.cast(image, tf.float32) / 255
return image, labels | b00545df670e7ba3869245fb8ed228e91b9f8e60 | 3,601,647 |
def simple_tag_without_context_parameter(arg):
"""Expected simple_tag_without_context_parameter __doc__"""
return "Expected result" | aad64452d051a587447696c6bd616b04f3f5b23e | 3,601,648 |
import random
import string
def create_ref_code():
"""Generate a random reference code."""
return "".join(random.choices(string.ascii_lowercase + string.digits, k=10)) | 9b09449a8a10e98fc91aa9a6e6773e30d4aa8caf | 3,601,649 |
def removeDuplicates(arr, indices):
""" Takes an arr and a sorted list of indices.
Removes arr[i] for i in indices and returns a new array.
if arr is 2D, removes the i^{th} row for i in indices.
:params arr: np.array. e.g., a timeline
:params indices: sorted list of indices to remove.
:returns ... | 16984e28a858a0a9f896628a9740906e57a8b482 | 3,601,650 |
def view_election_compound_party_strengths_chart(self, request):
"""" View the party strengths as grouped bar chart. """
@request.after
def add_last_modified(response):
add_last_modified_header(response, self.last_modified)
return {
'model': self,
'layout': DefaultLayout(self,... | 33df0ec1f8ef07f23ccadf943940c2a536984dfc | 3,601,651 |
def _validate_task_type_and_task_id(cluster_spec, task_env, chief_task_type):
"""Validates the task type and index in `task_env` according to cluster."""
if chief_task_type not in cluster_spec.jobs:
raise ValueError(
'If "cluster" is set in TF_CONFIG, it must have one "%s" node.' %
chief_task_ty... | 7d46e24dd06f17e2f42de54e107c4246635da7d6 | 3,601,652 |
from typing import Type
def make_hardware_module(
decoy: Decoy, type: Type[HardwareModuleT], serial_number: str
) -> HardwareModuleT:
"""Return a mock hardware module with the specified type and serial number.
Ideally, we wouldn't use mocks for this, since our subject uses these objects
as pure input... | 262bd44af3898f7e53166067a0100fe9b21a4bad | 3,601,653 |
def readGeneralData(filename):
"""Reads simulation data (includes printing data) from a given file."""
pfile = open(filename,'r')
# Read numerical scheme
scheme = lire_ligne(pfile).split()
scheme = int(scheme[0])
# Read space discretisation information
dx,xmax = lire_ligne(pfi... | 8f9eeba56dfba6438cdb68623636d432cbb5964c | 3,601,654 |
from typing import Tuple
def default_artifact_processor(artifact: riberry.model.job.JobExecutionArtifact) -> Tuple[str, dict]:
""" Returns basic information for generated artifacts """
return artifact.filename, {
'name': artifact.name,
'type': artifact.type.value,
'category': artifact... | 2ace58d7b9e52d192d9a47e395f527e5edac6b87 | 3,601,656 |
def list_datasets_view(user_data, cache):
"""List all datasets in project."""
return DatasetsListCtrl(cache, user_data, dict(request.args)).to_response() | 884c710d606edc311aa68298b2874f9b8a9b33b1 | 3,601,657 |
import re
def uuid(value: str):
"""
Validator for Universally unique identifier
Example Result:
[123e4567-e89b-12d3-a456-426655440000,
6a2f41a3-c54c-fce8-32d2-0324e1c32e22]
Detail: https://en.wikipedia.org/wiki/Universally_unique_identifier#Format
"""
_uuid_pat = r'[0-9a-fA-F]{... | 66f498669b52df2e3ff9ea281fb781cb6774c77c | 3,601,658 |
def openMultiple(parent=None, title='Open', directory='', filename='',
wildcard='All Files (*.*)|*.*',
style=wx.OPEN | wx.MULTIPLE):
"""File dialog wrapper function."""
return fileDialog(parent, title, directory, filename, wildcard, style) | ffbbe6a185b61127fab8222cb426bb84ee85ad8b | 3,601,660 |
def search_customer(request):
"""
:param request:
:return:
"""
t = loader.get_template('NearBeach/search/search_customers.html')
# Get the first 50 customers
customer_results = customer.objects.filter(
is_deleted=False,
).order_by('customer_last_name','customer_first_name')[:50]... | 7fe06a13d20b734286c92e2b3813755da30c8528 | 3,601,661 |
def merge_rows(df_arr: list,start: int,end: int):
""" 同一日時のデータをマージする関数
設定では温度取りローデータのディレクトリ内には複数のデータに分割されてファイルが配置されている
同じ日時のデータに合わせるために指定した範囲でデータをまとめる作業を行う
デフォルトでは4ファイルごと
Args:
df_arr [list] : 1ファイルごとのDataFrameが入ったリスト
start [int] : 開始時の添字
end [int] : 終了時の添字... | 0e80390db888809478a480eeb862960df0d987fc | 3,601,662 |
import requests
import json
def _update_latest_version(server, key, bundle, data):
"""Update latest version for the specified bot"""
j = json.dumps(data)
http_headers = {'API_KEY': key, 'Content-Type': 'application/json'}
r = requests.put(server + '/cloud/developer/versions?bundle=' + bundle, headers=... | c7be988910c07114b58bbf589af57b7cd2879989 | 3,601,663 |
def reset_command_registry():
"""Create empty global command registry"""
global _command_registry
_command_registry = CommandRegistry()
return _command_registry | f581b2c67a7396bb36f3c9f955190a9f89d3085d | 3,601,664 |
def compute_AT(ic) -> float:
"""
Args:
ic (IC): indepentent component.
Returns:
float: Alpha Topography - Difference between weights in frontal-central sites and other sites
"""
return np.abs(ic.select_weights(FC).mean()) - np.abs(ic.select_weights(FC_not).mean()) | 2dbcd23376956330168464acf2ad9ab95db7d70e | 3,601,666 |
def build_inpainter(input_shape=(None, None, 4), downsample=1, instance_norm=False):
"""
Build the full inpainting network
:downsample: reduce number of kernels by this factor
"""
with tf.name_scope("downsampler"):
downsampler = InpainterDownsampler(input_shape, downsample=downsample,
... | d49d38120459546ad6eed2b9b1c5bc39e36b26a3 | 3,601,667 |
def get_cooldown(member: discord.Member, cmd: Command):
""" Returns the member's time left as a str or None.
"""
if member not in cooldown_data:
return None
for cooldown in cooldown_data[member]:
if cooldown.command == cmd or cooldown.command is None:
diff = cooldown.date - ... | 734b97f71fda03051908bd154fbd6d2bc710d46c | 3,601,668 |
import uuid
from datetime import datetime
def formatCloudEvent(message: str, subject: str) -> str:
"""
Returns a correctly formatted CloudEvents compliant event
"""
attributes = {
"specversion" : "1.0",
"type" : "org.tmforum.for.type.event.an.invented.burton.brian",
"source" : ... | 128d7791e6d4225f62764d382b6934b9e03f49a4 | 3,601,669 |
from pathlib import Path
async def validate_item_id(
item_id: int = Path(...),
db_session: Session = Depends(get_db_session)
) -> Item:
"""Validates the if an item is present with the given id.
Args:
item_id: int. The id of the item.
db_session: Session. The database session u... | c27801b445b56ccfc16f0138bf88bdc68d819485 | 3,601,670 |
import json
def status(if_statuses):
"""Status
Arguments:
if_statuses {list} -- List of interface statuses
Returns:
str -- Pretty printed output
"""
status = HEADER
status_template = "{0:<9} {1:<4}\n"
if if_statuses is None:
return status
if_statuses ... | bae6ec2283fb598880281c03def375a36518fc98 | 3,601,671 |
def decode(code):
"""Decode morse code to char """
return CODE2CHAR[code] | 8f16ef0269183656ae00090dc6d36d2533f874f2 | 3,601,672 |
def standard_plot(dic_of_hists,normalise,xaxis_label):
"""
standard_plot() displays the (normalised or unnormalised) histograms
"""
hep.style.use(HEP_histogram_design_parameters["experiment"])
fig,ax = plt.subplots()
fig.set_size_inches(6,6)
HEP_histogram_design_parameters["HEP experimen... | c0a69d519632d9fca1c6037c458cde7889fc7914 | 3,601,673 |
def information(stock):
"""gets current information about a certain stock
:param stock: stock that will be analyzed
:return stock information"""
stock = yf.Ticker(str(stock))
return stock.info | 756c0a7cbaad19610b41c79f8e921ba27400aeb2 | 3,601,675 |
def _DoWeHaveLocalCommits(stable_branch, tracking_branch, cwd):
"""Returns true if there are local commits."""
output = git.RunGit(
cwd, ['rev-parse', stable_branch, tracking_branch]).output.split()
return output[0] != output[1] | 8c5626ea4c73227966ff713cc1747c64ea2daa30 | 3,601,676 |
def LikelihoodRedshiftMeasures( measures=[], datas=[], scenario=False, prior=True, renormalize=False, measurable=False ):
"""
returns likelihood functions of redshift for observed datas of measures,
can be used to obtain estimate and deviation
Parameters
----------
measure : string
in... | 836bd2d07f366d5aa6606bb63ec519a552ad72d5 | 3,601,677 |
def generate_mnemonic(strength=256, wordlist=wordlist):
"""Generate random mnemonic
Args:
strength (int, optional): The number of bits of the generated key. Defaults to 256.
wordlist (list[str], optional): The Word list used to generate the mnemonic. Defaults to wordlist.
Returns:
... | 75afeed28588ee1c545f59fc7b1393305d99653f | 3,601,678 |
def configuration(request):
"""Set up a Configurator instance.
This Configurator instance sets up a pointer to the location of the
database.
It also includes the models from your app's model package.
Finally it tears everything down, including the in-memory SQLite database.
This configurat... | d88a25ae0afeaa78e8ac4bb18734164877c6a21b | 3,601,679 |
def read_dictionary():
"""
This function reads file "dictionary.txt" stored in FILE
and appends words in each line into a Python list
"""
global dict_lst
with open(FILE, 'r') as f:
for line in f:
line = line.strip()
dict_lst.append(line)
return dict_lst | dcc71077146f713cf5a364319dbcad9de6d73353 | 3,601,680 |
def O2_molar2umkg(oxygen_conc=None, salinity=None, temperature=None, pressure=None):
"""unit conversalinity=Noneion for micromole/liter -> micromole/kg"""
sigmatheta_pri = sw.eos80.pden(salinity, temperature, pressure)
density = sigmatheta_pri / 1000
oxygen_conc = oxygen_conc / density
return oxyg... | 3bf2eaa4bdd1261d83ed41a88a2ef4933ce28f28 | 3,601,681 |
def find_coords(image, fourier_center, fourier_y, fourier_x, y_axis, x_axis):
"""
Convert the fourier positions to image axes.
Do not use numba to accelerate as LLVM IR
throws an error from the the if statements
Parameters
----------
image: ndarray
Original image
four_c: nd... | 73ee22179acf87da6f0986dddf3375c3bbb52176 | 3,601,682 |
def _extract_feats(data_test, model, what, skip=1, batch_size=16):
"""
:param data_test: test Dataset
:param model: network model
:param what: SK or IM
:param skip: skip a certain number of image/sketches to reduce computation
:return: a two-element list [extracted_features, extracted_labels]
... | 27f19d26396c778626f3792080cd34df5e7ca343 | 3,601,683 |
from typing import Tuple
from typing import Dict
def field_annotations(typed_dict) -> Tuple[Dict[str, type], Dict[str, type]]:
"""Return the required and optional fields in the TypedDict."""
return (typed_dict.__annotations__["required_fields"].__annotations__,
typed_dict.__annotations__["optional... | 2e88481a1668cd40caacb8bfc91a50c8746a704e | 3,601,684 |
def _SetDiskSize(build_config, messages, arg_disk_size):
"""Set the disk size used to run the build."""
if arg_disk_size is not None:
disk_size = compute_utils.BytesToGb(arg_disk_size)
if not build_config.options:
build_config.options = messages.BuildOptions()
build_config.options.diskSizeGb = int... | 802d361800e9690f5edbd4214e46a264958f78a5 | 3,601,685 |
def frobenious_norm_squared(X):
"""Calculate :math:`||X||_{F}^{2}`"""
return np.power(X, 2).sum() | 8a28d4ba9281a6fc2fbd2c0a14fb9b4939e93aba | 3,601,686 |
def read_record(fd):
"""Read a Record from a file handle.
:returns: A Record from the file
:rtype: BlipRecord
"""
header = fd.read(BlipRecord.converter.size)
try:
magic, exchange, length, payload_type = BlipRecord.converter.unpack(header)
except struct_error:
raise IncorrectLengthEx... | 1c7308c7acda6a52513728524d7935c51cba4487 | 3,601,687 |
def _clip_grad_norms(gradients_to_variables, max_norm=10):
"""Clips the gradients by the given value.
Args:
gradients_to_variables: A list of gradient to variable pairs (tuples).
max_norm: the maximum norm value.
Returns:
A list of clipped gradient to variable pairs.
"""
grads_and_vars = [... | 6ed880bffc279c409cdf5c9fb615431eb24b7618 | 3,601,688 |
from typing import Optional
def connection(conn: Optional["AbstractConnection"]) -> str:
"""
Formats connection to a string logged in stats
:param conn: Connection
:return: formatted string
"""
if conn is None:
return "<None>"
return conn.format_connection_desc | 41b5a75e12ab692c72ef14de424c9043dce99f1f | 3,601,691 |
def orthogonal_initializer(shape, gain=1., seed=None):
"""Initializer that generates a random orthogonal matrix.
# Arguments
gain: Multiplicative factor to apply to the orthogonal matrix.
seed: A Python integer. Used to seed the random generator.
# References
Saxe et al., http://... | 2599e898e085d1c387bc43066700543919312b33 | 3,601,693 |
from tpDcc.dccs.maya.core import gui
def get_camera_sequencer_panel():
"""
Returns Maya Camera Sequencer Panel as a QtWidget
:return: QtWidget or None
"""
open_camera_sequencer_window()
sequencer = maya.cmds.getPanel(scriptType='sequenceEditorPanel')[0]
qt_obj = gui.to_qt_object(sequencer)... | d58dd69535b8bd5bb95de398abb3754c832f708f | 3,601,694 |
def load_data():
""" Return the MNIST data as a tuple containing the training data,
the validation data, and the test data."""
f = open('../data/mnist.pkl', 'rb')
training_set, validation_set, test_set = cPickle.load(f)
f.close()
return (training_set, validation_set, test_set) | 31f7f336ab32937f6f5b52d6e59cefda60a4e8a3 | 3,601,696 |
def importmod(modname):
"""Import module according to policy and check API version"""
try:
verpkg, purepkg = _packageprefs[policy]
except KeyError:
raise ImportError('invalid HGMODULEPOLICY %r' % policy)
assert verpkg or purepkg
if verpkg:
pn, mn = _modredirects.get((verpkg, ... | 2eeb095b5bc25467eaf4195bf8404c146ad59994 | 3,601,697 |
import json
async def gadmin():
"""
:return : 分群管理json对象
"""
async with aiofiles.open(config_group, mode='r') as f:
admins_ = await f.read()
admins = json.loads(admins_)
return admins | 0203a208e8e83f5eb866d2288ab4a7a21e70881f | 3,601,698 |
import sqlite3
def get_member_data(member_id: str, conn: sqlite3.Connection) -> dict:
"""
Gets email and phone data from database based on passed member.
This function uses placeholders in query so it is injection safe.
Look up get_member_data_injection for example where it's NOT injection safe.
"... | a4ca505961352e292109e22318ff7a0188ffc454 | 3,601,699 |
def _from_deflection_angle(M_1, theta, weak, gamma):
"""Returns oblique shock given upstream Mach number and deflection angle.
"""
def eq(beta, M_1, theta, gamma):
os = _ShockClass(M_1, beta, gamma)
return os.theta - theta
theta_max, beta_theta_max = max_deflection(M_1)
if theta > ... | 89f1507124ce48f2c5d69f93cb71540a62a4d4a2 | 3,601,700 |
def make_crash_rollup(crashes_json):
"""
Generates a GeoDataframe with the total number of crashes and a comma-separated string
of crash dates per unique lat/lng pair
Inputs:
- a json of standardized crash data
Output:
- a GeoDataframe with the following columns:
- tota... | 5b1a5a79313900d0793e265e43e6170ab87f31bb | 3,601,701 |
import platform
import socket
def parseargs(p):
"""
Add arguments and `func` to `p`.
:param p: ArgumentParser
:return: ArgumentParser
"""
p.set_defaults(func=func)
p.description = "A simple sendmail implementation"
p.add_argument('recipient', nargs='*')
p.add_argument(
"-... | 5158665e1a8692d22d7fd59384ac1e946e83eaeb | 3,601,702 |
from pytest_selenium.safety import sensitive_url as orig_sensitive_url
def sensitive_url(request, base_url):
"""Override original fixture to change scope to module (we can have different base_urls for each module)"""
return orig_sensitive_url(request, base_url) | 339899ab2b12a2eea38abbc683de19ecf3468fc5 | 3,601,703 |
import requests
def stac_bands(url=None, collection=None, item=None, titiler_endpoint=None, **kwargs):
"""Get band names of a single SpatialTemporal Asset Catalog (STAC) item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spo... | a1b6f2d2c5e57c3d99df1ca02247c6ca8320c19f | 3,601,704 |
def sublists_from_list(input_list, chunk_size):
"""
Given a list, chunks it into sizes specified and returns the chunks as items
in a new list
Parameters
----------
input_list: list
Original list
chunk_size: int
Size of sublists
Returns
-------
sub_lists: list
... | 376780702af1ef3fd780f3964ad2cd6094135143 | 3,601,705 |
def node_short_name(node, **kwargs):
"""
Returns short name of the given node
:param node: str
:return: str
"""
return node | 67d1d5ff172544eb2b233a925d90bbd0ea767e83 | 3,601,706 |
def insertAsks(previous_asks, received_asks):
""" Inserts multiple new asks in the order book (assumes
that the order book AND the new_asks list are sorted)"""
new_asks = []
if len(received_asks) < 1:
return previous_asks
if len(previous_asks) < 1:
return received_asks
# print("Prev")
# ppri... | a984eafb8f93901752ac581ac5a207610e5cdbf6 | 3,601,708 |
def identity_loss(_, y_pred):
"""
:param _:
:param y_pred:
:return:
"""
return tf.math.reduce_mean(y_pred) | b9d6eb28a435a0f8dcb55fa13aa470cc9cb23d57 | 3,601,709 |
import itertools
def minimum_bounding_n(alfa: float) -> int:
"""Подбор минимального ограничивающего n для заданного уровня значимости.
Параметр n в формуле доверительных интервалов при последовательном тестировании отвечает за момент
начала тестов. Однако для малых n интервалы имеют ширину больше 0.5, то... | bb532ad50f0187b9884ad365b7c7e772e8a589ba | 3,601,710 |
def create_notify_payload(host, nt, usn, location=None, al=None, max_age=None, extra_fields=None):
"""
Create a NOTIFY packet using the given parameters.
Returns a bytes object containing a valid NOTIFY request.
The NOTIFY request is different between IETF SSDP and UPnP SSDP.
In IETF, the 'location... | 95b6a7ad37ec96d646116451340ed7ee96495632 | 3,601,711 |
from typing import Callable
from typing import Any
def flag(decorator: Callable):
"""Makes another decorator a flag.
`flag` is a high level decorator that should be
applied on decorators:
@flag
def enabled(): ...
Here the `enabled` decorator can be considered as a flag,
so when a... | 00481ca15e1c783437c712ac1b6034ac3630e0b9 | 3,601,712 |
import math
def runs(bit_str: str):
"""Runs Test
Determine whether the number of runs of ones and zeros of various
lengths is as expected for a random sequence.
See section 2.3 in this NIST publication:
https://tsapps.nist.gov/publication/get_pdf.cfm?pub_id=906762
"""
n = len(bit_str)
... | fce124ccf0b3da512c72ae866aca70572a768692 | 3,601,713 |
def alert_source_update(context, storage_id, values):
"""Update an alert source."""
return IMPL.alert_source_update(context, storage_id, values) | 4b76cf72f32c5bb2469f5bd41c8392a2af46e00e | 3,601,714 |
def plot_histograms(df, target = None, columns = None, rows = None, cols = None, width = None, height = None,
title = None, cumulative = None, barmode = "stack", opacity = 0.65, bins = 0,
hovermode = "x unified", template = None, colors = 0, font = {}, title_font = {}, legend_font = {}):
"""
plot_histog... | ddbe7de5e072dc482a2d390e68dffaa88e149032 | 3,601,716 |
def read_pfile(pfile_loc):
"""
Read in the kinetic profiles from a p file to be used as inputs (successfully tested 2018/1/3)
Returns a dictionary with a non-intuitive set of keys (units are included)
** Note: pfiles don't go into the SOL **
"""
with open(pfile_loc, mode='r') as pfile:
... | f43668a99648625ae9e3095e2fcd17e5d4077cff | 3,601,717 |
def acc1(true_value, estimate_value, tolerance=0.04):
"""
Accuracy 1.
:param true_value: reference value (must not be zero)
:param estimate_value: estimated value
:param tolerance: tolerance
:return: true or false
"""
return same_tempo(true_value, estimate_value, factor=1.0, toler... | 754111efee53beae2b069040b85ef5965f17a2f2 | 3,601,719 |
def newer(source, target):
"""
distutils.dep_utils.newer with zipfile support
"""
try:
return zipio.getmtime(source) > zipio.getmtime(target)
except IOError:
return True | 73373c191d7b51257c9d5b889a1fb4ee0e3582dd | 3,601,720 |
def config_get(section, option):
"""
Return the string value for a given option in a section
:param section: the named section.
:param option: the named option.
.
:returns: the configuration value.
"""
return __CONFIG.get(section, option) | 6856d3e17f44d5a60469204ed772798be151f6b0 | 3,601,722 |
def clear_data(table, where):
"""
Remove all rows from the table matching the expression in the where clause,
returning a count of deleted records.
:param table: name of table to search
:param where: where clause to find records to delete
:return: count of deleted rows
:rtype int
"""
... | d365942d2e9c6eb686d5327f80386e148d050569 | 3,601,724 |
def solve_sudoku(sudoku: np.matrix):
"""Solve the input sudoku puzzle recursively by guessing a number and then trying to solve the remaining puzzle.
N.B.: To avoid copying data each time a new recursion level is entered, the input sudoku is solved in-place.
"""
for y, x in product(range(9), range(9)):... | 08a8a8227302c9468ddcd23b0d0c0fbb9f68526a | 3,601,725 |
import pathlib
import pickle
def positional_data(experiment, dimensions='2d', pattern='pose_result', base_path=None,
experiment_path_template=None, positional_data_path_template=None, return_experiment_id=False):
"""
Returns the positional data for the given experiment.
Parameters:
... | c587d5da797e307295a1f7289863f30aa28b6cd6 | 3,601,726 |
def conv_relu_forward(x, w, b, conv_param):
"""
A convenience layer that performs a convolution followed by a ReLU.
Inputs:
- x: Input to the convolutional layer
- w, b, conv_param: Weights and parameters for the convolutional layer
Returns a tuple of:
- out: Output from the ReLU
- cache... | eeb9a3ef903176893892ba484da48cd35a79358b | 3,601,727 |
import numbers
import math
import cmath
def atan(x):
"""
Uncertain number arctangent function
.. note::
In the complex case there are two branch cuts:
One extends from :math:`\mathrm{j}` along the imaginary axis to
:math:`\mathrm{j}\infty`, continuous from the right.
... | 470af67f67a6c5c1aa63fb28b5590c4f699c988c | 3,601,728 |
from typing import Callable
from re import T
def is_owner() -> Callable[[T], T]:
"""A :func:`.check` that checks if the person invoking this command is the
owner of the bot.
This is powered by :meth:`.Bot.is_owner`.
This check raises a special exception, :exc:`.ApplicationNotOwner` that is derived
... | 25e59ed874931024cd43738033998b9220cb1344 | 3,601,730 |
def create_hash_chain(*args: tuple[str, str, int]) -> HashChainNode:
"""Create a HashChainNode based on the args"""
head = None
curr = None
for sender, recipient, amount in args:
if head is None:
node = HashChainNode(Transaction(
sender, recipient, amount), is_head=Tr... | f2f201b8ecbcf381fc217c84be1409187e246cc9 | 3,601,732 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.