content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from pathlib import Path
import os
import logging
def mnist_10K_cluster(dataset_dir: Path) -> bool:
"""
Abstract:
The MNIST database of handwritten digits with 784 features.
It can be split in a training set of the first 60,000 examples,
and a test set of 10,000 examples
Source:
Yann LeCun... | 1500387fca6b8b6528fb391649567fa8fe616197 | 3,652,500 |
def molefraction_2_pptv(n):
"""Convert mixing ratio units from mole fraction to parts per
thousand by volume (pptv)
INPUTS
n: mole fraction (moles per mole air)
OUTPUTS
q: mixing ratio in parts per trillion by volume (pptv)
"""
# - start with COS mixing ratio n as mole fraction:
# ... | a6a26267f45fb70c346e86421c427bd155bfa65a | 3,652,501 |
import warnings
def is_valid_y(y, warning=False, throw=False, name=None):
"""
"""
y = np.asarray(y, order='c')
valid = True
try:
if len(y.shape) != 1:
if name:
raise ValueError(('Condensed distance matrix \'%s\' must '
'have sha... | 6c3f56c8b931b325d521805902b526054f21e22d | 3,652,502 |
import json
import yaml
def yaml_parse(yamlstr):
"""Parse a yaml string"""
try:
# PyYAML doesn't support json as well as it should, so if the input
# is actually just json it is better to parse it with the standard
# json parser.
return json.loads(yamlstr)
except ValueError... | 8586e1e39ae9f0933b6552531d72cb3a6516f615 | 3,652,503 |
import collections
def csl_item_from_pubmed_article(article):
"""
article is a PubmedArticle xml element tree
https://github.com/citation-style-language/schema/blob/master/csl-data.json
"""
csl_item = collections.OrderedDict()
if not article.find("MedlineCitation/Article"):
raise Not... | 889bb8bbbafd85607936db7caeb33140c4e356fb | 3,652,504 |
import dateutil
def image(resource: celtypes.MapType) -> celtypes.Value:
"""
Reach into C7N to get the image details for this EC2 or ASG resource.
Minimally, the creation date is transformed into a CEL timestamp.
We may want to slightly generalize this to json_to_cell() the entire Image object.
... | f5125f6b5afb070d7aa7767a4acdb4afc82c90b8 | 3,652,505 |
def unphase_uvw(ra, dec, uvw):
"""
Calculate unphased uvws/positions from phased ones in an icrs or gcrs frame.
This code expects phased uvws or positions in the same frame that ra/dec
are in (e.g. icrs or gcrs) and returns unphased ones in the same frame.
Parameters
----------
ra : float
... | a6e3d1371ed612bd1ece08fc6fabd4ee77241603 | 3,652,506 |
import uuid
def sender_msg_to_array(msg):
"""
Parse a list argument as returned by L{array_to_msg} function of this
module, and returns the numpy array contained in the message body.
@param msg: a list as returned by L{array_to_msg} function
@rtype: numpy.ndarray
@return: The numpy array conta... | c959a535a4f47c86f9520167fa59dc8eecc70071 | 3,652,507 |
def find_shortest_path(node):
"""Finds shortest path from node to it's neighbors"""
next_node,next_min_cost=node.get_min_cost_neighbor()
if str(next_node)!=str(node):
return find_shortest_path(next_node)
else:
return node | 4fa3979ff665b5cf8df423ff9b3fbaa880d62a73 | 3,652,508 |
from .features import Sequence, get_nested_type
def cast_array_to_feature(array: pa.Array, feature: "FeatureType", allow_number_to_str=True):
"""Cast an array to the arrow type that corresponds to the requested feature type.
For custom features like Audio or Image, it takes into account the "cast_storage" met... | 28c3275445a79e869b8dfe5ec49522ff10ca6842 | 3,652,509 |
def check_key_match(config_name):
"""
Check key matches
@param config_name: Name of WG interface
@type config_name: str
@return: Return dictionary with status
"""
data = request.get_json()
private_key = data['private_key']
public_key = data['public_key']
return jsonify(f_check_k... | 00a3e78e403a54b16558e21e2c6d095560f272d0 | 3,652,510 |
def delete_user_group(request, group_id, *args, **kwargs):
"""This one is not really deleting the group object, rather setting the active status
to False (delete) which can be later restored (undelete) )"""
try:
hydroshare.set_group_active_status(request.user, group_id, False)
messages.succe... | acad59484befdc5448031343aad47989e9c67d64 | 3,652,511 |
from typing import List
def _generate_room_square(dungen: DungeonGenerator, room_data: RoomConceptData) -> RoomConcept:
"""
Generate a square-shaped room.
"""
map_width = dungen.map_data.width
map_height = dungen.map_data.height
# ensure not bigger than the map
room_width = min(dungen.rng... | d147f64aed8491ce9b4714f61b64f971683d913e | 3,652,512 |
import json
import os
import torch
def query(request):
"""
响应前端返回的数据并进行相应的推荐
:param request:
:return:
"""
content = {}
if request.method=='POST':
datatype = json.loads(request.body.decode('utf-8')) #得到前端返回的数据
province_all = datatype['all']
current_loc = datatype['cu... | c44b9d18d564dca1b544429b8d4dba1a7ab8a568 | 3,652,513 |
def str_is_float(value):
"""Test if a string can be parsed into a float.
:returns: True or False
"""
try:
_ = float(value)
return True
except ValueError:
return False | 08f2e30f134479137052fd821e53e050375cd11e | 3,652,514 |
import sys
from pathlib import Path
import os
import requests
import fnmatch
import tempfile
import shutil
import json
def get_from_cache(url, cache_dir=None, force_download=False, proxies=None, etag_timeout=10, resume_download=False):
#for bert-based-uncased, url is https://s3.amazonaws.com/models.huggingface.co... | d2c52e32bf344ccc4466478f15418e954bbf35db | 3,652,515 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Ruckus Unleashed from a config entry."""
try:
ruckus = await hass.async_add_executor_job(
Ruckus,
entry.data[CONF_HOST],
entry.data[CONF_USERNAME],
entry.data[CONF_PASS... | 567af55b3f46c2b5e2ef5204dbe85fabb87c9a74 | 3,652,516 |
def get_user_plugins_grouped(get_allowed_plugin_uids_func,
get_registered_plugins_grouped_func,
registry,
user,
sort_items=True):
"""Get user plugins grouped.
:param callable get_allowed_plugin_u... | f355738b99f503568a35945e1008f84145569b62 | 3,652,517 |
def calc_randnm7(reg_dict, mlx75027):
"""
Calculate the RANDMN7 register value
Parameters
----------
reg_dict : dict
The dictionary that contains all the register information
mlx75027 : bool
Set to True if using the MLX75027 sensor, False
if using the MLX75026 sensor.... | 898c4662f045fbcbe655870a8d5642de92debcaf | 3,652,518 |
def get_orientation(pose, ori):
"""Generate an orientation vector from yaw/pitch/roll angles in radians."""
yaw, pitch, roll = pose
c1 = np.cos(-yaw)
s1 = np.sin(-yaw)
c2 = np.cos(-pitch)
s2 = np.sin(-pitch)
c3 = np.cos(-roll)
s3 = np.sin(-roll)
Ryaw = np.array([[c1, s1, 0], [-s1, c1... | d00cc9befde7afd28b66c572116fb1234e109367 | 3,652,519 |
import copy
def draw_deformation(source_image, grid, grid_size = 12):
"""
source_image: PIL image object
sample_grid: the sampling grid
grid_size: the size of drawing grid
"""
im = copy.deepcopy(source_image)
d = ImageDraw.Draw(im)
H,W = source_image.size
dist =int(H/grid_size)
... | ec9c6b90e89221789ecba55e2c2360ccd24f9c8c | 3,652,520 |
def dial_socket(host='localhost', port):
"""
Connect to the socket created by the
server instance on specified host and port
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
return sock | 555c90f05cdf0feda97d5db160dd048542e03376 | 3,652,521 |
def analyseClassificationCoefficients(X: pd.DataFrame,
y: pd.Series,
D_learning_results: pd.DataFrame,
outputPath: str) -> dict:
"""
This function evaluates the importance coefficients of the input ... | 2e6a1e4e05d505ab5e43c638810fc23a6b11a228 | 3,652,522 |
def centerfreq_to_bandnum(center_freq, norm_freq, nth_oct):
"""Returns band number from given center frequency."""
return nth_oct * np.log2(center_freq / norm_freq) | 857b9b2598981ba608c958c8acce35a1e71d021f | 3,652,523 |
from typing import Union
from typing import Sequence
from typing import Optional
def crossval_model(
estimator: BaseEstimator,
X: pd.DataFrame,
y: Union[pd.Series, pd.DataFrame],
evaluators: Sequence[Evaluator],
cv: Optional[
Union[int, BaseCrossValidator]
] = None, # defaults to KFol... | 49c95241ed04c248221c6366cde717e575f5f7c1 | 3,652,524 |
import time
def measure_dist(positions,weights,v_ref,side = False):
"""
Will plot the mouse and allow me to click and measure with two clicks
side is false (so top view)
but can be True, then it's cut though the major axis of hte mouse (determined by v_reference)
"""
# simplest trick is to jus... | 4d67344b0df64d3721d87803772c8aad15936fd9 | 3,652,525 |
def _get_draft_comments(request, issue, preview=False):
"""Helper to return objects to put() and a list of draft comments.
If preview is True, the list of objects to put() is empty to avoid changes
to the datastore.
Args:
request: Django Request object.
issue: Issue instance.
preview: Preview flag... | affea5c09e42283057d70d7d1ce9f931d373d90d | 3,652,526 |
def activate_model(cfg):
"""Activate the dynamic parts."""
cfg["fake"] = cfg["fake"]()
return cfg | df8b0a23dc683435c1379e57bc9fd98149876d9d | 3,652,527 |
def convert_to_number(string):
"""
Tries to cast input into an integer number, returning the
number if successful and returning False otherwise.
"""
try:
number = int(string)
return number
except:
return False | 30110377077357d3e7d45cac4c106f5dc9349edd | 3,652,528 |
def _ts_value(position, counts, exposure, background, kernel, norm, flux_estimator):
"""Compute TS value at a given pixel position.
Uses approach described in Stewart (2009).
Parameters
----------
position : tuple (i, j)
Pixel position.
counts : `~numpy.ndarray`
Counts image
... | 5a53a408205e5aecf0b2035efbc3feb33097e46c | 3,652,529 |
from typing import List
def mean(nums: List) -> float:
"""
Find mean of a list of numbers.
Wiki: https://en.wikipedia.org/wiki/Mean
>>> mean([3, 6, 9, 12, 15, 18, 21])
12.0
>>> mean([5, 10, 15, 20, 25, 30, 35])
20.0
>>> mean([1, 2, 3, 4, 5, 6, 7, 8])
4.5
>>> mean([])
Trace... | 3c802b4967f646b6338e52b4ce12977274054c15 | 3,652,530 |
import scipy
def post_3d(post_paths, labels, colours, linestyles, contour_levels_sig, x_label=None, y_label=None, z_label=None,
x_lims=None, y_lims=None, z_lims=None, smooth_xy=None, smooth_xz=None, smooth_yz=None, smooth_x=None,
smooth_y=None, smooth_z=None, print_areas=False, save_path=None)... | 5e25de6f69a7d281e59ac1423b6be4b27080a689 | 3,652,531 |
def det(m1: ndarray) -> float:
"""
Compute the determinant of a double precision 3x3 matrix.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/det_c.html
:param m1: Matrix whose determinant is to be found.
:return: The determinant of the matrix.
"""
m1 = stypes.to_double_matrix(m1)
... | aa0a6629536df22ea016bb81a8e62769c7b3ab9e | 3,652,532 |
def path_to_xy(path: PointList) -> XYList:
"""Convert PointList to XYList"""
return [p.xy() for p in path] | ea8cc222ab2b8ce6634e9bb1ea7d456bfa451782 | 3,652,533 |
def diff(source: list):
"""
Compute the first-order discrete differences for a 1-dimensional list.
TODO: Support higher orders and dimensions as required.
"""
result = []
for index in range(1, len(source)):
result.append(source[index] - source[index - 1])
return result | e3773ca911130f4d1a2c70e43cb72b7b831e242a | 3,652,534 |
def is_gzip(name):
"""Return True if the name indicates that the file is compressed with
gzip."""
return name.endswith(".gz") | a6ea06f04808a07c4b26338f87273986eda86ef1 | 3,652,535 |
from os.path import exists, abspath, join
from os import pathsep, environ
def _search_on_path(filenames):
"""Find file on system path."""
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52224
search_path = environ["PATH"]
paths = search_path.split(pathsep)
for path in paths:
f... | c611797ce121c4dc9ecd01d0fafa5c74a38725a5 | 3,652,536 |
def possible_sums_of(numbers: list) -> list:
"""Compute all possible sums of numbers excluding self."""
possible_sums = []
for idx, nr_0 in enumerate(numbers[:-1]):
for nr_1 in numbers[idx + 1:]:
possible_sums.append(nr_0 + nr_1)
return possible_sums | 39ebe3e48c45a9c30f16b43e6c34778c5e813940 | 3,652,537 |
def normalize_norms(X, scale_factor=1, axis=0, by='sum'):
""" wrapper of `normalize_colsum` and `normalize_rowsum`
Parameters
----------
X:
a (sparse) matrix
scale_factor: numeric, None
if None, use the median of sum level as the scaling factor.
axis: int, {0, 1}
if axis... | 7c491245fc83b2b48c21cb91f79915af7261f5ba | 3,652,538 |
def full_solution(combined, prob_dists):
"""
combined: (w, n-1->n-w, 3, 3)
prob_dists: (n, 3, total_reads)
p[v,g,k] = prob of observing k of total_reads on ref if gneotype ig on varaint v
"""
N = len(combined[0])+1
best_idx, best_score = np.empty(N), -np.inf*np.ones(N)
for j, counts in e... | 2732c57e44aa0c17bd652b01226053c095d9fdb3 | 3,652,539 |
def ycbcr2bgr(img):
"""Convert a YCbCr image to BGR image.
The bgr version of ycbcr2rgb.
It implements the ITU-R BT.601 conversion for standard-definition
television. See more details in
https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.
It differs from a similar function in cv2.cvtCol... | e5e5c408e40645ae4844635fd0fbf065746f187d | 3,652,540 |
from datetime import datetime
def tensorize_fg_coeffs(
data,
wgts,
fg_model_comps,
notebook_progressbar=False,
verbose=False,
):
"""Initialize foreground coefficient tensors from uvdata and modeling component dictionaries.
Parameters
----------
data: list
list of tf.Tenso... | dbff52b154326df6a324ef454887c65bfe528044 | 3,652,541 |
def receive_incoming_bets():
"""
Sends fixtures to the front-end
"""
return fixtures.fixtures_information | 2ab61c0bc15bb9c8c4359bb8ca7e8b1287b1d182 | 3,652,542 |
def fibonacci(n):
"""
object: fibonacci(n) returns the first n Fibonacci numbers in a list
input: n- the number used to calculate the fibonacci list
return: retList- the fibonacci list
"""
if type(n) != int:
print(n)
print(":input not an integer")
return False
if... | ac37d952eecae57b33fb3768f1c8097d76769534 | 3,652,543 |
def psnr_batch(_mse_batch_val):
"""
:param _mse_val_each: ndarray
:return: ndarray
Usage:
1) The Bath is deal with channel.
Thus, it is recommended to call mse_batch function before the psnr_batch function.
2) cumsum_psnr_rgb += (metric_.psnr_batch(_mse_batch_val=... | c33eaa3e04fbd7d9749ad8989a15ea198ff4d806 | 3,652,544 |
def get_u0(u0_type, num_features):
"""return a polyhedral definition for U^0, B_mat and b_vec"""
assert u0_type in ["box", "positive_normed"]
if u0_type == "box":
B_mat, b_vec = U0_box(num_features)
if u0_type == "positive_normed":
B_mat, b_vec = U0_positive_normed(num_features)
r... | bb6856284067ac3d5b39ca50d30c5745a7ee5e07 | 3,652,545 |
def funcparser_callable_search_list(*args, caller=None, access="control", **kwargs):
"""
Usage: $objlist(#123)
Legacy alias for search with a return_list=True kwarg preset.
"""
return funcparser_callable_search(*args, caller=caller, access=access,
return_list=... | 511bff6803ba9b088fa94d32e9cb3f85c4823b94 | 3,652,546 |
def upcoming_movie_name(soup):
"""
Extracts the list of movies from BeautifulSoup object.
:param soup: BeautifulSoup object containing the html content.
:return: list of movie names
"""
movie_names = []
movie_name_tag = soup.find_all('h4')
for _movie in movie_name_tag:
_movie_result = _movie.find_all('a')
t... | 6bac06375109ec103492a079746e2c0364bfac17 | 3,652,547 |
def options(*args, **kw):
"""Mark the decorated function as a handler for OPTIONS requests."""
return _make_handler_decorator('OPTIONS', *args, **kw) | 21e6f830e054a84cd16e5cdfbb63c2202ff70d7b | 3,652,548 |
import codecs
import json
def lookup_vendor_name(mac_address):
"""
Translates the returned mac-address to a vendor
"""
url = "http://macvendors.co/api/%s" % mac_address
request = urllib2.Request(url, headers={'User-Agent': "API Browser"})
try:
response = urllib2.urlopen(request)
... | ad854390256c87c537b1d8e4e8906b3b3d0b10bd | 3,652,549 |
def train_on(text):
""" Return a dictionary whose keys are alle the tuple of len PREFIX
of consecutive words inside text, and whose value is the list of
every single word which follows that tuple inside the text. For ex:
{('Happy', 'birthday'): ['to', 'dear'] ...} """
words = text.split()
assert... | 40230bbb346cb4c98d6694fb0d18652e7d6bd4e7 | 3,652,550 |
def learning_rate_decay(alpha, decay_rate, global_step, decay_step):
"""learning_rate_decay: updates the learning rate using
inverse time decay in numpy
Args:
alpha : is the original learning rate
decay_rate : is the weight used to determine the
r... | a98f893acc7f14dafcf2dea551df4eb44da07bc4 | 3,652,551 |
def update_studio(request):
"""updates the studio
"""
studio_id = request.params.get('studio_id')
studio = Studio.query.filter_by(id=studio_id).first()
name = request.params.get('name', None)
dwh = request.params.get('dwh', None)
wh_mon_start = get_time(request, 'mon_start')
wh_mon_end... | 2fbdcbd04bb0ec7d0b2f5790e59e9211c831066f | 3,652,552 |
def flip_coin(num_of_experiments = 1000, num_of_flips = 30):
"""
Flip the coin `num_of_flips` times and repeat this experiment `num_of_experiments` times. And
return the number of heads grouped together in all the experiments.
"""
all_heads = []
for i in range(num_of_experiments):
heads ... | 24ccd52693233f93f5c0bb7bb4f09220e86f320c | 3,652,553 |
from pathlib import Path
def get_questions(
path: str,
uid2idx: dict = None,
path_data: Path = None,
) -> po.DataFrame:
"""
Identify correct answer text and filter out wrong distractors from question string
Get tokens and lemmas
Get explanation sentence ids and roles
"""
# Dropping questions without expla... | 877c75f20b7b766655ecda5dc4bc63ada7ee593c | 3,652,554 |
def simple_command(device, cmd_id, data=None, receive=True):
"""
Raises:
HIDException -> if reading/writing to the USB device failed:
KBProtocolException -> if the packet is too large
"""
cmd_packet = bytearray(EP_VENDOR_SIZE)
cmd_packet[0] = cmd_id
# Optional data component
if data... | 57a5e237f2296fec1563c125cb934ce1914d8bac | 3,652,555 |
def dbopen(dbname, perm = 'r'):
"""Open a Datascope database"""
return Dbptr(dbname, perm) | 08a083def4f792927232eff5d625ae4e6f3355fb | 3,652,556 |
def to_nx(dsk):
"""
Code mainly identical to dask.dot.to_graphviz and kept compatible.
"""
collapse_outputs = False
verbose = False
data_attributes = {}
function_attributes = {}
g = nx.DiGraph()
seen = set()
connected = set()
for k, v in dsk.items():
k_name = nam... | 140b6a74ce7e75ddbc906bc4b4c7330e7585e0d8 | 3,652,557 |
def predict(model, img_base64):
"""
Returns the prediction for a given image.
Params:
model: the neural network (classifier).
"""
return model.predict_disease(img_base64) | 545a98dd682b81a1662878f91091615871562226 | 3,652,558 |
import hashlib
def get_hash(x: str):
"""Generate a hash from a string."""
h = hashlib.md5(x.encode())
return h.hexdigest() | 538c936c29867bb934776333fb2dcc73c06e23d0 | 3,652,559 |
def pair_force(r1, r2, par1, par2, sigma_c, box, r_cut, lj=True, coulomb=True):
"""Compute the sum of the Lennard Jones force and the short ranged part
of the Coulomb force between two particles.
Arguments:
r1 (ndarray): A one dimensional numpy-array with d elements (position of... | 10c6eee7547f94c06e650a0a738aace3380de454 | 3,652,560 |
def delete_network_acl_entry(client, network_acl_id, num=100, egress=False, dry=True):
"""
Delete a network acl entry
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.delete_network_acl_entry
"""
try:
response = client.delete_network_acl_entry( E... | e27e476f2fe37e7e0150a97ebd4b5e3cb93e86b1 | 3,652,561 |
import time
def mp_run(data, process_num, func, *args):
""" run func with multi process
"""
level_start = time.time()
partn = max(len(data) / process_num, 1)
start = 0
p_idx = 0
ps = []
while start < len(data):
local_data = data[start:start + partn]
start += partn
... | 13576bb107eae5a49063bcba3d698eeb957dbb1e | 3,652,562 |
def spell(corpus):
"""
Train a Spelling Normalizer
Parameters
----------
corpus : list of strings. Prefer to feed with malaya.load_malay_dictionary().
Returns
-------
SPELL_NORMALIZE: Trained malaya.normalizer._SPELL_NORMALIZE class
"""
if not isinstance(corpus, list):
... | 1aee5a941e1553f50540a5327ee0e3c4d1ce0bd3 | 3,652,563 |
def check_PA_vector(angle_list, unit='deg'):
""" Checks if the angle list has the right format to avoid any bug in the
pca-adi algorithm. The right format complies to 3 criteria:
1) angles are expressed in degree
2) the angles are positive
3) there is no jump of more than 180 deg between c... | 9f369de90008e60965625acd403a6431c64763fc | 3,652,564 |
def client_id_to_org_type_id(client_id):
"""
Client ID should be a string: "g:" + self._options['org'] + ":" +
self._options['type'] + ":" + self._options['id'],
"""
split = client_id.split(':')
if len(split) != 4:
raise InvalidClientId()
org = split[1]
... | 475058962f81760dc65b19ddbdc1d74e0ec2f55e | 3,652,565 |
def get_total_implements():
"""Obtiene los implementos totales solicitados en prestamos."""
total_implements = 0
for i in Loans.objects.all():
total_implements += i.ammount_implements
return total_implements | 5b8e2b21f8c31e33c60518fd4fba20eded614f05 | 3,652,566 |
from typing import Optional
from typing import Union
def _parse_maybe_array(
type_name: str, innermost_type: Optional[Union[ast_nodes.ValueType,
ast_nodes.PointerType]]
) -> Union[ast_nodes.ValueType, ast_nodes.PointerType, ast_nodes.ArrayType]:
"""Internal-onl... | 8a284083e604688c2a1eff8767b6cb31b493cb07 | 3,652,567 |
def ema_decay_schedule(
base_rate: jnp.ndarray,
step: jnp.ndarray,
total_steps: jnp.ndarray,
use_schedule: bool,
) -> jnp.ndarray:
"""Anneals decay rate to 1 with cosine schedule."""
if not use_schedule:
return base_rate
multiplier = _cosine_decay(step, total_steps, 1.)
return 1. - (1. - bas... | a6269162e1a93544031b241ff43e043971bec488 | 3,652,568 |
from typing import Callable
def _kill_filter(mm: MergedMiningCoordinator, filter_fn: Callable[[MergedMiningStratumProtocol], bool]) -> int:
""" Kill all workers that the filter `fltr` returns true for.
"""
count = 0
for protocol in filter(filter_fn, mm.miner_protocols.values()):
count += 1
... | 8a73427e46a418bf1d3ba974f73992dce0f1ad8c | 3,652,569 |
def get_node_layer_sort_preference(device_role):
"""Layer priority selection function
Layer sort preference is designed as numeric value.
This function identifies it by LAYERS_SORT_ORDER
object position by default. With numeric values,
the logic may be improved without changes on NeXt app side.
... | 08fbdbcb272664498d3709ffc9f49dbb2042fef2 | 3,652,570 |
def is_anagram(s,t):
"""True if strings s and t are anagrams.
"""
# We can use sorted() on a string, which will give a list of characters
# == will then compare two lists of characters, now sorted.
return sorted(s)==sorted(t) | 2b615f8180bcaa598e24c0772893c9a528bc5153 | 3,652,571 |
def f1_score(labels, predict, name=None):
"""
Streaming f1 score.
"""
predictions = tf.floor(predict + 0.5)
with tf.variable_scope(name, 'f1', (labels, predictions)):
epsilon = 1e-7
_, tp = tf.metrics.true_positives(labels, predictions)
_, fn = tf.metrics.false_negatives(labe... | 243612cad4ca1a876ccfbccfe55fdeeed893d644 | 3,652,572 |
import requests
def test_notify_matrix_plugin_fetch(mock_post, mock_get):
"""
API: NotifyMatrix() Server Fetch/API Tests
"""
# Disable Throttling to speed testing
plugins.NotifyBase.request_rate_per_sec = 0
response_obj = {
'room_id': '!abc123:localhost',
'room_alias': '#abc1... | 27dde8766cdfd136104e647a5a97416a69982cb5 | 3,652,573 |
import copy
def site_summary_data(query, notime=True, extra="(1=1)"):
"""
Summary of jobs in different states for errors page to indicate if the errors caused by massive site failures or not
"""
summary = []
summaryResources = []
# remove jobstatus from the query
if 'jobstatus__in' in quer... | 010ca33e4de15c74199fbf54c565119f493698cc | 3,652,574 |
def Epsilon(u):
"""Vector symmetric gradient."""
return Sym(Grad(u.transpose())) | ed1d163ca031ada0d1645029690fa53c3d2acfa0 | 3,652,575 |
def at(seq, msg, cmd=None, *args, **kwargs):
"""Output the comwdg"""
return translator(seq)(*COMWDG_CMD)() | dd98234261731c3048444ab7d99ec6ed34eb62f1 | 3,652,576 |
def get_directory(f):
"""Get a directory in the form of a list of entries."""
entries = []
while 1:
line = f.readline()
if not line:
print '(Unexpected EOF from server)'
break
if line[-2:] == CRLF:
line = line[:-2]
elif line[-1:] in CRLF:
... | fdd83e040f23f5ab84e0eb7cef457dfd66159f78 | 3,652,577 |
import random
import os
def init(provider=None):
"""
Runs through a questionnaire to set up your project's deploy settings
"""
if os.path.exists(DEPLOY_YAML):
_yellow("\nIt looks like you've already gone through the questionnaire.")
cont = prompt("Do you want to go through it again and... | 63b3ee1771369666528438edfb7f803dbafdc9ac | 3,652,578 |
def get_worker_status(worker):
"""Retrieve worker status by worker ID from redis."""
set_redis_worker_status_pool()
global WORKER_STATUS_POOL
# retrieve worker status
r = StrictRedis(connection_pool=WORKER_STATUS_POOL)
res = r.get(WORKER_STATUS_KEY_TMPL % worker)
return res.decode() if has... | 886817f7995bc8259891b10699ec4d26587e0653 | 3,652,579 |
def lif_r_psc_aibs_converter(config, syn_tau=[5.5, 8.5, 2.8, 5.8]):
"""Creates a nest glif_lif_r_psc object"""
coeffs = config['coeffs']
threshold_params = config['threshold_dynamics_method']['params']
reset_params = config['voltage_reset_method']['params']
params = {'V_th': coeffs['th_inf'] * confi... | 091e45f44f9c777dac6c2b35fd51459a7947e301 | 3,652,580 |
def get_bigwig_values(bigwig_path, chrom_name, chrom_end, chrom_start=0):
"""
Get the values for a genomic region of interest from a bigwig file.
:param bigwig_path: Path to the bigwig file
:param chrom_name: Chromosome name
:param chrom_end: chromosome end
:param chrom_start: chromosome start
... | 37fe5a40a5fde1ccaee7cac32d8b9beb68a65c51 | 3,652,581 |
import logging
def dtool_config(files):
"""Provide default dtool config."""
logger = logging.getLogger(__name__)
# use environment variables instead of custom config file, see
# https://github.com/jic-dtool/dtoolcore/pull/17
# _original_environ = os.environ.copy()
# inject configuration into ... | 4dc6df375e9f2d0bd9b099c601c3826601520f9c | 3,652,582 |
def get_successors(state, maxwords):
"""Traverses state graph to find valid anagrams."""
terminal = len(state['chars']) == 0
# Check whether the state is invalid and should be pruned
if not is_valid(state['anagram'], terminal, maxwords):
return []
# If valid terminal state, stop search an... | 9c842edc378a781195ef41ed58c7952f216b642e | 3,652,583 |
def read_and_parse_cdl_file(file_name):
"""
Reads relevant information from a "cdl" file
"""
if file_name is None:
return None
wl_map = {}
bl_map = {}
colclk_wl_map = {}
# Parse line-by-line
with open(file_name, "r") as fp:
for line in fp:
line = line.... | e1bfbb75f473932861bb2e804dd0609c62544cf3 | 3,652,584 |
def detect_outlier_at_index(
srs: pd.Series,
idx: int,
n_samples: int,
z_score_threshold: float,
) -> bool:
"""
Check if a value at index `idx` in a series is an outlier.
The passed series is supposed to be ordered by increasing timestamps.
This function
- detects z-score window in... | 65a4d7e661f6cf4641d9cd82d1bb31c5e2d21616 | 3,652,585 |
def _organize_parameter(parameter):
"""
Convert operation parameter message to its dict format.
Args:
parameter (OperationParameter): Operation parameter message.
Returns:
dict, operation parameter.
"""
parameter_result = dict()
parameter_keys = [
'mapStr',
... | 8cbd7c863bb244e71266a573ba756647d0ba13ea | 3,652,586 |
def colorpicker(request):
"""
Controller for the app home page.
"""
my_param = MyParamColor()
context = get_context(request, my_param)
return render(request, 'tethys_django_form_tutorial/colorpicker.html', context) | 071f587683a24c101a7963a3934c989570c0fa66 | 3,652,587 |
def translate_date(default=defaults.get('language')):
"""Parse/translate a date."""
d = request.args.get('date')
if not d:
raise RuntimeError(_('Date is mandatory.'))
dest_lang = request.args.get('dest') if request.args.get('dest') else default
variation = request.args.get('variation') if r... | ada6f4416e227414dfc6f32fc3387c8b38830e70 | 3,652,588 |
from typing import Any
from typing import Union
from typing import Optional
def check_call(
*command: Any,
working_directory: Union[PathLike, str] = ".",
verbose: bool = False,
quoted: bool = False,
**kwargs: Any,
) -> Optional[str]:
"""Proxy for subprocess.check_call"""
return check_run(
... | 384cd78599355e694445a7c682613672bba374a1 | 3,652,589 |
from typing import Tuple
def fit_client(client: Client, weights: Weights) -> Tuple[Weights, int]:
"""Refine weights on a single client."""
return client.fit(weights) | db8e6003f452a5147274ac6e83df7d216ca46c91 | 3,652,590 |
def _find_rpms_in_packages(koji_api, name_list, major_minor):
"""
Given a list of package names, look up the RPMs that are built in them.
Of course, this is an inexact science to do generically; contents can
vary from build to build, and multiple packages could build the same RPM name.
We will first... | edfb55f0b6997d8f930c8d93c2ee1be1c111bcfc | 3,652,591 |
def calculate_algorithm_tags(analyses):
"""
Calculate the algorithm tags (eg. "ip", True) that should be applied to a sample document based on a list of its
associated analyses.
:param analyses: the analyses to calculate tags for
:type analyses: list
:return: algorithm tags to apply to the sam... | b2b13e3a0ccd21f446c5406baa966b2c0c4c6be9 | 3,652,592 |
import json
def open_json(filepath):
"""
Returns open .json file in python as a list.
:param: .json file path
:returns: list
:rvalue: str
"""
with open(filepath) as f:
notes = json.load(f)
return notes | a7cae15880ee1caaaf7bfa8c1aec98f5f83debe7 | 3,652,593 |
import json
def remove_user_list():
"""
Endpoint to remove a specific list or a complete user
---
tags:
- User Methods
parameters:
- name: user
type: string
in: query
required: true
description: user you want to qu... | b53660edd56fcf5bbe061331d5f2b8756f621dd8 | 3,652,594 |
import requests
def upload(f, content_type, token, api_key):
"""Upload a file with the given content type to Climate
This example supports files up to 5 MiB (5,242,880 bytes).
Returns The upload id if the upload is successful, False otherwise.
"""
uri = '{}/v4/uploads'.format(api_uri)
header... | d6ead1f029811ec5894848b71841fd008068cee0 | 3,652,595 |
def get_node_name_centres(nodeset: Nodeset, coordinates_field: Field, name_field: Field):
"""
Find mean locations of node coordinate with the same names.
:param nodeset: Zinc Nodeset or NodesetGroup to search.
:param coordinates_field: The coordinate field to evaluate.
:param name_field: The name fi... | 2dc1e670999d9491e52efce02e5d7ecd22b75226 | 3,652,596 |
from enum import Enum
def pred(a):
"""
pred :: a -> a
the predecessor of a value. For numeric types, pred subtracts 1.
"""
return Enum[a].pred(a) | 070bf20e7b7ecd694806e78bd705e872b2fd8464 | 3,652,597 |
import sys
def main():
"""
Entry point of the app.
"""
if len(sys.argv) != 2:
print(f"{sys.argv[0]} [SERVER_LIST_FILE]")
return 1
return process(server_list_file=sys.argv[1]) | 1fefab9f590db251dd68dc703d862f2818337d14 | 3,652,598 |
def pascal_to_snake(pascal_string):
"""Return a snake_string for a given PascalString."""
camel_string = _pascal_to_camel(pascal_string)
snake_string = _camel_to_snake(camel_string)
return "".join(snake_string) | 69c54fd8600878af2a8d168659a781b8389419ce | 3,652,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.