uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
652d1f4c05422b49491d8907
train
function
def init_runtime(): site_config = config.load_config('unittests/resources/settings.py') site_config.select_subconfig('generic') rt.init_runtime(site_config)
def init_runtime():
site_config = config.load_config('unittests/resources/settings.py') site_config.select_subconfig('generic') rt.init_runtime(site_config)
'modules' ) # Builtin configuration BUILTIN_CONFIG_FILE = 'reframe/core/settings.py' # Unit tests site configuration TEST_CONFIG_FILE = 'unittests/resources/settings.py' # User supplied configuration file and site configuration USER_CONFIG_FILE = None USER_SYSTEM = None def init_runtime():
64
64
35
4
59
jacwah/reframe
unittests/utility.py
Python
init_runtime
init_runtime
40
43
40
40
ec19c0eac6532feda918054c234c42f04b1a3e20
bigcode/the-stack
train
4c147eb81c1a4ff37307f126
train
function
def partition_by_name(name): for p in rt.runtime().system.partitions: if p.name == name: return p return None
def partition_by_name(name):
for p in rt.runtime().system.partitions: if p.name == name: return p return None
will be returned. ''' system = rt.runtime().system for p in system.partitions: if name is None and not p.scheduler.is_local: return p if p.scheduler.registered_name == name: return p return None def partition_by_name(name):
64
64
32
6
57
jacwah/reframe
unittests/utility.py
Python
partition_by_name
partition_by_name
65
70
65
65
f8b96e38536a06a2e809f661fe167f755ff7dc3c
bigcode/the-stack
train
c27083e12f969914bc8a8024
train
function
def dispatch(argname, suffix=None): '''Dispatch call to the decorated function to another one based on the type of the keyword argument ``argname``. The target function has the same name as the decorated one, but without the ``test_`` prefix and a suffix ``_{type(kwargs[argname])}`` will be appende...
def dispatch(argname, suffix=None):
'''Dispatch call to the decorated function to another one based on the type of the keyword argument ``argname``. The target function has the same name as the decorated one, but without the ``test_`` prefix and a suffix ``_{type(kwargs[argname])}`` will be appended. If the target function does not e...
: return p return None def environment_by_name(name, partition): for e in partition.environs: if e.name == name: return e return None def has_sane_modules_system(): return not isinstance(rt.runtime().modules_system.backend, (modules.NoModIm...
147
147
492
8
138
jacwah/reframe
unittests/utility.py
Python
dispatch
dispatch
99
162
99
99
be936e25fde995e3f49ed6a19b1920f2e169d7a2
bigcode/the-stack
train
0e314781df2a0ccbda6137eb
train
function
def partition_by_scheduler(name=None): '''Retrieve a system partition from the runtime whose scheduler is registered with ``name``. If ``name`` is :class:`None`, any partition with a non-local scheduler will be returned. ''' system = rt.runtime().system for p in system.partitions: ...
def partition_by_scheduler(name=None):
'''Retrieve a system partition from the runtime whose scheduler is registered with ``name``. If ``name`` is :class:`None`, any partition with a non-local scheduler will be returned. ''' system = rt.runtime().system for p in system.partitions: if name is None and not p.scheduler.is_...
.py' # User supplied configuration file and site configuration USER_CONFIG_FILE = None USER_SYSTEM = None def init_runtime(): site_config = config.load_config('unittests/resources/settings.py') site_config.select_subconfig('generic') rt.init_runtime(site_config) def partition_by_scheduler(name=None):
64
64
102
7
57
jacwah/reframe
unittests/utility.py
Python
partition_by_scheduler
partition_by_scheduler
46
62
46
46
3bed3385eb6deb884dcb26e4057c7399ffe57fb2
bigcode/the-stack
train
9946ebdea226896f59e318c2
train
function
def custom_prefix(prefix): '''Assign a custom prefix to a test. This is useful in unit tests when we want to create tests on-the-fly and associate them with existing resources.''' def _set_prefix(cls): cls._rfm_custom_prefix = prefix return cls return _set_prefix
def custom_prefix(prefix):
'''Assign a custom prefix to a test. This is useful in unit tests when we want to create tests on-the-fly and associate them with existing resources.''' def _set_prefix(cls): cls._rfm_custom_prefix = prefix return cls return _set_prefix
_by_name(name, partition): for e in partition.environs: if e.name == name: return e return None def has_sane_modules_system(): return not isinstance(rt.runtime().modules_system.backend, (modules.NoModImpl, modules.SpackImpl)) def custom_prefix(prefix):
64
64
69
5
59
jacwah/reframe
unittests/utility.py
Python
custom_prefix
custom_prefix
86
96
86
86
dcd635c35e0f55590ba1ebcf527ee3323bd9b4be
bigcode/the-stack
train
f0f7226571c22a7f163f5851
train
function
def environment_by_name(name, partition): for e in partition.environs: if e.name == name: return e return None
def environment_by_name(name, partition):
for e in partition.environs: if e.name == name: return e return None
_local: return p if p.scheduler.registered_name == name: return p return None def partition_by_name(name): for p in rt.runtime().system.partitions: if p.name == name: return p return None def environment_by_name(name, partition):
64
64
31
8
55
jacwah/reframe
unittests/utility.py
Python
environment_by_name
environment_by_name
73
78
73
73
f68fde4770486c33cbe792c417751ff88d4da2b2
bigcode/the-stack
train
f16e6ac1b761b3b0bfa96152
train
class
class LameInfoPlugin(LoaderPlugin): NAMES = ["lameinfo", "xing"] SUMMARY = u"Outputs lame header (if one exists) for file." DESCRIPTION = ( u"The 'lame' (or xing) header provides extra information about the mp3 " "that is useful to players and encoders but not officially part of " ...
class LameInfoPlugin(LoaderPlugin):
NAMES = ["lameinfo", "xing"] SUMMARY = u"Outputs lame header (if one exists) for file." DESCRIPTION = ( u"The 'lame' (or xing) header provides extra information about the mp3 " "that is useful to players and encoders but not officially part of " "the mp3 specification. Variable bit...
: utf-8 -*- ################################################################################ # Copyright (C) 2009 Travis Shirk <travis@pobox.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Found...
256
256
865
9
246
FosterFromGloster/PeskyDuplicates
eyeD3-0.7.8/src/eyed3/plugins/lameinfo.py
Python
LameInfoPlugin
LameInfoPlugin
27
110
27
27
170bf6d82a403a2d38fce44c8bed3eb89cae454a
bigcode/the-stack
train
d9bb9a0243055f307be2c7ad
train
class
class APIError(Exception): pass
class APIError(Exception):
pass
_REGION") or "US" YOUTUBE_LANGUAGE = environ.get("YOUTUBE_LANGUAGE") or "en" # see regionCode and relevance language at # https://developers.google.com/youtube/v3/docs/search/list SEARCH_URL = "https://www.googleapis.com/youtube/v3/search" class APIError(Exception):
64
64
8
5
59
culhatsker/discord_soundbar
discord_soundbar/youtube_search.py
Python
APIError
APIError
15
16
15
15
425ab189f4116abfd7adc78d2959e2f0545fbe1f
bigcode/the-stack
train
1d66fc4ab5c4cb3cc52a52c2
train
class
class YouTubeSearch: def __init__(self, query, max_results=10): self.query = query self.max_results = max_results async def youtube_search(self): request_coro = request("GET", SEARCH_URL, params={ "type": "video", "part": "snippet", "safeSearch": ...
class YouTubeSearch:
def __init__(self, query, max_results=10): self.query = query self.max_results = max_results async def youtube_search(self): request_coro = request("GET", SEARCH_URL, params={ "type": "video", "part": "snippet", "safeSearch": "none", "...
") or "US" YOUTUBE_LANGUAGE = environ.get("YOUTUBE_LANGUAGE") or "en" # see regionCode and relevance language at # https://developers.google.com/youtube/v3/docs/search/list SEARCH_URL = "https://www.googleapis.com/youtube/v3/search" class APIError(Exception): pass class YouTubeSearch:
71
71
237
5
65
culhatsker/discord_soundbar
discord_soundbar/youtube_search.py
Python
YouTubeSearch
YouTubeSearch
19
50
19
19
71d3fa4fbb9e7705025dca5e0b45c0d0a51fe522
bigcode/the-stack
train
6616fa022fd9346f14b81d6b
train
function
def run_ssh_server(port=2200, running=True, encodings=[]): # now connect sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('127.0.0.1', port)) sock.listen(100) while running: client, addr = sock.accept() ...
def run_ssh_server(port=2200, running=True, encodings=[]): # now connect
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('127.0.0.1', port)) sock.listen(100) while running: client, addr = sock.accept() print('Got a connection!') t = paramiko.Transport(client) ...
[command] channel.send(self.encoding) channel.shutdown(1) self.exec_event.set() return ret def check_channel_shell_request(self, channel): self.shell_event.set() return True def check_channel_pty_request(self, channel, term, width, height, ...
130
130
435
22
107
zero1limited/mdoq-webssh
tests/sshserver.py
Python
run_ssh_server
run_ssh_server
159
229
159
160
62aca6e0444b0856d0e40d81337e1811dde31a91
bigcode/the-stack
train
d27ca8a7ba3fae630d471dca
train
class
class Server(paramiko.ServerInterface): # 'data' is the output of base64.b64encode(key) # (using the "user_rsa_key" files) data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp' b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC' b'KDqIexkgHAfID/6mqvm...
class Server(paramiko.ServerInterface): # 'data' is the output of base64.b64encode(key) # (using the "user_rsa_key" files)
data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp' b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC' b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT' b'UWT10hcuO4Ks8=') good_pub_key = paramiko.RSAKey(data=decodebytes(dat...
# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with Paramiko; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. import random import...
256
256
1,073
36
219
zero1limited/mdoq-webssh
tests/sshserver.py
Python
Server
Server
45
156
45
47
b1c2ceb1b4e3ed6c6cad42665cbe3e1a6d69f6f7
bigcode/the-stack
train
c57b701d7a846d4c41c6c4f8
train
class
class Calibration: def __init__(self,hoz_cor, vir_cor, board_num): self.hoz_cor = hoz_cor self.vir_cor = vir_cor self.board_num = board_num self.board_size = (self.hoz_cor, self.vir_cor) self.img_left_sata = False self.img_right_sata = False self.bridge = cv_bridge.CvBridge() cv2.namedWindow("window"...
class Calibration:
def __init__(self,hoz_cor, vir_cor, board_num): self.hoz_cor = hoz_cor self.vir_cor = vir_cor self.board_num = board_num self.board_size = (self.hoz_cor, self.vir_cor) self.img_left_sata = False self.img_right_sata = False self.bridge = cv_bridge.CvBridge() cv2.namedWindow("window", 1) self.left_im...
#!/usr/bin/env python import rospy from sensor_msgs.msg import Image import cv2, cv_bridge import numpy as np class Calibration:
32
256
1,665
3
28
ahmohamed1/activeStereoVisionPlatform
src/platform_vision/scripts/calibrate_system.py
Python
Calibration
Calibration
8
135
8
8
eeebd1a38eec8662e95ea4358de5a26fcfd92d5e
bigcode/the-stack
train
15a3091171851022abd518cb
train
class
class Address(object): """The :class:`Address` object, which represents an address (public key) on Stellar's network. An :class:`Address` is initialized via a public key string, or derived via a secret seed. The network on which the account exists is also specified, as it is used to verify and set ...
class Address(object):
"""The :class:`Address` object, which represents an address (public key) on Stellar's network. An :class:`Address` is initialized via a public key string, or derived via a secret seed. The network on which the account exists is also specified, as it is used to verify and set attributes via connecti...
# coding: utf-8 from .horizon import Horizon from .keypair import Keypair from .exceptions import AccountNotExistError, NotValidParamError, HorizonError from .horizon import HORIZON_LIVE, HORIZON_TEST class Address(object):
59
256
1,403
4
54
shredding/py-stellar-base
stellar_base/address.py
Python
Address
Address
9
194
9
9
aebc9752d27cbbd83880fd35bc5cc605fb8e4bdd
bigcode/the-stack
train
a7fb10c3907dbe592c49fd16
train
function
def input_transform_net(point_cloud, is_training, bn_decay=None, K=3): """ Args: - point_cloud: Transform Net input, is BxNx3 gray image Return: - transform: Transformation matrix of size 3xK """ batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].valu...
def input_transform_net(point_cloud, is_training, bn_decay=None, K=3):
""" Args: - point_cloud: Transform Net input, is BxNx3 gray image Return: - transform: Transformation matrix of size 3xK """ batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value # expand dim: (B,N,3) -> (B,N,3,1) (B,H,W,C) input_image...
''' @Author: Shuai Wang @Github: https://github.com/wsustcid @Version: 1.0.0 @Date: 2020-04-23 23:01:52 @LastEditTime: 2020-05-04 11:28:25 ''' import tensorflow as tf import numpy as np import sys import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE...
134
177
591
18
115
wsustcid/pointnet
models/transform_nets.py
Python
input_transform_net
input_transform_net
17
69
17
17
2e589ba8b48b6f5011ba87d0169c1a389e7c0151
bigcode/the-stack
train
b8921eff47d6e7087f227245
train
function
def feature_transform_net(inputs, is_training, bn_decay=None, K=64): """ Feature Transform Net, Args: - inputs: input featuer with BxNx1xK Return: - transform: Transformation matrix of size (B,K,K) """ batch_size = inputs.get_shape()[0].value num_point = inputs.get_shape()[1].value ...
def feature_transform_net(inputs, is_training, bn_decay=None, K=64):
""" Feature Transform Net, Args: - inputs: input featuer with BxNx1xK Return: - transform: Transformation matrix of size (B,K,K) """ batch_size = inputs.get_shape()[0].value num_point = inputs.get_shape()[1].value net = tf_util.conv2d(inputs, 64, [1,1], pad...
0.0), dtype=tf.float32) biases = tf.get_variable('biases', [3*K], initializer=tf.constant_initializer(0.0), dtype=tf.float32) biases += tf.constant([1,0,0,0,1,0,0,0,1], dtype=tf.float32) transform...
142
142
476
17
124
wsustcid/pointnet
models/transform_nets.py
Python
feature_transform_net
feature_transform_net
72
115
72
72
c714a64efef5415d630a30b068df2afe87a2c55f
bigcode/the-stack
train
13210ce020fd90158b3cb4ba
train
class
class Env(gym.Env): def __init__(self, overlay_path, arrival_config): """ A new Gym environment. This environment represents the environment of NFVdeep. Args: overlay_path: A connection to the network where the agent will act arrival_config: Dictionary that specifies the...
class Env(gym.Env):
def __init__(self, overlay_path, arrival_config): """ A new Gym environment. This environment represents the environment of NFVdeep. Args: overlay_path: A connection to the network where the agent will act arrival_config: Dictionary that specifies the properties of the r...
import logging import gym import json import numpy as np from gym import spaces from pathlib import Path from tabulate import tabulate from copy import deepcopy from nfvdeep.environment.network import Network from nfvdeep.environment.arrival import ArrivalProcess from nfvdeep.environment.sfc import ServiceFunctionChain...
74
256
2,920
6
67
Tuantrung/NFVdeep
nfvdeep/environment/env.py
Python
Env
Env
14
311
14
14
c4c40f22c280749d46092baa4471f6c1a800ac5b
bigcode/the-stack
train
976154e899a713c86c5e507c
train
function
@torch.no_grad() def evaluate(model, criterion, postprocessors, data_loader, base_ds, device, output_dir): model.eval() criterion.eval() metric_logger = utils.MetricLogger(delimiter=" ") metric_logger.add_meter('class_error', utils.SmoothedValue(window_size=1, fmt='{value:.2f}')) header = 'Test:' ...
@torch.no_grad() def evaluate(model, criterion, postprocessors, data_loader, base_ds, device, output_dir):
model.eval() criterion.eval() metric_logger = utils.MetricLogger(delimiter=" ") metric_logger.add_meter('class_error', utils.SmoothedValue(window_size=1, fmt='{value:.2f}')) header = 'Test:' iou_types = tuple(k for k in ('segm', 'bbox') if k in postprocessors.keys()) coco_evaluator = Coco...
',loss_dict_reduced) print('DETR',loss_dict_reduced_detr) sys.exit(1) if max_norm > 0: torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm) optimizer.step() metric_logger.update(loss=loss_value, **loss_dict_reduced_scaled, **loss_dict_reduced_unsca...
255
256
929
25
230
anonymousCVPR9/Prior-HOI
engine.py
Python
evaluate
evaluate
224
309
224
225
c2528c11d6ac581f92d11c89b15676d04f4f46e4
bigcode/the-stack
train
a7af65be93e672e4b1e0f4ee
train
function
@torch.no_grad() def evaluate_hoi(dataset_file, model, postprocessors, data_loader, subject_category_id, device): model.eval() metric_logger = utils.MetricLogger(delimiter=" ") header = 'Test:' preds = [] gts = [] indices = [] for samples, targets in metric_logger.log_every(data_loader, 1...
@torch.no_grad() def evaluate_hoi(dataset_file, model, postprocessors, data_loader, subject_category_id, device):
model.eval() metric_logger = utils.MetricLogger(delimiter=" ") header = 'Test:' preds = [] gts = [] indices = [] for samples, targets in metric_logger.log_every(data_loader, 10, header): samples = samples.to(device) output_list = model(samples) outputs = output_li...
segm' in postprocessors.keys(): stats['coco_eval_masks'] = coco_evaluator.coco_eval['segm'].stats.tolist() if panoptic_res is not None: stats['PQ_all'] = panoptic_res["All"] stats['PQ_th'] = panoptic_res["Things"] stats['PQ_st'] = panoptic_res["Stuff"] return stats, coco_eval...
112
112
376
26
85
anonymousCVPR9/Prior-HOI
engine.py
Python
evaluate_hoi
evaluate_hoi
312
350
312
313
9277ff68d7e54f207d709a55a74eddc37316a6d5
bigcode/the-stack
train
dc57ee3a39bf82dea48911aa
train
function
def train_one_epoch_w_accum(model: torch.nn.Module, criterion: torch.nn.Module,criterion_detr: torch.nn.Module, criterion_verbs:torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, args): max_norm = ar...
def train_one_epoch_w_accum(model: torch.nn.Module, criterion: torch.nn.Module,criterion_detr: torch.nn.Module, criterion_verbs:torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, args):
max_norm = args.clip_max_norm model.train() criterion.train() criterion_detr.train() metric_logger = utils.MetricLogger(delimiter=" ") metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}')) if hasattr(criterion, 'loss_labels'): metric_logger.add_meter('...
.nn.utils.clip_grad_norm_(model.parameters(), max_norm) optimizer.step() metric_logger.update(loss=loss_value, **loss_dict_reduced_scaled, **loss_dict_reduced_unscaled) metric_logger.update(loss_detr=loss_value_detr, **loss_dict_reduced_scaled_detr, **loss_dict_reduced_unscaled_detr) me...
255
256
1,328
61
194
anonymousCVPR9/Prior-HOI
engine.py
Python
train_one_epoch_w_accum
train_one_epoch_w_accum
112
218
112
115
af3f9d6f3d006ad891da53b4a6ff5f7f726f9710
bigcode/the-stack
train
5b417895d7c9c5d709aac66a
train
function
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,criterion_detr: torch.nn.Module, criterion_verbs:torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, args): max_norm = args.clip_...
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,criterion_detr: torch.nn.Module, criterion_verbs:torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, args):
max_norm = args.clip_max_norm model.train() criterion.train() criterion_detr.train() metric_logger = utils.MetricLogger(delimiter=" ") metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}')) if hasattr(criterion, 'loss_labels'): metric_logger.add_meter('...
# ------------------------------------------------------------------------ # Copyright (c) Hitachi, Ltd. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/fac...
224
256
984
58
165
anonymousCVPR9/Prior-HOI
engine.py
Python
train_one_epoch
train_one_epoch
29
108
29
32
6cfe014220c5ce23e8a937d58db9b77f10e89f4a
bigcode/the-stack
train
d7e37cf91a6b9a1f641277d1
train
class
class CompassConfig(AlgorithmConfig): deltatol = ConfigField(0.01) deltainit = ConfigField(0.5) redfactor = ConfigField(1.5) niter = ConfigField(400) _section = 'algorithm.cmaes'
class CompassConfig(AlgorithmConfig):
deltatol = ConfigField(0.01) deltainit = ConfigField(0.5) redfactor = ConfigField(1.5) niter = ConfigField(400) _section = 'algorithm.cmaes'
from febo.algorithms import AlgorithmConfig from febo.algorithms.thread import ThreadAlgorithm from febo.utils.config import ConfigField, assign_config from noisyopt import minimizeCompass class CompassConfig(AlgorithmConfig):
45
64
61
7
37
eric-vader/HD-BO-Additive-Models
hdbo/febo/algorithms/compass.py
Python
CompassConfig
CompassConfig
6
11
6
6
ee130193d570c03477a74fb5fd709759d2e822c3
bigcode/the-stack
train
0ae1721d69a500f48b11fc2e
train
class
@assign_config(CompassConfig) class Compass(ThreadAlgorithm): def initialize(self, **kwargs): super().initialize(**kwargs) def minimize(self): # Compass requires an initial point if self.x0 is None: self.x0 = self.domain.l + self.domain._range / 2 res = minimizeCo...
@assign_config(CompassConfig) class Compass(ThreadAlgorithm):
def initialize(self, **kwargs): super().initialize(**kwargs) def minimize(self): # Compass requires an initial point if self.x0 is None: self.x0 = self.domain.l + self.domain._range / 2 res = minimizeCompass(self.f, bounds=self.domain.bounds, x0=self.x0, ...
import minimizeCompass class CompassConfig(AlgorithmConfig): deltatol = ConfigField(0.01) deltainit = ConfigField(0.5) redfactor = ConfigField(1.5) niter = ConfigField(400) _section = 'algorithm.cmaes' @assign_config(CompassConfig) class Compass(ThreadAlgorithm):
77
77
258
12
65
eric-vader/HD-BO-Additive-Models
hdbo/febo/algorithms/compass.py
Python
Compass
Compass
13
48
13
15
fe1d7c61c6347235e5f0d8b51266f15781c9b084
bigcode/the-stack
train
22c502665ebd2dd708d69a25
train
function
def export_exel(df): timestamp = time.strftime("%Y-%m-%d %H-%M-%S", time.localtime()) df.to_excel("export/echr_data " + timestamp + ".xlsx", sheet_name='data')
def export_exel(df):
timestamp = time.strftime("%Y-%m-%d %H-%M-%S", time.localtime()) df.to_excel("export/echr_data " + timestamp + ".xlsx", sheet_name='data')
import time import sqlite3 def export_exel(df):
13
64
50
6
6
serhiikanyhin/echr_uploader
modules/echr_export.py
Python
export_exel
export_exel
5
7
5
5
7e0ffafe5d3098cf71f225e43933544fd1c26202
bigcode/the-stack
train
0364500e676531c8aad18910
train
class
class Migration(migrations.Migration): dependencies = [ ('orders', '0009_auto_20190127_1505'), ] operations = [ migrations.AlterField( model_name='order', name='order_date', field=models.DateTimeField(blank=True, default=datetime.datetime(2019, 1, 27, 15...
class Migration(migrations.Migration):
dependencies = [ ('orders', '0009_auto_20190127_1505'), ] operations = [ migrations.AlterField( model_name='order', name='order_date', field=models.DateTimeField(blank=True, default=datetime.datetime(2019, 1, 27, 15, 8, 23, 430762)), ), ]
# Generated by Django 2.1.5 on 2019-01-27 09:08 import datetime from django.db import migrations, models class Migration(migrations.Migration):
41
64
89
7
33
MahmudulHassan5809/Ecommerce-WebSite-With-Django2
orders/migrations/0010_auto_20190127_1508.py
Python
Migration
Migration
7
19
7
8
37cdc4f1da6f18b501ed310f3f210cc3591cae11
bigcode/the-stack
train
a00546e6c2596f8f04032cbd
train
class
class AccountSingleton(object): """ 单例基类 """ _instance = None def __new__(cls, *args, **kwargs): if not isinstance(cls._instance, cls): cls._instance = object.__new__(cls, *args, **kwargs) return cls._instance
class AccountSingleton(object):
""" 单例基类 """ _instance = None def __new__(cls, *args, **kwargs): if not isinstance(cls._instance, cls): cls._instance = object.__new__(cls, *args, **kwargs) return cls._instance
from bkaccount.encryption import encrypt, decrypt, salt from bkaccount.models import Loignlog, BkToken from bkaccount.forms import AuthenticationAndRegisterForm from bkaccount.opsany_user_auth import OpsAnyRbacUserAuth from bkaccount.models import BkUser class AccountSingleton(object):
64
64
67
5
58
unixhot/opsany-paas
paas-ce/paas/login/bkaccount/accounts.py
Python
AccountSingleton
AccountSingleton
37
47
37
37
2f0cb9d12013637ffc7d24de39c1069339565ba8
bigcode/the-stack
train
df9752b95bab86faaa02535f
train
class
class Account(AccountSingleton): """ 账号体系相关的基类Account 提供通用的账号功能 """ # cookie名称 BK_COOKIE_NAME = settings.BK_COOKIE_NAME # cookie 有效期,默认为1天 BK_COOKIE_AGE = settings.BK_COOKIE_AGE # 登录回调链接 REDIRECT_FIELD_NAME = 'c_url' # 登录连接 BK_LOGIN_URL = str(settings.LOGIN_URL) # 允许...
class Account(AccountSingleton):
""" 账号体系相关的基类Account 提供通用的账号功能 """ # cookie名称 BK_COOKIE_NAME = settings.BK_COOKIE_NAME # cookie 有效期,默认为1天 BK_COOKIE_AGE = settings.BK_COOKIE_AGE # 登录回调链接 REDIRECT_FIELD_NAME = 'c_url' # 登录连接 BK_LOGIN_URL = str(settings.LOGIN_URL) # 允许误差时间,防止多台机器时间误差, 1分钟 BK_TOKEN...
import settings from django.utils.translation import ugettext as _ # Avoid shadowing the login() and logout() views below. from django.contrib.auth import (login as auth_login, logout as auth_logout) from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.view...
256
256
3,745
5
250
unixhot/opsany-paas
paas-ce/paas/login/bkaccount/accounts.py
Python
Account
Account
50
464
50
50
a19f7f99163962e7fac3d10ad5d20e583664ca9e
bigcode/the-stack
train
1b2db5191c199da8e641b66e
train
class
class CoinGecko(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('api.coingecko.com', '/api/v3/coins/axe') r = dict([(ccy.upper(), Decimal(d)) for ccy, d in json['market_data']['current_price'].items()]) return r ...
class CoinGecko(ExchangeBase):
async def get_rates(self, ccy): json = await self.get_json('api.coingecko.com', '/api/v3/coins/axe') r = dict([(ccy.upper(), Decimal(d)) for ccy, d in json['market_data']['current_price'].items()]) return r def history_ccys(self): ...
', '/v2/assets/axe/history?interval=d1&limit=2000') return dict([(datetime.utcfromtimestamp(h['time']/1000).strftime('%Y-%m-%d'), h['priceUsd']) for h in history['data']]) class CoinGecko(ExchangeBase):
64
64
193
8
56
ddude1/electrum-axe
electrum_axe/exchange_rate.py
Python
CoinGecko
CoinGecko
212
230
212
213
962d06806e285d026195e07c68988d245d8b1083
bigcode/the-stack
train
07efa0a7c795283a8c58782e
train
class
class BitcoinAverage(ExchangeBase): # note: historical rates used to be freely available # but this is no longer the case. see #5188 async def get_rates(self, ccy): json = await self.get_json('apiv2.bitcoinaverage.com', '/indices/local/ticker/AXE%s' % ccy) ...
class BitcoinAverage(ExchangeBase): # note: historical rates used to be freely available # but this is no longer the case. see #5188
async def get_rates(self, ccy): json = await self.get_json('apiv2.bitcoinaverage.com', '/indices/local/ticker/AXE%s' % ccy) return {ccy: Decimal(json['last'])}
_rates('') return sorted([str(a) for (a, b) in rates.items() if b is not None and len(a)==3]) class BitcoinAverage(ExchangeBase): # note: historical rates used to be freely available # but this is no longer the case. see #5188
64
64
87
34
30
ddude1/electrum-axe
electrum_axe/exchange_rate.py
Python
BitcoinAverage
BitcoinAverage
147
154
147
150
1b256886dd97288624087ebf059194a2c4a0a835
bigcode/the-stack
train
c28e95d4aa696bd3e462b95d
train
class
class ExchangeBase(Logger): def __init__(self, on_quotes, on_history): Logger.__init__(self) self.history = {} self.quotes = {} self.on_quotes = on_quotes self.on_history = on_history async def get_raw(self, site, get_string): # APIs must have https url ...
class ExchangeBase(Logger):
def __init__(self, on_quotes, on_history): Logger.__init__(self) self.history = {} self.quotes = {} self.on_quotes = on_quotes self.on_history = on_history async def get_raw(self, site, get_string): # APIs must have https url = ''.join(['https://', site, ...
://en.wikipedia.org/wiki/ISO_4217 CCY_PRECISIONS = {'BHD': 3, 'BIF': 0, 'BYR': 0, 'CLF': 4, 'CLP': 0, 'CVE': 0, 'DJF': 0, 'GNF': 0, 'IQD': 3, 'ISK': 0, 'JOD': 3, 'JPY': 0, 'KMF': 0, 'KRW': 0, 'KWD': 3, 'LYD': 3, 'MGA': 1, 'MRO': 1, 'OMR': 3, 'PYG': 0, ...
256
256
898
5
251
ddude1/electrum-axe
electrum_axe/exchange_rate.py
Python
ExchangeBase
ExchangeBase
40
144
40
41
076141016fd63479b73284fc808d048f204cdac4
bigcode/the-stack
train
1842fbfd46559a4405bcf110
train
function
def get_exchanges_and_currencies(): # load currencies.json from disk path = resource_path('currencies.json') try: with open(path, 'r', encoding='utf-8') as f: return json.loads(f.read()) except: pass # or if not present, generate it now. print("cannot find currencies....
def get_exchanges_and_currencies(): # load currencies.json from disk
path = resource_path('currencies.json') try: with open(path, 'r', encoding='utf-8') as f: return json.loads(f.read()) except: pass # or if not present, generate it now. print("cannot find currencies.json. will regenerate it now.") d = {} is_exchange = lambda obj: ...
dict([(datetime.utcfromtimestamp(h[0]/1000).strftime('%Y-%m-%d'), h[1]) for h in history['prices']]) def dictinvert(d): inv = {} for k, vlist in d.items(): for v in vlist: keys = inv.setdefault(v, []) keys.append(k) return inv def get_exchanges_and_cur...
93
93
311
16
76
ddude1/electrum-axe
electrum_axe/exchange_rate.py
Python
get_exchanges_and_currencies
get_exchanges_and_currencies
241
277
241
242
2d0af780290f099aeb8b9790a69f7d4f100c706c
bigcode/the-stack
train
e6a2d150379ec1059e9f0c92
train
class
class FxThread(ThreadJob): def __init__(self, config: SimpleConfig, network: Network): ThreadJob.__init__(self) self.config = config self.network = network if self.network: self.network.register_callback(self.set_proxy, ['proxy_set']) self.ccy = self.get_currency...
class FxThread(ThreadJob):
def __init__(self, config: SimpleConfig, network: Network): ThreadJob.__init__(self) self.config = config self.network = network if self.network: self.network.register_callback(self.set_proxy, ['proxy_set']) self.ccy = self.get_currency() self.history_used...
exchange): try: d[name] = await exchange.get_currencies() print(name, "ok") except: print(name, "error") async def query_all_exchanges_for_their_ccys_over_network(): async with timeout_after(10): async with TaskGroup() as group: ...
256
256
1,522
6
250
ddude1/electrum-axe
electrum_axe/exchange_rate.py
Python
FxThread
FxThread
295
472
295
296
0eb8614e9f6d93bc89e8cfe7d7c0ce2bf9f56a66
bigcode/the-stack
train
52030d5dece423a6b48bd4ed
train
class
class CoinCap(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('api.coincap.io', '/v2/rates/axe/') return {'USD': Decimal(json['data']['rateUsd'])} def history_ccys(self): return ['USD'] async def request_history(self, ccy): # Currently 2000 days i...
class CoinCap(ExchangeBase):
async def get_rates(self, ccy): json = await self.get_json('api.coincap.io', '/v2/rates/axe/') return {'USD': Decimal(json['data']['rateUsd'])} def history_ccys(self): return ['USD'] async def request_history(self, ccy): # Currently 2000 days is the maximum in 1 API call ...
urrencies json = json[0] for ccy, key in [ ('USD', 'price_usd'), ('BTC', 'price_btc'), ]: quote_currencies[ccy] = Decimal(json[key]) return quote_currencies class CoinCap(ExchangeBase):
64
64
173
7
56
ddude1/electrum-axe
electrum_axe/exchange_rate.py
Python
CoinCap
CoinCap
194
209
194
195
2bdbde7c8df8a7a26790ed178d25d32bd77b334c
bigcode/the-stack
train
671cbe4a3ef960c37030a514
train
class
class CoinMarketCap(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('api.coinmarketcap.com', '/v1/ticker/axe/') quote_currencies = {} if not isinstance(json, list): return quote_currencies json = json[0] for ccy, key in [ ('US...
class CoinMarketCap(ExchangeBase):
async def get_rates(self, ccy): json = await self.get_json('api.coinmarketcap.com', '/v1/ticker/axe/') quote_currencies = {} if not isinstance(json, list): return quote_currencies json = json[0] for ccy, key in [ ('USD', 'price_usd'), ('BTC...
.get_json('poloniex.com', '/public?command=returnTicker') quote_currencies = {} axe_ticker = json.get('BTC_AXE') quote_currencies['BTC'] = Decimal(axe_ticker['last']) return quote_currencies class CoinMarketCap(ExchangeBase):
64
64
115
8
55
ddude1/electrum-axe
electrum_axe/exchange_rate.py
Python
CoinMarketCap
CoinMarketCap
179
191
179
179
8d9e87c7fc2c4575e3d86123337d7c800a82b399
bigcode/the-stack
train
c7c1665365a3f8627e97e6ee
train
class
class Bittrex(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('bittrex.com', '/api/v1.1/public/' 'getticker?market=%s-AXE' % ccy) quote_currencies = {} if not json.get('success', False): ...
class Bittrex(ExchangeBase):
async def get_rates(self, ccy): json = await self.get_json('bittrex.com', '/api/v1.1/public/' 'getticker?market=%s-AXE' % ccy) quote_currencies = {} if not json.get('success', False): return quote_currencies ...
5188 async def get_rates(self, ccy): json = await self.get_json('apiv2.bitcoinaverage.com', '/indices/local/ticker/AXE%s' % ccy) return {ccy: Decimal(json['last'])} class Bittrex(ExchangeBase):
64
64
105
8
56
ddude1/electrum-axe
electrum_axe/exchange_rate.py
Python
Bittrex
Bittrex
157
167
157
157
a862eab55405f84e7d0cd9fa0535e949d9e57f59
bigcode/the-stack
train
b31b6da7395c421ad38fa856
train
function
def dictinvert(d): inv = {} for k, vlist in d.items(): for v in vlist: keys = inv.setdefault(v, []) keys.append(k) return inv
def dictinvert(d):
inv = {} for k, vlist in d.items(): for v in vlist: keys = inv.setdefault(v, []) keys.append(k) return inv
api/v3/coins/axe/market_chart?vs_currency=%s&days=max' % ccy) return dict([(datetime.utcfromtimestamp(h[0]/1000).strftime('%Y-%m-%d'), h[1]) for h in history['prices']]) def dictinvert(d):
64
64
43
5
59
ddude1/electrum-axe
electrum_axe/exchange_rate.py
Python
dictinvert
dictinvert
233
239
233
233
425e7557ba2c993552a1ac80909ff48e2618630e
bigcode/the-stack
train
09eda4731e4d4490c8d0dfd5
train
class
class Poloniex(ExchangeBase): async def get_rates(self, ccy): json = await self.get_json('poloniex.com', '/public?command=returnTicker') quote_currencies = {} axe_ticker = json.get('BTC_AXE') quote_currencies['BTC'] = Decimal(axe_ticker['last']) return quote_currencies
class Poloniex(ExchangeBase):
async def get_rates(self, ccy): json = await self.get_json('poloniex.com', '/public?command=returnTicker') quote_currencies = {} axe_ticker = json.get('BTC_AXE') quote_currencies['BTC'] = Decimal(axe_ticker['last']) return quote_currencies
AXE' % ccy) quote_currencies = {} if not json.get('success', False): return quote_currencies last = Decimal(json['result']['Last']) quote_currencies[ccy] = last return quote_currencies class Poloniex(ExchangeBase):
64
64
79
8
55
ddude1/electrum-axe
electrum_axe/exchange_rate.py
Python
Poloniex
Poloniex
170
176
170
170
ea522681025ad2149c31b05b4c762509634470bb
bigcode/the-stack
train
f48bb629e14865e65fac6a3a
train
function
def get_exchanges_by_ccy(history=True): if not history: return dictinvert(CURRENCIES) d = {} exchanges = CURRENCIES.keys() for name in exchanges: klass = globals()[name] exchange = klass(None, None) d[name] = exchange.history_ccys() return dictinvert(d)
def get_exchanges_by_ccy(history=True):
if not history: return dictinvert(CURRENCIES) d = {} exchanges = CURRENCIES.keys() for name in exchanges: klass = globals()[name] exchange = klass(None, None) d[name] = exchange.history_ccys() return dictinvert(d)
Exception as e: pass with open(path, 'w', encoding='utf-8') as f: f.write(json.dumps(d, indent=4, sort_keys=True)) return d CURRENCIES = get_exchanges_and_currencies() def get_exchanges_by_ccy(history=True):
64
64
72
10
54
ddude1/electrum-axe
electrum_axe/exchange_rate.py
Python
get_exchanges_by_ccy
get_exchanges_by_ccy
283
292
283
283
61e87bff02e95b99033bb19b18e105f39ab5eff2
bigcode/the-stack
train
7350304b4580e20bec5a68e7
train
function
def test_create_dataset_header_minimal_version(store, metadata_storage_format): with pytest.raises(NotImplementedError): create_empty_dataset_header( store=store, schema=pd.DataFrame({"col": [1]}), dataset_uuid="new_dataset_uuid", metadata_storage_format=metad...
def test_create_dataset_header_minimal_version(store, metadata_storage_format):
with pytest.raises(NotImplementedError): create_empty_dataset_header( store=store, schema=pd.DataFrame({"col": [1]}), dataset_uuid="new_dataset_uuid", metadata_storage_format=metadata_storage_format, metadata_version=3, ) create_empty_d...
Frame({"col": [datetime.date(2010, 1, 1)]}) write_single_partition( store=store_factory, dataset_uuid="some_dataset", data=new_data, table_name="table1", ) def test_create_dataset_header_minimal_version(store, metadata_storage_format):
64
64
118
14
50
data-engineering-collective/plateau
tests/io/eager/test_write.py
Python
test_create_dataset_header_minimal_version
test_create_dataset_header_minimal_version
74
89
74
74
63d56de122c73982e3ee3994515ac90f1d70e8b7
bigcode/the-stack
train
bbab98305dc959397dc08d17
train
function
def _store_dataframes(dfs, **kwargs): # Positional arguments in function but `None` is acceptable input for kw in ("dataset_uuid", "store"): if kw not in kwargs: kwargs[kw] = None return store_dataframes_as_dataset(dfs=dfs, **kwargs)
def _store_dataframes(dfs, **kwargs): # Positional arguments in function but `None` is acceptable input
for kw in ("dataset_uuid", "store"): if kw not in kwargs: kwargs[kw] = None return store_dataframes_as_dataset(dfs=dfs, **kwargs)
store_dataframes_as_dataset, write_single_partition, ) from plateau.io.testing.write import * # noqa: F40 from plateau.io_components.metapartition import MetaPartition def _store_dataframes(dfs, **kwargs): # Positional arguments in function but `None` is acceptable input
64
64
67
26
37
data-engineering-collective/plateau
tests/io/eager/test_write.py
Python
_store_dataframes
_store_dataframes
20
26
20
21
eaa7b6e4154a7553cc8c7bf6604c3c0d27a07e1e
bigcode/the-stack
train
33dd0222ad3852741f5f48ea
train
function
def test_store_dataframes_as_dataset_no_pipeline_partition_on(store): df = pd.DataFrame( {"P": np.arange(0, 10), "L": np.arange(0, 10), "TARGET": np.arange(10, 20)} ) dataset = store_dataframes_as_dataset( store=store, dataset_uuid="dataset_uuid", dfs=[df], partition...
def test_store_dataframes_as_dataset_no_pipeline_partition_on(store):
df = pd.DataFrame( {"P": np.arange(0, 10), "L": np.arange(0, 10), "TARGET": np.arange(10, 20)} ) dataset = store_dataframes_as_dataset( store=store, dataset_uuid="dataset_uuid", dfs=[df], partition_on="P", metadata_version=4, ) assert isinstance(data...
loaded == expected_dataset # If the read succeeds, the schema is written read_schema_metadata(dataset_uuid=new_dataset.uuid, store=store) # TODO: move `store_dataframes_as_dataset` tests to generic tests or remove if redundant def test_store_dataframes_as_dataset_no_pipeline_partition_on(store):
64
64
137
13
50
data-engineering-collective/plateau
tests/io/eager/test_write.py
Python
test_store_dataframes_as_dataset_no_pipeline_partition_on
test_store_dataframes_as_dataset_no_pipeline_partition_on
121
139
121
121
76b253870620a48e684d65fca6cfabb9cd35a70d
bigcode/the-stack
train
d407b9d1d27e54f50456007b
train
function
def test_store_dataframes_as_dataset_no_pipeline(metadata_version, store): df = pd.DataFrame( {"P": np.arange(0, 10), "L": np.arange(0, 10), "TARGET": np.arange(10, 20)} ) dataset = store_dataframes_as_dataset( store=store, dataset_uuid="dataset_uuid", dfs=[df], meta...
def test_store_dataframes_as_dataset_no_pipeline(metadata_version, store):
df = pd.DataFrame( {"P": np.arange(0, 10), "L": np.arange(0, 10), "TARGET": np.arange(10, 20)} ) dataset = store_dataframes_as_dataset( store=store, dataset_uuid="dataset_uuid", dfs=[df], metadata_version=metadata_version, ) assert isinstance(dataset, Datase...
=store, dataset_uuid="dataset_uuid", dfs=[df], partition_on=["NOT_IN_COLUMNS"], metadata_version=4, ) assert str(excinfo.value) == "Partition column(s) missing: NOT_IN_COLUMNS" def test_store_dataframes_as_dataset_no_pipeline(metadata_version, store):
64
64
142
14
50
data-engineering-collective/plateau
tests/io/eager/test_write.py
Python
test_store_dataframes_as_dataset_no_pipeline
test_store_dataframes_as_dataset_no_pipeline
158
176
158
158
86851b5da63167884e1ab7765dfb5dd8d39505ae
bigcode/the-stack
train
d8a1f224dad22f8047986b0b
train
function
def test_create_dataset_header(store, metadata_storage_format, frozen_time): schema = make_meta(pd.DataFrame({"col": [1]}), origin="1") new_dataset = create_empty_dataset_header( store=store, schema=schema, dataset_uuid="new_dataset_uuid", metadata_storage_format=metadata_storage...
def test_create_dataset_header(store, metadata_storage_format, frozen_time):
schema = make_meta(pd.DataFrame({"col": [1]}), origin="1") new_dataset = create_empty_dataset_header( store=store, schema=schema, dataset_uuid="new_dataset_uuid", metadata_storage_format=metadata_storage_format, metadata_version=4, ) expected_dataset = DatasetMet...
) create_empty_dataset_header( store=store, schema=pd.DataFrame({"col": [1]}), dataset_uuid="new_dataset_uuid", metadata_storage_format=metadata_storage_format, metadata_version=4, ) def test_create_dataset_header(store, metadata_storage_format, frozen_time):
64
64
187
14
50
data-engineering-collective/plateau
tests/io/eager/test_write.py
Python
test_create_dataset_header
test_create_dataset_header
92
117
92
92
039dca18462853d51966d0782c64869d26919961
bigcode/the-stack
train
af06d422f88d0625572a58dd
train
function
def test_write_single_partition_different_partitioning(store_factory): df = pd.DataFrame( OrderedDict([("location", ["0", "1", "2"]), ("other", ["a", "a", "a"])]) ) input_ = [df] dataset = store_dataframes_as_dataset( dfs=input_, store=store_factory, dataset_uuid="datas...
def test_write_single_partition_different_partitioning(store_factory):
df = pd.DataFrame( OrderedDict([("location", ["0", "1", "2"]), ("other", ["a", "a", "a"])]) ) input_ = [df] dataset = store_dataframes_as_dataset( dfs=input_, store=store_factory, dataset_uuid="dataset_uuid", metadata_version=4, partition_on=["other"], ...
_as_dataset( store=store, dataset_uuid="dataset_uuid", dfs=[mp], metadata_version=metadata_version, ) assert isinstance(dataset, DatasetMetadata) assert len(dataset.partitions) == 1 assert dataset.metadata_version == metadata_version stored_dataset = DatasetMetadata...
91
91
304
12
78
data-engineering-collective/plateau
tests/io/eager/test_write.py
Python
test_write_single_partition_different_partitioning
test_write_single_partition_different_partitioning
206
247
206
206
6858661449664028d8f7794dc721ffd318a53952
bigcode/the-stack
train
d3a4510db90c6bf81354187e
train
function
@pytest.fixture() def bound_store_dataframes(): return _store_dataframes
@pytest.fixture() def bound_store_dataframes():
return _store_dataframes
# Positional arguments in function but `None` is acceptable input for kw in ("dataset_uuid", "store"): if kw not in kwargs: kwargs[kw] = None return store_dataframes_as_dataset(dfs=dfs, **kwargs) @pytest.fixture() def bound_store_dataframes():
64
64
16
9
55
data-engineering-collective/plateau
tests/io/eager/test_write.py
Python
bound_store_dataframes
bound_store_dataframes
29
31
29
30
d74bbe9226980d8010159c1842f9e09f5a8ab2c1
bigcode/the-stack
train
47f144f54b66b341c325c9a8
train
function
def test_store_dataframes_as_dataset_mp(metadata_version, store): df = pd.DataFrame( {"P": np.arange(0, 10), "L": np.arange(0, 10), "TARGET": np.arange(10, 20)} ) mp = MetaPartition( label=gen_uuid(), data=df, metadata_version=metadata_version, ) dataset = store_dat...
def test_store_dataframes_as_dataset_mp(metadata_version, store):
df = pd.DataFrame( {"P": np.arange(0, 10), "L": np.arange(0, 10), "TARGET": np.arange(10, 20)} ) mp = MetaPartition( label=gen_uuid(), data=df, metadata_version=metadata_version, ) dataset = store_dataframes_as_dataset( store=store, dataset_uuid="dat...
) assert isinstance(dataset, DatasetMetadata) assert len(dataset.partitions) == 1 assert dataset.metadata_version == metadata_version stored_dataset = DatasetMetadata.load_from_store("dataset_uuid", store) assert dataset == stored_dataset def test_store_dataframes_as_dataset_mp(metadata_version,...
64
64
166
13
50
data-engineering-collective/plateau
tests/io/eager/test_write.py
Python
test_store_dataframes_as_dataset_mp
test_store_dataframes_as_dataset_mp
179
203
179
179
b149b931d881aa9cfb3ac30a3dbfbb3e87e51fa4
bigcode/the-stack
train
bf4ca13841802df046d60dbb
train
function
def test_store_dataframes_as_dataset_partition_on_inconsistent(store): df = pd.DataFrame( {"P": np.arange(0, 10), "L": np.arange(0, 10), "TARGET": np.arange(10, 20)} ) with pytest.raises(ValueError) as excinfo: store_dataframes_as_dataset( store=store, dataset_uuid="...
def test_store_dataframes_as_dataset_partition_on_inconsistent(store):
df = pd.DataFrame( {"P": np.arange(0, 10), "L": np.arange(0, 10), "TARGET": np.arange(10, 20)} ) with pytest.raises(ValueError) as excinfo: store_dataframes_as_dataset( store=store, dataset_uuid="dataset_uuid", dfs=[df], partition_on=["NOT_IN_...
P", metadata_version=4, ) assert isinstance(dataset, DatasetMetadata) assert len(dataset.partitions) == 10 stored_dataset = DatasetMetadata.load_from_store("dataset_uuid", store) assert dataset == stored_dataset def test_store_dataframes_as_dataset_partition_on_inconsistent(store):
64
64
126
13
50
data-engineering-collective/plateau
tests/io/eager/test_write.py
Python
test_store_dataframes_as_dataset_partition_on_inconsistent
test_store_dataframes_as_dataset_partition_on_inconsistent
142
155
142
142
ff1753b940ee7f81b9b0ba032401f69bab0a3a23
bigcode/the-stack
train
06e86538dfff090904539b44
train
function
def test_write_single_partition(store_factory, mock_uuid, metadata_version): create_empty_dataset_header( store=store_factory(), schema=pd.DataFrame({"col": [1]}), dataset_uuid="some_dataset", metadata_version=metadata_version, table_name="table1", ) new_data = pd.Da...
def test_write_single_partition(store_factory, mock_uuid, metadata_version):
create_empty_dataset_header( store=store_factory(), schema=pd.DataFrame({"col": [1]}), dataset_uuid="some_dataset", metadata_version=metadata_version, table_name="table1", ) new_data = pd.DataFrame({"col": [1, 2]}) keys_in_store = set(store_factory().keys()) ...
(dfs, **kwargs): # Positional arguments in function but `None` is acceptable input for kw in ("dataset_uuid", "store"): if kw not in kwargs: kwargs[kw] = None return store_dataframes_as_dataset(dfs=dfs, **kwargs) @pytest.fixture() def bound_store_dataframes(): return _store_datafr...
92
92
307
14
77
data-engineering-collective/plateau
tests/io/eager/test_write.py
Python
test_write_single_partition
test_write_single_partition
34
71
34
34
f814394055a95e26290d09d8bf79e4240f2d776e
bigcode/the-stack
train
3de76f8528c813a898920e9c
train
function
def filter(args): filter_TB() filter_NHIS() filter_UKBB()
def filter(args):
filter_TB() filter_NHIS() filter_UKBB()
from .NHIS.filter import filter as filter_NHIS from .UKBB.filter import filter as filter_UKBB from .TB.filter import filter as filter_TB def filter(args):
41
64
21
4
36
alexprz/NHIS_analyse
pvals/__init__.py
Python
filter
filter
6
9
6
6
adf08b119c927f890bff968819b8f9f820f7964b
bigcode/the-stack
train
33c45f0ebad1a5dfccbcc518
train
class
class Solution(object): def sortedSquares(self, A): """ :type A: List[int] :rtype: List[int] """ new_list = [] for i in A: new_list.append((abs(i)) ** 2) new_list.sort() a = sorted([abs(i) ** 2 for i in A]) return new_list
class Solution(object):
def sortedSquares(self, A): """ :type A: List[int] :rtype: List[int] """ new_list = [] for i in A: new_list.append((abs(i)) ** 2) new_list.sort() a = sorted([abs(i) ** 2 for i in A]) return new_list
class Solution(object):
4
64
80
4
0
shaohy/leetcode
H/977.Squares of a Sorted Array.py
Python
Solution
Solution
1
13
1
1
1d66bec2e686b8a5c0b3ffdcbef1d285b97d6247
bigcode/the-stack
train
7cc89ff0f1ff29fd1e3c1d67
train
class
class VoiceProtocol: """A class that represents the Discord voice protocol. This is an abstract class. The library provides a concrete implementation under :class:`VoiceClient`. This class allows you to implement a protocol to allow for an external method of sending voice, such as Lavalink_ or a n...
class VoiceProtocol:
"""A class that represents the Discord voice protocol. This is an abstract class. The library provides a concrete implementation under :class:`VoiceClient`. This class allows you to implement a protocol to allow for an external method of sending voice, such as Lavalink_ or a native library impleme...
transmit data to endpoint:port. """ from __future__ import annotations import asyncio import socket import logging import struct import threading from typing import Any, Callable, List, Optional, TYPE_CHECKING, Tuple from . import opus, utils from .backoff import ExponentialBackoff from .gateway import * from .erro...
243
243
813
4
239
Awayume/discord.py
discord/voice_client.py
Python
VoiceProtocol
VoiceProtocol
90
197
90
90
03ff8414535bf84082bd4f963979d6ea9c91278f
bigcode/the-stack
train
204368c9fb07c84ebea84878
train
class
class VoiceClient(VoiceProtocol): """Represents a Discord voice connection. You do not create these, you typically get them from e.g. :meth:`VoiceChannel.connect`. Warning -------- In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded th...
class VoiceClient(VoiceProtocol):
"""Represents a Discord voice connection. You do not create these, you typically get them from e.g. :meth:`VoiceChannel.connect`. Warning -------- In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through :func:`opus.load_opus`. ...
` will be called. The order that these two are called is unspecified. Parameters ------------ timeout: :class:`float` The timeout for the connection. reconnect: :class:`bool` Whether reconnection is expected. """ raise NotImplementedError ...
256
256
3,700
7
249
Awayume/discord.py
discord/voice_client.py
Python
VoiceClient
VoiceClient
199
677
199
199
0c92100f9365214ec24ba17768584ce7b927558b
bigcode/the-stack
train
c17325bed876c63973368639
train
class
class Event: __slots__ = ['response'] def __init__(self, response): self.response = response @property def ready(self): return self.response['t'] == 'READY' @property def ready_supplemental(self): return self.response['t'] == 'READY_SUPPLEMENTAL' @property def activity_join_request(self): #not sure wha...
class Event:
__slots__ = ['response'] def __init__(self, response): self.response = response @property def ready(self): return self.response['t'] == 'READY' @property def ready_supplemental(self): return self.response['t'] == 'READY_SUPPLEMENTAL' @property def activity_join_request(self): #not sure what this is r...
class Event:
3
256
2,729
3
0
BalaM314/Discord-S.C.U.M
discum/gateway/event.py
Python
Event
Event
1
396
1
1
e9d4f65df9e5cca45dbb07c8ef31006c13c9e17d
bigcode/the-stack
train
e91578b7ad064b076bb00fab
train
function
def get_arguments() -> argparse.Namespace: """ parse all the arguments from command line inteface return a list of parsed arguments """ parser = argparse.ArgumentParser(description="convert np.array to images.") parser.add_argument( "dir", type=str, help="path to a direc...
def get_arguments() -> argparse.Namespace:
""" parse all the arguments from command line inteface return a list of parsed arguments """ parser = argparse.ArgumentParser(description="convert np.array to images.") parser.add_argument( "dir", type=str, help="path to a directory containing arrays you want to convert"...
import argparse import glob import os from typing import List import numpy as np from PIL import Image def get_arguments() -> argparse.Namespace:
32
64
80
8
23
yiskw713/asrf
utils/convert_arr2img.py
Python
get_arguments
get_arguments
10
23
10
10
a2df9e40202749775bae292bc01e860758ab926e
bigcode/the-stack
train
dd47ded4020f2cf583afbb93
train
function
def convert_arr2img(arr: np.ndarray, palette: List[int]) -> Image.Image: """ Args: arr: 1d array(T, ) palette: color palette """ arr = arr.astype(np.uint8) arr = np.tile(arr, (100, 1)) img = Image.fromarray(arr) img = img.convert("P") img.putpalette(palette) return i...
def convert_arr2img(arr: np.ndarray, palette: List[int]) -> Image.Image:
""" Args: arr: 1d array(T, ) palette: color palette """ arr = arr.astype(np.uint8) arr = np.tile(arr, (100, 1)) img = Image.fromarray(arr) img = img.convert("P") img.putpalette(palette) return img
.ArgumentParser(description="convert np.array to images.") parser.add_argument( "dir", type=str, help="path to a directory containing arrays you want to convert", ) return parser.parse_args() def convert_arr2img(arr: np.ndarray, palette: List[int]) -> Image.Image:
64
64
91
19
45
yiskw713/asrf
utils/convert_arr2img.py
Python
convert_arr2img
convert_arr2img
26
38
26
26
df116e509afd8d4ab47e1bab6dbfdbfb02d747d4
bigcode/the-stack
train
7132660517f3125a6cc710d9
train
function
def main() -> None: args = get_arguments() voc = Image.open("./imgs/voc_sample.png") voc = voc.convert("P") palette = voc.getpalette() arr_paths = glob.glob(os.path.join(args.dir, "*.npy")) for path in arr_paths: name = os.path.basename(path)[:-4] # remove .npy arr = np.load(...
def main() -> None:
args = get_arguments() voc = Image.open("./imgs/voc_sample.png") voc = voc.convert("P") palette = voc.getpalette() arr_paths = glob.glob(os.path.join(args.dir, "*.npy")) for path in arr_paths: name = os.path.basename(path)[:-4] # remove .npy arr = np.load(path) img =...
) palette: color palette """ arr = arr.astype(np.uint8) arr = np.tile(arr, (100, 1)) img = Image.fromarray(arr) img = img.convert("P") img.putpalette(palette) return img def main() -> None:
64
64
117
6
57
yiskw713/asrf
utils/convert_arr2img.py
Python
main
main
41
57
41
41
e921150ce30aebc447ac1eaba4202ebbd3d4a353
bigcode/the-stack
train
f66a6ab90c3b641999057612
train
function
def send_action(url, payload, timeout=60): log.error("skygear.container.send_action is deprecated.\n" "Please use SkygearContainer().send_action instead.") headers = {'Content-type': 'application/json', 'Accept': 'application/json'} _data = json.dumps(payload, cls=PayloadEncoder...
def send_action(url, payload, timeout=60):
log.error("skygear.container.send_action is deprecated.\n" "Please use SkygearContainer().send_action instead.") headers = {'Content-type': 'application/json', 'Accept': 'application/json'} _data = json.dumps(payload, cls=PayloadEncoder) return requests.post(url, data=_data,...
= logging.getLogger(__name__) class PayloadEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): ts = obj.timestamp() return strict_rfc3339.timestamp_to_rfc3339_utcoffset(ts) def send_action(url, payload, timeout=60):
64
64
91
11
53
IniZio/py-skygear
skygear/container.py
Python
send_action
send_action
33
40
33
33
bd6855f16d7cb0e4ccb36453c5a48df283ec925b
bigcode/the-stack
train
6ca272862f1bc2ae3fd565a8
train
class
class SkygearContainer(object): endpoint = 'http://localhost:3000' api_key = None access_token = None user_id = None app_name = '' transport = None def __init__(self, endpoint=None, api_key=None, access_token=None, user_id=None, transport=None): if endpoint: ...
class SkygearContainer(object):
endpoint = 'http://localhost:3000' api_key = None access_token = None user_id = None app_name = '' transport = None def __init__(self, endpoint=None, api_key=None, access_token=None, user_id=None, transport=None): if endpoint: self.endpoint = endpoint ...
): def default(self, obj): if isinstance(obj, datetime.datetime): ts = obj.timestamp() return strict_rfc3339.timestamp_to_rfc3339_utcoffset(ts) def send_action(url, payload, timeout=60): log.error("skygear.container.send_action is deprecated.\n" "Please use Skygea...
137
137
457
6
131
IniZio/py-skygear
skygear/container.py
Python
SkygearContainer
SkygearContainer
43
108
43
43
3c73bc128b9ea06e170dfb75b3da3b11c369cc30
bigcode/the-stack
train
967126f450cae5e476d6c1ff
train
class
class PayloadEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): ts = obj.timestamp() return strict_rfc3339.timestamp_to_rfc3339_utcoffset(ts)
class PayloadEncoder(json.JSONEncoder):
def default(self, obj): if isinstance(obj, datetime.datetime): ts = obj.timestamp() return strict_rfc3339.timestamp_to_rfc3339_utcoffset(ts)
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import json import logging import requests import strict_rfc3339 log = logging.getLogger(__name__) class PayloadEncoder(json.JSONEn...
64
64
46
7
57
IniZio/py-skygear
skygear/container.py
Python
PayloadEncoder
PayloadEncoder
26
30
26
26
e24c71f1b2fdc199b07f6a4e36ecec670c668d5d
bigcode/the-stack
train
784804146e4a6eea502b765e
train
class
class AlipayUserTwostageCommonUseRequest(object): def __init__(self, biz_model=None): self._biz_model = biz_model self._biz_content = None self._version = "1.0" self._terminal_type = None self._terminal_info = None self._prod_code = None self._notify_url = No...
class AlipayUserTwostageCommonUseRequest(object):
def __init__(self, biz_model=None): self._biz_model = biz_model self._biz_content = None self._version = "1.0" self._terminal_type = None self._terminal_info = None self._prod_code = None self._notify_url = None self._return_url = None self._ud...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.FileItem import FileItem from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.AlipayUserTwostageCommonUseModel import AlipayUserTwostageCommonUseModel class AlipayUserTwostageCommonUseRequest(object):
79
254
848
12
66
snowxmas/alipay-sdk-python-all
alipay/aop/api/request/AlipayUserTwostageCommonUseRequest.py
Python
AlipayUserTwostageCommonUseRequest
AlipayUserTwostageCommonUseRequest
12
144
12
13
1481c4b1f3dccb71bf98d8b72d589bf43e73e9c4
bigcode/the-stack
train
b9c24c2a51e85dca99ce3dfd
train
function
def is_valid(v): '''Check vector v for validity''' result = b58decode_chk(v) if result is None: return False for template in templates: prefix = str(bytearray(template[0])) suffix = str(bytearray(template[2])) if result.startswith(prefix) and result.endswith(suffix): ...
def is_valid(v):
'''Check vector v for validity''' result = b58decode_chk(v) if result is None: return False for template in templates: prefix = str(bytearray(template[0])) suffix = str(bytearray(template[2])) if result.startswith(prefix) and result.endswith(suffix): if (len(r...
False, None, True)), ((PRIVKEY_TEST,), 32, (), (True, True, None, False)), ((PRIVKEY_TEST,), 32, (1,), (True, True, None, True)) ] def is_valid(v):
64
64
98
5
59
graventi/Seci
contrib/testgen/gen_base58_test_vectors.py
Python
is_valid
is_valid
43
54
43
43
8f834b76f890608b9c5ad22ebf362246b28dbfbb
bigcode/the-stack
train
f5737e0d5403369922c3c570
train
function
def gen_invalid_vectors(): '''Generate invalid test vectors''' # start with some manual edge-cases yield "", yield "x", while True: # kinds of invalid vectors: # invalid prefix # invalid payload length # invalid (randomized) suffix (add random data) # ...
def gen_invalid_vectors():
'''Generate invalid test vectors''' # start with some manual edge-cases yield "", yield "x", while True: # kinds of invalid vectors: # invalid prefix # invalid payload length # invalid (randomized) suffix (add random data) # corrupt checksum fo...
urandom(len(template[2])) else: suffix = str(bytearray(template[2])) return b58encode_chk(prefix + payload + suffix) def randbool(p = 0.5): '''Return True with P(p)''' return random.random() < p def gen_invalid_vectors():
64
64
199
5
58
graventi/Seci
contrib/testgen/gen_base58_test_vectors.py
Python
gen_invalid_vectors
gen_invalid_vectors
91
111
91
91
469f642697feb63be8c22a393700bea7bbe4a326
bigcode/the-stack
train
7eff214096ca9868c75d6315
train
function
def gen_valid_vectors(): '''Generate valid test vectors''' while True: for template in templates: prefix = str(bytearray(template[0])) payload = os.urandom(template[1]) suffix = str(bytearray(template[2])) rv = b58encode_chk(prefix + payload + suffix) ...
def gen_valid_vectors():
'''Generate valid test vectors''' while True: for template in templates: prefix = str(bytearray(template[0])) payload = os.urandom(template[1]) suffix = str(bytearray(template[2])) rv = b58encode_chk(prefix + payload + suffix) assert is_valid(...
prefix = str(bytearray(template[0])) suffix = str(bytearray(template[2])) if result.startswith(prefix) and result.endswith(suffix): if (len(result) - len(prefix) - len(suffix)) == template[1]: return True return False def gen_valid_vectors():
64
64
114
5
58
graventi/Seci
contrib/testgen/gen_base58_test_vectors.py
Python
gen_valid_vectors
gen_valid_vectors
56
66
56
56
b1986229c14e3faf5a0d2a15a56e0ded3de4f2a5
bigcode/the-stack
train
49e0efc429d8f317f56a4ab9
train
function
def gen_invalid_vector(template, corrupt_prefix, randomize_payload_size, corrupt_suffix): '''Generate possibly invalid vector''' if corrupt_prefix: prefix = os.urandom(1) else: prefix = str(bytearray(template[0])) if randomize_payload_size: payload = os.urandom(max(int(rando...
def gen_invalid_vector(template, corrupt_prefix, randomize_payload_size, corrupt_suffix):
'''Generate possibly invalid vector''' if corrupt_prefix: prefix = os.urandom(1) else: prefix = str(bytearray(template[0])) if randomize_payload_size: payload = os.urandom(max(int(random.expovariate(0.5)), 50)) else: payload = os.urandom(template[1]) if ...
assert is_valid(rv) metadata = dict([(x,y) for (x,y) in zip(metadata_keys,template[3]) if y is not None]) yield (rv, b2a_hex(payload), metadata) def gen_invalid_vector(template, corrupt_prefix, randomize_payload_size, corrupt_suffix):
64
64
139
17
47
graventi/Seci
contrib/testgen/gen_base58_test_vectors.py
Python
gen_invalid_vector
gen_invalid_vector
68
85
68
68
fdab786fb98b0dd5933c731798036d8fb9d468dc
bigcode/the-stack
train
0589a18c6d33eee27931e42a
train
function
def randbool(p = 0.5): '''Return True with P(p)''' return random.random() < p
def randbool(p = 0.5):
'''Return True with P(p)''' return random.random() < p
payload = os.urandom(template[1]) if corrupt_suffix: suffix = os.urandom(len(template[2])) else: suffix = str(bytearray(template[2])) return b58encode_chk(prefix + payload + suffix) def randbool(p = 0.5):
64
64
27
10
54
graventi/Seci
contrib/testgen/gen_base58_test_vectors.py
Python
randbool
randbool
87
89
87
87
a629ea48ddb3a57d33c165551bf8590b614cd206
bigcode/the-stack
train
d25f526688f7d228b3ecb3fd
train
function
def remove(array): if len(array) <= 1: return array pre = 0 for cur in range(1, len(array)): if array[pre] != array[cur]: pre += 1 array[pre] = array[cur] return array[:pre + 1], pre + 1
def remove(array):
if len(array) <= 1: return array pre = 0 for cur in range(1, len(array)): if array[pre] != array[cur]: pre += 1 array[pre] = array[cur] return array[:pre + 1], pre + 1
liu """ 移除排序好的重复数字,返回不重复的数字个数 使用快慢指针法 [0, 0, 1, 2, 2, 5] ---> [0, 1, 2, 5] 4 """ def remove(array):
64
64
73
4
60
bigfoolliu/liu_aistuff
interview/code/remove_duplicates_from_sorted_list.py
Python
remove
remove
13
22
13
13
3a46ece841ea1503e558c6e981a766698b029f99
bigcode/the-stack
train
47f0488963b0c85023a7d736
train
function
def train(args): print(args) device = paddle.set_device(args.device) train_loader, dev_loader, test_loader, vocab, bos_id, pad_id, train_data_len = create_data_loader( args) net = VAESeq2SeqModel( embed_dim=args.embed_dim, hidden_size=args.hidden_size, latent_size=args.l...
def train(args):
print(args) device = paddle.set_device(args.device) train_loader, dev_loader, test_loader, vocab, bos_id, pad_id, train_data_len = create_data_loader( args) net = VAESeq2SeqModel( embed_dim=args.embed_dim, hidden_size=args.hidden_size, latent_size=args.latent_size, ...
2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License...
115
115
386
4
110
tanhanzhuo/PaddleNLP
examples/text_generation/vae-seq2seq/train.py
Python
train
train
24
74
24
24
d8086a6a5c18290a2ed6a6d0c4f99d49aec45f12
bigcode/the-stack
train
bd180b5a49e60684e4c1b10b
train
class
class AutoloadJsHandler(SessionHandler): ''' Implements a custom Tornado handler for the autoload JS chunk ''' @gen.coroutine def get(self, *args, **kwargs): session = yield self.get_session() element_id = self.get_argument("bokeh-autoload-element", default=None) if not element...
class AutoloadJsHandler(SessionHandler):
''' Implements a custom Tornado handler for the autoload JS chunk ''' @gen.coroutine def get(self, *args, **kwargs): session = yield self.get_session() element_id = self.get_argument("bokeh-autoload-element", default=None) if not element_id: self.send_error(status_c...
okeh.core.templates import AUTOLOAD_JS from bokeh.util.string import encode_utf8 from bokeh.util.compiler import bundle_all_models from bokeh.embed.elements import script_for_render_items from bokeh.embed.util import RenderItem from .session_handler import SessionHandler #---------------------------------------------...
104
105
353
8
96
al-yakubovich/bokeh
bokeh/server/views/autoload_js_handler.py
Python
AutoloadJsHandler
AutoloadJsHandler
55
99
55
55
cec2a26bc31688fbb5c72a8fb8ebbfe7ed04ab7c
bigcode/the-stack
train
f655898d988123a716c6445c
train
function
def vote_class(face_encoding, tolerance=0.3, topN=5): myprint('vote start ', time.time()) """ 当比较的结果小于tolerance的时候,有多个值,采用取topN 进行投票 ,决定最终的分类,此处没有对 distance 距离进行加权 :param face_encoding: face encoding :param tolerance: 距离的阈值,越小越相似 :param topN: 参与投票的最大数量 :return: detect name """ # 计算出距...
def vote_class(face_encoding, tolerance=0.3, topN=5):
myprint('vote start ', time.time()) """ 当比较的结果小于tolerance的时候,有多个值,采用取topN 进行投票 ,决定最终的分类,此处没有对 distance 距离进行加权 :param face_encoding: face encoding :param tolerance: 距离的阈值,越小越相似 :param topN: 参与投票的最大数量 :return: detect name """ # 计算出距离 distance_ = face_recognition.face_distance(known...
", time.localtime()) myprint(time_format + " update last_time and clear current_names.") with open(name_record, 'a') as f: if len(current_names) > 0: f.writelines("{}:{} \n".format(time_format, str(current_names))) print("======", current_names) current_names ...
113
113
377
17
96
matiji66/face-card-machine
facerec_from_webcam_faster.py
Python
vote_class
vote_class
101
129
101
101
2bfab71fcbc5b3adca70ca1336f08c36a64bb55a
bigcode/the-stack
train
50e3da1a3537181210f27b3e
train
function
def myprint(log, ts=time.time()): global last_ts diff = ts - last_ts print(log, '--------', diff) last_ts = ts
def myprint(log, ts=time.time()):
global last_ts diff = ts - last_ts print(log, '--------', diff) last_ts = ts
直接进行保存. name_record = "./dataset/face_record.txt" # 持久化识别出的人脸结果 NAME_DF = pd.DataFrame(known_face_names, columns=["name"]) import datetime import time last_ts = time.time() def myprint(log, ts=time.time()):
64
64
37
9
55
matiji66/face-card-machine
facerec_from_webcam_faster.py
Python
myprint
myprint
62
66
62
62
ed2f7c34fa7f592e685ef0ba18d8350e1e18cc38
bigcode/the-stack
train
4436565d37cb01a907d7ec8e
train
function
def face_process(): myprint("face process start",time.time()) # Find all the faces and face encodings in the current frame of video # face_locations = face_recognition.face_locations(rgb_small_frame, model="cnn") myprint('face_locations start', time.time()) face_locations = face_recognition.face_loc...
def face_process():
myprint("face process start",time.time()) # Find all the faces and face encodings in the current frame of video # face_locations = face_recognition.face_locations(rgb_small_frame, model="cnn") myprint('face_locations start', time.time()) face_locations = face_recognition.face_locations(rgb_small_fra...
.concat([topDF, namedf], axis=1) # concat name and distance # print('con', con) group = con.groupby(["name"])['dis'].sum() gp = group.reset_index() print('vote -- ', gp) if len(gp) == 0: print("------unknown -----") return "Unknown", 10 import numpy as np # TODO optimize a...
156
156
522
4
151
matiji66/face-card-machine
facerec_from_webcam_faster.py
Python
face_process
face_process
132
171
132
132
94e2c7c625b909965928cafad269f3af1b25aedd
bigcode/the-stack
train
a69eeb6067d82aeb7f744b34
train
function
def process_face_records(name): """ 处理每一条识别的记录 ,并在一定时间之后将数据持久化到文件中 :param name: :return: """ print('process_face_records start', time.time()) global current_names, last_time # myprint("global current_names {}, last_time {}".format(current_names, last_time)) # 判断是不是在识别的列表中,不在的话就进行问候...
def process_face_records(name):
""" 处理每一条识别的记录 ,并在一定时间之后将数据持久化到文件中 :param name: :return: """ print('process_face_records start', time.time()) global current_names, last_time # myprint("global current_names {}, last_time {}".format(current_names, last_time)) # 判断是不是在识别的列表中,不在的话就进行问候 if name not in current_name...
进行保存. name_record = "./dataset/face_record.txt" # 持久化识别出的人脸结果 NAME_DF = pd.DataFrame(known_face_names, columns=["name"]) import datetime import time last_ts = time.time() def myprint(log, ts=time.time()): global last_ts diff = ts - last_ts print(log, '--------', diff) last_ts = ts def process_face_...
97
97
324
6
90
matiji66/face-card-machine
facerec_from_webcam_faster.py
Python
process_face_records
process_face_records
69
98
69
69
5a3395bc0055a4734a69f61ab6918420f6f01724
bigcode/the-stack
train
e9e469c81585a89eb99a9f9a
train
class
class SNNModel: def __init__(self, entities, relations, entity_shape=32, relation_shape=64, input_type='instances', **kwargs): self.snn = SNN(entities, relations, entity_shape=entity_shape, relation_shape=relation_shape) self.input = self._build_input(input_type, **kwargs) self.output = self...
class SNNModel:
def __init__(self, entities, relations, entity_shape=32, relation_shape=64, input_type='instances', **kwargs): self.snn = SNN(entities, relations, entity_shape=entity_shape, relation_shape=relation_shape) self.input = self._build_input(input_type, **kwargs) self.output = self.snn(self.input)...
from .base import SNN from keras.layers import Input class SNNModel:
18
64
183
5
12
fsadannn/snn
snn/models.py
Python
SNNModel
SNNModel
5
21
5
5
66229b8da39a5b1a3345dbcdc3507854bcff989a
bigcode/the-stack
train
7f4cd281c460dae9da7defdd
train
function
def init_cached(db_session, backend_obj): """ 初始化缓存 :param db_session: :type db_session: :param backend_obj: :type backend_obj: :return: :rtype: """ global db, backend db = db_session backend = backend_obj
def init_cached(db_session, backend_obj):
""" 初始化缓存 :param db_session: :type db_session: :param backend_obj: :type backend_obj: :return: :rtype: """ global db, backend db = db_session backend = backend_obj
# coding=utf8 from sqlalchemy import event try: from cPickle import loads, dumps except: from pickle import loads, dumps db = None models = {} backend = None def init_cached(db_session, backend_obj):
52
64
73
9
42
hausir/CacheAlchemy
build/lib/CacheAlchemy/cached.py
Python
init_cached
init_cached
12
24
12
12
3ab622af0ef2d7ca7449b9a539174d12a9f86658
bigcode/the-stack
train
bb6feacdba48cf134b11ff30
train
function
def cached(model_class, _id, expire=3600): """ 通过id读取缓存对象 :param model_class: :type model_class: :param _id: :type _id: :param expire: :type expire: :return: :rtype: """ obj = backend.get_obj(str(model_class)) if not obj: obj = db.query(model_class).ge...
def cached(model_class, _id, expire=3600):
""" 通过id读取缓存对象 :param model_class: :type model_class: :param _id: :type _id: :param expire: :type expire: :return: :rtype: """ obj = backend.get_obj(str(model_class)) if not obj: obj = db.query(model_class).get(_id) if obj: backend....
:type db_session: :param backend_obj: :type backend_obj: :return: :rtype: """ global db, backend db = db_session backend = backend_obj def cached(model_class, _id, expire=3600):
64
64
204
13
50
hausir/CacheAlchemy
build/lib/CacheAlchemy/cached.py
Python
cached
cached
27
56
27
27
6d226d511d4e2c614a7996411c796ba812b2c3e7
bigcode/the-stack
train
12fa8d40c5c09d602551b4c1
train
function
def clustering_with_hdbscan(data): clust_count = np.linspace(1, 20, num=20, dtype='int') clust_number = 2 plot_number = 1 plt.figure (figsize=(17,12)) while clust_number < 21: hdb = hdbscan.HDBSCAN(min_cluster_size=clust_number) hdb_pred = hdb.fit(data) plt.subplot(5, 4, plot_number, title = 'Min. ...
def clustering_with_hdbscan(data):
clust_count = np.linspace(1, 20, num=20, dtype='int') clust_number = 2 plot_number = 1 plt.figure (figsize=(17,12)) while clust_number < 21: hdb = hdbscan.HDBSCAN(min_cluster_size=clust_number) hdb_pred = hdb.fit(data) plt.subplot(5, 4, plot_number, title = 'Min. Cluster Size = {}'.format(clust_num...
import label_binarize from sklearn.multiclass import OneVsRestClassifier from scipy import interp from sklearn.metrics import roc_auc_score from sklearn.metrics import accuracy_score LabeledSentence = gensim.models.doc2vec.LabeledSentence import hdbscan def clustering_with_hdbscan(data):
64
64
160
8
55
AghilasSini/AT-Annotator
features_extractions/clustering_audiobook.py
Python
clustering_with_hdbscan
clustering_with_hdbscan
104
119
104
104
70d94e43a666c72a7f5ee062456c4f846aa02bf1
bigcode/the-stack
train
77cf59988ecc6d7c1e566216
train
function
def main(): parser = argparse.ArgumentParser(description="") # Add options parser.add_argument("-v", "--verbosity", action="count", default=0, help="increase output verbosity") # Add arguments parser.add_argument("input_file", help="The input file to be projected") # parser.add_argument("speech_feats_...
def main():
parser = argparse.ArgumentParser(description="") # Add options parser.add_argument("-v", "--verbosity", action="count", default=0, help="increase output verbosity") # Add arguments parser.add_argument("input_file", help="The input file to be projected") # parser.add_argument("speech_feats_file", help=...
, title = 'Min. Cluster Size = {}'.format(clust_number)) plt.scatter(unbal[:,0], unbal[:,1], c=hdb_pred.labels_, cmap=cmap) plot_number += 1 clust_number += 1 plt.tight_layout() plt.show() def main():
64
64
216
3
61
AghilasSini/AT-Annotator
features_extractions/clustering_audiobook.py
Python
main
main
123
150
123
123
bbfddc9e86c13efddd5b1d2071e50160ff96ef31
bigcode/the-stack
train
c5f914b14014fb74338d51e7
train
class
class TestBuilder: def test_basic(self, aws_iam, aws_batch, service_role, security_group, subnets): now = datetime.datetime.now(tz=datetime.timezone.utc) """ GIVEN a basic alpine image """ manager = Builder().build( service_role, security_group, subnets, "alpine",...
class TestBuilder:
def test_basic(self, aws_iam, aws_batch, service_role, security_group, subnets): now = datetime.datetime.now(tz=datetime.timezone.utc) """ GIVEN a basic alpine image """ manager = Builder().build( service_role, security_group, subnets, "alpine", "3.15.0" )...
import datetime from chorecoral import Builder class TestBuilder:
14
64
157
4
9
sanogenetics/chore-coral
tests/builder_test.py
Python
TestBuilder
TestBuilder
6
24
6
6
67f1e5194eed6741b3f29133b9fa28b44ab6d6e6
bigcode/the-stack
train
fcc7a88c7e27e1e109b8344e
train
class
class TestFakeNamespace(TestYamlConfig): def setup(self): self.test_class = config.FakeNamespace def test_docopt_dict(self): """ Tests if a dict in the format that docopt returns can be parsed correctly. """ d = { "--verbose": True, "--an-...
class TestFakeNamespace(TestYamlConfig):
def setup(self): self.test_class = config.FakeNamespace def test_docopt_dict(self): """ Tests if a dict in the format that docopt returns can be parsed correctly. """ d = { "--verbose": True, "--an-option": "some_option", "<an_...
conf_obj.zbkc_git_base_url == "git://git.zbkc.com/" def test_get_reserve_machines_default(self): conf_obj = self.test_class() conf_obj.yaml_path = '' conf_obj.load() assert conf_obj.reserve_machines == 5 def test_set_reserve_machines_via_private(self): conf_obj = self....
174
174
582
8
165
zbkc-teuthology/teuthology
teuthology/test/test_config.py
Python
TestFakeNamespace
TestFakeNamespace
119
189
119
119
024d072001920f787a93e3d6e1afad24e425dd9c
bigcode/the-stack
train
89cd063e14b963536ba13453
train
class
class TestTeuthologyConfig(TestYamlConfig): def setup(self): self.test_class = config.TeuthologyConfig def test_get_zbkc_git_base_default(self): conf_obj = self.test_class() conf_obj.yaml_path = '' conf_obj.load() assert conf_obj.zbkc_git_base_url == "https://github.com/...
class TestTeuthologyConfig(TestYamlConfig):
def setup(self): self.test_class = config.TeuthologyConfig def test_get_zbkc_git_base_default(self): conf_obj = self.test_class() conf_obj.yaml_path = '' conf_obj.load() assert conf_obj.zbkc_git_base_url == "https://github.com/zbkc/" def test_set_zbkc_git_base_via_p...
) assert d["foo"] == "bar" def test_get(self): conf_obj = self.test_class() assert conf_obj.get('foo') is None assert conf_obj.get('foo', 'bar') == 'bar' conf_obj.foo = 'baz' assert conf_obj.get('foo') == 'baz' class TestTeuthologyConfig(TestYamlConfig):
81
81
271
10
71
zbkc-teuthology/teuthology
teuthology/test/test_config.py
Python
TestTeuthologyConfig
TestTeuthologyConfig
81
111
81
81
fb5d58abb462e9d23030399435afd94033c9b95b
bigcode/the-stack
train
8a97338416677fc09c43c812
train
class
class TestJobConfig(TestYamlConfig): def setup(self): self.test_class = config.JobConfig
class TestJobConfig(TestYamlConfig):
def setup(self): self.test_class = config.JobConfig
reserve_machines'] = 2 assert conf_obj.reserve_machines == 2 def test_set_nonstandard(self): conf_obj = self.test_class() conf_obj.something = 'something else' assert conf_obj.something == 'something else' class TestJobConfig(TestYamlConfig):
64
64
22
8
56
zbkc-teuthology/teuthology
teuthology/test/test_config.py
Python
TestJobConfig
TestJobConfig
114
116
114
114
f136b5ac417a3affb93277f5d58bfbe663f0a239
bigcode/the-stack
train
a14a9f256889f6876bb766c2
train
class
class TestYamlConfig(object): def setup(self): self.test_class = config.YamlConfig def test_set_multiple(self): conf_obj = self.test_class() conf_obj.foo = 'foo' conf_obj.bar = 'bar' assert conf_obj.foo == 'foo' assert conf_obj.bar == 'bar' assert conf_ob...
class TestYamlConfig(object):
def setup(self): self.test_class = config.YamlConfig def test_set_multiple(self): conf_obj = self.test_class() conf_obj.foo = 'foo' conf_obj.bar = 'bar' assert conf_obj.foo == 'foo' assert conf_obj.bar == 'bar' assert conf_obj.to_dict()['foo'] == 'foo' ...
import pytest from .. import config class TestYamlConfig(object):
14
165
550
6
7
zbkc-teuthology/teuthology
teuthology/test/test_config.py
Python
TestYamlConfig
TestYamlConfig
6
78
6
6
e7f31cfeb63dac463f821e88eca37ce0ee591409
bigcode/the-stack
train
ce115ff8cf7b19d081f475f3
train
function
def _check_resolvers(resolvers): if resolvers is not None: for resolver in resolvers: if not hasattr(resolver, "__getitem__"): name = type(resolver).__name__ raise TypeError( "Resolver of type {name!r} does not implement " "...
def _check_resolvers(resolvers):
if resolvers is not None: for resolver in resolvers: if not hasattr(resolver, "__getitem__"): name = type(resolver).__name__ raise TypeError( "Resolver of type {name!r} does not implement " "the __getitem__ method".format(na...
an invalid parser is passed """ if parser not in _parsers: raise KeyError( "Invalid parser {parser!r} passed, valid parsers are" " {valid}".format(parser=parser, valid=_parsers.keys()) ) def _check_resolvers(resolvers):
64
64
76
8
56
Martynas-P/pandas
pandas/core/computation/eval.py
Python
_check_resolvers
_check_resolvers
89
97
89
89
8304bb34c279b413426335685e6bc1a63ff14268
bigcode/the-stack
train
c9033ca06340b2998f85202c
train
function
def eval( expr, parser="pandas", engine=None, truediv=True, local_dict=None, global_dict=None, resolvers=(), level=0, target=None, inplace=False, ): """ Evaluate a Python expression as a string using various backends. The following arithmetic operations are supported...
def eval( expr, parser="pandas", engine=None, truediv=True, local_dict=None, global_dict=None, resolvers=(), level=0, target=None, inplace=False, ):
""" Evaluate a Python expression as a string using various backends. The following arithmetic operations are supported: ``+``, ``-``, ``*``, ``/``, ``**``, ``%``, ``//`` (python engine only) along with the following boolean operations: ``|`` (or), ``&`` (and), and ``~`` (not). Additionally, the...
string representation of an object. Raises ------ ValueError * If the expression is empty. """ s = pprint_thing(expr) _check_expression(s) return s def _check_for_locals(expr: str, stack_level: int, parser: str): at_top_of_stack = stack_level == 0 not_pandas_parser = parse...
256
256
1,780
51
205
Martynas-P/pandas
pandas/core/computation/eval.py
Python
eval
eval
168
378
168
179
39579feffc4199bd77be3abbcb12b6718a4c27dc
bigcode/the-stack
train
c40e01de8f26ecb9eb8e8090
train
function
def _check_parser(parser: str): """ Make sure a valid parser is passed. Parameters ---------- parser : str Raises ------ KeyError * If an invalid parser is passed """ if parser not in _parsers: raise KeyError( "Invalid parser {parser!r} passed, valid ...
def _check_parser(parser: str):
""" Make sure a valid parser is passed. Parameters ---------- parser : str Raises ------ KeyError * If an invalid parser is passed """ if parser not in _parsers: raise KeyError( "Invalid parser {parser!r} passed, valid parsers are" " {vali...
_INSTALLED: raise ImportError( "'numexpr' is not installed or an " "unsupported version. Cannot use " "engine='numexpr' for query/eval " "if 'numexpr' is not installed" ) return engine def _check_parser(parser: str):
64
64
98
8
55
Martynas-P/pandas
pandas/core/computation/eval.py
Python
_check_parser
_check_parser
68
86
68
68
375503d6d62043c769cb16837cc43b1094db30e0
bigcode/the-stack
train
fcf162ccdff1159ffa85d3c4
train
function
def _convert_expression(expr) -> str: """ Convert an object to an expression. This function converts an object to an expression (a unicode string) and checks to make sure it isn't empty after conversion. This is used to convert operators to their string representation for recursive calls to :fu...
def _convert_expression(expr) -> str:
""" Convert an object to an expression. This function converts an object to an expression (a unicode string) and checks to make sure it isn't empty after conversion. This is used to convert operators to their string representation for recursive calls to :func:`~pandas.eval`. Parameters ...
---------- expr : object An object that can be converted to a string Raises ------ ValueError * If expr is an empty string """ if not expr: raise ValueError("expr cannot be an empty string") def _convert_expression(expr) -> str:
64
64
146
9
55
Martynas-P/pandas
pandas/core/computation/eval.py
Python
_convert_expression
_convert_expression
118
144
118
118
0ddf61954d26afae9d7841ada88ef3596a587398
bigcode/the-stack
train
44c6ca878a4b21c93917fea2
train
function
def _check_expression(expr): """ Make sure an expression is not an empty string Parameters ---------- expr : object An object that can be converted to a string Raises ------ ValueError * If expr is an empty string """ if not expr: raise ValueError("expr ca...
def _check_expression(expr):
""" Make sure an expression is not an empty string Parameters ---------- expr : object An object that can be converted to a string Raises ------ ValueError * If expr is an empty string """ if not expr: raise ValueError("expr cannot be an empty string")
resolver in resolvers: if not hasattr(resolver, "__getitem__"): name = type(resolver).__name__ raise TypeError( "Resolver of type {name!r} does not implement " "the __getitem__ method".format(name=name) ) def _check_exp...
64
64
78
6
58
Martynas-P/pandas
pandas/core/computation/eval.py
Python
_check_expression
_check_expression
100
115
100
100
60155f80e9f4cee6b10087ad5df6fb637115cc11
bigcode/the-stack
train
9463eb879f7f20383a88cda5
train
function
def _check_for_locals(expr: str, stack_level: int, parser: str): at_top_of_stack = stack_level == 0 not_pandas_parser = parser != "pandas" if not_pandas_parser: msg = "The '@' prefix is only supported by the pandas parser" elif at_top_of_stack: msg = ( "The '@' prefix is no...
def _check_for_locals(expr: str, stack_level: int, parser: str):
at_top_of_stack = stack_level == 0 not_pandas_parser = parser != "pandas" if not_pandas_parser: msg = "The '@' prefix is only supported by the pandas parser" elif at_top_of_stack: msg = ( "The '@' prefix is not allowed in " "top-level eval calls, \nplease refer t...
The string representation of an object. Raises ------ ValueError * If the expression is empty. """ s = pprint_thing(expr) _check_expression(s) return s def _check_for_locals(expr: str, stack_level: int, parser: str):
64
64
161
19
44
Martynas-P/pandas
pandas/core/computation/eval.py
Python
_check_for_locals
_check_for_locals
147
165
147
148
7768e60cd9b80e21df8ec6cde42aa51a6f210539
bigcode/the-stack
train
ff89b5ca21a43fc3521f5de5
train
function
def _check_engine(engine): """ Make sure a valid engine is passed. Parameters ---------- engine : str Raises ------ KeyError * If an invalid engine is passed ImportError * If numexpr was requested but doesn't exist Returns ------- string engine """ ...
def _check_engine(engine):
""" Make sure a valid engine is passed. Parameters ---------- engine : str Raises ------ KeyError * If an invalid engine is passed ImportError * If numexpr was requested but doesn't exist Returns ------- string engine """ from pandas.core.computatio...
""" Top level ``eval`` module. """ import tokenize import warnings from pandas.util._validators import validate_bool_kwarg from pandas.core.computation.engines import _engines from pandas.core.computation.expr import Expr, _parsers, tokenize_string from pandas.core.computation.scope import _ensure_scope from pand...
84
84
280
6
77
Martynas-P/pandas
pandas/core/computation/eval.py
Python
_check_engine
_check_engine
19
65
19
19
60f170f44591d60a32f6b370397bd6bd24cd2b3b
bigcode/the-stack
train
35e55684414ab94535735652
train
function
def create_dashboard_payload(json_path): with open(json_path, 'r') as f: dashboard = json.load(f) dashboard['id'] = None return { 'dashboard': dashboard, 'overwrite': True }
def create_dashboard_payload(json_path):
with open(json_path, 'r') as f: dashboard = json.load(f) dashboard['id'] = None return { 'dashboard': dashboard, 'overwrite': True }
return grafana_users @retry(retries=24, delay=5.0) def login(session, user): r = session.post('{url}/login'.format(url=GRAFANA_URL), json=user, timeout=5) r.raise_for_status() def create_dashboard_payload(json_path):
64
64
51
7
57
scottwedge/OpenStack-Stein
monasca-log-api-2.9.0/devstack/files/grafana/grafana.py
Python
create_dashboard_payload
create_dashboard_payload
81
89
81
81
8753345cb37657ae62f945f3295fc431ca77d1cc
bigcode/the-stack
train
ef617468fcbf6a0e0499e294
train
function
@retry(retries=24, delay=5.0) def login(session, user): r = session.post('{url}/login'.format(url=GRAFANA_URL), json=user, timeout=5) r.raise_for_status()
@retry(retries=24, delay=5.0) def login(session, user):
r = session.post('{url}/login'.format(url=GRAFANA_URL), json=user, timeout=5) r.raise_for_status()
Invalid type GRAFANA_USERS") raise grafana_users = json.loads(os.environ.get('GRAFANA_USERS')) else: grafana_users = GRAFANA_USERS return grafana_users @retry(retries=24, delay=5.0) def login(session, user):
64
64
52
19
44
scottwedge/OpenStack-Stein
monasca-log-api-2.9.0/devstack/files/grafana/grafana.py
Python
login
login
74
79
74
75
acddf615370703d89b4df3d7b8b2fd24427348fd
bigcode/the-stack
train
32940216c241078b242f1842
train
function
def main(): for user in create_login_payload(): logging.info('Opening a Grafana session...') session = Session() login(session, user) for path in sorted(glob.glob('{dir}/*.json'.format(dir=DASHBOARDS_DIR))): logging.info('Creating dashboard from file: {path}'.format(path...
def main():
for user in create_login_payload(): logging.info('Opening a Grafana session...') session = Session() login(session, user) for path in sorted(glob.glob('{dir}/*.json'.format(dir=DASHBOARDS_DIR))): logging.info('Creating dashboard from file: {path}'.format(path=path)) ...
timeout=5) r.raise_for_status() def create_dashboard_payload(json_path): with open(json_path, 'r') as f: dashboard = json.load(f) dashboard['id'] = None return { 'dashboard': dashboard, 'overwrite': True } def main():
64
64
156
3
61
scottwedge/OpenStack-Stein
monasca-log-api-2.9.0/devstack/files/grafana/grafana.py
Python
main
main
91
107
91
91
4ebb1446f07d91de3844d4c52017288720e8d55e
bigcode/the-stack
train
ff7690d4cd7b9313dfafae55
train
function
def create_login_payload(): if os.environ.get('GRAFANA_USERS'): try: json.loads(os.environ.get('GRAFANA_USERS')) except ValueError: print("Invalid type GRAFANA_USERS") raise grafana_users = json.loads(os.environ.get('GRAFANA_USERS')) else: graf...
def create_login_payload():
if os.environ.get('GRAFANA_USERS'): try: json.loads(os.environ.get('GRAFANA_USERS')) except ValueError: print("Invalid type GRAFANA_USERS") raise grafana_users = json.loads(os.environ.get('GRAFANA_USERS')) else: grafana_users = GRAFANA_USERS ...
exc_info=True) time.sleep(delay) else: logger.exception('Failed after %d attempts', retries) if isinstance(exc, RequestException): logger.debug('Response was: %r',...
64
64
84
5
58
scottwedge/OpenStack-Stein
monasca-log-api-2.9.0/devstack/files/grafana/grafana.py
Python
create_login_payload
create_login_payload
62
72
62
62
b3be56657785b530693abe456107359e8674a3bc
bigcode/the-stack
train
8e5a4174c120c9dcca46b6f2
train
function
def retry(retries=5, delay=2.0, exc_types=(RequestException,)): def decorator(func): def f_retry(*args, **kwargs): for i in range(retries): try: return func(*args, **kwargs) except exc_types as exc: if i < retries - 1: ...
def retry(retries=5, delay=2.0, exc_types=(RequestException,)):
def decorator(func): def f_retry(*args, **kwargs): for i in range(retries): try: return func(*args, **kwargs) except exc_types as exc: if i < retries - 1: logger.debug('Caught exception, retrying...',...
ANA_PASSWORD', 'password') GRAFANA_USERS = [{'user': GRAFANA_USERNAME, 'password': GRAFANA_PASSWORD, 'email': ''}] DASHBOARDS_DIR = sys.argv[1] def retry(retries=5, delay=2.0, exc_types=(RequestException,)):
64
64
140
20
44
scottwedge/OpenStack-Stein
monasca-log-api-2.9.0/devstack/files/grafana/grafana.py
Python
retry
retry
42
60
42
42
59858d34de82d676eab1c27782d0c6eb2ecccfe6
bigcode/the-stack
train
8390e85de5cc2cadf6dcc6c1
train
function
def processResponse(event): for msg in event: if msg.messageType() == ERROR_RESPONSE: print(f"Received error: {msg}") continue results = msg.getElement(NAME_RESULTS) print(f"Processing {len(results)} results:") for i, result in enumerate(results): ...
def processResponse(event):
for msg in event: if msg.messageType() == ERROR_RESPONSE: print(f"Received error: {msg}") continue results = msg.getElement(NAME_RESULTS) print(f"Processing {len(results)} results:") for i, result in enumerate(results): parsekey = result...
query, maxResults, filters): request = instrumentsService.createRequest("govtListRequest") request[NAME_QUERY] = query request[NAME_MAX_RESULTS] = maxResults for f in filters: request[f.name] = f.value return request def processResponse(event):
64
64
114
5
58
vegabook/dstreams
clients/bbg/snippets/instruments/GovtListRequests.py
Python
processResponse
processResponse
24
37
24
24
672e54918a63aa304122536cd5f3287c6c7bf72b
bigcode/the-stack
train
799db23c57db561cee4ac3b0
train
function
def createRequest(instrumentsService, query, maxResults, filters): request = instrumentsService.createRequest("govtListRequest") request[NAME_QUERY] = query request[NAME_MAX_RESULTS] = maxResults for f in filters: request[f.name] = f.value return request
def createRequest(instrumentsService, query, maxResults, filters):
request = instrumentsService.createRequest("govtListRequest") request[NAME_QUERY] = query request[NAME_MAX_RESULTS] = maxResults for f in filters: request[f.name] = f.value return request
NAME_RESULTS = Name("results") NAME_MAX_RESULTS = Name("maxResults") NAME_PARSEKY = Name("parseky") NAME_NAME = Name("name") NAME_TICKER = Name("ticker") ERROR_RESPONSE = Name("ErrorResponse") def createRequest(instrumentsService, query, maxResults, filters):
63
64
66
14
49
vegabook/dstreams
clients/bbg/snippets/instruments/GovtListRequests.py
Python
createRequest
createRequest
13
21
13
13
d48e4d4bfd8a79b83a77501eb1b39d0fd964c9ef
bigcode/the-stack
train
c39520f965e1528b4da3b931
train
class
class ReindexTest(CircuitTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def reindex(self): self.nodes[0].generate(3) blockcount = self.nodes[0].getblockcount() self.stop_nodes() time.sleep(5) extra_args = [["-...
class ReindexTest(CircuitTestFramework):
def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def reindex(self): self.nodes[0].generate(3) blockcount = self.nodes[0].getblockcount() self.stop_nodes() time.sleep(5) extra_args = [["-reindex", "-checkblockindex=1"]] s...
up to block 3. - Stop the node and restart it with -reindex-chainstate. Verify that the node has reindexed up to block 3. """ from test_framework.test_framework import CircuitTestFramework from test_framework.util import wait_until import time class ReindexTest(CircuitTestFramework):
64
64
138
9
54
CircuitProject/Circuit-Core
test/functional/feature_reindex.py
Python
ReindexTest
ReindexTest
16
34
16
17
2b9543c94e46c7e3538ac3fa71c48dd62a56fc18
bigcode/the-stack
train
048551c46d8a2d6604d53dc4
train
class
class Reload(object): """ Reload functions for reload scripts """ def __init__( self, # Machine information machine_name, version, bmp_details, down_chips, down_cores, number_of_boards, height, width, auto_detect_bmp, enable_reinjection, scamp_co...
class Reload(object):
""" Reload functions for reload scripts """ def __init__( self, # Machine information machine_name, version, bmp_details, down_chips, down_cores, number_of_boards, height, width, auto_detect_bmp, enable_reinjection, scamp_connection_data, boot_po...
from pacman.operations.pacman_algorithm_executor import PACMANAlgorithmExecutor from spinn_front_end_common.utilities import helpful_functions class Reload(object):
30
256
951
4
25
Roboy/LSM_SpiNNaker_MyoArm
src/spinnaker_ros_lsm/venv/lib/python2.7/site-packages/spinn_front_end_common/utilities/reload/reload.py
Python
Reload
Reload
5
119
5
5
31bc8d2bd53f6d69a6ba8282996627aebd1b7e96
bigcode/the-stack
train
84017a5dec475f0f8138b8fd
train
function
@retry(3) def get_bucket_region(url): # Get the headers for this bucket. # Verify=False because the wildcard matching doesn't work for buckets with '.' r = requests.head(url, verify=False) if r.status_code == requests.codes.not_found: print(r.headers) print("{} {} {}".format(r.status_co...
@retry(3) def get_bucket_region(url): # Get the headers for this bucket. # Verify=False because the wildcard matching doesn't work for buckets with '.'
r = requests.head(url, verify=False) if r.status_code == requests.codes.not_found: print(r.headers) print("{} {} {}".format(r.status_code, r.reason, r.url)) raise Exception( "Bucket {} doesn't exist or there was a momentary glitch".format(url) ) if not "x-amz-bu...
(explore_regex, value): print("Explore string '{}' is not a valid link".format(value)) return False return True @retry(3) def get_bucket_region(url): # Get the headers for this bucket. # Verify=False because the wildcard matching doesn't work for buckets with '.'
64
64
160
35
28
Litalku/open-data-registry
ext.py
Python
get_bucket_region
get_bucket_region
116
134
116
119
e8f3ff9f8e1ae7479697c76182fff6509b380545
bigcode/the-stack
train
aeeec13d3a5142d4a01dd935
train
function
def ext_resources_controlled_access(value, rule_obj, path): if not re.fullmatch(controlled_access_regex, value): print("Controlled Access string '{}' is not valid".format(value)) return False return True
def ext_resources_controlled_access(value, rule_obj, path):
if not re.fullmatch(controlled_access_regex, value): print("Controlled Access string '{}' is not valid".format(value)) return False return True
(value, rule_obj, path): if not re.fullmatch(host_regex, value): print("Host '{}' is not valid".format(value)) return False return True # Check to make sure we have a valid controlled access string def ext_resources_controlled_access(value, rule_obj, path):
64
64
48
13
50
Litalku/open-data-registry
ext.py
Python
ext_resources_controlled_access
ext_resources_controlled_access
97
103
97
98
3f3c979653a66c19991e62d528e143b9dd374371
bigcode/the-stack
train
fe3e06ebcda8186a4d1ec431
train
function
def ext_resources_explore(value, rule_obj, path): if not re.fullmatch(explore_regex, value): print("Explore string '{}' is not a valid link".format(value)) return False return True
def ext_resources_explore(value, rule_obj, path):
if not re.fullmatch(explore_regex, value): print("Explore string '{}' is not a valid link".format(value)) return False return True
_obj, path): if not re.fullmatch(controlled_access_regex, value): print("Controlled Access string '{}' is not valid".format(value)) return False return True # Check to make sure we have a valid array of links def ext_resources_explore(value, rule_obj, path):
64
64
47
12
51
Litalku/open-data-registry
ext.py
Python
ext_resources_explore
ext_resources_explore
107
113
107
108
40916b9133e165b2872595fe30b3dd125195bb26
bigcode/the-stack
train