content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def flow_schema(dps):
"""Return schema used in config flow."""
return {
vol.Required(CONF_OPTIONS): str,
vol.Optional(CONF_OPTIONS_FRIENDLY): str,
} | 078c356bf8a3091855ba7f76d04588295927f4ba | 50,900 |
import os
import setuptools_scm.version # only present during setup time
def local_scheme(version):
"""Generate a PEP440 compatible version if PEP440_VERSION is enabled"""
return (
""
if "PEP440_VERSION" in os.environ
else setuptools_scm.version.get_local_node_and_date(version)
... | 38e5f58cafbdf13d680f5901eddddedb6c915af3 | 50,901 |
import os
def dirname(path):
"""
Returns the directory in which a shapefile exists.
"""
# GitPython can't handle paths starting with "./".
if path.startswith('./'):
path = path[2:]
if os.path.isdir(path):
return path
else:
return os.path.dirname(path) | c4c8dcfb511f27984386ee97f8d1ea414561603a | 50,902 |
from typing import List
import sys
import glob
def serial_ports() -> List[str]:
"""List serial port names."""
if sys.platform.startswith("win"):
ports = ["COM%s" % (i + 1) for i in range(256)]
elif sys.platform.startswith("linux") or sys.platform.startswith("cygwin"):
# this excludes your ... | 5c13e868e395861a8756fafd3f3e58ca67c8df47 | 50,903 |
import math
def RFK2(X, Z):
"""This function computes RF kernel for two-layer ReLU neural networks via
an analytic formula.
Input:
X: d times n_1 matrix, where d is the feature dimension and n_i are # obs.
Z: d times n_2 matrix, where d is the feature dimension and n_i are # obs.
output:
C: The kernel matrix... | d7c2e8737aa93b575034b068bcef34c608ad60dc | 50,904 |
import math
def num_tiles_not_in_position(state):
"""
Calculates and returns the number of tiles which are not in their
final positions.
"""
n = len(state)
total = 0
for row in state:
for tile in row:
try:
y = int(math.floor(float(tile)/n - (float(1)/n))... | 102d2eb616f8b459fc31e68788f355440bac97e0 | 50,905 |
def data_quality_item_html(item, caption=None, export_name='item'):
"""Create the HTML for a data quality item.
The generated html looks as follows.
<figure class="data-quality-item" data-export-name="... your export name here ...">
{... your data item content here ...}
<figcaption>
... | e46f295c6c374cb6d0251887e7ec7b914befae9c | 50,906 |
def _is_reparse_point(path):
"""
Returns True if path is a reparse point; False otherwise.
"""
result = win32file.GetFileAttributesW(path)
if result == -1:
return False
return True if result & 0x400 else False | 662a77e3efc01ba6eb279ccc60c46c050d39192b | 50,907 |
from bs4 import BeautifulSoup
import re
def unifi():
"""Returns the latest version available for unifi products."""
expression = r"UniFi Cloud Key firmware (.*)<\/td>"
browser = create_headless_firefox_browser()
cloud_key_url = "https://www.ui.com/download/unifi/unifi-cloud-key"
browser.get(cloud... | 1bade012725251a51ed6262cae2e332fcd7fd02a | 50,908 |
def check_participant(request):
"""Check and add participant if not exist
Args:
request ([Request]): Django request object with expected key and value data
Returns:
[HttpResponse]: Http response message
"""
if not request.method =='POST':
return HttpResponseNotAllowed(['POST'... | 38825496fe27119b00a2537259b499b8a7f20d96 | 50,909 |
def update_cluster_config(cluster_id):
"""update cluster config.
Supported fields: ['os_config', 'package_config', 'config_step']
"""
data = _get_request_data()
return utils.make_json_response(
200,
cluster_api.update_cluster_config(
cluster_id, user=current_user, **data... | ddb6f0a3d310afd8f9f4b8376e56aab3a6bdc2ae | 50,910 |
import random
def make_babies(parents, size=10000):
"""Create a new population by randomly selecting two parents and
randomly selecting the character from a parent for each position."""
children = []
for i in range(size):
p1, p2 = random.sample(parents, 2)
children.append(''.join([p1[i... | 74ac5106259eb504ce70a00fccf610137238bbbe | 50,911 |
def lowess(x, w, x0, kernel=epanechnikov, l=1, robust=False):
"""
Locally linear regression with the LOWESS algorithm.
Parameters
----------
x: float n-d array
Values of x for which f(x) is known (e.g. measured). The shape of this
is (n, j), where n is the number the dimensions of t... | 789025a2e6d82b39173731ef0a3d15f160e6bacf | 50,912 |
def make_app():
""" Function for creating the server instance """
app = web.Application()
app.on_startup.append(on_startup)
app.add_routes(ROUTER)
return app | fd49a93c2d00d59b48a72789afed9ca11b989825 | 50,913 |
def market_timing(ticker, dt, timing='EOD', tz='local') -> str:
"""
Market close time for ticker
Args:
ticker: ticker name
dt: date
timing: [EOD (default), BOD]
tz: conversion to timezone
Returns:
str: date & time
Examples:
>>> market_timing('7267 J... | 3e4cef1c206041b062ef01aaa54895b93921f141 | 50,914 |
def plus(cell1, cell2, back_val):
"""Moves forward between two cells.
Requires a third cell, though truly only requires the value of that the
form takes at the cell.
"""
(x1, y1), val1 = cell1
(x2, y2), val2 = cell2
# back_val, val1 + val2, val form an arithmetic progression
val = 2 * (... | ecf20c2a46f6ae834e0625f5a54fd30f46af2a7a | 50,915 |
def get_bool_symbols(a_boolean):
"""
:param a_boolean: Any boolean representation
:return: Symbols corresponding the to the
True or False value of some boolean representation
Motivation: this is reused on multiple occasions
"""
if a_boolean:
return "✅"
return "❌" | b95a4fc5ca29e07a89c63c97ba88d256a24a7431 | 50,916 |
def rc_int(index, r0, m):
"""ported from MATLAB
function that takes a matrix and performs a Gaussian integral
over the row and column specified by index and returns
a new matrix. Tested against maple integration.
"""
r = sqrt(2 * pi / m[index, index]) * r0
# remove columns and rows from m... | 048e56eb4d8dc9b72fc079d95aecb898a720bbd5 | 50,917 |
from pathlib import Path
def _sort_yaml_first(item_1: _pytest.nodes.Item, item_2: _pytest.nodes.Item) -> int:
"""Sort yaml item first vs module at or below yaml parent directory."""
path_1 = Path(item_1.fspath)
path_2 = Path(item_2.fspath)
if path_1 == path_2 or path_1.suffix == path_2.suffix:
... | be3a5527191ee29e62b6e0b6702b3bed506f1fee | 50,918 |
from typing import Iterable
def lat_lon_kml(row_iter: Rows) -> Iterable[LL_Text]:
"""
>>> data= [['-76.33029518659048', '37.54901619777347', '0']]
>>> list(lat_lon_kml( data ))
[('37.54901619777347', '-76.33029518659048')]
"""
return (pick_lat_lon(*row) for row in row_iter) | ab41c7ca42d716c55687a19373ed6209bf46f2e7 | 50,919 |
def rodogram(x, lag=1, win_size=5, win_geom="square", **kwargs):
"""
Calculate moveing window rodogram with specified
lag for array.
Parameters
----------
x : array like
Input array
lag : int
Lag distance for variogram, defaults to 1.
win_size : int, optional
... | 875f83ba1d1ae73fceeb39846e0b8cb4adc6269a | 50,920 |
from typing import Optional
from pathlib import Path
import pkg_resources
import json
def load_schema(schema_id: str,
version:Optional[str]=None):
"""
Schema functionality adopted from https://github.com/scikit-hep/pyhf/blob/master/src/pyhf/utils.py
"""
global SCHEMA_CACHE
if not ... | 86cbb7f67775cd4d56d58dbb3f44e3258c0a1873 | 50,921 |
from pypy.interpreter import gateway
from pypy.interpreter.error import OperationError as gOperationError
def initexceptions(space):
"""NOT_RPYTHON"""
__doc__ = \
"""Python's standard exception class hierarchy.
Before Python 1.5, the standard exceptions were all simple string objects.
In Python 1.5, the standar... | c1e5db6ec7ef03d08d98d9ac576766e438a0afe9 | 50,922 |
def returner(x):
"""
Create a function that takes any arguments and always
returns x.
"""
def func(*args, **kwargs):
return x
return func | 43476f89cae80cd2b61d64771a3dfac5e4297b5a | 50,923 |
import typing
import collections
def is_iterable_type(tp: type) -> bool:
"""
Test if the given type is iterable.
Some examples of iterable type hints are:
Iterable[str]
Collection[str]
Mapping[str, int]
Sequence[str]
List[str]
Set[str]
Dict[str, in... | c2ef055556040a21923eed0588d14cce745c2ebc | 50,924 |
from typing import Counter
def get_unique_characters(rows, min_count=2):
"""Given a bunch of text rows, get all unique chars that occur in it."""
def char_iterator():
for row in rows.values:
for char in row:
yield str(char).lower()
return [
c for c, count
... | ecba44e44222bb63c2f794e7ee9e87eb3754f695 | 50,925 |
from Qt import QtWidgets
def get_main_window():
"""Acquire Maya's main window"""
if self._parent is None:
self._parent = {
widget.objectName(): widget
for widget in QtWidgets.QApplication.topLevelWidgets()
}["MayaWindow"]
return self._parent | 1a4b90e3406155f860930627168a154ed796b3a5 | 50,926 |
def build_data_type_name(sources, properties, statistic, subtype=None):
"""
Parameters
----------
sources: str or list[str]
type(s) of astrophysical sources to which this applies
properties: str or list[str]
feature(s)/characterisic(s) of those sources/fields to
which the st... | 103a7440dfe3b8f6ccce0fdf6cdca86202e27ac5 | 50,927 |
def build_domain_chaindict(domlist):
"""
Build the diction of min and max residue sequence numbers for each
chain in the supplied domain decompositions (list of PTDomain objects).
Parameters:
domlist - list of PTDomain objects represetning a domain decomp.
Return value:
... | 955062d1ab5973123e69c7741d9500ab1d13ab9b | 50,928 |
def machineCostPerH(fixed, operating):
"""
fixed = fixed costs
operating = operating costs
"""
return {'Machine cost per H': [fixed + operating]} | d6fd47e14402504dc277375d87a786b7c54cea98 | 50,929 |
import re
def expand_symbols(text):
"""
expand symbols in text
"""
text = re.sub("\;", ",", text)
text = re.sub("\:", ",", text)
text = re.sub("\-", " ", text)
text = re.sub("\&", "and", text)
return text | 9f212718745ef0f2964490b692cab491ad74430c | 50,930 |
def _sqlite_format_dtdelta(connector, lhs, rhs):
"""
LHS and RHS can be either:
- An integer number of microseconds
- A string representing a datetime
- A scalar value, e.g. float
"""
if connector is None or lhs is None or rhs is None:
return None
connector = connector.strip()
... | 62040d2bd974bcc8a7f92550551b1871ad19cc93 | 50,931 |
import itertools
def get_conv(outfile):
"""
Helper function to get the convergence info from SCF loops
Args:
outfile (str): output file to parse
Returns:
returns convergence info (change in energy between SCF steps) as a
single list (flattened across outer scf loops).
"""
... | 91c7d7301cdffb01cebce0247ded87004429214e | 50,932 |
def totext(self):
"""Returns row data in tab-delimited text format."""
words = []
column_index = 0
for column in self.columns:
if column['type'].startswith('bit'):
column_index += 1
for bitcolumn in column['columns']:
words.append(format(self[column_index]... | 12a2185c17c7a47a5ec52c900ecf6ba29e929138 | 50,933 |
from .mft import fit_density, exp_density_f
def fit_density(density, wi, fraction_fit=1., return_xy=False):
"""Fit average density curve from a set of density samples.
This is an easier interface than mft.fit_density
Parameters
----------
density : list of ndarray
Density from leftmost f... | ef32d716c47896fc3fd083ee63a8339e24000794 | 50,934 |
def priter(self, **kwargs):
"""Prints solution summary data.
APDL Command: PRITER
Notes
-----
Prints solution summary data (such as time step size, number of
equilibrium iterations, convergence values, etc.) from a static or full
transient analysis. All other analyses print zeros for the d... | aae2dd4c8103d0244887fc7010ca95814f1b853f | 50,935 |
import urllib
def make_socket(address, ssl_context=None):
"""Creates a new listening socket bound to the interface, socket or file
descriptor indicated by the address parameter.
To bind to a port on an interface:
To listen for http traffic on localhost port 8080:
make_socket('http://localho... | a0c8c567a9d4b359885f78d142a2f3a7a9f7de7d | 50,936 |
import sqlite3
def create_connection(db_file):
"""
create a database connection
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn | 97d0299cc9bc62724cd8504f6a0dec88f6844f56 | 50,937 |
from typing import Dict
from typing import Any
import base64
def new_from_user_input(user_input: Dict[str, Any]) -> "EthereumNetwork": # noqa: C901
"""Create a new EthereumNetwork model from user input
Args:
user_input: User dictionary input (assumed already passing create_ethereum_interchain_schema)... | 52e926301be2adb93968fd610197f3acb7ac351b | 50,938 |
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
"""Set up MyQ from a config entry."""
opp.data.setdefault(DOMAIN, {})
websession = aiohttp_client.async_get_clientsession(opp)
conf = entry.data
try:
myq = await pymyq.login(conf[CONF_USERNAME], conf[CONF_PASSWORD], webse... | f545ae1e4a5f37994a248445eb41028508c90381 | 50,939 |
def handle_pose(output, input_shape):
"""
Handles the output of the Pose Estimation model.
Returns ONLY the keypoint heatmaps, and not the Part Affinity Fields.
From: https://docs.openvinotoolkit.org/latest/_models_intel_human_pose_estimation_0001_description_human_pose_estimation_0001.html
Inputs
... | e3867dee7ce85434b10009e93c4b97017d5487d6 | 50,940 |
import requests
import logging
def load_metadata_from_youtube(video_id, request):
"""
Get metadata about a YouTube video.
This method is used via the standalone /courses/yt_video_metadata REST API
endpoint, or via the video XBlock as a its 'yt_video_metadata' handler.
"""
metadata = {}
st... | 7140c18fabd877593c7b58c17a93fb89a0b8efb9 | 50,941 |
from datetime import datetime
def format_date(val, fmt='%m-%d-%Y'):
"""
Transform the input string to a datetime object
:param val: the input string for date
:param fmt: the input format for the date
"""
date_obj = None
try:
date_obj = datetime.strptime(val, fmt)
except Excep... | c6911d3640df0bd54b74aef77e27de801982cd77 | 50,942 |
def gaussian(x, ampl, center, dev):
"""Computes the Gaussian function.
Parameters
----------
x : number
Point to evaluate the Gaussian for.
a : number
Amplitude.
b : number
Center.
c : number
Width.
Returns
-------
float
Value of the spec... | c1a301b680fac6e89ea36af16609601c342200ef | 50,943 |
def choix_repas(num_choix=4):
"""
Choix d'un repas en utilisant les dictionnaires
"""
choix = {1: pizza, 2: nuggets, 3: quiche, 4: courgettes}
return choix.get(num_choix, 4)() | 00b190b2abbb2934754faefed077d5a28a8d3379 | 50,944 |
def is_valid_id(id_: str) -> bool:
"""If it is not nullptr.
Parameters
----------
id_ : str
Notes
-----
Not actually does anything else than id is not 0x00000
Returns
-------
bool
"""
return not id_.endswith("0x0000000000000000") | 6520900966475771e2a0d1fcdfd2b60d3ea2ee9b | 50,945 |
def mtx_gauss_vectors (Omega, i, omega):
"""
Computes the transformation matrix from the orbital plane coordinate
system to the ecliptic system being the sun at the center
Its column vectors (P,Q,R) are the Gauss vectors
It is equivalent and the U matrix:
Rz_3d(-Omega).dot(Rx_3d(-i)).do... | 5950d476a6e6a77c21dd525723ccefce3992ce38 | 50,946 |
def scoring_handler(request):
"""
Renders a random AbsoluteScoringTask for testing.
"""
if request.method == "POST":
try:
score = int(request.POST['score'])
if score != -1:
user = request.user
task_id = request.POST['task_id']
... | aa046f45b4d71849e3a557b105a1ba32e3360ccf | 50,947 |
def computeOmegaAndOmegaDotTrajectory(QT, QdT, QddT):
"""Extracting/converting omega and omegad (trajectories)
from trajectories of Q, Qd, and Qdd.
"""
assert ((len(QT.shape) >= 1) and
(len(QT.shape) <= 2)), "QT has invalid number of dimensions!"
assert ((len(QdT.shape) >= 1) and
(le... | 8aa61053e0bbcfb2b955cac7a5586fad13255d1e | 50,948 |
def async_is_zwave_js_migrated(hass):
"""Return True if migration to Z-Wave JS is done."""
zwave_js_config_entries = hass.config_entries.async_entries("zwave_js")
if not zwave_js_config_entries:
return False
migrated = any(
config_entry.data.get("migrated") for config_entry in zwave_js_... | ca6a5397ec8329557e8be523f4fa416175347c84 | 50,949 |
def clear_portchannel_configuration(dut_list, thread=True, cli_type=""):
"""
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param dut_list:
:param thread: True (Default) / False
:return:
"""
dut_li = list(dut_list) if isinstance(dut_list, list) else [dut_list]
[out, exceptions] =... | d7c43fab91440856deaa4afacca9543f73e6e8f9 | 50,950 |
def device_array_like(ary, stream=0):
"""Call cuda.devicearray() with information from the array.
"""
return device_array(shape=ary.shape, dtype=ary.dtype,
strides=ary.strides, stream=stream) | 4dfc226f55f7af3aff4e891443c759356c312776 | 50,951 |
def get_limit_from_tag(tag_parts):
"""Get the key and value from a notebook limit tag.
Args:
tag_parts: annotation or label notebook tag
Returns (tuple): key (limit name), values
"""
return tag_parts.pop(0), tag_parts.pop(0) | e7d4858b166b2a62ec497952853d95b81a608e85 | 50,952 |
def group_by_node(notifications, limit=15):
"""Take list of notifications and group by node.
:param notifications: List of stored email notifications
:return:
"""
emails = NotificationsDict()
for notification in notifications[:15]:
emails.add_message(notification['node_lineage'], notifi... | 6bb4e6def8df36af1efa72efc297699ca6bed4b0 | 50,953 |
def _normalize_distribution(distribution):
"""Check whether probability distribution sums to 1"""
distribution = _check_all_zero(distribution)
distribution = distribution / distribution.sum()
return distribution | 0753e3b7b3b212cc90f81c58b2377f8345a746a3 | 50,954 |
def ldescent(A, B):
"""
Return a non-trivial solution to `w^2 = Ax^2 + By^2` using
Lagrange's method; return None if there is no such solution.
.
Here, `A \\neq 0` and `B \\neq 0` and `A` and `B` are square free. Output a
tuple `(w_0, x_0, y_0)` which is a solution to the above equation.
E... | 6c837280c9648c61d2f5930694edfecefa1b0f5e | 50,955 |
def PackLikelihoodDataStructuresAsArrays(pairKeys, rholms_intpDictionaryForDetector, rholmsDictionaryForDetector,crossTermsForDetector, crossTermsForDetectorV):
"""
Accepts list of LM pairs, dictionary for rholms against keys, and cross terms (a dictionary)
PROBLEM: Different detectors may have different t... | 3a5bd5edfdaba3a92d05b4941c335d6a60748528 | 50,956 |
def skew(outer, inner, maxrows=-1):
"""
Compute the Schur expansion of a skew Schur function.
Return a linear combination of partitions representing the Schur
function of the skew Young diagram ``outer / inner``, consisting
of boxes in the partition ``outer`` that are not in ``inner``.
INPUT:
... | 557702b973095fa853043d2f9a146fccf00c3938 | 50,957 |
def R(u):
""" Strong form residual """
return div(grad(u)) | 3382a2669f9c6813995b058a151a0895557aa7a3 | 50,958 |
def _tocomplex(arr):
"""Convert its input `arr` to a complex array.
The input is returned as a complex array of the smallest type that will fit
the original data: types like single, byte, short, etc. become csingle,
while others become cdouble.
A copy of the input is always made.
Parameters
... | b4fe82ce3e75122a23f37b9fbd329002045993f9 | 50,959 |
def update(request):
"""Update account details."""
account = _get_account(request.token)
if not account:
return False, _NO_ACCOUNT
if request.playstore_url:
account.playstore_url = request.playstore_url
if request.appstore_url:
account.appstore_url = request.appstore_url
... | 860fec9bb80b3225a4722aab8af5dbaf55e71f86 | 50,960 |
def residue(b, a, tol=1e-3, rtype='avg'):
"""Compute partial-fraction expansion of b(s) / a(s).
If `M` is the degree of numerator `b` and `N` the degree of denominator
`a`::
b(s) b[0] s**(M) + b[1] s**(M-1) + ... + b[M]
H(s) = ------ = ------------------------------------------
... | 31bac7eec896cb6ecf1ed7c93f2c85b3caef18cc | 50,961 |
import scipy
def getShapeProfiles(nr=50):
"""
Returns the shape profiles for magnetic field to use.
"""
global a, B0, Rp
r = np.linspace(0, a*1.05, nr)
rG_R0, G_R0 = r, B0 * np.ones(r.shape)
#rDelta, Delta = r, np.linspace(0, 0.05*a, nr)
rkappa, kappa = r, np.linspace(1, 1.4, nr)
... | 39a2fb98856e754c7006630164c0bf90c53b201d | 50,962 |
async def aio_s3_object_uri(
aio_s3_bucket_name, aio_s3_key, aio_s3_uri, aio_s3_object_text, aio_s3_bucket, aio_aws_s3_client
) -> str:
"""s3 object data is PUT to the aio_s3_uri"""
resp = await aio_aws_s3_client.put_object(
Bucket=aio_s3_bucket_name,
Key=aio_s3_key,
Body=aio_s3_obje... | a694b267f3eab3dbd1087fac8f0f336425489998 | 50,963 |
import json
def put_saved_command(request):
"""
:param request:
:return:
"""
response = {"errors": 0,
"saved": []}
if request.method == "POST":
plugin_data = {"id": request.POST.get("Name"),
"Name": request.POST.get("Name"),
... | a99be27e992c2546761a5dd442f3884b2d2aeb57 | 50,964 |
def get_nb_all_agents():
"""Get quota of all available agents.
Returns
--------
dict
Mapping between agent type and quota of this agent type.
"""
return dict(db.session.query(
Quota.type, Quota.maximum_quota
).all()) | 8cd7b0525f6f3644b15af2d9d9c490d11390ae63 | 50,965 |
def Percent(numerator, denominator):
"""Convert two integers into a display friendly percentage string.
Percent(5, 10) -> ' 50%'
Percent(5, 5) -> '100%'
Percent(1, 100) -> ' 1%'
Percent(1, 1000) -> ' 0%'
Args:
numerator: Integer.
denominator: Integer.
Returns:
string formatted result.
"... | a0081a387a737b44268fd71ab9746c7edd72221f | 50,966 |
import torch
def dataset_to_dataloader(dataset=None, num_workers=1, batch_size=32, shuffle=True, pin_memory="auto"):
"""
Returns batch of img, speed, target_vec, mask_vec
"""
if pin_memory == "auto":
pin_memory = True if torch.cuda.is_available() else False
if dataset is None:
dat... | 00bec599dbbabab00a549450d1a1b89f509750d4 | 50,967 |
from tabulate import tabulate
import hatchet as ht
from timemory.common import dart_measurement_file
import os
def dump_tabulate(dtype, data, metric, file=None, echo_dart=False):
""" Dumps a non-graphframe """
def _get_dataframe(x):
return x.dataframe if isinstance(x, ht.graphframe.GraphFrame) else... | 1da8d393b00432f6e52023accb9a06283f68a84c | 50,968 |
def bin_count(dump_class:dumpFile,axis,number_of_bins,overlap_proportion = 0.0)-> pd.DataFrame:
"""
given a dumpFile class axis number_of_bins and overlap this will make a list of how
many atoms are in the given area
number_of_bins[int] = the number of bins
overlap_proportion[float] = proportional ... | 88cfca724707da74fc205b59f4703689e34b8a3b | 50,969 |
def f_macd(close_prices, window_slow, window_fast, window_signal):
"""Calculates moving average convergence divergence (MACD)
Args:
close_prices (list of float): A list of close prices for each period.
window_slow (int): The moving window to take averages over for the slow MACD period.
... | 55c50fc7110c48ce6e1473c49b5cb82624d0063c | 50,970 |
import os
import logging
from typing import Union
from pathlib import Path
import sys
def get_logger(
name: str,
console_level: int = int(os.getenv("COMPSYN_LOG_LEVEL", logging.INFO)),
log_file: Union[str, Path, None] = os.getenv("COMPSYN_LOG_FILE", None),
file_level: int = logging.DEBUG,
) -> logging... | 1a379e115ee23ec47a9b2ea8d6cdc609e24df6ab | 50,971 |
import zipfile
import re
def search_zipfile(zip_name, name_re, check_hash, master_hash):
"""
Returns a list of matched items
Required:
zip_name (arg): ZIP-like object path
name_Re (arg): Regex to match
check_hash (arg): A Boolean to check for file hashes
mster_hash (arg): ... | c9d691681f55fb6d2859440dfde0b8005fee164b | 50,972 |
def repl_add(name: str, old: str, new: str):
"""
if the string old is in the string name, it is removed, and the string new
is added at the end of the string name
the updated string is returned
"""
if old in name:
name = name.replace(old, '')
name = name + new
return name | 0a2fec8ce75082641b76be7d7394b0bc3e8a963f | 50,973 |
def RenderPassStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | 50f831f8b19c39e15a2965a54b04a0fa110add18 | 50,974 |
from typing import Dict
from typing import Any
def create_lab2d_settings(ascii_map: str,
num_players: int) -> Dict[str, Any]:
"""Returns the lab2d settings."""
ascii_map = ASCII_MAPS[ascii_map]
game_objects = create_game_objects(ascii_map)
extra_game_objects = create_avatar_objects(n... | 3651173301e9a96b4ae4498e5bfacbab79546e47 | 50,975 |
import time
def load2():
""" Route to return the posts """
time.sleep(0.2)
if request.args:
counter = int(request.args.get("c"))
if counter == 0:
print(f"Returning posts 0 to {quantity}")
res = make_response(jsonify(db3[0: quantity]), 200)
... | 29a1a994224360b52da9a970b959c10963e7a10b | 50,976 |
import sqlite3
def adapt_names(odds, site, sport, competition):
"""
Uniformisation des noms d'équipe/joueur d'un site donné conformément aux noms disponibles sur
comparateur-de-cotes.fr. Par exemple, le match "OM - PSG" devient "Marseille - Paris SG"
"""
new_dict = {}
id_competition = get_comp... | 34395f3d1f6648197cd79a6990ff03cf84a69557 | 50,977 |
import random
def sequence_generator(maps,edges):
"""
Calls the function to generate a sequence.
Parameters
----------
maps : dict
key: node [int]
value: state [float]
edges : list
A list of tuples where each tuple represents an edge connection between two nodes, e.g., (2,10)
Returns
-------
[str]
... | 449df7aa836c4f3c8f93530cae6c4b5583edc0ed | 50,978 |
def calc_radial_distribution(arr):
"""
Calculate 1D-radially averaged distrubution profile
from 2D-PNBD diffraction pattern.
Parameters
----------
arr : 2D-numpy array
The numpy array which contains the 2D-PNBD pattern.
Returns
-------
radial_distance, intensity : 1D numpy ... | af1afab326411cdb287d6ea749b5fd3057c90d6c | 50,979 |
from typing import Callable
def evaluate_epoch(
eval_fn: Callable,
data_loader: DataLoader,
use_cuda: bool = False,
) -> float:
"""
Go through a dataset and return the total loss
:param eval_fn: typically either SVI.step (for training)
or SVI.evaluate_loss (for testing)
... | eeb36a1bc96db042426b754fd3c0e05d4636d925 | 50,980 |
def get_drift(x: int) -> int:
"""Returns an int if not zero, otherwise defaults to one."""
return int(x) if isinstance(x, int) and x != 0 else 1 | fdb60d8b44aab4dfda107ba96f0538b3e28deb8b | 50,981 |
import time
def train(train_loader,
model,
criterion,
optimizer,
scheduler,
args):
"""Train the model.
Args:
train_loader (DataLoader): The training data loader.
model (CNNs): The model.
criterion (Loss): The loss function.
opt... | cdade6ad31946b5aac335b3c6eb40cbcdec6c917 | 50,982 |
def get_hd_used_space():
"""
get_hd_used_space()
Returns the amount of space used on the machine (float)
"""
capacity = float(get_hd_capacity())
available = float(get_free_hd_space("gigabytes"))
return capacity - available | 9126489ac13626a2b878da8ac0be2f7ffb7e0aeb | 50,983 |
def create_project(projectname):
"""
Create a new project on the specified storage
Returns a json object
"""
auth_id = request.get_json().get("auth_id")
storage_accesses = request.get_json().get("storage_accesses", [])
response = jsonify(
admin.create_project(current_session, project... | 049107c99f44570b5b87f3f9544166c218119a39 | 50,984 |
import os
def get_feature_size_per_file(f_name):
"""
Return the dimensionality of the features in a given file.
Typically, this will be the number of bins in a T-F representation
"""
shape = get_shape(os.path.join(f_name.replace('.data', '.shape')))
return shape[1] | 7f712b06fb52abfaaef1c1bebab9cc84067d4f28 | 50,985 |
import csv
def load_settings (filename):
"""Load the settings file"""
settings = {}
data_reader = csv.reader(open(filename, 'rU'), delimiter='\t')
# Ignore header
header = next(data_reader)
# Process each line
for row in data_reader:
if len(row) == len(header):
sample = row[0]
sample_data = {}
for e... | 41867e0fb5e6afff412713cd6b14d78aa63e39fd | 50,986 |
import random
import string
def gen_program(min_size, max_size):
"""gen_program generates a random program."""
size = random.randrange(min_size, max_size)
prog = []
for _ in range(size):
# Randomly pick if we add a program symbol or random word.
if random.choice([True, False]):
... | ccf8a70bba0c0bd8f3b1cb52e47de0597959a079 | 50,987 |
def _get_sort_function(camera: Camera):
"""Given a scene object, get a function to sort wobject-tuples"""
def sort_func(wobject_tuple: WorldObject):
wobject = wobject_tuple[0]
z = (
Vector3()
.set_from_matrix_position(wobject.matrix_world)
.apply_matrix4(proj... | f91ddcf2702648f0c66267e3c3b6400b8347a658 | 50,988 |
def check_aws_libs() -> bool:
"""Check Imports for AWS libs"""
libs = ["boto3", "botocore"]
return check_import_libs(libs) | b28a10818564a3e97045680083b980f6c72e6813 | 50,989 |
def run_platform_imputation(
mt: hl.MatrixTable,
plat_min_cluster_size: int,
plat_min_sample_size: int,
plat_assignment_pcs: int,
) -> hl.Table:
"""
Run PCA using sample callrate across gnomAD's evaluation interval and create Hail Table
with platform PCs and assigned platform.
:param Mat... | 6543cafe33585b5abee8c47727fda6c861271380 | 50,990 |
def fmin(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None, maxfun=None,
full_output=0, disp=1, retall=0, callback=None, initial_simplex=None):
"""
Minimize a function using the downhill simplex algorithm.
This algorithm only uses function values, not derivatives or second
derivatives.
... | cae5e1776b42d8e1bb78b3cbefea49c869b6912d | 50,991 |
import time
import test
def train(args, device, train_loader, net, writer, test_loader, summary,
val_loader):
"""
Train the given network on the given training dataset with DTP.
Args:
args (Namespace): The command-line arguments.
device: The PyTorch device to be used
trai... | d06cb3809ec48a014ccce3edbff6e0dc5fcfa7e1 | 50,992 |
import logging
def validate_endpoint_put(request: Request) -> str:
"""Ensure that the given endpoint is valid. If not raise a 405."""
endpoint = validate_endpoint_get(request)
if endpoint not in request.app["put_endpoints"]:
logging.info("Failed to put %s", endpoint)
raise web.HTTPMethod... | 34be638b1540610b878e9fbfd4e52f25b641ed54 | 50,993 |
def get_sat_pos_vel_acc(t, eph):
"""Calculate positions, velocities, and accelerations of satellites.
Accepts arrays for t / eph, i.e., can calculate multiple points in time
/ multiple satellites at once.
Does not interpolate GLONASS.
Implemented according to
Thompson, Blair F., et al. “Compu... | 5a41bba16b77ef90f199cd07134a18c5429582f3 | 50,994 |
def git_version() -> str:
"""Get the current git head sha1."""
# Determine if we're at master
try:
out = _minimal_ext_cmd(["git", "rev-parse", "HEAD"])
git_revision = out.strip().decode("ascii")
except OSError:
git_revision = "Unknown"
return git_revision | 1f800c45e48bc214a231cc180f200fa24166c1d1 | 50,995 |
def create_gScore(self):
"""Creates and returns a data structure that holds the cost of getting from the start node to that node, for each node.
The cost of going from start to start is zero."""
# TODO: a data structure that holds the cost of getting from the start node to that node, for each node.
# f... | 8acffbd6378f6bd77154f6d0d4cd2ccd22025b11 | 50,996 |
def _parse_seconds_fraction(frac: str) -> int:
""" Parse the fraction part of a timestamp seconds, using maximum 9 digits
Returns the nanoseconds
"""
ns = 0
mult = MAX_NANOSEC
for c in frac:
if c < '0' or c > '9' or int(mult) < 1:
break
mult = mult // 10
ns +=... | e6f60edad855e73c823ad88bdecbcd02f1f151e0 | 50,997 |
import time
def test_increment_as_decorator():
"""We test that the `ProgressExt.report` function works as a context manager
- Click the button multiple times and check that the progress is reset every 2 clicks
"""
progress = ProgressExt()
run_button = pn.widgets.Button(name="Click me")
@prog... | 2646a9c233088d96fcdcf17a42eea31eff224241 | 50,998 |
def link_filtered_DLC_predictions(nwb_file,video_dir): # add the DLC files (need code/write code)
""" Function to link filtered DLC predictions to a NWB file"""
return nwb_file | d51980fe2bc7099e13d784eb9fc6e324c547c38d | 50,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.