content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import tqdm
import torch
def train_model_sepQA_v2(net, trainloader, validloader, epochs, lr, grad_accum_steps=1, warmup_epoch=1, milestones=[5, 10], gamma=0.2, pair_w=None, l2=0.0):
"""
pair
"""
net = net.cuda()
if pair_w is None:
PAIR_WEIHGT = 1.0
else:
PAIR_WEIHGT = pair_w
... | 04c0f43810a33a7847cc7c3f16202a3b543a5f9c | 68,413 |
def region_of_content_of_headline_at_point(view, from_point):
"""Extract the region of the content of under current headline."""
_, level = headline_and_level_at_point(view, from_point)
if level == None:
return None
if is_content_empty_at_point(view, from_point):
return None
line_n... | d3c3cdd69313f02621021035acffb1c8764aeec0 | 68,414 |
import numpy
def summary_bed(args):
"""Filter bed file on percentage of sites being called and context"""
bed_in_handle = open(args.bed,'r')
bed_out_handle = open(args.bedout,'w')
header = bed_in_handle.readline().split('\t')
group_info, header_out = parse_sample_inf(args)
bed_out_handle.write... | 04505c02c670a8198b88a5f9890c257ccf05af2d | 68,415 |
def floatdiff(x, y):
""" Return the (broadcasted) order difference from x to y.
Inputs x and y must be both float32 or both float64.
"""
x = asanyarray(x)
y = asanyarray(y)
if x.dtype is not y.dtype:
raise TypeError("%s is not %s" % (x.dtype, y.dtype))
if x.dtype.type is float... | 94c8b83dbb0b491140545bc195cf24090ab2c5f7 | 68,417 |
def asnr_activate(x, sr, wind, hop, nfft, noise=None, zphase=True,
noisesmooth=.98, llkthres=.15, rule='wiener', fn='classic'):
"""Implement a priori SNR Estimation in the view of nonlinear activation.
This implementation should be identital to asnr, except the estimation of
mu is interpr... | 0d5eff4837fb7b7fe5d6901859bccb7cd978d57b | 68,419 |
def update(table_name, rowid, values):
"""Updates a table with new field values.
Args:
table_name: name of table in database.
rowid: id of row to be updated.
values: dictionary of fields and values to be updated.
Returns:
Dictionary of newly updated table row.
"""
table_entry = {tabl... | c43877c4ec1d01b5a98bb36f10ded6965ff9e6f4 | 68,420 |
def f(z):
"""
vector form of sigmoid activation function
"""
return np.vectorize(sigmoid)(z) | 8ee1bfb8520e210095080e1424089155fde92d9f | 68,421 |
def can_t_attack(size, board):
"""Check that none of the queens can attack each others.
Args:
size (int): size of the board
board (array): 2 dimensional array containing the content of the board
Returns:
[boolean]: True, if none of them can attack
"""
if not isinstance(board, Bo... | 7a7566e85964ebe03c1b02e571289d54298abfdf | 68,422 |
def get_reader_versions(reader):
"""Return the available versions for a given reader."""
records = get_reader_output_records([reader])
return {record['version'] for record in records} | 802f3e27fbf44739e92c9266f9952891b52fd878 | 68,423 |
def launch_from_devices(devices, auto_exit=False):
"""Alternate entry point for non-cli testing of loader."""
app = get_qapp()
suite = TyphosSuite.from_devices(devices)
if auto_exit:
QTimer.singleShot(0, app.exit)
return launch_suite(suite) | a5425200e88dd1e78d3c4dac5f28851529594589 | 68,424 |
def playing():
"""Retrieve playback status."""
return status().playing | c8c25337b171cfa1eeb0dfc5573673309360a35e | 68,425 |
def shorten(s: str, max_len: int = 60) -> str:
"""Truncate a long string, appending '...' if a change is made."""
if len(s) < max_len:
return s
return s[:max_len-3] + '...' | 8bafe69253e12a67fdb4c476a2d4b55f6ad4d2af | 68,426 |
import json
def elasticsearch_bulk_decorate(bulk_index, bulk_type, msg):
""" Decorates the msg with elasticsearch bulk format and adds index and message type"""
command = json.dumps({'index': {'_index': bulk_index, '_type': bulk_type}})
return '{0}\n{1}\n'.format(command, msg) | e215ab15b347046b22dcc46317632c68fa9d36c0 | 68,427 |
def bbh_final_spin_average_non_precessing(
*args, fits=FINALSPIN_FITS, return_fits_used=False
):
"""Return the final spin averaged across multiple non-precessing fits
Parameters
----------
mass_1: float/np.ndarray
float/array of masses for the primary object
mass_2: float/np.ndarray
... | 88f3371fe0fdcb825d7cb216374f59151718e076 | 68,428 |
from typing import Any
from typing import get_args
from typing import get_origin
from typing import Collection
from typing import Tuple
from typing import Literal
def get_dims(type_: Any) -> Dims:
"""Parse a type and return dims.
Example:
All of the following expressions will be ``True``::
... | 9ed40eda5d206190eace20c4c4502b553c3bd3a5 | 68,430 |
import random
from jinfo.sequence import DNASeq
def random_DNASeq(seq_length: int) -> DNASeq:
"""
Generate a random DNA sequence
Returns: random DNASeq of length seq_length
"""
dna_base_list = ["A", "T", "C", "G"]
seq_list = [random.choice(dna_base_list) for i in range(seq_length)]
retu... | d0a3c368837832ad6086388466799701b2e7735d | 68,433 |
def trans(input_seq,stop='*'):
"""
translate a string
this is fast, but note that it doesn't look for invalid characters - it will just translate a codon containing them as "X"
"""
#import string
codon_table['TAA'] = stop
codon_table['TGA'] = stop
codon_table['TAG'] = stop
codon_tabl... | 4461fa1b12521b10a7d66dc123f73f403c650bf6 | 68,434 |
import itertools
def get_hp_fold_iterator(hp_grid, num_folds):
""" Create an iterator over all combinations of hyperparameters and folds
"""
hp_grid = list(hp_grid)
folds = list(range(num_folds))
hp_fold_it = itertools.product(hp_grid, folds)
hp_fold_it = list(hp_fold_it)
return hp_f... | ea16c3b3867dc87a18f2dc1dc2f59e5a48f7c04d | 68,435 |
import re
def make_systematic_name(name):
"""
Something like AddAppealBaseBonusChangingHpRateMax ->
Add appeal base bonus changing hp rate max .
Word soup for most enumerated skill names but is a good starting point
"""
return " ".join(re.findall(r"([A-Z]+[a-z]*)", name)).capitalize() | 6bd2b1a78091476456b9e2d95a085032c19d28c4 | 68,436 |
def yp_processed_reviews(yelp_username):
"""
Raw form of reviews that contains ony status and reviews.
File Type: CSV
"""
return '../data/processed/{}.csv'.format(yelp_username) | d4be5addf2f8014ebb096493ce9e037b1c4550ac | 68,437 |
def sub_dir_algo(d):
""" build out the algorithm portion of the directory structure.
:param dict d: A dictionary holding BIDS terms for path-building
"""
return "_".join([
'-'.join(['tgt', d['tgt'], ]),
'-'.join(['algo', d['algo'], ]),
'-'.join(['shuf', d['shuf'], ]),
]) | 73d91f4f5517bbb6966109bd04f111df5f6302e4 | 68,438 |
def set_img_path(tgtcmd, new_img_path, cfg) -> (str, list):
""" Replace the image path with new_img_path in the program's command
and returns the path of the new output image.
str is empty if the match failed
@return Tuple with first element the new image path and second element the
n... | 80460d2823618f4ea708dd7871fc8e104b2190a2 | 68,439 |
def neq():
"""
Returns class instance of `Neq`.
For more details, please have a look at the implementations inside `Neq`.
Returns
-------
Neq :
Class instance implementing all 'neq' processes.
"""
return Neq() | 1979dc46d4ae59d53aa78cdfbdd5b2940498d352 | 68,441 |
def add_conditional_formatting(ws, column, low, high):
"""Adds conditional formatting to a column in a worksheet
Args:
ws (worksheet): Worksheet object for the Prompt Payment report
column (str): Name of the column to apply the conditional formatting to
low (int): The cutoff between gree... | c3539103f70d28707f32c0b7704a907c5e658c87 | 68,442 |
def _get_words(data_dir):
"""Get list of words from history file.
Parameters
----------
data_dir : pathlib.Path
Directory where data is saved.
Returns
-------
word_list : list of str
List of words.
"""
words_file = data_dir.joinpath("words.txt")
word_list = []
... | 40728b61ed4af05d26a8ece678661cddf838602a | 68,443 |
def list_zoo_datasets():
"""Returns the list of available datasets in the FiftyOne Dataset Zoo.
Returns:
a list of dataset names
"""
datasets = set()
all_datasets = _get_zoo_datasets()
for d in all_datasets.values():
datasets |= d.keys()
return sorted(datasets) | c5c471608275de783b0fc889e47f3aeb45157cbf | 68,444 |
def xception_41(inputs,
num_classes=None,
is_training=True,
global_pool=True,
keep_prob=0.5,
output_stride=None,
regularize_depthwise=False,
multi_grid=None,
reuse=None,
scope=... | 98267bad4dcbcaa11c4013379af75dccc15b42e8 | 68,446 |
import requests
import json
def load_data():
"""
Get list of events from SloComps.
Returns:
list: List of telegram messages.
"""
# Download data.
login_url = 'https://comps.sffa.org/user/login'
request_utl = 'https://comps.sffa.org/calendar'
payload = {
'name': 'teleg... | fa69238a2684c52eb29ef6deda167061638b1d89 | 68,447 |
import copy
def annotate_paths(paths):
"""
Annotate a set of paths identifying peculiar types of paths.
- **shortest**: topological shortest paths
- **fastest**: paths that have minimal duration
- **foremost**: first paths that reach the destination
- **shortest fastest**:... | a91642bd10fd56e3ac0cad8318a98b68fa93ce35 | 68,448 |
def random_crop(images, labels, width, height, num_channels, percent):
"""Randomly crops images with a 20x20 bounding box and resize them to 28x28
Arguments:
images: Array of images with shape [batch_size,
width * height * num_channels]
labels: Array of labels with shape [batch_size... | 341b461d4e2755a3e58febe64e8148bb62c0bec9 | 68,450 |
import scipy
def algebraic_connectivity_directed(G):
"""
calculate algebraic connectivity a(G) and quantity b(G) of directed graph G,
where G is a networkx digraph with Laplacian matrix L
Reference: C. W. Wu, "Algebraic connecivity of directed graphs",
Linear and Multilinear Algebra, vol. 53, no.... | e2df19f36a382ea0b00b9e72b24262e93fc4844e | 68,451 |
def reduction(input_type, output_type):
"""Define a user-defined reduction function that takes N pandas Series
or scalar values as inputs and produces one row of output.
Parameters
----------
input_type : List[ibis.expr.datatypes.DataType]
A list of the types found in :mod:`~ibis.expr.datat... | 1a27ed0ad9004ef655794459abe08340cb5ae67b | 68,452 |
def splitMSOData(cmaxSamples, data):
"""
splitMSODataPort1(
c_int32 cmaxSamples
c_int16 array data
)
"""
# Makes an array for each digital channel
bufferBinaryD0 = np.chararray((cmaxSamples.value, 1))
bufferBin... | 4e114ada3681b1f3f3d0db89062353868bd96bc5 | 68,454 |
def _create_sphere(x0, y0, z0, radius):
"""
Creates a sphere of a given radius with a given center.
Parameters
----------
x0 : int
x-coordinate (index) of the sphere's center
y0 : int
y-coordinate (index) of the sphere's center
z0 : int
z-coordinate (index) of the sp... | c4479b6724b47e9d4c81950df5c0d9daa56d19f8 | 68,455 |
def containsAll(target, keys):
"""Returns true iff target contains all keys.
"""
result = ((i in target) for i in keys)
return all(result) | 75fda44a515e2249bd4c6ee1146c36eb91657b56 | 68,456 |
def GetReferenceAssemblies(parentNodes=None):
"""
Gets the names of USD reference assembly nodes in the scene.
If parentNodes is a Maya node name or a list of Maya node names, all
assemblies that match or are descendants of those nodes will be returned.
Otherwise, all assemblies in the scene will b... | f3c11e2961a735128482c9bd51a70b14271d3580 | 68,457 |
def idnencode(domain, encoding='utf-8', errors='strict'):
"""Encode International domain string."""
if not isinstance(domain, bytes):
return domain.encode('idna', errors).decode(encoding)
else:
return domain.decode(encoding, errors).encode('idna', errors) | 3adae031f14a4127b6d2a78f7575b1eb1b165274 | 68,458 |
def get_data(cfg):
"""Gets the Huffman codes table from the source, the current contents of the output file, the new version control string and tells you if the file is up to date
The function tries to do the least work possible.
If etag or date and file size are the same on the output and the source it will not re... | ed71f5a41a20a21998267e03dd98ab80e7c89234 | 68,459 |
def minimize(cost_function):
"""
Higher order function lifting the cost function into a objective function
returning a cipy.algorithms.core.Minimum.
Args:
cost_function (callable): The cost function to minimize.
Returns:
callable: Function accepting a solution and returning a
... | f786c774e1f3f6a420f083a732bf54bf82b2fa91 | 68,460 |
def dev_version():
"""Retrieve the dev version."""
return ver_from_file(DEV_VER_PATH) | 67bd0812fb658e15097b1b6497f4bf71c6c42ce6 | 68,462 |
def epochs_plot(epochs, legend=True, show=True):
"""
Plot epochs.
Parameters
----------
epochs : dict
A dict containing one DataFrame per event/trial. Usually obtained via `epochs_create()`.
legend : bool
Display the legend (the key of each epoch).
show : bool
If Tru... | a983bf54a8b8715c91b329e43d9425100e06bf44 | 68,463 |
def delete_quiz(request):
"""AJAX request accessible to teachers to delete quizzes"""
if(request.method == "POST" and request.user.is_teacher):
quiz = request.POST.get("quiz_pk")
try:
Quiz.objects.get(pk=int(quiz)).delete()
except:
raise Exception("unable to dele... | 53ea636469683a42a978243c4ce9dbdff3dddcce | 68,464 |
import asyncio
def send_custom_message(message, msg, dm=False, user=None, format_content=True):
"""send_custom_message
Sends a message with custom text.
:param message: MessageWrapper object with data for formatting.
:param msg: str() contents to send.
:param dm: [Optional] Whether the message sho... | 87416c00903d4deedd1efb42ff06b2ca8363c72d | 68,465 |
def balance_actions(X, y, drop_prob):
""" Balance samples. Gets hide of a share of the most common action (accelerate) """
# Condificação da ação acelerar
acceler = np.zeros(7)
acceler[1] = 1.
# Find out what samples are labeled as accelerate
is_accel = np.all(y==acceler, axis=1)
# Get the i... | a4d5b5bf58156e65001a34ab545b9cd2e46172e1 | 68,466 |
def pes_dictionary(mech_str, mech_type, spc_dct, printlog=True):
""" Calls mechanalyzer to do the dictionary
"""
return mechanalyzer.parser.pes.pes_dictionary(
mech_str, mech_type, spc_dct, printlog=printlog) | 73e8290ee265669ee6b8e28e72019a2527b3fba7 | 68,467 |
def cylindrical_bearing_example():
"""Create an example of a cylindrical bearing with termo hydrodynamic effects.
This function returns pressure and temperature field and dynamic coefficient.
The purpose is to make available a simple model so that a doctest can be written
using it.
Returns
-----... | 080f37c373ad3fc1a7361a1e6c35149eed1e31ea | 68,468 |
def validate_results(pred_df, labels, thres=0.2):
"""Compares predicted labels with actual labels
Args:
pred_df (df): all prediction probabilities
labels (series): labels
thres (float): minimum threshold to consider a sector present in the predictions
"""
out = pd.DataFrame(
... | 22c2bebd28fbba62bebad3cf2611d4086e1fa74a | 68,469 |
def _roitmpl2roiname(roitmpl):
"""
generate roiNames out of roitempl
written in an amazing function to easyly change pattern for roiNames
in all further function at once. This way keep the
featureAttributes (fa) consistent
"""
roiRname = 'Right'+roitmpl
roiLname = 'Left... | 4e2d198821f8e7cbca80722f41aed811dc0bd598 | 68,470 |
def s(feature, n_splines=20, spline_order=3, lam=0.6,
penalties='auto', constraints=None, dtype='numerical',
basis='ps', by=None, edge_knots=None, verbose=False):
"""
See Also
--------
SplineTerm : for developer details
"""
return SplineTerm(feature=feature, n_splines=n_splines, spl... | a9673a264ad0c989025fb56f89fe23eaad91d805 | 68,471 |
def _strip_external_workspace_prefix(path):
"""Either 'external/workspace_name/' or '../workspace_name/'."""
# Label.EXTERNAL_PATH_PREFIX is due to change from 'external' to '..' in Bazel 0.4.5.
# This code is for forwards and backwards compatibility.
# Remove the 'external/' check when Bazel 0.4.4 and... | 3fe846b5349f0859fa0bcaa9274a09a64687bc84 | 68,472 |
def abs_sobel_threshold(img, direction="x", thresh=(0, 255), ksize=3, bgr=False):
"""
Applies the Sobel operator in the given direction and return
a binary image after applying the threshold.
"""
gray = convert_to_gray(img, bgr)
s = None
if direction=="x":
s = cv2.Sobel(gray, cv2.C... | f0d10484787e88899fa1c1029d705279caa58f1f | 68,473 |
def convert2gray(img):
"""
图片转为灰度图,如果是3通道图则计算,单通道图则直接返回
:param img:
:return:
"""
if len(img.shape) > 2:
r, g, b = img[:, :, 0], img[:, :, 1], img[:, :, 2]
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
return gray
else:
return img | 42bde7f1c3ced85ea7e2e078063e63361e4d734a | 68,474 |
def decode_status_data(data):
"""
voltage, current in Amps and Power in Watts
data is expected in RAW bytes array converted to int
with no command and no checksum
"""
if len(data) !=7 :
print(f"Wrong bytes number in response: '{data}'")
return [[]]*3
voltage = bytes_to_in... | 80372d8289d94f03f687c08426951be72056a180 | 68,475 |
def stub_out_utils_spawn_n(stubs):
"""Stubs out spawn_n with a blocking version.
This aids testing async processes by blocking until they're done.
"""
def no_spawn(func, *args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
# NOTE(danms): This is ... | e8d920a690d6accd3e6defc63be2c49c4174dae8 | 68,476 |
from typing import Tuple
def _get_aws_uri_(obj: str) -> Tuple[str, str]:
"""
Lookup the URI for an AWS S3 object and the profile for accessing it.
Lookup the AWS S3 URI and the profile for accessing it. Returns the
values as a Tuple (aws_s3_uri, aws_profile)
"""
aws_bucket = get_setting("AWS... | 39f710c484d5fb680e69de9179807bb0bb84428c | 68,477 |
def get_camera_names(inputPath=None):
"""Read the names of the cameras.
Parameters
==========
infile : str
Full path of the input DL1 file.
fileName : str
Name of the input DL1 file.
Returns
=======
camera_names : list(str)
Table names as a list.
"""
if ... | 059007b38564024d9b6d2ae7a2ef061894547485 | 68,478 |
def after_request(response):
"""
Enables CORS to allow AJAX requests from the webpage
"""
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Headers",
"Content-Type,Authorization")
response.headers.add("Access-Control-All... | 672bbd6637c9a7193ff3e09f83f83a7189cc4120 | 68,479 |
import time
def return_timestamp():
"""
Gets and returns the current local time.
:return string timestamp: Current local time in format %Y-%m-%d %H:%M:%S %Z.
"""
timestamp = time.strftime('%Y-%m-%d %H:%M:%S %Z')
return timestamp | a01b6d29e82a8790191626d8e7b155e41b63cf20 | 68,480 |
def get_one_differing_var(vars1, vars2):
"""Checks to see if two sets of variables have one differing one??
"""
if len(vars1) != len(vars2):
return None
ans = None
for var in vars1:
if var in vars2:
if vars1[var] != vars2[var]:
if ans is None:
... | 64aeb8694331668133dc8ffcf97d32d0bf8ae58b | 68,481 |
def _path_to_module_format(py_path):
"""Transform a python file path to module format."""
return py_path.split("/")[-1].rstrip(".py") | 9cf3140edcdf202434da35b35fa219f861b1c20f | 68,483 |
def boolean(value: bool) -> bytes:
"""Encode a boolean value
:param value: Value to encode
:raises TypeError: when the value is not the correct type
"""
if not isinstance(value, bool):
raise TypeError('bool required, received {}'.format(type(value)))
return common.Struct.short_short.pa... | af8d936ab72b14eff30f3ad6bf191c0dc3ea1669 | 68,484 |
import csv
def read_csv_file(input_filepath):
"""
This function reads a .csv file and parses it into a list of dictionaries,
where each dictionary is formed from the data on one line of the .csv file.
This function takes one argument <input_filepath>, which is the path of the file
to be read. You ... | 7db24e902c5c8d9086881d3bb8e1fb18e06ccc0d | 68,485 |
def download(cm_response, **data):
"""
@clmview_user
@cm_request_transparent{iso_image.download()}
"""
return cm_response | ee62f8ed9d870ad720fc064f83d10c0de866d59b | 68,486 |
from typing import Collection
from typing import Mapping
def _get_val_id_from_collection(
val: Collection[object], # noqa: WPS110
) -> str | object:
"""Extract a suitible test ID string from a collection, if possible."""
if isinstance(val, Mapping):
# static analysis: ignore[undefined_attribute]
... | 6fcb2e1b6636decabc29f8508cfa75ac7c12367f | 68,487 |
def get_random_tree(nodes):
"""
Constructs a dictionary describing a random tree, with the name of the vertices are taken from the 'nodes'
:param nodes: list of str
Name of the nodes to be used
:return: dct
keys are the names of the nodes and values their neighbors
"""
tree = nx.... | cf7252d793c803538e8b4c2210772d5e669e56aa | 68,488 |
def get_bits_img(image, interval):
"""Returns only bits specified into the interval
Args:
image: image to convert using this interval of bits value to keep
interval: (begin, end) of bits values
Returns:
Numpy array with reduced values
Raises:
ValueError: If min value f... | 4bae26013cc811b1efcff0ec76ba599dbf72ec10 | 68,490 |
import requests
def _konfuzio_session(token: str = KONFUZIO_TOKEN):
"""
Create a session incl. base auth to the KONFUZIO_HOST.
:return: Request session.
"""
retry_strategy = Retry(
total=5,
status_forcelist=[429, 500, 502, 503, 504],
backoff_factor=2,
# allowed_met... | 62fd4068f2203a689c4ea652174a1da342c0c1ad | 68,491 |
def markley(k, r0, v0, tof):
"""Solves the kepler problem by a non-iterative method. Relative error is
around 1e-18, only limited by machine double-precision errors.
Parameters
----------
k : float
Standar Gravitational parameter.
r0 : numpy.ndarray
Initial position vector wrt a... | 620d35424640293ab18a65936f9b63e20c2c98e0 | 68,492 |
def disconnect_all_containers_from_network(network_id):
"""
.. versionadded:: 2018.3.0
Runs :py:func:`docker.disconnect_container_from_network
<salt.modules.dockermod.disconnect_container_from_network>` on all
containers connected to the specified network, and returns the names of all
container... | c9a9751fa9028b6414d4aefcd0adfa44e18ec223 | 68,493 |
from typing import List
from typing import Tuple
def _convert_filters_type(
filter: List[Tuple[str, SupportedFilterType]], schema: StateSchema
) -> List[Tuple[str, SupportedFilterType]]:
"""Convert the given filter's type to SupportedFilterType.
This method is necessary because click can only accept a si... | faa7b84b6d91d0878835631875c907152b2c326d | 68,494 |
def enumerate(collection):
""" Create a list of lists in which each element of the list is:
[index, element]. For example, if you parse a FeatureCollection with 3
Features you'll get: [[0, feat0], [1, feat1], [2, feat2]]
:param collection: can be an ImageCollection or a FeatureCollection
:return: ee... | aaddc6f53216f1474563d9161fb88e97f7e9fe0e | 68,495 |
import math
def scaled_rgb(mag, color_min, color_max):
""" Return a tuple of integers, as used in AWT/Java plots. """
try:
x = float(mag - color_min) / (color_max - color_min)
except ZeroDivisionError:
logger.exception("Scaled rgb tried to divide by 0")
x = 0.5 # color_max == colo... | 242aa4a4032e9198fb94f3201ba6ae863c00031b | 68,496 |
def get_DHT11_output():
"""
Gets the data from the DHT11 Temperature and Humidity Sensor.
:return: array where index zero is temp and index and index one is humidity.
"""
data = []
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
data.append(temperature)
data.append(humidity)
r... | ed174a09e3391d8fb15923c64abe1fd4ae397218 | 68,497 |
from typing import Union
def timezone(name: Union[str, int]) -> Union[Timezone, FixedTimezone]:
"""
Return a Timezone instance given its name.
"""
if isinstance(name, int):
return fixed_timezone(name)
if name.lower() == "utc":
return UTC
return Timezone(name) | 1cbc555a220ef4f02e002ed15cc5fa9be080b98c | 68,498 |
def get_sections(filepath):
"""Gets the sections from git config."""
reader = get_config_reader(filepath)
sections = {}
for sec_name in reader.sections():
sections[sec_name] = reader.items_all(sec_name)
return sections | 708ea648277b68dac8e27d4b799f8930d670eb2b | 68,499 |
def compare_runs(runs, value, board=None):
"""Compare a value between runs and return indication of better/worse.
:return: HTML symbol to indicate status.
"""
if "Previous" in runs:
if board:
last = runs["Last"]["Boards"][board][value]
if board in runs["Previous"]["Boar... | 3fdceb49e4b78050c0063851e4cf3dded1ab6293 | 68,503 |
def create_hparams(hparams_string=None, verbose=False):
"""Create model hyperparameters. Parse nondefault from given string."""
hparams = tf.contrib.training.HParams(
################################
# Experiment Parameters #
################################
epochs=300,
... | cc55ef7bd87bae5389117d3a9f07b36a54876c0e | 68,504 |
def plot_xyz(data, x='time', y='amp', z=None, pol='absI', labels=None, sigma=1.0, band='all',
power_in_dB=False, compact=True, monotonic_axis='auto', ax=None, **kwargs):
"""Generic plotting of 2 or 3 quantities extracted from sequence of scans.
This is a very generic plotting routine that plots qu... | a3726c2a358fef46e85307f497f501454548aecf | 68,505 |
def drhodr_Newt(r, M, M_dm, rho, EOS, EOS_deriv, m_dm):
"""
Hydrostatic equilibrium for a star modelled as a Newtonian body
"""
M_tot = M + M_dm
return -cg.G * M_tot * rho / r / r / EOS_deriv(rho, m_dm) | 822ab8feaea5e58e1e2dba1bac536a157c913dcd | 68,506 |
def gen_pkfield(npix=32, alpha=-11.0 / 3, fknee=1, res=1):
"""Generate a 2D square map with P(k) field"""
ufreq = np.fft.fftfreq(npix, d=res)
kfreq = np.sqrt(ufreq[:, np.newaxis] ** 2 + ufreq ** 2)
with np.errstate(divide="ignore"):
psd = 2 * P(kfreq, alpha=alpha, fknee=fknee)
psd[0, 0] = ... | 5dba55fb00d4310c5e3bcdf2806b9ca9244f0b5b | 68,508 |
def rsi(df, nb=14):
""" Compute RSI (Relative Strength Index). RSI measures the speed and change of price movements.
RSI = 100 - (100 / (1 + RS)) where RS = average gain / average loss over 14 days.
"""
column_rsi = f"RSI{nb}"
avg_gain = None
avg_loss = None
if len(df) >= nb:
for... | 48b54c786f926f46061a39fab767c063cd38760d | 68,510 |
def _build_people_params(distinct_id, set, add, token):
"""
Returns a new params dictionary appropriate for people tracking.
"""
if not set and not add:
raise InvalidPeopleProperties("People analytics requires either $set or $add")
if set and add:
raise InvalidPeopleProperties("Mixpa... | 51cef6585a0f6b676d4e431de12fb6391efabbe9 | 68,511 |
def is_run() -> bool:
"""
Test if the graphics system is running.
:return: True if the graphics system is running.
"""
return _is_run | 42d7777446d672596884d4a313a9eddd04b1fca4 | 68,512 |
def getRelationToZOI(collarData, pointIdx, lyr_in):
"""
Classify 2 consecutive daily locations as:
Outside: Outside of ZOI (2 FALSE days)
Enter: Entering ZOI (1 FALSE and 1 TRUE day)
Stay: Stay in ZOI (2 TRUE days)
Leave: Leaving Zone of Influence (1 TRUE and 1 FALSE day)
... | 85f3a0b0caf57cd2e1d547e5a151ad7481eaee9a | 68,513 |
def stations_highest_rel_level(stations, N):
"""Return the N stations with the highest relative water levels.
Only N values are returned regarless of any tie conditions.
Fewer than N may be returned if len(stations) < N
Parameters
----------
stations : list[MonitoringStation]
generate... | d2bf0cd53866286e1739f367833ff15298eb6bd5 | 68,514 |
def singularityintegrate(f, x):
"""
This function handles the indefinite integrations of Singularity functions.
The ``integrate`` function calls this function intenally whenever an
instance of SingularityFunction is passed as argument.
The idea for integration is the following:
- If we are dea... | 4460624363d6428040cccfb1bf2fd768198cb81a | 68,515 |
def helicsBrokerDisconnect(broker: 'helics_broker') -> "void":
"""
get the network address associated with a broker
Parameters
----------
* `broker` :
the broker to query
* `identifier` :
storage space to place the identifier string
* `maxlen` :
the maximum space a... | f1ecd63e0dbe2f22ecdb6ed67d65c92dad7ae874 | 68,516 |
import ast
def lambda_in_rhs(node: AnyAssign) -> bool:
"""Return `True` if the RHS of the given assignment contains a lambda."""
_iterable = (ast.Tuple, ast.List)
if isinstance(node.value, ast.Lambda):
return True
elif isinstance(node.value, _iterable):
return any(isinstance(v, ast.La... | 9a733bc720da6176102959ecc74e128c97f83603 | 68,517 |
import re
def parse_log_entry(msg):
"""
Parse a log entry from the format
$ip_addr - [$time_local] "$request" $status $bytes_sent $http_user_agent"
to a dictionary
"""
data = {}
# Regular expression that parses a log entry
search_term = '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+\-\s+\[(... | f237696e8215793b4cf17e7b20543ac01494b686 | 68,518 |
def create_stats(measures: "List of function timings.",
col: "Current Column.", row: "Current Row",
scenario: "Current Scenario.") -> dict:
"""Helper function to create result dataset."""
return {"scenario": scenario,
"no_column": col,
"data_length": row... | 81baee4dd587b26eb360c72ea16a9c90b17d373b | 68,519 |
def build(sch, inputs, outputs, name="hybrid_func"):
"""Dump the corrent schedule to hybrid module
Parameters
----------
sch: Schedule
The schedule to be dumped
inputs: An array of Tensors or Vars
The inputs of the function body
outputs: An array of Tensors
The outputs... | 5a84a9eb11e3f370fdaa716e10c8b1af74c0da7e | 68,521 |
from typing import Optional
from typing import Union
from typing import Sequence
from operator import invert
def psqi(data: pd.DataFrame, columns: Optional[Union[Sequence[str], pd.Index]] = None) -> pd.DataFrame:
"""Compute the **Pittsburgh Sleep Quality Index (PSQI)**.
Parameters
----------
data : :... | 5f64d336415db1ce595114fc5a3bd15ddf3c630f | 68,522 |
from typing import List
def create_app(routes: List[web.RouteDef]) -> web.Application:
"""Create web application."""
app = web.Application()
app.add_routes(routes)
return app | 54d21870d7e3e1ac59c849910c499f4f7a61b0dc | 68,523 |
def PositionCallback(cb):
"""Creates a position callback from a function pointer."""
return OSVR_PositionCallback(cb) | 7041e412c885e95d10ac4f9028ea1808b0c63b16 | 68,524 |
from typing import List
def has_no_illegal_char(password: List[int]) -> bool:
"""True if the password contains none of the illegal chars."""
return not any(is_illegal_char(char) for char in password) | 96973236b2a7462e5bb3a29796e904dad2bd26ac | 68,526 |
def generate_distance_map(system):
""" Precomputes a distance-map for all tasks in the system.
"""
dist = dict()
for r in system.resources:
for t in r.tasks:
dist[t] = dijkstra(t)
return dist | bd5deec714430581096edacff71f91a734de3317 | 68,527 |
def selection():
"""Returns user selection and catches input errors.
"""
input_value = input("Select a number: ").strip()
if input_value == "break":
return "break"
# catch input errors
try:
input_value = int(input_value)
if (input_value > 0) and (input_value < 5):
... | ddbd04a0f14395543bf37ac8d29e19c9b3ccd8f2 | 68,528 |
def convert_to_feature(item, type):
"""Convert item to FeatureList.
Args:
item: item to be converted
type: string denoting the type of item. Can be "float", "byte", or "int"
"""
if type == "float":
item = tf.train.FloatList(value=item)
item = tf.train.Feature(float_list=item)
elif type == "by... | 6b4990633a3e40fcad8107961cb4e33e7c882e49 | 68,530 |
from datetime import datetime
def get_last_elapsed_tax_year() -> int:
"""Get last ended tax year."""
now = datetime.datetime.now()
if now.date() >= datetime.date(now.year, 4, 6):
return now.year - 1
return now.year - 2 | ed7db4d597f2f125549e028651b5e88761ab641e | 68,531 |
from typing import List
from re import T
from typing import Dict
def get_difference(previous_list: List[T], current_list: List[T]) -> Dict[int, T]:
"""
Get the difference between two lists.
:param previous_list: First iteration of the list.
:param current_list: Second iteration of the list
:return... | df0833c3bdf66003075d84ed57f34dbd6285d1a4 | 68,533 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.