content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def image_get_all(client, filters=None, marker=None, limit=None,
sort_key='created_at', sort_dir='desc',
member_status='accepted', is_public=None,
admin_as_user=False):
"""
Get all images that match zero or more filters.
:param filters: dict of filter k... | 1176b22dac3a45c3cd2ba3a33d52acb77710dfe0 | 33,700 |
import urllib
import json
def handleDBS(reqmgrOutDsets, cmswebUrl):
"""
Get total number of lumi sections in each dataset
"""
if 'testbed' in cmswebUrl:
dbsUrl = cmswebUrl + "/dbs/int/global/DBSReader/"
else:
dbsUrl = cmswebUrl + "/dbs/prod/global/DBSReader/"
dbsOutput = {}
... | 89dc385828ac042431fffb02c8c4201b5223ed4d | 33,701 |
def get_sub_folders(session, ds_browser, ds_path):
"""Return a set of subfolders for a path on a datastore.
If the path does not exist then an empty set is returned.
"""
search_task = session._call_method(
session._get_vim(),
"SearchDatastore_Task",
ds_browser,
... | e240973e4569208904ec6fcd3b7563ee213ca9e9 | 33,702 |
import requests
def stock_board_concept_cons_em(symbol: str = "车联网") -> pd.DataFrame:
"""
东方财富-沪深板块-概念板块-板块成份
http://quote.eastmoney.com/center/boardlist.html#boards-BK06551
:param symbol: 板块名称
:type symbol: str
:return: 板块成份
:rtype: pandas.DataFrame
"""
stock_board_concept_em_map ... | a3789c92a483b61504f4e98c0200d358e66a64b0 | 33,703 |
import torch
def jittered_center_crop(frames, box_extract, box_gt, search_area_factor, output_sz, masks=None):
""" For each frame in frames, extracts a square crop centered at box_extract, of area search_area_factor^2
times box_extract area. The extracted crops are then resized to output_sz. Further, the co-o... | 477bde7a6b1697ddf6fe2d1a3e2858b9cbdcd84b | 33,704 |
def bayesquad(fun, fun0, bounds, nevals=None, type="vanilla", **kwargs):
"""
One-dimensional Bayesian quadrature.
Parameters
----------
fun : function
Function to be integrated.
fun0 : RandomProcess
Stochastic process modelling the function to be integrated.
bounds : ndarray... | cd084d0ff8c34de5aadc98e56a4535e6d7d49f72 | 33,705 |
def track():
""" RESTful CRUD controller """
if deployment_settings.get_security_map() and not shn_has_role("MapAdmin"):
unauthorised()
resource = request.function
table = module + "_" + resource
# Model options
# used in multiple controllers, so defined in model
# CRUD Strings
... | 321f4cc50a4f8a08f1c49450f2269fd85113d83c | 33,706 |
import re
import logging
import os
import time
import random
def files_download(urls, referer=None, cookies=None, fileinfo=None):
"""
文件下载
:param urls: 文件连接[列表]
:return: 上传后的地址列表
"""
assert urls, "文件地址为空"
uploads_paths = []
local_paths = []
for url in urls:
if re.search(r"... | 98db1e73bc3d1d090baceb039595e7eebfceee3b | 33,707 |
def slice_or_index(index):
"""Return index or slice the array [:]."""
return slice(None) if index is None else index | 7bdf34a0667cfcc387c41bfcfc000d0881c3f6cd | 33,708 |
def get_driver():
"""Returns current driver."""
return _driver | 291543a22af57aa757641c7b77554dd3b1480e5b | 33,709 |
from matplotlib.pyplot import legend
def comparecf(clist1, clist2=None, shift=0., fac=1., ploterrbar=True, fill=False,
filtneg=False, label=None, plotratio=False, ratioxrange=None,
color1=None, marker1=None, markers1=None, linestyle1=None, linewidth1=None,
color2=None, mar... | 68ad46dfedbd7c539783f0566cdb469530be2dd5 | 33,710 |
import torch
def transform_points(trans_01, points_1):
"""
Function that applies transformations to a set of points.
"""
if not (trans_01.device == points_1.device and trans_01.dtype == points_1.dtype):
raise TypeError(
"Tensor must be in the same device and dtype. "
... | 739881cb0080cc69a53caf6a821dbf354319dec0 | 33,711 |
def insert(*entities, **options):
"""
bulk inserts the given entities.
note that entities must be from the same type.
:param BaseEntity entities: entities to be inserted.
:keyword int chunk_size: chunk size to insert values.
after each chunk, store will be committed.
... | 9ce71916232175be5878237e95263834edd6878c | 33,712 |
def batch_resample(X, new_dim, mode="bilinear"):
"""
Resample each image (or similar grid-based 2D signal) in a batch to
`new_dim` using the specified resampling strategy.
Parameters
----------
X : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, in_rows, in_cols, in_channels)`
An i... | ef8dc6c2c8d062b6da5254b770fe930f0fe33024 | 33,713 |
def register(request):
"""
Sets a session variable and redirects users to register for BCeID
"""
if settings.DEPLOYMENT_TYPE == 'localdev':
return render(request, 'localdev/register.html')
request.session['went_to_register'] = True
return redirect(settings.REGISTER_BCEID_URL) | 3d5487b9d6018079b1f6b9bd97050cb03164912c | 33,714 |
def get_bits(byte_size, number):
"""Returns last byte_size*8 bits from number."""
res = []
for i in range(byte_size * 8):
res.append(str(number % 2))
number //= 2
res.reverse()
return res | ad41d3c9f1192b2f7026caa0f42a084ea39c82fa | 33,715 |
import copy
def greedy_find_path(entrance, exits, corridors):
""" Find ANY path connecting input and output, """
print("corridors at start: ", corridors)
#max_flow = float("inf")
# Not the case.
#if entrance in exits:
# return 1/0
cur_pos = entrance
path = [entrance]
... | c47065d2d9e6913009cb4e41daf0730c7a04c3ef | 33,716 |
import time
def blacklist_chat(chat_id: int, reason: str):
"""
BLACKLIST A CHAT
"""
c.execute(
"""
UPDATE chats
SET blacklisted = 1
WHERE chat_id=?
""",
(chat_id,),
)
c.execute(
"""
INSERT
INTO reas... | 5c327c99787d52d8576a82f6deb3509525826759 | 33,717 |
from pathlib import Path
def load_artefacts_from_file(file_path: Path) -> Artefacts:
"""
Load an artefacts file.
Args:
file_path: path to the artefacts file
Returns:
the artefacts created from the given file
"""
documents = load_yaml(file_path)
version_header = VersionHea... | 699f5f980ebf8f61c02b53b1b9f10b2d29a782a7 | 33,718 |
def date(date):
"""Return a date object representing the ISO 8601 date.
:param date: The ISO 8601 date.
:return: boolean
"""
return runner(date, r.dates) | 15805363f017cfa3ab90ce4b6dab4ba38f7f1423 | 33,719 |
from typing import Optional
def get_mean_var(
array: np.ndarray,
axis: Optional[int] = None,
weights: Optional[np.ndarray] = None,
):
"""Calculate average and variance of an array."""
average = np.average(array, axis=axis, weights=weights)
variance = np.average((array - average) ** 2, axis=axi... | 8e023f09de922475d3acca51edf61947767047f5 | 33,720 |
import json
from networkx.readwrite import json_graph
def write_nxgraph_to_json(g, output):
"""
Write a networkx graph as JSON to the specified output
Args:
g (networkx.Graph): graph to write as JSON
output (filelike): output to write to
"""
jsond = json_graph.node_link_data(g)
... | a909fd3f4e8c87bb3fe059b310819570758c553e | 33,721 |
import random
def heterogeneous_length(chromosome, generator, probability):
"""Return a mutant made through point mutation that may grow or shrink.
In this scheme, mutated alleles will be replaced with a value provided by
calling ``generator``. It is suitable for use with list encoding. Be warned
tha... | f14a3ce8f3af5be674553a93bb60841766315cbd | 33,722 |
from typing import Optional
from typing import List
def clean_eisenhower(raw_eisen: Optional[List[str]]) -> List[str]:
"""Clean the raw Eisenhower values from Notion."""
if raw_eisen is None:
return []
return [e for e in raw_eisen if e != ''] | a8dd48a307455f20b8dd7afbf5b5aec1835c7a2d | 33,723 |
import struct
def binary(num):
"""
calculate R, G, B components from bytes number
:param num: int
:return: list
"""
packed = struct.pack('!f', num)
integers = [ord(c) for c in packed]
return integers | 02a98dea32ed4270c90d4c1377726b4f59b5136e | 33,724 |
def giou_loss(pred, target, eps=1e-6):
"""IoU loss.
Computing the IoU loss between a set of predicted bboxes and target bboxes.
The loss is calculated as negative log of IoU.
Args:
pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2),
shape (n, 4).
target (Tensor): Co... | a5432f9b7924887e0baca111f9a2ae8d1a92fd93 | 33,725 |
def raw(text):
"""Returns a raw string representation of text"""
new_string=''
for char in text:
try: new_string+=escape_dict[char]
except KeyError: new_string+=char
return new_string | b8cd0ad183f1fd1e38bff446feb3b89f3acceeab | 33,726 |
def queries_to_retract_from_unioned_dataset(project_id, dataset_id, sandbox_dataset_id, pid_table_id):
"""
Get list of queries to remove all records in all tables associated with supplied ids
:param project_id: identifies associated project
:param dataset_id: identifies associated dataset
:param sa... | 30f41725098a98cf1e8875d5769064e7c3183cbc | 33,727 |
from typing import List
import os
import glob
def from_waymo(
data_path: str,
output_dir: str,
save_images: bool = False,
use_lidar_labels: bool = False,
nproc: int = NPROC,
) -> List[Frame]:
"""Function converting Waymo data to Scalabel format."""
if not os.path.exists(output_dir):
... | 2934320cf93c5074846deba8ea84e15a825bf5d6 | 33,728 |
import os
def list_keys(key_prefix, n, marker=''):
"""
List keys that start with key_prefix (<> key_prefix itself)
@n = number of items to return
@marker = name of last item
"""
key_list = []
i = 0
for file in os.listdir(key_prefix):
key_list.append(os.path.join(key_prefix, fi... | 26b0d282ac745da523854e6a59773aa136fc54f3 | 33,729 |
def get_instance_type(entity_name, instance_dict=None):
"""
:param entity_name: name of an entity;
:param instance_dict: dictionary that contains the instance type of each entity;
:return: the instance type of the provided entity;
Get the instance type of a given entity, as specified by the ins... | 0fead313271ee8b2b0d7be0d8048d506657b4944 | 33,730 |
import traceback
def gather_doi (schol, graph, partition, pub):
"""
use `title_search()` across scholarly infrastructure APIs to
identify this publication's DOI, etc.
"""
title = pub["title"]
title_match = False
for api in [schol.crossref, schol.openaire, schol.europepmc]:
try:
... | d035444b269c7290271c917a42220425a356c88e | 33,731 |
def file_keyword(request):
"""Return multiple possible styles for the bumpsemver:file keyword."""
return request.param | 86700f811786a99b290557e9498bba03b800618d | 33,732 |
def get_compound(name):
"""Get a workspace compound by name as a dictionary"""
return get_object(name) | 390985cb25fe705b056788acd00b3519aa8ee2f4 | 33,733 |
import os
import json
def fake_pocket_response(scope="module") -> MagicMock: # pylint: disable=unused-argument
"""Get fake Pocket response."""
response = MagicMock()
fake_pocket_response_file = os.path.realpath(
os.path.join(os.path.dirname(DATA_FILE), '..', 'tests', 'data', 'pocket.json')
)... | 737522d4cd3c12c9d79bad9f939d020a63eba54e | 33,734 |
import dateutil
def parse_iso_date(date):
"""
Parses and returns a human-readable date from a ISO datetime.
Args:
date (string): ISO datetime.
Returns:
The date in a more human-readable format.
"""
if date is None:
return "an unknown time"
parsed = dateutil.parse... | 4647192d9db9bf21ffc102fe5e0d950ec1d6667b | 33,735 |
def deconvolve_tf(y: np.ndarray, x: np.ndarray,
C: np.ndarray,
kernel: np.ndarray, lam: float, gam: float,
n_iters: int = 200, k: int = 3,
natural: bool = True,
clip: bool = False) -> np.ndarray:
"""
Perform deconvolut... | 0515672baf18d497d64b7ace195ea308a3621b7d | 33,736 |
from typing import Tuple
def get_bounds(features: list) -> Tuple[np.array, np.array]:
"""Given a list of feature names, generate a numpy array
with the bounds for the optimization and the variable types.
Args:
features (list): List of feature names, following the convention
from the L... | 5e86095f4beb46d12e10d1f78fa9a39627498e4d | 33,737 |
def findNeighbors(g, r, c):
"""
Check all neighbors of cell at row r, column c in grid g to find the count
of all living neighbor cells
"""
nAlive = checkArray(g, r-1, c-1) + checkArray(g, r-1, c) + \
checkArray(g, r-1, c+1) + checkArray(g, r+1, c-1) + \
checkArray(g, r+1, c) + check... | 012f64900f165b98f93095828141b1e8b1a994d2 | 33,738 |
def summarize_results(warmup_rewards, rewards):
"""
Print a summary of running a Bandit algorithm for a number of runs
"""
warmup_reward = warmup_rewards.sum()
rewards = rewards.sum(axis=-1)
r_mean = rewards.mean()
r_std = rewards.std()
r_total = r_mean + warmup_reward
print(f"Expec... | 2a3b786fdc835d312fe826600f46f4ab7a7ccaa7 | 33,739 |
def extract_zone(zone_url):
"""Given zone URL (as in instance['zone']) returns zone name."""
zone = zone_url[zone_url.rfind('/')+1:]
assert is_valid_zone(zone), zone
return zone | 446a723edb9f1aba9a4f9273c8172b192b2d05d5 | 33,740 |
def forward_transfer_metrics(*, experience=False, stream=False):
"""
Helper method that can be used to obtain the desired set of
plugin metrics.
:param experience: If True, will return a metric able to log
the forward transfer on each evaluation experience.
:param stream: If True, will retu... | afd53bf92bc16775685369ec971322a9a72b1b70 | 33,741 |
def tail(f, lines=10):
""" Get the n last lines from file f """
if lines == 0:
return ""
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = lines + 1
block = -1
data = []
while size > 0 and bytes > 0:
if bytes - BUFSIZ > 0:
# Seek back one whole BUFSIZ
... | edd84be7bfa87cf3d21c785f08cbfaaee4eb029e | 33,742 |
def get_traffic_matrix(n, scale: float = 100, fixed_total: float = None) -> np.ndarray:
"""
Creates a traffic matrix of size n x n using the gravity model with independent exponential distributed weight vectors
:param n: size of network (# communication nodes)
:param scale: used for generating the expon... | 7de387a7b2d5ce4acb5d22d37240ec93c37a7bb6 | 33,743 |
def rectMask(size, corner=[0,0], dimensions=[0,0], channels=3):
"""
Create a mask in the shape of a (non-rotated) rectangle, in which the inside
of the rectangle is the desired region.
Parameters
----------
size : [int, int] or [int, int, int]
The size of the mask to be created (height... | cbeefbf45bc93d5c9de64a9fcc71be6189da828b | 33,744 |
def getCoursebycourseCredit(courseCredit):
"""
根据学分查询课程
"""
return generalGet('course', 0, 'courseCredit = \'{}\''.format(courseCredit)) | 4d8fb0f1c8f8bb7f0d70af1370b07783dd862f67 | 33,745 |
def main(brute_force=False, grid_width=3, sample_size=10000):
"""
:param brute_force: boolean - if True then grid width must be less than or equal to 3
:param grid_width: One dimension of a square grid - e.g. value of 3 = grid of 3x3
:param sample_size: sample size if using sampling - number of uni... | 25a67273e6a1982f93f15e004484a89c270414ce | 33,746 |
def get_E_beta_3(parameter, fid, did, N_data, N_flow):
"""
Predict the expected response for a set of combinations between different models and datasets
Parameters
----------
parameter: numpy.ndarray
The estimated parameters for the Beta-3 IRT model.
fid: numpy.ndarray
A (n_tes... | f6b2c5c7089b5df96f50f05fc24704b1c5d66780 | 33,747 |
import torch
def l1_gradient(x: torch.Tensor,
*,
zero_tol: float = 0.,
subgradient_samples: np.ndarray = None) -> torch.Tensor:
"""
Compute all the possible gradient of the 1-norm |x|₁
Notice that when x(i)=0, the 1-norm is non-differentiable. We consider
... | b7685dc9c5541e3e4286e6e6719220990f1f205f | 33,748 |
from datetime import datetime
from typing import cast
def _is_visible_with_salt(ra: Quantity, dec: Quantity, t: datetime) -> bool:
"""
Checks whether a target is visible by SALT.
Parameters
----------
ra: Quantity
Right ascension.
dec: Quantity
Declination.
t: datetime
... | 5148cfec973f0d76cbfe859263c4bcad61bcbc30 | 33,749 |
def sorted_date_list(df, col_collect: str):
"""
Builds a sorted list of every value for a date column in a given DataFrame
:param df: data to analyze
:param col_collect: column to analyze
:return: list
"""
try:
logger.info("Order Date List")
return sorted([x.operation_date fo... | d335b2979cf11101b362a1855a0b8bf09939a31b | 33,750 |
def get_tags(blog_id, username, password):
"""
wp.getTags(blog_id, username, password)
=> tag structure[]
"""
authenticate(username, password)
return [tag_structure(tag)
for tag in Tag.objects.usage_for_queryset(
Post.is_publish.all(), counts=True)] | 50445cc6014db2c4b600ae44a0292b569313d377 | 33,751 |
def add_scalebar(
ax, left, right, label, fontsize=15,
ax_y=-0.01,
):
"""
"""
ax.hlines(ax_y, left, right, color='k', linewidth=3,
transform=ax.get_xaxis_transform(),
clip_on=False,
)
ax.text(right, ax_y-0.01, label,
va='top', ha='rig... | 077d8a095c548085e1544050f1144bcb51f307b9 | 33,752 |
from functools import partial
from multiprocessing import pool
def mol_wt_from_smiles(smiles, workers=1):
"""
Calculate molecular weights for molecules represented by SMILES strings.
Args:
smiles (list or str): List of SMILES strings.
workers (int): Number of parallel threads to use for ... | 5017566a79a401262450f2032035014a52e87d8c | 33,753 |
import sys
def loadObject(self, name):
""" Loads a cPickle object """
try:
return cPickle.load(open(name))
except IOError:
print >> sys.stderr, name + " file could not be found!"
return None | 1b5f7d94d0329220046c6abf4ecee52633d5a3b1 | 33,754 |
def PolyArea(x, y):
"""Calculate area of polygon given (x,y) coordinates (Shoelace formula)
:param x: np.ndarray(N, )
:param y: np.ndarray(N, )
:return: area
"""
return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) | 23d17edc863cb2551fdf41cba96d71aa839ce073 | 33,755 |
def find_keyword(URL, title, keywords):
""" find keyword helper function of history_list """
for keyword in keywords:
# case insensitive
if len(keyword) > 0 and (URL is not None and keyword.lower() in URL.lower()) or (title is not None and keyword.lower() in title.lower()):
return T... | b956cc3744411a409a227cb80423dcf52ca9d248 | 33,756 |
def parsetypes(dtype):
"""
Parse the types from a structured numpy dtype object.
Return list of string representations of types from a structured numpy
dtype object, e.g. ['int', 'float', 'str'].
Used by :func:`tabular.io.saveSV` to write out type information in the
header.
**Parameters... | 6f373135f751b243104cc7222326d995048d7c93 | 33,757 |
import random
def random_flip(image):
"""50% chance to flip the image for some variation"""
if random.random() < 0.5:
image = cv2.flip(image, 1) # 1 = vertical flip
return image | 8e9898dd0a505f4db4a56e6cea8fa8631790e6c4 | 33,758 |
def sites_only(exclude_isoforms=False):
"""Return PhosphositePlus data as a flat list of proteins and sites.
Parameters
----------
exclude_isoforms : bool
Whether to exclude sites for protein isoforms. Default is False
(includes isoforms).
Returns
-------
list of tuples
... | b3c021e7e4332274c875b189b0f73f7ad3e43e0d | 33,759 |
def transform_url(url, qparams=None, **kwargs):
""" Modify url
:param url: url to transform (can be relative)
:param qparams: additional query params to add to end of url
:param kwargs: pieces of URL to modify - e.g. netloc=localhost:8000
:return: Modified URL
.. versionadded:: 3.2.0
"""
... | d19d5845e6ebe4d14579849ed937160dc71a0421 | 33,760 |
def coords_in_bbox(pose, bbox):
"""
Return coords normalized to interval's bbox as dict of np arrays. origin at box center, (.5, .5)
"""
x1, x2, y1, y2 = bbox
width = x2 - x1
height = y2 - y1
origin = np.array([x1, y1])
scale = np.array([width, height])
normalized_pose = {}
for j... | 96f98fe26bff8095311966fc640f887464c7cd4f | 33,761 |
def display_instances(image, boxes, masks, ids, names, scores):
"""
take the image and results and apply the mask, box, and Label
"""
n_instances = boxes.shape[0]
colors = random_colors(n_instances)
if not n_instances:
print('NO INSTANCES TO DISPLAY')
else:
assert boxes.... | 60bdc9b8500dc0004837a630c72c361204820328 | 33,762 |
import os
from bs4 import BeautifulSoup
def scrape_page(url):
"""
Given a URL, it adds in the database all the links contained in that web page.
:param url: A string containing the URL of the web page to analyse.
:return: None.
"""
print(f"{get_time()} [SELENIUM] Page rendering started.")
... | 19d770c51a6524bb8b6ccffc950a5f2052c6c7e8 | 33,763 |
def _find_xy(ll, T, M, maxiter, atol, rtol, low_path):
"""Computes all x, y for given number of revolutions."""
# For abs(ll) == 1 the derivative is not continuous
assert abs(ll) < 1
M_max = np.floor(T / pi)
T_00 = np.arccos(ll) + ll * np.sqrt(1 - ll ** 2) # T_xM
# Refine maximum number of re... | 09bfe02e08e7b9975f65a99cb1e706ba96ed71f9 | 33,764 |
def ligne_vivante(ligne, x_1, x_2):
""" Retourne un booléen indiquant si la ligne spécifiée contient au moins une cellule vivante """
for colonne in range(x_1, x_2 + 1):
if plateau[ligne][colonne] != CELLULE_MORTE:
return True
return False | db9be50c14458eb11ee853d15fe5997ea857d55a | 33,765 |
def changeMatchingReciprocity(G, i, j):
"""
change statistic for categorical matching reciprocity
"""
return G.catattr[i] == G.catattr[j] and G.isArc(j, i) | 30ece553661b71e8cb2674d88b0daa4905dd9039 | 33,766 |
def compare_letters(letter1, letter2, table=ambiguity_code_to_nt_set):
"""Compare two extended nucleotide letters and return True if they match"""
set1 = table[letter1]
set2 = table[letter2]
if set1 & set2 != set():
is_match = True
else:
is_match = False
return is_match | 190d00cb52890e52f58e07192227f9af7173ee35 | 33,767 |
import numpy as np
def get_swarm_yspans(coll, round_result=False, decimals=12):
"""
Given a matplotlib Collection, will obtain the y spans
for the collection. Will return None if this fails.
Modified from `get_swarm_spans` in plot_tools.py.
"""
_, y = np.array(coll.get_offsets()).T
try:
... | 2561f04243e63dfa87896e891ae337ab9be310a7 | 33,768 |
def secondes(heure):
"""Prend une heure au format `H:M:S` et renvoie le nombre de secondes
correspondantes (entier).
On suppose que l'heure est bien formattée. On aura toujours un nombre
d'heures valide, un nombre de minutes valide et un nombre de secondes valide.
"""
H, M, S = heure.split(":")... | 33d380005479d66041e747130a4451c555baf497 | 33,769 |
def central_crop(image, crop_height, crop_width, channels=3):
"""Performs central crops of the given image list.
Args:
image: a 3-D image tensor
crop_height: the height of the image following the crop.
crop_width: the width of the image following the crop.
Returns:
3-D tensor with ... | fc9ad33ad5fc9150a299328fb3c77bb662c25339 | 33,770 |
import enum
def mapper_or_checker(container):
"""Callable to map the function parameter values.
Parameters
----------
container : dict-like object
Raises
------
TypeError
If the unit argument cannot be interpreted.
Example
-------
>>> conv = mapper_or_checker({True: ... | 7c8b22fd3ef7fa52b7ebb94f7d5b5fda48a1a683 | 33,771 |
def cmd_konesyntees(bot, update, args):
"""Use superior estonian technology to express your feelings like you've never before!"""
chatid = update.message.chat_id
text = ''
for x in args:
text += f'{x} '
try:
tts = gTTS(text=text, lang='et')
tts.save('bot/konesyntees/konesynt... | 368ebd43191c219f4f0d7b3b362bb94d117d238e | 33,772 |
import os
import urllib
import subprocess
def download_file(filename_with_path, url, use_curl=False, overwrite=False):
"""
downloads a file from any URL
:param filename_with_path:
filename with path to download file to
:type filename_with_path: ``str``
:param url:
URL to download... | da92dac8757c96aa03b8c6590e76873a6e87c64b | 33,773 |
def tinynet_a(pretrained=False, **kwargs):
""" TinyNet """
r, c, d = TINYNET_CFG['a']
default_cfg = default_cfgs['tinynet_a']
assert default_cfg['input_size'] == (3, 224, 224)
channel, height, width = default_cfg['input_size']
height = int(r * height)
width = int(r * width)
default_cfg[... | 08bb62c45f8ed5b3eab3ec3ad2aab2d0bcb917ea | 33,774 |
import requests
def reserve_offer_request(offer_id: int, adult_count: int, children_count: int):
"""
Request order offer
"""
# call to API Gateway for getting offers
response = requests.post(
ORDER_RESERVE_REQUEST_ENDPOINT,
data={
"offer_id": offer_id,
"cust... | d3c2b1d62c7f64229dfbce3b0688f135b0c8ca1a | 33,775 |
def evaluate_nccl(baseline: dict, results: dict, failures: int,
tolerance: int) -> int:
"""
Evaluate the NCCL test results against the baseline.
Determine if the NCCL test results meet the expected threshold and display
the outcome with appropriate units.
Parameters
---------... | 3fdf3d75def46f98f971a1740f397db0b786fd7c | 33,776 |
def calculate_AUC(x_axis, y_axis):
"""
Calculates the Area Under Curve (AUC) for the supplied x/y values.
It is assumed that the x axis data is either monotonoically increasing or decreasing
Input:
x_axis: List/numpy array of values
y_axis: list/numpy array of values
Output:
... | fa474fd210ee9bb86738e9f93795dd580680c2db | 33,777 |
def bisec_method(func, tol=0.01, lo=None, up=None, debug=False, flex_up=False,
increasing=None):
# TODO-doc TODO-PW
"""
Execute the bisection method to find a root of func.
Parameters
----------
func: function-handle
the function
tol: float or tuple
the erro... | 8013faa1f5d1ff3e8ec2ea71f406d9c58ba18806 | 33,778 |
def next_nibble(term, nibble, head, worm):
"""
Provide the next nibble.
continuously generate a random new nibble so long as the current nibble hits any location of the
worm. Otherwise, return a nibble of the same location and value as provided.
"""
loc, val = nibble.location, nibble.value
... | a8861672b0dcc22e5aad2736d87a50f31eb0b864 | 33,779 |
def line_pattern_matrix(wl, wlc, depth, weight, vels):
"""
Function to calculate the line pattern matrix M given in Eq (4) of paper
Donati et al. (1997), MNRAS 291, 658-682
:param wl: numpy array (1D), input wavelength data (size n = spectrum size)
:param wlc: numpy array (1D), central wavelengths ... | fc5e50000ccbd7cad539e7ee2acd5767dd81c8be | 33,780 |
def pandas_join_string_list(row, field, sep=";"):
""" This function checks if the value for field in the row is a list. If so,
it is replaced by a string in which each value is separated by the
given separator.
Args:
row (pd.Series or similar): the row to check
field... | dd185fc0aad5a6247f8ea3280b18a3c910fbd723 | 33,781 |
def OpenClipboardCautious(nToTry=4, waiting_time=0.1):
"""sometimes, wait a little before you can open the clipboard...
"""
for i in range(nToTry):
try:
win32clipboard.OpenClipboard()
except:
time.sleep(waiting_time)
continue
else:
wait... | ac67eb130b2564508eb5b77176736df06032dd9b | 33,782 |
def data_change_url_to_name(subject_data: tuple, column_name: str) -> tuple:
""" Changes names instead of urls in cell data (later displayed on the buttons). """
return tuple(dh.change_url_to_name(list(subject_data), column_name)) | 43030eab85d087c6c09b7154342e60e90f97b28f | 33,783 |
from datetime import datetime
import requests
def get_run_ids(release_id, request_url, auth_token):
"""
Get the test run IDs for the given release ID - each feature will have a unique run ID
:param release_id: the release ID from Azure DevOps
:param request_url: the URL for the Microsoft API
:para... | ee8d99fbe0bdc1a937e889f5184bc854a21ab2a7 | 33,784 |
def operGet(fn):
""" this is Decoration method get opearte """
def _new(self, *args, **kws):
try:
obj = args[0]
#print obj.id
if hasattr(obj, "id") or hasattr(obj, "_id"):
key = operKey(obj, self.name)
args = args[1:]
k... | 8395496d99fc4e88599c77a30836c1d49944240d | 33,785 |
def latent_iterative_pca(layer, batch, conv_method: str = 'median'):
"""Get NxN matrix of principal components sorted in descending order from `layer_history`
Args:
layer_history : list, layer outputs during training
Returns:
eig_vals : numpy.ndarray of absolute value of eigenvalues, s... | 320408f3eec33075e808b9c92de951b7bc30c6ae | 33,786 |
import scipy
def filter_max(data,s=(1,1),m="wrap",c=0.0):
"""
Apply maximum filter to data (real and imaginary seperately)
Parameters:
* data Array of spectral data.
* s tuple defining shape or size taken for each step of the filter.
* m Defines how edges are determinded ('reflect',... | 2e701d2751f394e5a1d25355a8c5b4533972d92d | 33,787 |
def update_alarms(_):
"""
Entry point for the CloudWatch scheduled task to discover and cache services.
"""
return periodic_handlers.update_alarms() | 9e5f9bf94ed051194e502524420a0e47ac7e75f2 | 33,788 |
def price_to_sales(asset: Asset, period: str, period_direction: FundamentalMetricPeriodDirection,
*, source: str = None, real_time: bool = False) -> Series:
"""
Price to Sales of the single stock or the asset-weighted average value of a composite's underliers.
1y forward: time-weighted a... | d5176db94740465feb2adad60c454de3728ad848 | 33,789 |
def create_mapping(alphabet):
"""
Change list of chars to list of ints, taking sequencial natural numbers
:param alphabet: list of char
:return: dictionary with keys that are letters from alphabet and ints as values
"""
mapping = {}
for (letter, i) in zip(alphabet, range(len(alphabet))):
... | 20ef12101597206e08ca0ea399d97af0f5c8b760 | 33,790 |
import subprocess
import sys
def check_config(content):
"""checks if config contains valid service names - runs systemctl --all --type service and saves it to an array \\
also appends .service if it's missing"""
valid_process_names = []
command = "systemctl --all --type service"
try:... | 805007c4ed5b158b29c5c07b9d67a90e31dab54a | 33,791 |
async def async_setup_entry(hass, config_entry, async_add_devices):
"""Set up the Alexa alarm control panel platform by config_entry."""
return await async_setup_platform(
hass, config_entry.data, async_add_devices, discovery_info=None
) | 0a80a5d9e2cd5ff8e39200def1d86f30cdc552aa | 33,792 |
def admin_get_all_requests(current_user):
"""Gets all requests"""
requests = admin_get_all(current_user['id'])
return jsonify(requests),200 | a3e7202e73894ab05a4575f98460d1b012c0243e | 33,793 |
import json
def git_drv_info(url, version):
"""
Retrieve the necessary git info to create a nix expression using `fetchgit`.
"""
rev = []
if version != "master":
rev = ["--rev", version]
ret = run_cmd(
["nix-prefetch-git", "--no-deepClone", "--quiet", "--url", url,] + rev
... | d08d40da42fa24c3f50ac2069d8a4b73b4d09b37 | 33,794 |
import colorsys
import random
def draw_bbox(image, bboxes, classes):
"""
[[[original function from Yun-Yuan: bboxes: [x_min, y_min, x_max, y_max, probability, cls_id] format coordinates.]]]
bboxes: [cls_id, probability, x_min, y_min, x_max, y_max] format coordinates.]
"""
num_classes = len(classe... | 8f479e8ed5ecef60195df5edc82c2b0e2c3e261c | 33,795 |
def is_admin(user):
""" Test if a user has the admin group.
This function is meant to be used by the user_passes_test decorator to control access
to views. It uses the is_member function with a predefined list of groups.
Parameters
----------
user : django.contrib.auth.models.User
The ... | 044550ec2f3aaf8f748fb823b64ba1fb099f71fd | 33,796 |
import time
import pickle
import marshal
import msgpack
import os
import json
def testJSON():
"""
Compressing structured text dictionaries is a test case where we expect
compression to have a big impact.
This requires a 'sample.json' file which is not included in the distribution.
I recommen... | b74970a86db78c44dc92354e33d12767f7445f2e | 33,797 |
def Grid(gridtype, *args, **kwargs):
"""Return an instance of the GridBase child class based on type.
Parameters
----------
gridtype : string
Type of grid;
choices: ['cell-centered', 'x-face', 'y-face'].
var_names : list of strings
List of names for the variables to crea... | 29fc912d7cfece5a290950eb9925e99001c8a231 | 33,798 |
def read_tess_lightcurve(filename,
flux_column="pdcsap_flux",
quality_bitmask="default"):
"""Returns a `TessLightCurve`.
Parameters
----------
filename : str
Local path or remote url of a Kepler light curve FITS file.
flux_column : 'pdcsap_f... | 85dec44f2bab3724e5201110d1ec48c283468843 | 33,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.