content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_route_count(device, table, protocol, active=True, output=None):
"""
Get total route count for each table via 'show route target_route extensive'
Args:
device (`obj`): Device object
table (`str`): Table name such as `inet.0`, `inet6.0`
protocol (`str`): Protocol name such as ... | b152088e5d6d0c9e4e2b68e9b141181b9577b9ad | 39,200 |
import os
def get_dataset(folder, url):
""" Returns the corresponding file name for the desired dataset """
return os.path.join(folder, get_filename_url(url)[0]) | 9b9c8351b8a87a0ed691a054be316f888d270080 | 39,201 |
def deep_replace(arr, x, y):
"""
Help function for extended_euclid
"""
for i in range(len(arr)):
element = arr[i]
if type(element) == list:
arr[i] = deep_replace(element, x, y)
else:
if element == x:
arr[i] = y
return arr | 55ef1c7efe04d436f9ce96bda0f565a092131400 | 39,202 |
def get_imgaug_transform(cfg: DictConfig) -> iaa.Sequential:
"""Create simple data transform pipeline that resizes images."""
data_transform = iaa.Resize(
{
"height": cfg.data.image_resize_dims.height,
"width": cfg.data.image_resize_dims.width,
}
)
return iaa.Sequ... | 6a18dc04fca1d18e40a3f28ae22d6761a96dd53f | 39,203 |
def inerIntra(groupes, centres):
"""Calcul de l'inertie intra-groupe d'une liste de groupes"""
inerGroupeList = []
i = 0
for centre in centres:
inerGroupeList.append(inerGroupe(groupes[i], centre))
i = i + 1
inersum = 0
for iner in inerGroupeList:
inersum += iner
retu... | 0d2f39eefdcfd3f02191111e318820e1c767234f | 39,204 |
def k_prototypes(X, n_clusters, gamma, init, n_init, max_iter, verbose):
"""k-prototypes algorithm"""
assert len(X) == 2, "X should be a list of Xnum and Xcat arrays"
# List where [0] = numerical part of centroid and
# [1] = categorical part. Same for centroids.
Xnum, Xcat = X
# Convert to nump... | 5ee8cb28ef84862fe980b1e6b70437b6893a675a | 39,205 |
def update_password(password, value, position=None):
"""Update password with value
:param str password: The password string
:param str value: The character(s) to update with
:param int position: The position in which to insert the character(s)
:return: The updated password
"""
result = list... | 19287d5fd65141de6edbd806b18419e54492e201 | 39,206 |
import yaml
def run_distribute(filename, distribution, graph=None, algo=None):
"""
Run the distribute cli command with the given parameters
"""
filename = instance_path(filename)
algo_opt = '' if algo is None else '-a ' + algo
graph_opt = '' if graph is None else '-g ' + graph
cmd = 'pydco... | 395d956f922ffedf4bfbe7cbcfe6f200017543f6 | 39,207 |
def find_pmp(df):
"""simple function to find Pmp on an IV curve"""
return df.product(axis=1).max() | 5ed7c14bc58a62f6168308ccd1dfa17e56e2db89 | 39,208 |
def chebyshev_distance(v1, v2, norm=False):
"""
return ||v1 - v2||_oo
"""
v1, v2 = check_pairwise_vector(v1, v2, norm)
diff = v1 - v2
K = np.abs(diff).max()
return K | b65fbdfe3dee68f360ef66e0fd3c4ee5085be062 | 39,209 |
def get_distances_from_other_points(point_index: int, num_samples: int, distance_matrix: ndarray):
"""Get distances from point i to other points in the dataset.
Args:
point_index: The index of the point.
num_samples: The number of points.
distance_matrix: Condensed distance matrix.
... | e9610355ddc37fd58261bfb9233cc5a20ca4c2ac | 39,210 |
import subprocess
def collect():
"""Collects and aggregates contents of TinyPilot-related logs and files.
Returns:
A large string with the full contents of TinyPilot's debug logs and
configuration files.
"""
try:
# return subprocess.check_output(
# ['sudo', '/opt/t... | ef7a5172a9c31bf96ba28065b4d241052f9c8ea7 | 39,211 |
def get_help_option(input_args):
"""Get help about option or values authorized for option."""
global cmdhelp_settings, cmdhelp_option_infolist
global cmdhelp_option_infolist_fields
pos = input_args.find(' ')
if pos > 0:
option = input_args[0:pos]
else:
option = input_args
opt... | 5436480c38a32de189ab1c2418519d5216502a46 | 39,212 |
import math
from datetime import datetime
def aggregate_report():
"""Generate a report with total of resources in used and reserved for
each aggregate."""
context = {}
aggregates = Aggregates.objects.all()
for aggregate in aggregates:
# Add aggregate on context dict
if aggregate... | 134d59d1c58cb7160b88bbf596fe9f51b39e0cdb | 39,213 |
def create_app(object_name):
"""
:argument object_name: the python path of the config object
:return: app
"""
app = Flask(__name__)
app.config.from_object(object_name)
db.init_app(app)
app.register_blueprint(main_blueprint)
return app | 3596a4c887326af72692189654e936bc4816308e | 39,214 |
def fix_timestamp(dataframe):
"""
Convert timestamp from UTC into engine timezone and from ISO to format expected by graphs
:param1 dataframe: data frame to process
return: dataframe with converted timestamp column
"""
dataframe["timestamp"] = dataframe["timestamp"].apply(convert_from_utc, args=(__eng... | 8ed075fb6afb5c5269ebf5def7c75a3632ccc7a4 | 39,215 |
def cve_last_week():
"""
Get CVEs from last week of the year
---
tags:
- CVE
responses:
200:
description: Get CVEs from last week of the year
408:
description: Request timeout
"""
# FIXME: get rid of hardcoded year
cves = CVE.query.filter(
2019 =... | bb49e6727f57e146c96e6cbdfd694e440ba2e516 | 39,216 |
def scale(data, remove_outliers=False):
"""
Scales the input and removes outliers
"""
if remove_outliers:
perc_2 = np.zeros(data.shape[1])
perc_98 = np.zeros(data.shape[1])
for i in range(data.shape[1]):
perc_2[i] = np.percentile(data[:, i], 2)
perc_98[i] ... | 1eec5537e3762f36e46eef37b36297c7b83359a8 | 39,217 |
def subpixel_values(img, pts):
"""
References:
stackoverflow.com/uestions/12729228/simple-efficient-binlinear-interpolation-of-images-in-numpy-and-python
SeeAlso:
cv2.getRectSubPix(image, patchSize, center[, patch[, patchType]])
"""
# Image info
nChannels = get_num_channels(img)... | 7778c91a320a61caecef42dec98d83861d4798a4 | 39,218 |
def loadZenMakeMetaFile(filePath):
"""
Load ZenMake common ConfigSet file. Return None if failed
"""
dbfile = db.PyDBFile(filePath, extension = '')
try:
data = dbfile.load(asConfigSet = True)
except EnvironmentError:
return None
return data | 5ab84701e2f18ffb397f4d22528a87c627e84041 | 39,219 |
def readable_timedelta(days):
"""Print the number of weeks and days in a number of days."""
#to get the number of weeks we use integer division
weeks = days // 7
#to get the number of days that remain we use %, the modulus operator
remainder = days % 7
return "{} week(s) and {} day(s).".format(w... | 120f517939842b4e0686a57a3117221e3db63004 | 39,220 |
def create_net(in_sx, in_sy, out_sx):
"""
Creates a tflearn neural network with the correct
architecture for learning to hear the keyword
"""
net = tflearn.input_data([None, in_sx, in_sy])
net = tflearn.lstm(net, lstm_size, dropout=lstm_dropout)
net = tflearn.fully_connected(net, out_sx, activation='softmax')
n... | 686df9637496c1595fc0bed55e03a9eec550e0b9 | 39,221 |
def compute_iou(boxes1, boxes2):
"""
compute_iou() 函数用来计算 IOU 值,即真实检测框与预测检测框(
当然也可以是任意两个检测框)的交集面积比上
它们的并集面积,这个值越大,代表这个预测框与真实框的位置越接近
如果说得到的 IOU 值大于设置的正阈值,那么我们称这个预测框为正预测框(
positive anchor)其中包含着检测目标;
如果说得到的 IOU 值小于于设置的负阈值,那么我们称这个预测框为负预测框(
)negative anchor),其中包含着背景
"""
le... | ba6ae63a8d15233fd18a100c6e50c2176559ecaa | 39,222 |
import pytz
from datetime import datetime
def localize_date_utc(date):
"""
Localizes in the UTC timezone the given date object.
:param date: The date object to be localized.
:return: A localized datetime object in the UTC timezone.
TODO :: unit test
"""
return pytz.utc.localize(
da... | 512793f7d66c9ef88b957d0bbfe51b35b620dcb7 | 39,223 |
def compute_box_3d_tracker(tracker, P):
""" Takes an tracker object and a projection matrix (P) and projects the 3d
bounding box into the image plane.
Returns:
corners_2d: (8,2) array in left image coord.
corners_3d: (8,3) array in in rect camera coord.
"""
# compute ... | daceaf3740006805216b8e38d3093c83ceb8a89b | 39,224 |
def lang_exists(cursor, lang):
"""Checks if language exists for db"""
query = "SELECT lanname FROM pg_language WHERE lanname = %(lang)s"
cursor.execute(query, {'lang': lang})
return cursor.rowcount > 0 | 085ed58920f3b13464a0f332d695ff39336cda8d | 39,225 |
def create_init(fields, # type: Iterable[Field]
user_init_fun=None, # type: Callable[[...], Any]
inject_fields=False, # type: bool
user_init_args_before=True # type: bool
):
"""
Creates the new init function that... | 1ced8f4dd528fd71ff3275d0c180f7ac6d7d05d6 | 39,226 |
def search_comments_for_terms(terms, comments):
"""
Adds Boolean columns indicating whether a search term was located
Args:
terms {tuple} : a collection of unique search terms
comments {DataFrame} : a Pandas DataFrame with comment data
Returns:
A Pandas DataFrame with the update... | 0654cf1430102e774e03f20939316a2fc38ad399 | 39,227 |
import os
def calculate_folder_checksum(folderpath, format_checksum=True,
recursive=True):
""" Calculate the checksum of a specified folder
Checksum is calculated with :func:`zlib.crc32`.
Parameters
----------
folderpath: :obj:`str`
Path to the folder for wh... | 3daed51a2fa934d9b6cc9036a0e54596016dc2d6 | 39,228 |
import requests
def update_node_data_join():
"""
This is a route for ALL NODES.
Whenever the PREVIOUS NODE departs from the ring,
all of its data are transfered to us through this route.
"""
start_id = request.form['start_id']
k = int(request.form['k'])
prev_storage = {}
to_be_dele... | 0fa96c05d67f1f87eaf85f6d8aa993fdf072b3ab | 39,229 |
import os
import sys
import PIL
def load_image(fname=None):
"""Load example image.
"""
if fname is None:
fname = 'chelsea.jpg'
fname = os.path.join(os.path.dirname(__file__), 'data/' + fname)
if len(sys.argv) == 2:
img = PIL.Image.open(sys.argv[1])
else:
img = PIL.Im... | 3310fef8d68c8b5ce00b4a6a15e5304d3dc4e1b2 | 39,230 |
def isMessageBody(line: str) -> bool:
"""
Returns True if line has more than just whitepsace and unempty or is a comment (contains #)
"""
return not (line.isspace() or line.lstrip().startswith('#')) | 990ae3ff01f794a6c8d4d45ecb766a763c51dff8 | 39,231 |
def getHistoricalUmuxChartData(allProjectSnapshots):
"""
UMUX history line chart on project detail page.
Loop thru quarters starting at first meaningful quarter 2 years or less ago.
If a quarter has no (meaningful) snapshot, it gets an empty x-axis tick.
Return: {obj} Chart data with xaxis quarters, scores, and ta... | 0660780b9d5b4d667f47dddd83d9e0cee0ffd467 | 39,232 |
import re
def is_number(string):
"""Test whether a string is number-ish. Ignoring units like 'cwt' and 'hd'."""
if string:
string = re.sub(r'\$|[,-/]|cwt|he?a?d?|per', '', string, flags = re.IGNORECASE)
try:
float(string)
result = True
except ValueError:
... | 3e401d0bedcc7608bb33c7d158f57bd8dd95a35e | 39,233 |
import signal
def downgrade_pan_3d(I_MS , I_PAN, ratio, sensor=None):
"""
downgrade MS and PAN by a ratio factor with given sensor's gains
"""
I_MS=np.double(I_MS)
I_PAN=np.double(I_PAN)
I_MS = np.transpose(I_MS, (2, 0, 1)) #
#I_PAN = np.squeeze(I_PAN) #从数组的形状中删除... | 88c308e08a14ae0de666890510f4be1356786664 | 39,234 |
def readSedML(*args):
"""
readSedML(self, string filename) -> SedDocument
Reads an SEDML document from a file.
This method is identical to readSedMLFromFile().
If the file named 'filename' does not exist or its content is not
valid SEDML, one or more errors will be logged with the SedDocument
object re... | 86e4f3179e70720c109a17b1948c1aa2fd757231 | 39,235 |
from my_library import test_socket, ClassDB
from collections import namedtuple, defaultdict
import json
def show_status_json():
""" List current status of sensors in json-format """
db_ip = server_settings['db_ip']
db_user = server_settings['db_user']
db_pass = server_settings['db_pass']
db_name ... | 70d9a9b78886f73d7f73ee1c54e0a00452bf9c30 | 39,236 |
def get_recommended_dictionary_gcs_path(fuzzer_name):
"""Generate a GCS url to a recommended dictionary.
Returns:
String representing GCS path for a dictionary.
"""
bucket_name = environment.get_value('FUZZ_LOGS_BUCKET')
bucket_subdirectory_name = 'dictionaries'
recommended_dictionary_gcs_path = '/%s/%... | e27dfc9259823754b4ac5738481db810476b469c | 39,237 |
def PlaneEHfield(z, t=0.0, sig=1.0, mu=mu_0, epsilon=epsilon_0, E0=1.0):
"""
Plane wave propagating downward (negative z (depth))
"""
bunja = -E0 * (mu * sig) ** 0.5 * z * np.exp(-(mu * sig * z ** 2) / (4 * t))
bunmo = 2 * np.pi ** 0.5 * t ** 1.5
Ex = bunja / bunmo
Hy = E0 * np.sqrt(sig ... | 9b97030e01718f608003b93c95f50dcf11631fb6 | 39,238 |
import os
def find_grass_dir():
"""Try to find GRASS install directory."""
if "GISBASE" in os.environ:
return os.environ["GISBASE"]
p = run(["grass", "--config", "path"], capture_output=True)
if p.returncode == 0:
return p.stdout.decode().strip()
else:
raise GrassNotFound() | af2eb0024807e999ce4702787e52737001cee1e8 | 39,239 |
from pathlib import Path
def playbook_path(request: SubRequest, tmp_path: Path) -> str:
"""Create a playbook with a role in a temporary directory."""
playbook_text = request.param[0]
role_name = request.param[1]
role_layout = request.param[2]
role_path = tmp_path / role_name
role_path.mkdir()
... | 66457aa20ac74504cac9374ba97d068da6f12b7a | 39,240 |
import posixpath
def _address_to_placement(address):
"""
Parameters
----------
address : str
The address of a node or an actor pool which running in a ray actor.
Returns
-------
tuple
A tuple consisting of placement group name, bundle index, process index.
"""
par... | 1e20394a5deddcb06571273f51dccccead96adca | 39,241 |
def ideal_season_state(season_states, conditions_season):
"""Classify ideal season states # (prefer dry rainy over early/late states)"""
(
dry_condition,
dry_early_condition,
dry_late_condition,
rainy_condition,
rainy_early_condition,
rainy_late_condition,
) =... | f48bab9ddcabce24186204796812f67877363af5 | 39,242 |
def estimate_post_transplant_death(txids, doids):
"""
This function estimate the number of post transplant deaths.
@Input:
@txids: list of patients who received transplants
@doids: list of donated organs
@Output:
@output_totals: number of post transplant deaths for each replication
"""
#set seed
nump.rand... | 3d341214ed3d8ce03c99323c84c01b00af3c8d1c | 39,243 |
def geolytica(location):
"""
# Geolytica
Geocoder.ca - A Canadian and US location geocoder.
Using Geocoder you can retrieve Geolytica's geocoded data from Geocoder.ca.
## Python Example
>>> import geocoder
>>> g = geocoder.geolytica(<address>)
>>> g.lat, g.lng
45.4... | 1e44582548d972aada50e25271e88d264d6bf3dc | 39,244 |
from discopy.monoidal import Functor
def flatten(self):
"""
Takes a diagram of diagrams and returns a diagram.
>>> from discopy.monoidal import *
>>> x, y = Ty('x'), Ty('y')
>>> f0, f1 = Box('f0', x, y), Box('f1', y, x)
>>> g = Box('g', x @ y, y)
>>> d = (Id(y) @ f0 @ Id(x) >> f0.dagger()... | d648bfa88e2343c2e0d91ce023ebde574aa12f38 | 39,245 |
def accuracy_count(y_true, y_pred) -> int:
"""
accuracy 计数
Examples:
# 单标签分类
>>> _y_true = [0,1,2,3]
>>> _y_pred = [0,1,2,2]
>>> accuracy_count(_y_true, _y_pred)
3
# 多标签分类:使用 one-hot 标签
>>> _y_true = [[0,1],[1,1],[1,0],[0,0]]
>>> _y_pred = [[... | d8ee8d30053b0bbc6b7e529e83cfd974d75599db | 39,246 |
import io
import random
def label_image(image_bytes, labels):
"""
Plot an image and corresponding bounding
boxes of detected labels
Parameters
----------
image_bytes : bytes
Image as bytes
labels : [n_label,] dict
Returned from api.get_json() function or from
Reko... | dcaf2c52c53cceb1233d2a18848572d94a0eeef2 | 39,247 |
def parse_prelink_info():
"""Find and parse the kernel __PRELINK_INFO dictionary."""
segments = _find_prelink_info_segments()
for segment in segments:
seg_size = idc.get_segm_end(segment) - idc.get_segm_start(segment)
prelink_info_string = idc.get_bytes(segment, seg_size)
prelink_info_string = prelink_info_str... | 7e2aed1ae52ff9631ee66a3bc7a6f3e58d6119f9 | 39,248 |
def box_plots(df, plotField, groupField, groupFieldItems):
"""
Returns a dictionary of box plot statistics for the plotField,
where the keys are the unique items in the groupField.
"""
# reduce df and drop the nulls
df = df[[plotField, groupField]].dropna()
# group the requests by type and ... | 7ae43364794439d248dca4a62eae9cac44f442dc | 39,249 |
def model(X_train, Y1_train, Y2_train, X_dev, Y1_dev, Y2_dev, numOutputNodes, learning_rate = 0.0001, iterations = 5000, minibatch_size = 16, print_cost = True, \
layer1 = 100, layer2_1 = 50, layer2_2 = 50, beta1 = 0.01, beta2 = 0.1):
""" Three-layer NN to predict Fe coordination numbers around oxygen.
... | 740a7a1fe2d1ae2d52d67329ca3b44eb555fbedb | 39,250 |
def send_shared_files(path):
"""Files used accross different web apps"""
return flask.send_from_directory(SHARED_PATH, path) | 0de2f50ea37724b4084e2cfc7b16b4429b051da8 | 39,251 |
def create_creative_sets(creative_sets):
"""
Creates creative sets in DFP.
Args:
creative sets (arr): an array of objects, each having creative set configuration
Returns:
an array: an array of created creative set IDs
"""
dfp_client = get_client()
creative_set_service = df... | 3eabc5c8850f9521e0d3be90d3ef14a7a63548ee | 39,252 |
def get_combinations(limit, numbers_count, combination):
"""Get all combinations of numbers_count numbers summing to limit."""
if sum(combination) >= limit:
return None
if numbers_count == 1:
return [combination + [limit - sum(combination)]]
combinations = []
for number in range(1, l... | caecaeb8a5ef5f68bc47936c3b4db3d7514b6c52 | 39,253 |
def read_el_cards():
"""
Read information about space group from file to list of cards ldcard.
Info in file fitables:
1 P1 Triclinic
choice: 1
centr: false
pcentr: 0, 0, 0
symmetry: X,Y,Z
2 P-1 Triclinic
...
"""
fid = open(F_ITABLES, "r")
... | fc4b2f5891e4ea924da2d7cd72fb3298d705a644 | 39,254 |
from typing import Union
from typing import List
def resize_image(
image: pygame.surface.Surface, new_size: Union[List[int], CoordsType]
) -> pygame.surface.Surface:
"""
wrapper for pygame.transform.scale
:param image: pygame.surface.Surface
:param new_size: Union[List[int], Tuple[int, int, int]]
... | 401a2d15f2c47feb68ac27730b2da38a7677d68b | 39,255 |
def isoDuration(value):
"""(str) -- Text of contained (inner) text nodes except for any whose localName
starts with URI, for label and reference parts displaying purposes.
(Footnotes, which return serialized html content of footnote.)
"""
if not isinstance(value, str):
raise TypeErr... | 6b75c0dbad9cda86bb48c77b23f6bde095895670 | 39,256 |
def bit_list_to_int(bit_list):
"""
Converts binary number represented as a list of 0's and 1's into its corresponding base 10
integer value.
Args:
bit_list: a binary number represented as a list of 0's and 1's
Returns:
The base 10 integer value of the input binary number
"""
... | ade66899fe1d23a22c76cccf4ba57e9ad9bf0ba1 | 39,257 |
def max_labor_budget_rule(M):
"""
Put upper bound on total labor cost.
Using individual shift variables multiplied by their length and a tour
type specific cost multiplier. Could easily generalize this to make costs
be complex function of time of day, day of week, shift length, tour type,
o... | f2637e4b2dba8cc4eb6e5afcae57c45d1b9560d7 | 39,258 |
def _trace_prefixes(trace: Trace, prefix_length: int) -> list:
"""List of indexes of the position they are in event_names
"""
prefixes = []
for idx, event in enumerate(trace):
if idx == prefix_length:
break
event_name = event['concept:name']
prefixes.append(event_nam... | 837474c0e8b244bc4a49dc2abe31271cec512cf7 | 39,259 |
def _diff_args(type, options):
"""generate argument list to pass to diff or rcsdiff"""
args = []
if type == CONTEXT:
if "context" in options:
if options["context"] is None:
args.append("--context=-1")
else:
args.append("--context=%i" % options[... | f52d7a2513d1726693b4493d0ed9d421476493a4 | 39,260 |
import re
def email(value: str):
"""
Extract email from document
Example Result: ['crazyvn@gmail.com', 'feedback@tp.com']
"""
_email_pat = r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+'
return re.findall(_email_pat, value) | c8f3dcb4163e99f0aefe7eb42e61b127ffbaa393 | 39,261 |
def TransposeTable(table):
"""Transpose a list of lists, using None to extend all input lists to the
same length.
For example:
>>> TransposeTable(
[ [11, 12, 13],
[21, 22],
[31, 32, 33, 34]])
[ [11, 21, 31],
[12, 22, 32],
[13, None, 33],
[None, None, 34]]
"""
... | d53dc20a9eff391560269e818e99d41f8dc2ce94 | 39,262 |
import typing
def compile_metric_telegraf(
prefix: str,
path: str,
value: str,
type_code: str,
rate: str = "",
tags: typing.Optional[typing.Dict[str, str]] = None,
) -> str:
"""Compile metrics for telegraf."""
rate = serialize_rate(rate)
if tags is None:
return f"{prefix}... | bbb10bfbcb3717d83960637ef005bc4ff07f96ec | 39,263 |
from typing import Optional
from typing import Sequence
def _canonicalize_depends_on(
dep_param, *, max_depth: Optional[int] = None
) -> Sequence[DependencyNode]:
"""
For convenience, we allow specifying the depends_on parameter when submitting a job
in numerous ways.
"""
if max_depth is not N... | be51aed923d61fe54d60f46496cea0815a22d84d | 39,264 |
def handle_exceptions(func):
"""Catch exceptions and return appropriate HTTP error."""
@wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as err:
return http_500(str(err))
return wrapper | 57fbaa07e9f7549ab6a96ca4650764d461bb4eae | 39,265 |
import subprocess
from io import StringIO
def get_gpu_memory_usage() -> pd.DataFrame:
"""Return the free and used memory per GPU device on the node"""
gpu_stats = subprocess.check_output(["nvidia-smi", "--format=csv", "--query-gpu=memory.used,memory.free"])
gpu_df = pd.read_csv(StringIO(gpu_stats.decode(... | c24e5a5503360f967d4aabcfeb43df054de51e51 | 39,266 |
def stochastic_RSI_strategy(df: pd.DataFrame, window: int = 14, max_investment: float = 0.1) -> pd.DataFrame:
"""
Stochastic Relative Strength Index Strategy
"""
# https://www.investopedia.com/terms/s/stochrsi.asp
stochRSI = signals.stochastic_relative_strength_index(df, window=window)["signal"]
... | 1bc6216a03554885dbee0d286b56188977e78eaf | 39,267 |
def conv3x3(in_planes, out_planes, stride = 1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size = 3, stride = stride, padding = 1, bias = False) | 4e32b1d6f81ecdbe24b59ec46ccba22395faf59b | 39,268 |
async def handler(request: web.Request) -> web.Response:
"""
Expose API specification to the world
"""
return web.json_response(request.app["spec"].to_dict(), dumps=ujson.dumps) | fb8f7e3f6620a8db2265089183ae87198fede1ff | 39,269 |
from operator import or_
def storage_get_active_by_window(context,
begin,
end=None,
project_id=None):
"""Return storages that were active during window."""
session = get_session()
query = session.query(models.H... | 69fd18955ad1f88cd196cd5d4593891a9b30bf8d | 39,270 |
import os
def dns(host, timeout=10):
"""
Return list of ip addresses of a given host. Errors out after timeout seconds.
"""
a = os.popen3("host -t A -W %s %s | awk '{print $4}'"%(timeout,host))
err = a[2].read().strip()
if err:
raise RuntimeError(err)
out = a[1].read()
if 'fou... | 09cba184f29c28a346b3539750adb9c0702fdde1 | 39,271 |
def eval_against_random_bots(env, trained_agents, random_agents, num_episodes):
"""Evaluates `trained_agents` against `random_agents` for `num_episodes`."""
wins = np.zeros(2)
for player_pos in range(2):
if player_pos == 0:
cur_agents = [trained_agents[0], random_agents[1]]
else:... | 9fae8b61062e372273055894af0cd33a0b6e091f | 39,272 |
def _get_number_divisiors(number: int):
"""
Function return number of divisiors of a given number.
"""
if number <= 1:
raise ValueError("Number must be greater than 1.")
return len(list(divisior for divisior in range(1, floor(sqrt(number) + 1)) \
... | b2be8e4cca1d238fa453744562bc679c7b3f6a3e | 39,273 |
import os
import logging
def checksum_from_label(path):
"""Extract checksum from a label rather than calculating it.
:param path: Product path
:type path: str
:return: MD5 Sum for the file indicated by path
:rtype: str
"""
checksum = ""
product_label = path.split(".")[0] + ".xml"
... | 69da6b07d091b0c296d09ec0d9a3d0586c34b978 | 39,274 |
def vvisegment2dict( link):
"""
Intern rutine for å gjøre om visveginfo-data til håndterbar liste
"""
start = round( float( link['FromMeasure'] ), 8 )
slutt = round( float( link['ToMeasure'] ), 8 )
mydict = { 'vegref' : str( link['County']).zfill(2) + str( link['Municipality'] ).zfill(2... | ad8c5de2065ee2e935b63674c7f4d11ba11bcff8 | 39,275 |
def pow_frac(T1, T2, freqs):
""" Fractional power between two physical temperatures """
return bb_pow_spec(freqs, T1) / bb_pow_spec(freqs, T2) | 036e40cac05ae0170ce0713bf10df61c77022820 | 39,276 |
import sys
def _generate_resources_cfg(ips: list = (), cpus: int = 4):
"""
Generates the resources.xml according to the given parameters.
:param ips: List of ip of the worker nodes.
:param cpus: Number of cores per worker node.
:returns: The cfg file contents for the resources.
"""
# ./gen... | a8fe7ebfc969020e6b864762e4034d069adc4f9b | 39,277 |
def setup_mongo() -> pymongo.collection.Collection:
"""Setup mongo client."""
client = pymongo.MongoClient("mongodb://localhost:27017/")
vdm_database = client["vdm"]
return vdm_database | 2224810aa635c6a7f1cd7b89b30594537a48dd8b | 39,278 |
def add_doub_doub(db1, db2, entityName):
"""
## This function adds two doubles
## Input : db1 - double (number)
: db2 - double (value)
"""
add = Add_of_double(entityName)
add.sin1.value = db1
add.sin2.value = db2
return add | e62fec9496afdd1eb7e4384758a6358d37882787 | 39,279 |
def build_dataset(nb_holograms, nb_file, nb_holograms_class, nb_class, hol_dataset_list):
"""
Build a large dataset with datataset with small datasets.
"""
# Create new dataset
nb_total = nb_holograms * nb_file
hol_dataset = np.zeros([200, 200, nb_total], dtype=complex)
init_list = np.aran... | e5f78fad9837f903bbb218431c45ca9d81d15085 | 39,280 |
def percentage(value):
"""Return a float with 1 point of precision and a percent sign."""
return format(value, ".1%") | 43567c120e4994b54a92570405c02934eb989a6f | 39,281 |
def PricingAddBondPricingDetails(builder, bondPricingDetails):
"""This method is deprecated. Please switch to AddBondPricingDetails."""
return AddBondPricingDetails(builder, bondPricingDetails) | 1278af0118f3d3f51c8879c450d2681e1e8e9746 | 39,282 |
def get_chunk_size(N, n):
"""Given a two-dimensional array with a dimension of size 'N',
determine the number of rows or columns that can fit into memory.
Parameters
----------
N : int
The size of one of the dimensions of a two-dimensional array.
n : int
The number of ar... | d4fb5abbd30a9fe1b1666555b0ac54baf20b8450 | 39,283 |
def get_peering_partner(peering):
"""
Inserts a new node of the type Peering partner and ensures that this node
is unique for AS number.
Returns the created node.
"""
try:
return PEER_AS_CACHE[peering['as_number']]
except KeyError:
logger.info('Peering Partner {name} not in c... | 15b4b896995026a0e837b51fb97319a3004d8c36 | 39,284 |
def get_v3_atlas_fine_path():
"""Get v3 atlas fine path.
Returns
-------
: pathlib.Path
v3 atlas fine path.
"""
return get_data_dir() / "ccfv3_atlas_fine.nrrd" | e9fc612838e20cb1908f7583e8ad9ca0cf2ae95e | 39,285 |
import traceback
def run_action(action, conv_list, params, return_dict):
"""
This method runs the specified action.
Args:
action(str): The action name, e.g., 'retrieval', 'qa', etc.
conv_list(list): List of util.msg.Message, each corresponding to a conversational message from / to the
... | 8db0fc99c346fbda1277f4aeb23c1a8d6a85561c | 39,286 |
def delete_comment(comment_id):
"""Delete an existing comment. For admins only."""
if current_user.roles.role_label != 'admin':
flash("Admin privileges required.", "danger")
return redirect("/")
if request.method == "POST":
comment = Comment.query.get_or_404(comment_id)
... | 51334b0a4ad558d572353d845714f5c657c7f343 | 39,287 |
def bfill(arr, dim=None, limit=None):
"""backfill missing values"""
axis = arr.get_axis_num(dim)
# work around for bottleneck 178
_limit = limit if limit is not None else arr.shape[axis]
return apply_ufunc(
_bfill,
arr,
dask="parallelized",
keep_attrs=True,
... | a3b019a04876e915447e25ca1b199cccfc99bdd2 | 39,288 |
def resource_descriptor(session, Type='String', RepCap='', AttrID=1050304, buffsize=2048, action=['Get', '']):
"""[Get/Set Resource Descriptor]
"""
return session, Type, RepCap, AttrID, buffsize, action | 4547d30bc7260236a5c1718847f7bc9574f27246 | 39,289 |
import os
def dbdirname(db, rc):
"""Gets the database dir name."""
dbsdir = os.path.join(rc.builddir, '_dbs')
dbdir = os.path.join(dbsdir, db['name'])
return dbdir | 87ac1ce28d3a0de8e22a3a29cfe48fb1005f2346 | 39,290 |
def delete_obj(patientid, objid):
"""
Get info of a doctor in the system.
:param doctorid: doctor's uid
:returns: a status, a str ( doctor's info on success, err info on failure)
"""
# print(doctorid)
info = {}
try:
resp_dict = {}
conn = swiftclient.client.Connection(co... | 031ab1afe63322ddbc218e6a22b9a181c6803628 | 39,291 |
def min_version_string():
"""Returns the minimum supported API version (as a string)"""
return _MIN_VERSION_STRING | 42f004759c5246d89613ab21397e64d4be76ad29 | 39,292 |
def coord_clip(pos, chrlen, binsize=128000, window_radius=16000000):
"""
Clip the coordinate to make sure that full window
centered at the coordinate to stay within chromosome boundaries.
coord_clip also try to preserve the relative position of the coordinate
to the grid as specified by binsize when... | 81acd78a417bc015eef71c29e0aa675aea9cf374 | 39,293 |
def get_peak_length(lc_table, peak_frac=0.75):
"""Returns peak length for given lightcurve table
"""
lc_filled = fill_lightcurve(lc_table)
peak = np.max(lc_table.flux)
mask = lc_filled[:, 1] > peak_frac*peak
time_slice = lc_filled[mask, 0]
return time_slice[-1] - time_slice[0] | 63d6b922811717e1da9ac3d5cb285a32eeeb5bbb | 39,294 |
from typing import List
from pathlib import Path
import re
def filter_files(path_list: List[Path]):
"""
Categorize paths into libraries or files
Libraries are resolved with the linker and are to be imported in a special
location. They can only be ELF files.
Files are referenced using their paths... | 228c92d8c442c8bdd98f1c6f4a138d89a5d184fe | 39,295 |
from typing import Counter
def get_collocations(relations):
"""
Calculate collocations based on the list of all relations in the corpus
input: list of all binary syntactic relations in the corpus (result of get_relations())
output: pandas DataFrame with all syntactic collocations and their llr scores
... | c6eada543761edc4b7d322e6cb780121c33b0a89 | 39,296 |
def prefix(expof10):
"""
Args:
expof10 : Exponent of a power of 10 associated with a SI unit
character.
Returns:
str : One of the characters in "yzafpnum kMGTPEZY".
"""
prefix_levels = (len(SI_PREFIX_UNITS) - 1) // 2
si_level = expof10 // 3
if abs(si_level) > ... | a66975bfaa93c31ad1de5e5f05b1807958c2784c | 39,297 |
def _Pick_CF3(st, cf3, iniPick, f=np.linspace(50, 1000, 20), tol=10e-3):
"""
input :
st - stream object
cf3 - characteristic function number 3
f - list of frequency (used instead of the Ns parameter)
tol - maximum time to move a pick
"""
sr = st.traces[0].stats['sampling_rate']
ST =... | 47c4ebb2f003e1f4c179ac463e7bb5f4c9ea993c | 39,298 |
def flatten_dims(tensor, start=0, end=None, name=None):
"""Flatten a contiguous range of dimensions in a tensor.
Args:
tensor: The tensor or array to reshape.
start: First dimension to flatten. An integer.
end: One past the last the last dimension to flatten.
An integer or `... | 5bf1a5f31630ea5dd5a55828fbe05f67453bce05 | 39,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.