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
051c60e03c2cdfbace3665d4
train
class
class MainWindow(qtw.QWidget): def __init__(self): """MainWindow constructor. This widget will be our main window. We'll define all the UI components in here. """ super().__init__() # Main UI code goes here self.setLayout(qtw.QVBoxLayout()) lcd = qtw...
class MainWindow(qtw.QWidget):
def __init__(self): """MainWindow constructor. This widget will be our main window. We'll define all the UI components in here. """ super().__init__() # Main UI code goes here self.setLayout(qtw.QVBoxLayout()) lcd = qtw.QLCDNumber(self) self.l...
import sys from PyQt5 import QtWidgets as qtw from PyQt5 import QtGui as qtg from PyQt5 import QtCore as qtc class MainWindow(qtw.QWidget):
44
86
289
8
35
trappn/Mastering-GUI-Programming-with-Python
Chapter02/calculator_form.py
Python
MainWindow
MainWindow
6
41
6
7
435461800225a32c49f76568f04dd997cfc1318f
bigcode/the-stack
train
5f49e3140efa3be8bce0f01d
train
class
class TestIssue135(unittest.TestCase): def test_issue135(self): wd = os.path.join(support, 'issue135') stringio = StringIO() old_argv = sys.argv old_stderr = sys.stderr sys.stderr = stringio sys.argv = ["nosetests", wd] try: main(exit=False) ...
class TestIssue135(unittest.TestCase):
def test_issue135(self): wd = os.path.join(support, 'issue135') stringio = StringIO() old_argv = sys.argv old_stderr = sys.stderr sys.stderr = stringio sys.argv = ["nosetests", wd] try: main(exit=False) finally: sys.argv = old_a...
IO except ImportError: from io import BytesIO as StringIO support = os.path.join(os.path.dirname(__file__), 'support') expected_output_pattern = """KeyError: '?fake'?\n-+ >> begin captured stdout << -+\nsomething\n""" class TestIssue135(unittest.TestCase):
64
64
126
8
56
kokosing/hue
desktop/core/ext-py/nose-1.3.7/unit_tests/test_issue135.py
Python
TestIssue135
TestIssue135
15
30
15
15
bb0528f1f85a102f4922c0090e6b0bf327a1a85f
bigcode/the-stack
train
3d2cc69bf6c05ed0d266001a
train
class
class ServiceIdentification(object): def __init__(self, infoset, version): self._root = infoset self.type = testXMLValue(self._root.find(nspath('Name', WMS_NAMESPACE))) self.version = version self.title = testXMLValue(self._root.find(nspath('Title', WMS_NAMESPACE))) self.abst...
class ServiceIdentification(object):
def __init__(self, infoset, version): self._root = infoset self.type = testXMLValue(self._root.find(nspath('Name', WMS_NAMESPACE))) self.version = version self.title = testXMLValue(self._root.find(nspath('Title', WMS_NAMESPACE))) self.abstract = testXMLValue(self._root.find(n...
.se_xml', 'text/xml']: se_xml = u.read() se_tree = etree.fromstring(se_xml) err_message = six.text_type(se_tree.find(nspath('ServiceException', OGC_NAMESPACE)).text).strip() raise ServiceException(err_message) return u class ServiceIdentification(object):
64
64
158
5
58
meteogrid/OWSLib
owslib/map/wms130.py
Python
ServiceIdentification
ServiceIdentification
501
510
501
501
f17eaf26905947a953840c492e0393ef2249fd05
bigcode/the-stack
train
9204ef127943343a9bf4d627
train
class
class OperationMetadata(object): def __init__(self, elem): """.""" self.name = xmltag_split(elem.tag) # formatOptions self.formatOptions = [f.text for f in elem.findall(nspath('Format', WMS_NAMESPACE))] self.methods = [] for verb in elem.findall(nspath('DCPType/HTTP/*...
class OperationMetadata(object):
def __init__(self, elem): """.""" self.name = xmltag_split(elem.tag) # formatOptions self.formatOptions = [f.text for f in elem.findall(nspath('Format', WMS_NAMESPACE))] self.methods = [] for verb in elem.findall(nspath('DCPType/HTTP/*', WMS_NAMESPACE)): u...
def children(self, value): if self._children is None: self._children = value else: self._children.extend(value) def __str__(self): return 'Layer Name: %s Title: %s' % (self.name, self.title) class OperationMetadata(object):
64
64
130
5
59
meteogrid/OWSLib
owslib/map/wms130.py
Python
OperationMetadata
OperationMetadata
797
806
797
797
db65a937879b66970aece6eecf2c8a4e307c2bcc
bigcode/the-stack
train
2f4f0bbc5d26df3d92b57160
train
class
class WebMapService_1_3_0(object): def __getitem__(self, name): ''' check contents dictionary to allow dict like access to service layers ''' if name in self.__getattribute__('contents'): return self.__getattribute__('contents')[name] else: raise KeyE...
class WebMapService_1_3_0(object):
def __getitem__(self, name): ''' check contents dictionary to allow dict like access to service layers ''' if name in self.__getattribute__('contents'): return self.__getattribute__('contents')[name] else: raise KeyError("No content named %s" % name) ...
<sgillies@frii.com> # Julien Anguenot <ja@nuxeo.com> # # Contact email: sgillies@frii.com # ============================================================================= """ API For Web Map Service version 1.3.0. """ from __future__ import (absolute_import, division, print_function) try: ...
256
256
3,264
12
244
meteogrid/OWSLib
owslib/map/wms130.py
Python
WebMapService_1_3_0
WebMapService_1_3_0
43
499
43
44
8d2360a4c6c5f5e622341bf9e549ed56cb5b4755
bigcode/the-stack
train
548704535f460b064b58356b
train
class
class ContactMetadata(object): def __init__(self, elem): name = elem.find(nspath('ContactPersonPrimary/ContactPerson', WMS_NAMESPACE)) if name is not None: self.name = name.text else: self.name = None email = elem.find('ContactElectronicMailAddress') i...
class ContactMetadata(object):
def __init__(self, elem): name = elem.find(nspath('ContactPersonPrimary/ContactPerson', WMS_NAMESPACE)) if name is not None: self.name = name.text else: self.name = None email = elem.find('ContactElectronicMailAddress') if email is not None: ...
# formatOptions self.formatOptions = [f.text for f in elem.findall(nspath('Format', WMS_NAMESPACE))] self.methods = [] for verb in elem.findall(nspath('DCPType/HTTP/*', WMS_NAMESPACE)): url = verb.find(nspath('OnlineResource', WMS_NAMESPACE)).attrib['{http://www.w3.org/1999/xlink}hr...
107
107
358
5
102
meteogrid/OWSLib
owslib/map/wms130.py
Python
ContactMetadata
ContactMetadata
809
856
809
809
a8621c350b3ae78ac36aeb713e75b0277c49a6b4
bigcode/the-stack
train
66d031a35ccc246efc4727fd
train
class
class ServiceProvider(object): def __init__(self, infoset): self._root = infoset name = self._root.find(nspath('ContactInformation/ContactPersonPrimary/ContactOrganization', WMS_NAMESPACE)) if name is not None: self.name = name.text else: self.name = None ...
class ServiceProvider(object):
def __init__(self, infoset): self._root = infoset name = self._root.find(nspath('ContactInformation/ContactPersonPrimary/ContactOrganization', WMS_NAMESPACE)) if name is not None: self.name = name.text else: self.name = None self.url = self._root.find(...
._root.findall(nspath('KeywordList/Keyword', WMS_NAMESPACE))) self.accessconstraints = testXMLValue(self._root.find(nspath('AccessConstraints', WMS_NAMESPACE))) self.fees = testXMLValue(self._root.find(nspath('Fees', WMS_NAMESPACE))) class ServiceProvider(object):
63
64
181
5
58
meteogrid/OWSLib
owslib/map/wms130.py
Python
ServiceProvider
ServiceProvider
513
529
513
513
facd8a187e6f5bc443e7eff3c94a8d15d3299130
bigcode/the-stack
train
941b8451d99b748637fb84b3
train
class
class ContentMetadata(object): def __init__(self, elem, parent=None, children=None, index=0, parse_remote_metadata=False, timeout=30): if xmltag_split(elem.tag) != 'Layer': raise ValueError('%s should be a Layer' % (elem,)) self.parent = parent if parent: self.index ...
class ContentMetadata(object):
def __init__(self, elem, parent=None, children=None, index=0, parse_remote_metadata=False, timeout=30): if xmltag_split(elem.tag) != 'Layer': raise ValueError('%s should be a Layer' % (elem,)) self.parent = parent if parent: self.index = "%s.%d" % (parent.index, inde...
_NAMESPACE))) self.keywords = extract_xml_list(self._root.findall(nspath('KeywordList/Keyword', WMS_NAMESPACE))) self.accessconstraints = testXMLValue(self._root.find(nspath('AccessConstraints', WMS_NAMESPACE))) self.fees = testXMLValue(self._root.find(nspath('Fees', WMS_NAMESPACE))) class Ser...
256
256
2,775
5
250
meteogrid/OWSLib
owslib/map/wms130.py
Python
ContentMetadata
ContentMetadata
532
795
532
532
f19a091d016a826aa6a39b369724c7ad491f2acd
bigcode/the-stack
train
dae4cc706575dc99ad1426a5
train
function
def split_list(arr, n): return [arr[i::n] for i in range(n)]
def split_list(arr, n):
return [arr[i::n] for i in range(n)]
s = call_trainers(args, extra_args, model, data, server_rrefs) wait_all(futs) for server_rref in server_rrefs.values(): server_rref.rpc_sync().reset_state(server_rref) print("benchmark warmup done\n") def split_list(arr, n):
64
64
21
7
57
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
split_list
split_list
149
150
149
149
b55b9dac3197c28a7aae0fc283e8479597f6646e
bigcode/the-stack
train
a9528a88e77e044c5e626b05
train
function
def get_json_config(file_name, id): with open(os.path.join(Path(__file__).parent, file_name), "r") as f: json_config = json.load(f)[id] return json_config
def get_json_config(file_name, id):
with open(os.path.join(Path(__file__).parent, file_name), "r") as f: json_config = json.load(f)[id] return json_config
_rank} ) trainer_name = get_name( rank, args ) rpc.init_rpc( trainer_name, rank=rank, world_size=world_size, rpc_backend_options=rpc_backend_options ) rpc.shutdown() def get_json_config(file_name, id)...
64
64
45
9
55
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
get_json_config
get_json_config
245
249
245
245
7d8ae09ccf667ffc31a1daa9d3f1270a1f8e7f9b
bigcode/the-stack
train
ff0f54324cea5b2e6ce071b9
train
function
def get_server_rref(server_rank, args, extra_args): server = get_benchmark_server_map()[str(args.server)] name = get_name( server_rank, args ) if extra_args is not None: server_args = extra_args.values() else: server_args = [] if server_rank >= args.ntrainer + arg...
def get_server_rref(server_rank, args, extra_args):
server = get_benchmark_server_map()[str(args.server)] name = get_name( server_rank, args ) if extra_args is not None: server_args = extra_args.values() else: server_args = [] if server_rank >= args.ntrainer + args.ncudatrainer + args.nserver: trainer_count...
args.ntrainer + args.ncudatrainer + args.nserver t_index = rank - args.ntrainer ctps = args.ncudatrainer // args.ncudaserver return t_index // ctps + s_offset def get_server_rref(server_rank, args, extra_args):
64
64
166
13
50
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
get_server_rref
get_server_rref
46
71
46
46
d2d74cf8d53848baec0871d61a1d117cf9d0e9ff
bigcode/the-stack
train
8d93448d5285e34d2e530374
train
function
def load_data(args): data_config_file = args.data_config_path data_config = get_json_config(data_config_file, args.data) return get_data(data_config["data_class"], data_config["configurations"])
def load_data(args):
data_config_file = args.data_config_path data_config = get_json_config(data_config_file, args.data) return get_data(data_config["data_class"], data_config["configurations"])
and server_config_file is not None: configurations["server_config"] = get_json_config(server_config_file, args.server) return configurations def get_data(data_class, data_config): data_class = get_benchmark_data_map()[data_class] return data_class(**data_config) def load_data(args):
64
64
45
5
59
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
load_data
load_data
271
274
271
271
1c08e78174099f3201608dc3fe1e18feb544b8d5
bigcode/the-stack
train
3ba7dc6c82ac2e1423b70dbc
train
function
def run_trainer( args, extra_args, model, data, rank, server_rref ): trainer_class = get_benchmark_trainer_map()[str(args.trainer)] if extra_args is not None: trainer_args = extra_args.values() else: trainer_args = [] trainer_count = args.ntrainer + args.ncudatrainer store = c10d...
def run_trainer( args, extra_args, model, data, rank, server_rref ):
trainer_class = get_benchmark_trainer_map()[str(args.trainer)] if extra_args is not None: trainer_args = extra_args.values() else: trainer_args = [] trainer_count = args.ntrainer + args.ncudatrainer store = c10d.FileStore(args.filestore, trainer_count) if args.backend == "gloo": ...
/ args.nserver use_cuda_rpc = False return rpc.remote( name, server, args=( server_rank, trainer_count, use_cuda_rpc, *server_args, ), ) def run_trainer( args, extra_args, model, data, rank, server_rref ):
71
71
237
22
49
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
run_trainer
run_trainer
74
105
74
76
8249877740811840dc492311cd5f88a4f09cf50f
bigcode/the-stack
train
d3a473c83608ac445f748587
train
function
def get_server_rank(args, rank): s_offset = args.ntrainer + args.ncudatrainer tps = args.ntrainer // args.nserver return rank // tps + s_offset
def get_server_rank(args, rank):
s_offset = args.ntrainer + args.ncudatrainer tps = args.ntrainer // args.nserver return rank // tps + s_offset
s_count = args.nserver + args.ncudaserver if rank < t_count: return f"trainer{rank}" elif rank < (t_count + s_count): return f"server{rank}" else: return "master" def get_server_rank(args, rank):
64
64
44
8
56
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
get_server_rank
get_server_rank
33
36
33
33
6bb8069f3e94e739f687e172593644eca516717e
bigcode/the-stack
train
6ff7eb9d0523fcfb40745144
train
function
def get_server_metrics(server_rrefs): rank_metrics = [] for rank, server_rref in server_rrefs.items(): metrics = server_rref.rpc_sync().get_metrics(server_rref) rank_metrics.append([rank, metrics]) return rank_metrics
def get_server_metrics(server_rrefs):
rank_metrics = [] for rank, server_rref in server_rrefs.items(): metrics = server_rref.rpc_sync().get_metrics(server_rref) rank_metrics.append([rank, metrics]) return rank_metrics
) for server_rref in server_rrefs.values(): server_rref.rpc_sync().reset_state(server_rref) print("benchmark warmup done\n") def split_list(arr, n): return [arr[i::n] for i in range(n)] def get_server_metrics(server_rrefs):
63
64
55
8
55
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
get_server_metrics
get_server_metrics
153
158
153
153
f082cc693f8c9bd0354585f2eb6d698a5261de13
bigcode/the-stack
train
14e5a14ec6f1d4771f693fe9
train
function
def run_benchmark(rank, model, data, args, config): torch.manual_seed(args.torch_seed) torch.cuda.manual_seed_all(args.cuda_seed) torch.backends.cudnn.benchmark = True torch.backends.cudnn.deterministic = True world_size = args.ntrainer + args.ncudatrainer + args.nserver + args.ncudaserver + 1 ...
def run_benchmark(rank, model, data, args, config):
torch.manual_seed(args.torch_seed) torch.cuda.manual_seed_all(args.cuda_seed) torch.backends.cudnn.benchmark = True torch.backends.cudnn.deterministic = True world_size = args.ntrainer + args.ncudatrainer + args.nserver + args.ncudaserver + 1 os.environ['MASTER_ADDR'] = args.master_addr os....
# run the benchmark trainer_futs = call_trainers( args, extra_configs["trainer_config"], model, train_data, server_rrefs ) # collect metrics and print metrics_printer = ProcessedMetricsPrinter() rank_metrics_list = wait_all(trainer_futs) metrics_printer.print_metrics("trainer", rank_...
117
117
393
14
103
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
run_benchmark
run_benchmark
198
242
198
199
6e261d303cd6e4725404c090a54116fa81e44343
bigcode/the-stack
train
b7a2877c565dc2c34b9986b0
train
function
def get_cuda_server_rank(args, rank): s_offset = args.ntrainer + args.ncudatrainer + args.nserver t_index = rank - args.ntrainer ctps = args.ncudatrainer // args.ncudaserver return t_index // ctps + s_offset
def get_cuda_server_rank(args, rank):
s_offset = args.ntrainer + args.ncudatrainer + args.nserver t_index = rank - args.ntrainer ctps = args.ncudatrainer // args.ncudaserver return t_index // ctps + s_offset
{rank}" else: return "master" def get_server_rank(args, rank): s_offset = args.ntrainer + args.ncudatrainer tps = args.ntrainer // args.nserver return rank // tps + s_offset def get_cuda_server_rank(args, rank):
64
64
64
9
54
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
get_cuda_server_rank
get_cuda_server_rank
39
43
39
39
029995abeb297af35ec35ae5625297ef3843035b
bigcode/the-stack
train
94fe28bcadeba6fef4833e31
train
function
def run_master(rank, model, data, args, extra_configs, rpc_backend_options): world_size = args.ntrainer + args.ncudatrainer + args.nserver + args.ncudaserver + 1 rpc.init_rpc( get_name( rank, args ), rank=rank, world_size=world_size, rpc_backend_op...
def run_master(rank, model, data, args, extra_configs, rpc_backend_options):
world_size = args.ntrainer + args.ncudatrainer + args.nserver + args.ncudaserver + 1 rpc.init_rpc( get_name( rank, args ), rank=rank, world_size=world_size, rpc_backend_options=rpc_backend_options ) server_rrefs = {} for i in range( ...
, n): return [arr[i::n] for i in range(n)] def get_server_metrics(server_rrefs): rank_metrics = [] for rank, server_rref in server_rrefs.items(): metrics = server_rref.rpc_sync().get_metrics(server_rref) rank_metrics.append([rank, metrics]) return rank_metrics def run_master(rank, mode...
91
91
306
18
72
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
run_master
run_master
161
195
161
161
1cc152235558f666987fdce75a0d779b5dde4c11
bigcode/the-stack
train
3cdd70680ce2b1231a41630c
train
function
def get_model(model_class, model_config): model_class = get_benchmark_model_map()[model_class] return model_class(**model_config)
def get_model(model_class, model_config):
model_class = get_benchmark_model_map()[model_class] return model_class(**model_config)
] return data_class(**data_config) def load_data(args): data_config_file = args.data_config_path data_config = get_json_config(data_config_file, args.data) return get_data(data_config["data_class"], data_config["configurations"]) def get_model(model_class, model_config):
63
64
30
9
54
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
get_model
get_model
277
279
277
277
2d2be63d637c9bb991a8d91f69269f926d118606
bigcode/the-stack
train
801c56a861bc8d95c19c622a
train
function
def load_model(args): model_config_file = args.model_config_path model_config = get_json_config(model_config_file, args.model) return get_model(model_config["model_class"], model_config["configurations"])
def load_model(args):
model_config_file = args.model_config_path model_config = get_json_config(model_config_file, args.model) return get_model(model_config["model_class"], model_config["configurations"])
_config = get_json_config(data_config_file, args.data) return get_data(data_config["data_class"], data_config["configurations"]) def get_model(model_class, model_config): model_class = get_benchmark_model_map()[model_class] return model_class(**model_config) def load_model(args):
64
64
45
5
59
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
load_model
load_model
282
285
282
282
c5975a41d4d1676730c4897063edf8953d3f17f5
bigcode/the-stack
train
cfa8b60bceb84cf3e3f02cf1
train
function
def get_data(data_class, data_config): data_class = get_benchmark_data_map()[data_class] return data_class(**data_config)
def get_data(data_class, data_config):
data_class = get_benchmark_data_map()[data_class] return data_class(**data_config)
configurations["trainer_config"] = get_json_config(trainer_config_file, args.trainer) if args.server is not None and server_config_file is not None: configurations["server_config"] = get_json_config(server_config_file, args.server) return configurations def get_data(data_class, data_config):
64
64
30
9
54
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
get_data
get_data
266
268
266
266
b0b7a07a10a3b63014e02e36992bb33994f018cb
bigcode/the-stack
train
69ad682353add9cd42bdd59b
train
function
def benchmark_warmup( args, extra_args, model, data, server_rrefs ): futs = call_trainers(args, extra_args, model, data, server_rrefs) wait_all(futs) for server_rref in server_rrefs.values(): server_rref.rpc_sync().reset_state(server_rref) print("benchmark warmup done\n")
def benchmark_warmup( args, extra_args, model, data, server_rrefs ):
futs = call_trainers(args, extra_args, model, data, server_rrefs) wait_all(futs) for server_rref in server_rrefs.values(): server_rref.rpc_sync().reset_state(server_rref) print("benchmark warmup done\n")
copy.deepcopy(model), train_data[trainer_rank], trainer_rank, server_rref, ), timeout=args.rpc_timeout ) futs.append(fut) return futs def benchmark_warmup( args, extra_args, model, data, server_rrefs ):
64
64
80
21
42
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
benchmark_warmup
benchmark_warmup
139
146
139
141
4feab8f69b9bd360779d911d930a79f0c67da4ac
bigcode/the-stack
train
6031630896e1ec9c873b2b35
train
function
def main(args): # CPU and RPC trainer checks if args.ntrainer > 0 and args.ncudatrainer > 0: assert args.nserver > 0 and args.ncudaserver > 0 if args.nserver > 0: assert args.ntrainer > 0 assert args.ntrainer % args.nserver == 0 if args.ncudaserver > 0: assert args.ncuda...
def main(args): # CPU and RPC trainer checks
if args.ntrainer > 0 and args.ncudatrainer > 0: assert args.nserver > 0 and args.ncudaserver > 0 if args.nserver > 0: assert args.ntrainer > 0 assert args.ntrainer % args.nserver == 0 if args.ncudaserver > 0: assert args.ncudatrainer > 0 assert args.ncudatrainer % arg...
model_class(**model_config) def load_model(args): model_config_file = args.model_config_path model_config = get_json_config(model_config_file, args.model) return get_model(model_config["model_class"], model_config["configurations"]) def main(args): # CPU and RPC trainer checks
63
64
214
12
51
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
main
main
288
318
288
290
5bda5b7b91f9f402cd93fc2ced3ab20af64c54cf
bigcode/the-stack
train
464208ab6ad0054f49b3d37e
train
function
def load_extra_configs(args): trainer_config_file = args.trainer_config_path server_config_file = args.server_config_path configurations = { "trainer_config": None, "server_config": None } if args.trainer is not None and trainer_config_file is not None: configurations["traine...
def load_extra_configs(args):
trainer_config_file = args.trainer_config_path server_config_file = args.server_config_path configurations = { "trainer_config": None, "server_config": None } if args.trainer is not None and trainer_config_file is not None: configurations["trainer_config"] = get_json_config(t...
_backend_options=rpc_backend_options ) rpc.shutdown() def get_json_config(file_name, id): with open(os.path.join(Path(__file__).parent, file_name), "r") as f: json_config = json.load(f)[id] return json_config def load_extra_configs(args):
64
64
118
6
57
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
load_extra_configs
load_extra_configs
252
263
252
252
d460d826f19b1c98e3f292c4ce39f4cae36d03bb
bigcode/the-stack
train
2e44fd24c2added828cd0f9c
train
function
def call_trainers(args, extra_args, model, train_data, server_rrefs): futs = [] for trainer_rank in range(0, args.ntrainer + args.ncudatrainer): trainer_name = get_name( trainer_rank, args ) server_rref = None if server_rrefs: if trainer_rank >...
def call_trainers(args, extra_args, model, train_data, server_rrefs):
futs = [] for trainer_rank in range(0, args.ntrainer + args.ncudatrainer): trainer_name = get_name( trainer_rank, args ) server_rref = None if server_rrefs: if trainer_rank >= args.ntrainer: server_rank = get_cuda_server_rank(ar...
use_cuda_rpc, server_rref, args.backend, args.epochs, *trainer_args ) trainer.train(model, data) metrics = trainer.get_metrics() return [rank, metrics] def call_trainers(args, extra_args, model, train_data, server_rrefs):
64
64
190
18
46
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
call_trainers
call_trainers
108
136
108
108
ebe53bcc49cb593c5ab825a99e39237713ef0f9d
bigcode/the-stack
train
5da8b3eaf9f72ed9540bb62a
train
function
def get_name(rank, args): t_count = args.ntrainer + args.ncudatrainer s_count = args.nserver + args.ncudaserver if rank < t_count: return f"trainer{rank}" elif rank < (t_count + s_count): return f"server{rank}" else: return "master"
def get_name(rank, args):
t_count = args.ntrainer + args.ncudatrainer s_count = args.nserver + args.ncudaserver if rank < t_count: return f"trainer{rank}" elif rank < (t_count + s_count): return f"server{rank}" else: return "master"
wait_all from torch.utils.data import DataLoader from benchmark_class_helper import (get_benchmark_data_map, get_benchmark_model_map, get_benchmark_server_map, get_benchmark_trainer_map) from metrics.ProcessedM...
64
64
77
7
56
chloeyutianyi/pytorch
benchmarks/distributed/rpc/parameter_server/launcher.py
Python
get_name
get_name
22
30
22
22
52c22365b62fee908033db65459fe7d7e3b80a11
bigcode/the-stack
train
262998429bf6f3102a540750
train
class
class FasterRCNNVGG16(FasterRCNN): """Faster R-CNN based on VGG-16. For descriptions on the interface of this model, please refer to :class:`model.faster_rcnn.FasterRCNN`. Args: n_fg_class (int): The number of classes excluding the background. ratios (list of floats): This is ratios of ...
class FasterRCNNVGG16(FasterRCNN):
"""Faster R-CNN based on VGG-16. For descriptions on the interface of this model, please refer to :class:`model.faster_rcnn.FasterRCNN`. Args: n_fg_class (int): The number of classes excluding the background. ratios (list of floats): This is ratios of width to height of the ...
30] classifier = model.classifier classifier = list(classifier) del classifier[6] if not opt.use_drop: del classifier[5] del classifier[2] classifier = nn.Sequential(*classifier) # freeze top4 conv for layer in features[:10]: for p in layer.parameters(): ...
99
99
330
12
86
mahavird/vehicle_detection
model/faster_rcnn_vgg16.py
Python
FasterRCNNVGG16
FasterRCNNVGG16
38
82
38
38
c9ea4fc0f0d1d3f472a8ee2dc216e3ea5c4e6140
bigcode/the-stack
train
9f9a5559d162911acaf23990
train
function
def normal_init(m, mean, stddev, truncated=False): """ weight initalizer: truncated normal and random normal. """ # x is a parameter if truncated: m.weight.data.normal_().fmod_(2).mul_(stddev).add_(mean) # not a perfect approximation else: m.weight.data.normal_(mean, stddev) ...
def normal_init(m, mean, stddev, truncated=False):
""" weight initalizer: truncated normal and random normal. """ # x is a parameter if truncated: m.weight.data.normal_().fmod_(2).mul_(stddev).add_(mean) # not a perfect approximation else: m.weight.data.normal_(mean, stddev) m.bias.data.zero_()
= pool.view(pool.size(0), -1) fc7 = self.classifier(pool) roi_cls_locs = self.cls_loc(fc7) roi_scores = self.score(fc7) return roi_cls_locs, roi_scores def normal_init(m, mean, stddev, truncated=False):
64
64
89
13
50
mahavird/vehicle_detection
model/faster_rcnn_vgg16.py
Python
normal_init
normal_init
149
158
149
149
fff9b5bcceea17194b900a1ef1e5aa907468231b
bigcode/the-stack
train
4b440aee0f48dec4afdd9b55
train
class
class VGG16RoIHead(nn.Module): """Faster R-CNN Head for VGG-16 based implementation. This class is used as a head for Faster R-CNN. This outputs class-wise localizations and classification based on feature maps in the given RoIs. Args: n_class (int): The number of classes possibly inclu...
class VGG16RoIHead(nn.Module):
"""Faster R-CNN Head for VGG-16 based implementation. This class is used as a head for Faster R-CNN. This outputs class-wise localizations and classification based on feature maps in the given RoIs. Args: n_class (int): The number of classes possibly including the background. ro...
16 # downsample 16x for output of conv5 in vgg16 def __init__(self, n_fg_class=20, ratios=[0.5, 1, 2], anchor_scales=[8, 16, 32] ): extractor, classifier = decom_vgg16() rpn = RegionProposalNetwork( ...
192
192
641
10
182
mahavird/vehicle_detection
model/faster_rcnn_vgg16.py
Python
VGG16RoIHead
VGG16RoIHead
85
146
85
85
e5064e1d19a09cb6bffb8002dccaaad59cc40cff
bigcode/the-stack
train
f812f9e7f9d97b9737f5a751
train
function
def decom_vgg16(): # the 30th layer of features is relu of conv5_3 if opt.caffe_pretrain: model = vgg16(pretrained=False) if not opt.load_path: model.load_state_dict(t.load(opt.caffe_pretrain_path)) else: model = vgg16(not opt.load_path) features = list(model.feature...
def decom_vgg16(): # the 30th layer of features is relu of conv5_3
if opt.caffe_pretrain: model = vgg16(pretrained=False) if not opt.load_path: model.load_state_dict(t.load(opt.caffe_pretrain_path)) else: model = vgg16(not opt.load_path) features = list(model.features)[:30] classifier = model.classifier classifier = list(classi...
ProposalNetwork from model.faster_rcnn import FasterRCNN from model.roi_module import RoIPooling2D from utils import array_tool as at from utils.config import opt def decom_vgg16(): # the 30th layer of features is relu of conv5_3
64
64
172
24
39
mahavird/vehicle_detection
model/faster_rcnn_vgg16.py
Python
decom_vgg16
decom_vgg16
11
35
11
12
ddb9144b2f4c72e73355708a841fe46c80c3dcf0
bigcode/the-stack
train
9d060a0270e8ff3d8ece62ce
train
class
class StorageStoragePolicyList(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. att...
class StorageStoragePolicyList(object):
""" NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute ...
# coding: utf-8 """ Intersight REST API This is Intersight REST API OpenAPI spec version: 1.0.9-255 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class StorageStoragePolicyList(object):
77
229
764
7
69
gumpcraca/intersight-python
intersight/models/storage_storage_policy_list.py
Python
StorageStoragePolicyList
StorageStoragePolicyList
19
153
19
19
78753ff64458c9d2f9a9f1178e086a92f76644c4
bigcode/the-stack
train
3b6bdd23e2b28dd980d41f88
train
class
class SeqReader: def __init__(self, in_file): """ Initialize sequence file to be parsed. :param in_file: """ if not isinstance(in_file, str): raise AttributeError('Only a string can be used to instantiate a SeqReader object.') self.in_file = in_file ...
class SeqReader:
def __init__(self, in_file): """ Initialize sequence file to be parsed. :param in_file: """ if not isinstance(in_file, str): raise AttributeError('Only a string can be used to instantiate a SeqReader object.') self.in_file = in_file def parse_fasta(se...
import gzip class SeqReader:
7
155
517
4
2
malonge/RaGOO
ragoo_utilities/SeqReader.py
Python
SeqReader
SeqReader
4
76
4
5
7b9c7972b18fee5a17e6b0eff9f485c00ebe18d2
bigcode/the-stack
train
faed6e98c1a09d7a88212147
train
class
class _TroupeManager(object): def __init__(self, actorClass, mgr_addr, idle_count, max_count): self.mgr_addr = mgr_addr self.idle_count = idle_count self.max_count = max_count self._troupers = [] self._idle_troupers = [] self._extra_troupers = [] self._pending...
class _TroupeManager(object):
def __init__(self, actorClass, mgr_addr, idle_count, max_count): self.mgr_addr = mgr_addr self.idle_count = idle_count self.max_count = max_count self._troupers = [] self._idle_troupers = [] self._extra_troupers = [] self._pending_work = [] self._handl...
believes the actor is finished. Failure to reset the "troupe_work_in_progress" attribute to False will cause the troupe manager to never send any more work requests to the troupe actor, even if the latter is idle. The troupe actor will also never be killed until the troupe manager itself is killed. """ from thespi...
256
256
1,026
7
249
dendron2000/Thespian
thespian/troupe.py
Python
_TroupeManager
_TroupeManager
88
185
88
88
fcfa709d3265b26986698c698f1d3eb440dfb716
bigcode/the-stack
train
85a9f79f5349f8d94c4c7e0e
train
function
def troupe(max_count=10, idle_count=2): def _troupe(actorClass): actorName = '.'.join((inspect.getmodule(actorClass).__name__, actorClass.__name__)) def manageTroupe(self, message, sender): isTroupeWork = isinstance(message, _TroupeWork) troupeW...
def troupe(max_count=10, idle_count=2):
def _troupe(actorClass): actorName = '.'.join((inspect.getmodule(actorClass).__name__, actorClass.__name__)) def manageTroupe(self, message, sender): isTroupeWork = isinstance(message, _TroupeWork) troupeWorker = getattr(self, '_is_a_troupe_work...
to avoid a fork bomb. return wfnd self._pending_work.append(wfnd) return None def status(self): return 'Idle=%d, Max=%d, Troupers [%d, %d idle, %d extra]: %s, Pending=%d' % ( self.idle_count, self.max_count, len(self._troupers), len(self._idle_tr...
170
170
568
12
158
dendron2000/Thespian
thespian/troupe.py
Python
troupe
troupe
188
241
188
188
d03cfb8334b903dee10ee3cbdaf2841af93e3d3d
bigcode/the-stack
train
6995b8ef3fd3819a52eefc38
train
class
class _TroupeWork(object): def __init__(self, message, orig_sender, troupe_mgr): self.message = message self.orig_sender = orig_sender self.troupe_mgr = troupe_mgr self.ident = None def __str__(self): return '_TroupeWork(from=%s, msg=%s)' % \ (self.orig_sende...
class _TroupeWork(object):
def __init__(self, message, orig_sender, troupe_mgr): self.message = message self.orig_sender = orig_sender self.troupe_mgr = troupe_mgr self.ident = None def __str__(self): return '_TroupeWork(from=%s, msg=%s)' % \ (self.orig_sender, self.message)
for this long and # they are over the idle count, they can be dismissed (killed). DISMISS_EXTRA_PERIOD = timedelta(seconds=2) class _TroupeMemberReady(object): def __init__(self, work_ident): self.ident_done = work_ident class _TroupeWork(object):
64
64
83
7
56
dendron2000/Thespian
thespian/troupe.py
Python
_TroupeWork
_TroupeWork
76
85
76
76
fe07be04287923cfca6819fefba2319b840e5b1d
bigcode/the-stack
train
d457a52600d73cabb517339c
train
class
class _TroupeMemberReady(object): def __init__(self, work_ident): self.ident_done = work_ident
class _TroupeMemberReady(object):
def __init__(self, work_ident): self.ident_done = work_ident
ActorExited, WakeupMessage) from datetime import timedelta import inspect # If at least some troupe members have been idle for this long and # they are over the idle count, they can be dismissed (killed). DISMISS_EXTRA_PERIOD = timedelta(seconds=2) class _TroupeMemberReady(object):
64
64
26
8
56
dendron2000/Thespian
thespian/troupe.py
Python
_TroupeMemberReady
_TroupeMemberReady
71
73
71
71
c54bb48563414ba0e11275ee8d8cce4b849e1cdf
bigcode/the-stack
train
56b48526133e45811504c33b
train
class
class VT(): """ This check queries VirusTotal API given a list of md5 hashes. """ def __init__(self, api_key): self.logger = logging.getLogger('alarm_filehash.ioc_vt') self.api_key = api_key def get_remaining_quota(self): """ Returns the number of hashes that could be queried within...
class VT():
""" This check queries VirusTotal API given a list of md5 hashes. """ def __init__(self, api_key): self.logger = logging.getLogger('alarm_filehash.ioc_vt') self.api_key = api_key def get_remaining_quota(self): """ Returns the number of hashes that could be queried within this run ""...
#!/usr/bin/python3 """ Part of RedELK This check queries VirusTotal API given a list of md5 hashes. Authors: - Outflank B.V. / Mark Bergman (@xychix) - Lorenzo Bernardi (@fastlorenzo) """ import logging from datetime import datetime import requests from modules.helpers import get_value # The Public API is limited to...
98
256
1,008
3
95
gitradar/RedELK
elkserver/docker/redelk-base/redelkinstalldata/scripts/modules/alarm_filehash/ioc_vt.py
Python
VT
VT
18
130
18
18
76f296fc8a8a8b48911c3efa0760868c7940e2e0
bigcode/the-stack
train
97f763a88fef3b90a5a64b70
train
class
class TestCollector(unittest.TestCase): def test_parse_01(self): """It parses a collector name & number.""" self.assertEqual( COLLECTOR.parse('Coll. M. P. Locke No. 4823'), [Trait(col_name='M. P. Locke', col_no='4823', start=0, end=26)]) def test_parse_02(self): ...
class TestCollector(unittest.TestCase):
def test_parse_01(self): """It parses a collector name & number.""" self.assertEqual( COLLECTOR.parse('Coll. M. P. Locke No. 4823'), [Trait(col_name='M. P. Locke', col_no='4823', start=0, end=26)]) def test_parse_02(self): """It parses a several collectors.""" ...
# pylint: disable=missing-module-docstring,missing-class-docstring # pylint: disable=missing-function-docstring,too-many-public-methods import textwrap import unittest from digi_leap.pylib.trait import Trait from digi_leap.parsers.collector import COLLECTOR class TestCollector(unittest.TestCase):
69
256
1,682
7
61
rafelafrance/traiter_label_babel
tests/parsers/test_collector.py
Python
TestCollector
TestCollector
10
188
10
11
aae802de916878be2e7264f064596029238e4022
bigcode/the-stack
train
8811487522f76242844d33db
train
function
def _run_applymap(df, func, args=None, pandas_kwds=None): """Run DataFrame.applymap(). Parameters ---------- df : DataFrame Any pandas DataFrame args : tuple A tuple of arguments to submit to the function pandas_kwds : dict A dictionary of keyword arguments to pass to Da...
def _run_applymap(df, func, args=None, pandas_kwds=None):
"""Run DataFrame.applymap(). Parameters ---------- df : DataFrame Any pandas DataFrame args : tuple A tuple of arguments to submit to the function pandas_kwds : dict A dictionary of keyword arguments to pass to DataFrame.apply() Returns ------- DataFrame ...
result of apply() """ apply_kwds = {'args': args} if args else {} if pandas_kwds: apply_kwds.update(pandas_kwds) return df.apply(func, **apply_kwds) def _run_applymap(df, func, args=None, pandas_kwds=None):
64
64
138
17
47
MikeDacre/python_slurm
fyrd/helpers.py
Python
_run_applymap
_run_applymap
447
467
447
447
4943f63c9e9d18fbcc498878e86d2a4aecaef708
bigcode/the-stack
train
f2c503a922f555023d8bb56b
train
function
def _parapply_summary(jobs, df, func, args=(), profile=None, applymap=False, name='parapply', imports=None, **kwds): """Direct running function for parapply_sumary, see that docstring.""" imports = _run.export_imports(func, {'imports': imports}) out = parapply(jobs, df, func, args, pro...
def _parapply_summary(jobs, df, func, args=(), profile=None, applymap=False, name='parapply', imports=None, **kwds):
"""Direct running function for parapply_sumary, see that docstring.""" imports = _run.export_imports(func, {'imports': imports}) out = parapply(jobs, df, func, args, profile, applymap, name=name, merge_axis=1, imports=imports, **kwds) # Pick function and get args sub_func = _run_...
, kwargs) return _wrap_runner( _parapply_summary, *(jobs, df, func), **kwargs ) def _parapply_summary(jobs, df, func, args=(), profile=None, applymap=False, name='parapply', imports=None, **kwds):
64
64
173
35
29
MikeDacre/python_slurm
fyrd/helpers.py
Python
_parapply_summary
_parapply_summary
406
421
406
407
da3a21fbe3c640ad8ab7c5646e3a4c6515a4de7d
bigcode/the-stack
train
968ec83fca4659f936a7fba5
train
function
def _wrap_runner(command, *args, **kkk): """Run a command as a job, for use with the functions in this file. *Note*: Only uses the 'profile', 'imports', 'syspaths', 'mem', 'clean_files', 'clean_outputs', and 'partition' keyword arguments for job submission, all others are ignored. Returns ----...
def _wrap_runner(command, *args, **kkk):
"""Run a command as a job, for use with the functions in this file. *Note*: Only uses the 'profile', 'imports', 'syspaths', 'mem', 'clean_files', 'clean_outputs', and 'partition' keyword arguments for job submission, all others are ignored. Returns ------- fyrd.job.Job A Job class ...
(outfile, 'w') as fout: if outheader: with open(files[0]) as fin: fout.write(fin.readline()) for f in files: with open(f + '.out') as fin: if outheader: fin.readline() fout.write(f...
142
143
478
13
129
MikeDacre/python_slurm
fyrd/helpers.py
Python
_wrap_runner
_wrap_runner
719
758
719
719
8d8c829a00a880e1118dce7c7840070fa181e26a
bigcode/the-stack
train
7a60573adce4f83a5f8675d3
train
function
def _run_apply(df, func, args=None, pandas_kwds=None): """Run DataFrame.apply(). Parameters ---------- df : DataFrame Any pandas DataFrame args : tuple A tuple of arguments to submit to the function pandas_kwds : dict A dictionary of keyword arguments to pass to DataFram...
def _run_apply(df, func, args=None, pandas_kwds=None):
"""Run DataFrame.apply(). Parameters ---------- df : DataFrame Any pandas DataFrame args : tuple A tuple of arguments to submit to the function pandas_kwds : dict A dictionary of keyword arguments to pass to DataFrame.apply() Returns ------- DataFrame ...
pandas_kwds = _options.split_keywords(kwds)[1] # Transpose out = out.T # Run the function again return sub_func(out, func, args, pandas_kwds) def _run_apply(df, func, args=None, pandas_kwds=None):
64
64
135
16
48
MikeDacre/python_slurm
fyrd/helpers.py
Python
_run_apply
_run_apply
424
444
424
424
d79932a1a4dfd422ca70b9c4ae5350885ff29b4e
bigcode/the-stack
train
aa8bde8e5e513deb83baf2ce
train
function
def jobify(name=None, profile=None, qtype=None, submit=True, **kwds): """Decorator to make any function a job. Will make any function return a Job object that will execute the function on the cluster. If `submit` is `True`, the job will be submitted when it is returned. Usage: .. code:: pyth...
def jobify(name=None, profile=None, qtype=None, submit=True, **kwds):
"""Decorator to make any function a job. Will make any function return a Job object that will execute the function on the cluster. If `submit` is `True`, the job will be submitted when it is returned. Usage: .. code:: python @fyrd.jobify(name='my_job', profile='small', mem='8GB', ...
parapply and merge the results (don't concatenate). splitrun Split a file, run a command in parallel, return result. """ import os as _os from six import text_type as _txt from six import string_types as _str from six import integer_types as _int ###################################################################...
226
227
759
20
206
MikeDacre/python_slurm
fyrd/helpers.py
Python
jobify
jobify
48
138
48
48
a250716e7f39edc193388ed566c200672ef944bd
bigcode/the-stack
train
fafa2452fbfe1256fd36d30b
train
function
def parapply_summary(jobs, df, func, args=(), profile=None, applymap=False, name='parapply', imports=None, direct=True, **kwds): """Run parapply for a function with summary stats. Instead of returning the concatenated result, merge the result using the same function as was used during ...
def parapply_summary(jobs, df, func, args=(), profile=None, applymap=False, name='parapply', imports=None, direct=True, **kwds):
"""Run parapply for a function with summary stats. Instead of returning the concatenated result, merge the result using the same function as was used during apply. This works best for summary functions like `.mean()`, which do a linear operation on a whole dataframe or series. Parameters ...
logme.log('Waiting for results', 'debug') results = [] for out in outs: try: results.append(out.get()) except IOError: _logme.log('Result getting failed, most likely one of the child ' + 'jobs crashed, check the error files', 'critical') ...
191
191
639
37
153
MikeDacre/python_slurm
fyrd/helpers.py
Python
parapply_summary
parapply_summary
323
403
323
324
92dda290b3de5de4dae1973e086a844be7671e0e
bigcode/the-stack
train
5875fef27e99e6026cc84e07
train
function
def _parapply(jobs, df, func, args=(), profile=None, applymap=False, merge_axis=0, merge_apply=False, name='parapply', imports=None, **kwds): """Direct running function for parapply, see parapply docstring.""" # Handle arguments if not isinstance(jobs, _int): raise ValueE...
def _parapply(jobs, df, func, args=(), profile=None, applymap=False, merge_axis=0, merge_apply=False, name='parapply', imports=None, **kwds):
"""Direct running function for parapply, see parapply docstring.""" # Handle arguments if not isinstance(jobs, _int): raise ValueError('Jobs argument must be an integer.') if not isinstance(df, (_pd.core.frame.DataFrame, _np.ndarray)): raise ValueError('df must be a dataframe or numpy ar...
, args=args, profile=profile, applymap=applymap, merge_axis=merge_axis, merge_apply=merge_apply, name=name, imports=imports, **kwds ) kwargs = dict( args=args, profile=profile, applymap=applymap, merge_axis=merge_axis, merge_apply=merge_apply, name=name, impor...
207
207
690
44
163
MikeDacre/python_slurm
fyrd/helpers.py
Python
_parapply
_parapply
242
320
242
244
94bfecfb484fc2adf72ff35e8b1dcb692dce156a
bigcode/the-stack
train
06a4dd612ecd5852b2bc08f0
train
function
def _splitrun(jobs, infile, inheader, command, args=None, kwargs=None, name=None, qtype=None, profile=None, outfile=None, outheader=False, merge_func=None, **kwds): """This is the direct running function for `splitrun()`. Please see that function's docstring for information and do n...
def _splitrun(jobs, infile, inheader, command, args=None, kwargs=None, name=None, qtype=None, profile=None, outfile=None, outheader=False, merge_func=None, **kwds):
"""This is the direct running function for `splitrun()`. Please see that function's docstring for information and do not call this function directly. """ # Handle arguments if not isinstance(jobs, _int): raise ValueError('Jobs argument must be an integer.') if profile is not None an...
options.check_arguments(kwds) if direct: return _splitrun( jobs, infile, inheader, command, args=args, kwargs=kwargs, name=name, qtype=qtype, profile=profile, outfile=outfile, outheader=outheader, merge_func=merge_func, **kwds ) else: kk = dict( ...
256
256
916
47
209
MikeDacre/python_slurm
fyrd/helpers.py
Python
_splitrun
_splitrun
594
711
594
596
3c649c9f74addf8a23e6e079b25d6460718c202a
bigcode/the-stack
train
899a9ff120bf1bc50e5d6b14
train
function
def splitrun(jobs, infile, inheader, command, args=None, kwargs=None, name=None, qtype=None, profile=None, outfile=None, outheader=False, merge_func=None, direct=True, **kwds): """Split a file, run command in parallel, return result. This function will split a file into however many p...
def splitrun(jobs, infile, inheader, command, args=None, kwargs=None, name=None, qtype=None, profile=None, outfile=None, outheader=False, merge_func=None, direct=True, **kwds):
"""Split a file, run command in parallel, return result. This function will split a file into however many pieces are requested with the jobs argument, and run command on each. Accepts exactly the same arguments as the Job class, with the exception of the first three and last four arguments, which...
Returns ------- DataFrame The result of apply() """ apply_kwds = {'args': args} if args else {} if pandas_kwds: apply_kwds.update(pandas_kwds) return df.apply(func, **apply_kwds) def _run_applymap(df, func, args=None, pandas_kwds=None): """Run DataFrame.applymap(). ...
255
256
1,032
49
206
MikeDacre/python_slurm
fyrd/helpers.py
Python
splitrun
splitrun
475
591
475
477
8b0d0ce55f2a4c3362e6f7f492263dc8863d9f58
bigcode/the-stack
train
f3d6d32a02fc9ec971a249e0
train
function
def parapply(jobs, df, func, args=(), profile=None, applymap=False, merge_axis=0, merge_apply=False, name='parapply', imports=None, direct=True, **kwds): """Split a dataframe, run apply in parallel, return result. This function will split a dataframe into however many pieces are reque...
def parapply(jobs, df, func, args=(), profile=None, applymap=False, merge_axis=0, merge_apply=False, name='parapply', imports=None, direct=True, **kwds):
"""Split a dataframe, run apply in parallel, return result. This function will split a dataframe into however many pieces are requested with the jobs argument, run apply in parallel by submitting the jobs to the cluster, and then recombine the outputs. If the 'clean_files' and 'clean_outputs' argu...
job = _Job(func, args=args, kwargs=kwargs, name=name, qtype=qtype, profile=profile, **kwds) jdoc = job.__doc__ if jdoc: jdoc = "\n\nJob documentation:\n\n{0}".format(jdoc) else: jdoc = "" job.__doc__ = ( ...
253
254
847
46
207
MikeDacre/python_slurm
fyrd/helpers.py
Python
parapply
parapply
146
239
146
148
c1f4a4c330a5bbec33c6698cb73e2baba96d8f56
bigcode/the-stack
train
663efb38b59fb1b2da4fd86a
train
class
class IRLDatabaseMessage(Enum): ENABLE_TRAINING = 0 DISABLE_TRAINING = 1 ENABLE_SAMPLING = 2 DISABLE_SAMPLING = 3
class IRLDatabaseMessage(Enum):
ENABLE_TRAINING = 0 DISABLE_TRAINING = 1 ENABLE_SAMPLING = 2 DISABLE_SAMPLING = 3
import gridfs import pymongo IS_MONGO_AVAILABLE = True except ImportError: IS_MONGO_AVAILABLE = False from misc import dict2structed_trajectory, structed2dict_trajectory, Trajectory from catalyst.utils import pack, unpack class IRLDatabaseMessage(Enum):
64
64
45
7
56
tadejsv/catalyst
examples/catalyst_rl/db.py
Python
IRLDatabaseMessage
IRLDatabaseMessage
27
31
27
27
b915fe233a359749bdbd798565df39c744586ff4
bigcode/the-stack
train
444651d3667ecda66437c285
train
class
class IRLDatabase(ABC): @property @abstractmethod def training_enabled(self) -> bool: pass @property @abstractmethod def sampling_enabled(self) -> bool: pass @property @abstractmethod def epoch(self) -> int: pass @property @abstractmethod def nu...
class IRLDatabase(ABC): @property @abstractmethod
def training_enabled(self) -> bool: pass @property @abstractmethod def sampling_enabled(self) -> bool: pass @property @abstractmethod def epoch(self) -> int: pass @property @abstractmethod def num_trajectories(self) -> int: pass @abstractme...
pack, unpack class IRLDatabaseMessage(Enum): ENABLE_TRAINING = 0 DISABLE_TRAINING = 1 ENABLE_SAMPLING = 2 DISABLE_SAMPLING = 3 class IRLDatabase(ABC): @property @abstractmethod
65
65
217
16
48
tadejsv/catalyst
examples/catalyst_rl/db.py
Python
IRLDatabase
IRLDatabase
34
81
34
36
b57fc1bb19555e55b6b78a546fcf32d039a3b774
bigcode/the-stack
train
a3d18467e00adca3498e0125
train
function
def main(): parser = argparse.ArgumentParser(description="Create an instrument model") parser.add_argument('config', type=str, metavar='INPUT') args = parser.parse_args(sys.argv[1:]) config = json_load_ascii(args.config, shell_replace=True) configdir, configfile = split(abspath(args.config)) i...
def main():
parser = argparse.ArgumentParser(description="Create an instrument model") parser.add_argument('config', type=str, metavar='INPUT') args = parser.parse_args(sys.argv[1:]) config = json_load_ascii(args.config, shell_replace=True) configdir, configfile = split(abspath(args.config)) infile = expan...
(dists-distsp) < uthresh) use = dists < thresh C = s.cov(xsub[use, :], rowvar=False) [U, V, D] = svd(C) V[V < 1e-8] = 1e-8 C = U.dot(s.diagflat(V)).dot(D) models.append(C) use_C.append(use) return s.array(models), Xvert, Xvertp, s.array(use_C).T # parse the ...
127
127
424
3
124
lewismc/isofit
utils/instmodel.py
Python
main
main
131
164
131
132
1cdc5652a3c2dae8f00e92c63311db85941b1fcc
bigcode/the-stack
train
73f3437aee03af99c5d84cc6
train
function
def find_header(imgfile): if os.path.exists(imgfile+'.hdr'): return imgfile+'.hdr' ind = imgfile.rfind('.raw') if ind >= 0: return imgfile[0:ind]+'.hdr' ind = imgfile.rfind('.img') if ind >= 0: return imgfile[0:ind]+'.hdr' raise IOError('No header found for file {0}'.form...
def find_header(imgfile):
if os.path.exists(imgfile+'.hdr'): return imgfile+'.hdr' ind = imgfile.rfind('.raw') if ind >= 0: return imgfile[0:ind]+'.hdr' ind = imgfile.rfind('.img') if ind >= 0: return imgfile[0:ind]+'.hdr' raise IOError('No header found for file {0}'.format(imgfile))
type = 4 interleave = bsq byte order = 0 ''' def percentile(X, p): S = sorted(X) return S[int(s.floor(len(S)*(p/100.0)))] # Return the header associated with an image file def find_header(imgfile):
64
64
97
6
57
lewismc/isofit
utils/instmodel.py
Python
find_header
find_header
52
61
52
52
e624a047e3f4b81787763783f7263f02c85d0318
bigcode/the-stack
train
9aa2db42dd5c791b1b5748a7
train
function
def flat_field(X, uniformity_thresh): Xhoriz = low_frequency_horiz(X, sigma=4.0) Xhorizp = low_frequency_horiz(X, sigma=3.0) nl, nb, nc = X.shape FF = s.zeros((nb, nc)) use_ff = s.ones((X.shape[0], X.shape[2])) > 0 for b in range(nb): xsub = Xhoriz[:, b, :] xsubp = Xhorizp[:, b, ...
def flat_field(X, uniformity_thresh):
Xhoriz = low_frequency_horiz(X, sigma=4.0) Xhorizp = low_frequency_horiz(X, sigma=3.0) nl, nb, nc = X.shape FF = s.zeros((nb, nc)) use_ff = s.ones((X.shape[0], X.shape[2])) > 0 for b in range(nb): xsub = Xhoriz[:, b, :] xsubp = Xhorizp[:, b, :] mu = xsub.mean(axis=0) ...
4.0): nl, nb, nr = X.shape Xhoriz = X.copy() for l in range(nl): for b in range(nb): Xhoriz[l, b, :] = gaussian_filter1d( Xhoriz[l, b, :], sigma, mode='nearest') return Xhoriz def flat_field(X, uniformity_thresh):
83
83
278
9
73
lewismc/isofit
utils/instmodel.py
Python
flat_field
flat_field
84
103
84
84
425469b8911f4d0cd93a494e82316d3d836b6922
bigcode/the-stack
train
1d3e52382ea28c355898ca9d
train
function
def percentile(X, p): S = sorted(X) return S[int(s.floor(len(S)*(p/100.0)))]
def percentile(X, p):
S = sorted(X) return S[int(s.floor(len(S)*(p/100.0)))]
hdr_template = '''ENVI samples = {samples} lines = {lines} bands = 1 header offset = 0 file type = ENVI Standard data type = 4 interleave = bsq byte order = 0 ''' def percentile(X, p):
63
64
28
6
57
lewismc/isofit
utils/instmodel.py
Python
percentile
percentile
46
48
46
46
930a64d2d5becbc61c782923cda8b4fcc4d94a40
bigcode/the-stack
train
6f55638b3311773818d37256
train
function
def column_covariances(X, uniformity_thresh): Xvert = high_frequency_vert(X, sigma=4.0) Xvertp = high_frequency_vert(X, sigma=3.0) models = [] use_C = [] for i in range(X.shape[2]): xsub = Xvert[:, :, i] xsubp = Xvertp[:, :, i] mu = xsub.mean(axis=0) dists = s.sqrt(po...
def column_covariances(X, uniformity_thresh):
Xvert = high_frequency_vert(X, sigma=4.0) Xvertp = high_frequency_vert(X, sigma=3.0) models = [] use_C = [] for i in range(X.shape[2]): xsub = Xvert[:, :, i] xsubp = Xvertp[:, :, i] mu = xsub.mean(axis=0) dists = s.sqrt(pow((xsub - mu), 2).sum(axis=1)) distsp ...
, :] = ((xsub*use).sum(axis=0)/use.sum(axis=0)) / \ ((X[:, b, :]*use).sum(axis=0)/use.sum(axis=0)) use_ff = s.logical_and(use_ff, use) return FF, Xhoriz, Xhorizp, s.array(use_ff) def column_covariances(X, uniformity_thresh):
84
84
282
11
73
lewismc/isofit
utils/instmodel.py
Python
column_covariances
column_covariances
106
127
106
106
65ad3779869d0d0f764371d51dfe7be2915cebf5
bigcode/the-stack
train
efb71acfc263012ceae2c229
train
function
def low_frequency_horiz(X, sigma=4.0): nl, nb, nr = X.shape Xhoriz = X.copy() for l in range(nl): for b in range(nb): Xhoriz[l, b, :] = gaussian_filter1d( Xhoriz[l, b, :], sigma, mode='nearest') return Xhoriz
def low_frequency_horiz(X, sigma=4.0):
nl, nb, nr = X.shape Xhoriz = X.copy() for l in range(nl): for b in range(nb): Xhoriz[l, b, :] = gaussian_filter1d( Xhoriz[l, b, :], sigma, mode='nearest') return Xhoriz
): for b in range(nb): filt = gaussian_filter1d(Xvert[:, b, r], sigma, mode='nearest') Xvert[:, b, r] = X[:, b, r] - filt return Xvert def low_frequency_horiz(X, sigma=4.0):
64
64
83
13
50
lewismc/isofit
utils/instmodel.py
Python
low_frequency_horiz
low_frequency_horiz
74
81
74
74
38f3c99fb6b859b9314ec60d761b80602377534f
bigcode/the-stack
train
46c320c1aa05a1fe27d39d87
train
function
def high_frequency_vert(X, sigma=4.0): nl, nb, nr = X.shape Xvert = X.copy() for r in range(nr): for b in range(nb): filt = gaussian_filter1d(Xvert[:, b, r], sigma, mode='nearest') Xvert[:, b, r] = X[:, b, r] - filt return Xvert
def high_frequency_vert(X, sigma=4.0):
nl, nb, nr = X.shape Xvert = X.copy() for r in range(nr): for b in range(nb): filt = gaussian_filter1d(Xvert[:, b, r], sigma, mode='nearest') Xvert[:, b, r] = X[:, b, r] - filt return Xvert
0:ind]+'.hdr' ind = imgfile.rfind('.img') if ind >= 0: return imgfile[0:ind]+'.hdr' raise IOError('No header found for file {0}'.format(imgfile)) def high_frequency_vert(X, sigma=4.0):
64
64
87
12
52
lewismc/isofit
utils/instmodel.py
Python
high_frequency_vert
high_frequency_vert
64
71
64
64
4185cb2fc92e855c01f47ad7697d2b54aee44e75
bigcode/the-stack
train
0f2da5492f513cbd11a80702
train
function
def _warn_no_xgaps_deprecated(value): warnings.warn('\n\n ================================================================= '+ '\n\n WARNING: `no_xgaps` is /deprecated/:'+ '\n Default value is now `no_xgaps=True`'+ '\n However, to set `no_xgaps=False` ...
def _warn_no_xgaps_deprecated(value):
warnings.warn('\n\n ================================================================= '+ '\n\n WARNING: `no_xgaps` is /deprecated/:'+ '\n Default value is now `no_xgaps=True`'+ '\n However, to set `no_xgaps=False` and silence this warning,'+ ...
be reversed when the decorated function returns (therefore those changes have no effect outside of the decorated function). ''' def decorator(*args, **kwargs): with plt.rc_context(): return func(*args, **kwargs) return decorator def _warn_no_xgaps_deprecated(value):
64
64
114
11
52
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_warn_no_xgaps_deprecated
_warn_no_xgaps_deprecated
67
75
67
67
919df43d28eac8f71f813aaa95649e442d277440
bigcode/the-stack
train
4f0c8b16a63e0c86931a0acf
train
function
def _adjust_figsize(fig,config): if fig is None: return if config['figsize'] is None: w,h = config['figratio'] r = float(w)/float(h) if r < 0.20 or r > 5.0: raise ValueError('"figratio" (aspect ratio) must be between 0.20 and 5.0 (but is '+str(r)+')') default...
def _adjust_figsize(fig,config):
if fig is None: return if config['figsize'] is None: w,h = config['figratio'] r = float(w)/float(h) if r < 0.20 or r > 5.0: raise ValueError('"figratio" (aspect ratio) must be between 0.20 and 5.0 (but is '+str(r)+')') default_scale = DEFAULT_FIGRATIO[1]/h ...
plt.rcParams) # rcpdf = rcParams_to_df(rcp) # print('type(rcpdf)=',type(rcpdf)) # print('rcpdfhead(3)=',rcpdf.head(3)) # return # rcpdf def _adjust_figsize(fig,config):
64
64
175
9
54
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_adjust_figsize
_adjust_figsize
795
811
795
795
2fa4f8605368793b735cb6e84154c57d56f19a9f
bigcode/the-stack
train
bd471f3d27410b1d9ddc8bba
train
function
def _auto_secondary_y( panels, panid, ylo, yhi ): # If mag(nitude) for this panel is not yet set, then set it # here, as this is the first ydata to be plotted on this panel: # i.e. consider this to be the 'primary' axis for this panel. secondary_y = False p = panid,'mag' if panels.at[p] is None:...
def _auto_secondary_y( panels, panid, ylo, yhi ): # If mag(nitude) for this panel is not yet set, then set it # here, as this is the first ydata to be plotted on this panel: # i.e. consider this to be the 'primary' axis for this panel.
secondary_y = False p = panid,'mag' if panels.at[p] is None: panels.at[p] = {'lo':ylo,'hi':yhi} elif ylo < panels.at[p]['lo'] or yhi > panels.at[p]['hi']: secondary_y = True #if secondary_y: # print('auto says USE secondary_y ... for panel',panid) #else: # print('au...
def _auto_secondary_y( panels, panid, ylo, yhi ): # If mag(nitude) for this panel is not yet set, then set it # here, as this is the first ydata to be plotted on this panel: # i.e. consider this to be the 'primary' axis for this panel.
72
64
190
72
0
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_auto_secondary_y
_auto_secondary_y
1,026
1,040
1,026
1,029
0915900273e1027ee8fe0e1a2fe768aa1631327c
bigcode/the-stack
train
48a197bfaa465c55ecedcafe
train
function
def _adjust_fontsize(config): if config['fontscale'] is None: return if not isinstance(plt.rcParams['font.size'],(float,int)): warnings.warn('\n\n ================================================================= '+ '\n\n WARNING: Unable to scale fonts: plt.rcParams["font...
def _adjust_fontsize(config):
if config['fontscale'] is None: return if not isinstance(plt.rcParams['font.size'],(float,int)): warnings.warn('\n\n ================================================================= '+ '\n\n WARNING: Unable to scale fonts: plt.rcParams["font.size"] is NOT a float!'+ ...
5.0 (but is '+str(r)+')') default_scale = DEFAULT_FIGRATIO[1]/h h *= default_scale w *= default_scale base = (w,h) figscale = config['figscale'] fsize = [d*figscale for d in base] else: fsize = config['figsize'] fig.set_size_inches(fsize) def _ad...
98
98
328
7
91
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_adjust_fontsize
_adjust_fontsize
813
842
813
813
26fa190e944c5be890f00feab3c69d5d929c1799
bigcode/the-stack
train
2e6520f07d51e90de62e7420
train
function
def _addplot_columns(panid,panels,ydata,apdict,xdates,config): external_axes_mode = apdict['ax'] is not None if not external_axes_mode: secondary_y = False if apdict['secondary_y'] == 'auto': yd = [y for y in ydata if not math.isnan(y)] ymhi = math.log(max(math.fabs(np.na...
def _addplot_columns(panid,panels,ydata,apdict,xdates,config):
external_axes_mode = apdict['ax'] is not None if not external_axes_mode: secondary_y = False if apdict['secondary_y'] == 'auto': yd = [y for y in ydata if not math.isnan(y)] ymhi = math.log(max(math.fabs(np.nanmax(yd)),1e-7),10) ymlo = math.log(max(math.fabs(n...
7),10) - 0.5 hi = math.log(max(math.fabs(np.nanmax(h)),1e-7),10) + 0.5 secondary_y = _auto_secondary_y( panels, panid, lo, hi ) if 'auto' != apdict['secondary_y']: secondary_y = apdict['secondary_y'] if secondary_y: ax = panels.at[panid,'axes'][1] pa...
218
218
728
21
196
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_addplot_columns
_addplot_columns
899
958
899
899
88af51bc7c3e6298ad116c81dd533ba13b2d5972
bigcode/the-stack
train
731406807ebd76f9bd920b93
train
function
def with_rc_context(func): ''' This decoractor creates an rcParams context around a function, so that any changes the function makes to rcParams will be reversed when the decorated function returns (therefore those changes have no effect outside of the decorated function). ''' def decorator(*arg...
def with_rc_context(func):
''' This decoractor creates an rcParams context around a function, so that any changes the function makes to rcParams will be reversed when the decorated function returns (therefore those changes have no effect outside of the decorated function). ''' def decorator(*args, **kwargs): with ...
_list_of_dict from mplfinance._helpers import _num_or_seq_of_num from mplfinance._helpers import _adjust_color_brightness VALID_PMOVE_TYPES = ['renko', 'pnf'] DEFAULT_FIGRATIO = (8.00,5.75) def with_rc_context(func):
64
64
87
6
58
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
with_rc_context
with_rc_context
56
65
56
56
e592ed98a31c4c619f08b6cc540ca9957a5a5057
bigcode/the-stack
train
0118b29e7f4377feab79adc1
train
function
def _valid_plot_kwargs(): ''' Construct and return the "valid kwargs table" for the mplfinance.plot() function. A valid kwargs table is a `dict` of `dict`s. The keys of the outer dict are the valid key-words for the function. The value for each key is a dict containing 2 specific keys: "Default", ...
def _valid_plot_kwargs():
''' Construct and return the "valid kwargs table" for the mplfinance.plot() function. A valid kwargs table is a `dict` of `dict`s. The keys of the outer dict are the valid key-words for the function. The value for each key is a dict containing 2 specific keys: "Default", and "Validator" with the f...
reversed when the decorated function returns (therefore those changes have no effect outside of the decorated function). ''' def decorator(*args, **kwargs): with plt.rc_context(): return func(*args, **kwargs) return decorator def _warn_no_xgaps_deprecated(value): warnings.warn(...
256
256
2,365
6
250
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_valid_plot_kwargs
_valid_plot_kwargs
87
283
87
87
912c1e6549e1dd8dde96c39501ac6cdde178cf09
bigcode/the-stack
train
2a59fd93841113e241f4f418
train
function
def _plot_mav(ax,config,xdates,prices,apmav=None,apwidth=None): style = config['style'] if apmav is not None: mavgs = apmav else: mavgs = config['mav'] mavp_list = [] if mavgs is not None: shift = None if isinstance(mavgs,dict): shift = mavgs['shift'] ...
def _plot_mav(ax,config,xdates,prices,apmav=None,apwidth=None):
style = config['style'] if apmav is not None: mavgs = apmav else: mavgs = config['mav'] mavp_list = [] if mavgs is not None: shift = None if isinstance(mavgs,dict): shift = mavgs['shift'] mavgs = mavgs['period'] if isinstance(mavgs,int)...
else: # treat non-True as False, whether False, None, or anything else. ax_pri.yaxis.set_label_position('left') ax_pri.yaxis.tick_left() if ax_sec is not None: ax_sec.yaxis.set_label_position('right') ax_sec.yaxis.tick_right() def _plot_mav(ax,config,xdates,prices,ap...
91
91
304
22
69
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_plot_mav
_plot_mav
991
1,024
991
991
1057a9acee4e16f1b6660286f1c4f1b194d75799
bigcode/the-stack
train
f50bef584c40dbf9677a055c
train
function
def _set_ylabels_side(ax_pri,ax_sec,primary_on_right): # put the primary axis on one side, # and the twinx() on the "other" side: if primary_on_right == True: ax_pri.yaxis.set_label_position('right') ax_pri.yaxis.tick_right() if ax_sec is not None: ax_sec.yaxis.set_label_...
def _set_ylabels_side(ax_pri,ax_sec,primary_on_right): # put the primary axis on one side, # and the twinx() on the "other" side:
if primary_on_right == True: ax_pri.yaxis.set_label_position('right') ax_pri.yaxis.tick_right() if ax_sec is not None: ax_sec.yaxis.set_label_position('left') ax_sec.yaxis.tick_left() else: # treat non-True as False, whether False, None, or anything else. ...
,**ysd) elif isinstance(ysd,str): ax.set_yscale(ysd) def _set_ylabels_side(ax_pri,ax_sec,primary_on_right): # put the primary axis on one side, # and the twinx() on the "other" side:
64
64
166
41
23
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_set_ylabels_side
_set_ylabels_side
975
989
975
977
f533b1f8a80fd9efae74956ef7676b60ff78b3c9
bigcode/the-stack
train
5d79907b8f12e8d02e8a726f
train
function
def _addplot_apply_supplements(ax,apdict): if (apdict['ylabel'] is not None): ax.set_ylabel(apdict['ylabel']) if apdict['ylim'] is not None: ax.set_ylim(apdict['ylim'][0],apdict['ylim'][1]) if apdict['title'] is not None: ax.set_title(apdict['title']) ysd = apdict['yscale'] i...
def _addplot_apply_supplements(ax,apdict):
if (apdict['ylabel'] is not None): ax.set_ylabel(apdict['ylabel']) if apdict['ylim'] is not None: ax.set_ylim(apdict['ylim'][0],apdict['ylim'][1]) if apdict['title'] is not None: ax.set_title(apdict['title']) ysd = apdict['yscale'] if isinstance(ysd,dict): yscale = ys...
"'+str(aptype)+'" NOT yet supported.') if apdict['mav'] is not None: apmavprices = _plot_mav(ax,config,xdates,ydata,apdict['mav']) return ax def _addplot_apply_supplements(ax,apdict):
64
64
153
13
50
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_addplot_apply_supplements
_addplot_apply_supplements
960
973
960
960
60ae0c6550b7b42fcd3cea9c61b8387df4dae9d9
bigcode/the-stack
train
3979f57558ef6ad66c48f729
train
function
def make_addplot(data, **kwargs): ''' Take data (pd.Series, pd.DataFrame, np.ndarray of floats, list of floats), and kwargs (see valid_addplot_kwargs_table) and construct a correctly structured dict to be passed into plot() using kwarg `addplot`. NOTE WELL: len(data) here must match the len(data) ...
def make_addplot(data, **kwargs):
''' Take data (pd.Series, pd.DataFrame, np.ndarray of floats, list of floats), and kwargs (see valid_addplot_kwargs_table) and construct a correctly structured dict to be passed into plot() using kwarg `addplot`. NOTE WELL: len(data) here must match the len(data) passed into plot() ''' if ...
marketcolors' : { 'Default' : None, # use 'style' for default, instead. 'Validator' : lambda value: _is_marketcolor_object(value) }, } _validate_vkwargs_dict(vkwargs) return vkwargs def make_addplot(data, **kwargs):
64
64
183
9
54
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
make_addplot
make_addplot
1,126
1,142
1,126
1,126
d179c11ade8dca0a458bca2533ce008b7f66ad8e
bigcode/the-stack
train
53a8df718335b4c9b037794a
train
function
def _warn_set_ylim_deprecated(value): warnings.warn('\n\n ================================================================= '+ '\n\n WARNING: `set_ylim=(ymin,ymax)` kwarg '+ '\n has been replaced with: '+ '\n `ylim=(ymin,ymax)`.'+ ...
def _warn_set_ylim_deprecated(value):
warnings.warn('\n\n ================================================================= '+ '\n\n WARNING: `set_ylim=(ymin,ymax)` kwarg '+ '\n has been replaced with: '+ '\n `ylim=(ymin,ymax)`.'+ '\n\n ================...
However, to set `no_xgaps=False` and silence this warning,'+ '\n use instead: `show_nontrading=True`.'+ '\n\n ================================================================ ', category=DeprecationWarning) return isinstance(value,bool) def _warn_set_yl...
64
64
84
9
55
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_warn_set_ylim_deprecated
_warn_set_ylim_deprecated
77
84
77
77
6497a7680270ad1420b329dc5459f8bc7e8b577d
bigcode/the-stack
train
fa738cfe001563663edecf7b
train
function
def _addplot_collections(panid,panels,apdict,xdates,config): apdata = apdict['data'] aptype = apdict['type'] external_axes_mode = apdict['ax'] is not None #--------------------------------------------------------------# # Note: _auto_secondary_y() sets the 'magnitude' column in the # ...
def _addplot_collections(panid,panels,apdict,xdates,config):
apdata = apdict['data'] aptype = apdict['type'] external_axes_mode = apdict['ax'] is not None #--------------------------------------------------------------# # Note: _auto_secondary_y() sets the 'magnitude' column in the # `panels` dataframe, which is needed for automatically # ...
# 'medium': 1.0, # 'large': 1.200, # 'x-large': 1.440, # 'xx-large': 1.728, # 'larger': 1.2, # 'smaller': 0.833, # None: 1.0, # } # -------------------------------------------- fontstuff = ['axes.labelsize','axes.tit...
186
186
623
20
166
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_addplot_collections
_addplot_collections
844
897
844
845
1e42ee8722df41a7571acbdc65c58a9f5638fea3
bigcode/the-stack
train
c4c98f52a4e1676d7d4352ed
train
function
def _valid_addplot_kwargs(): valid_linestyles = ('-','solid','--','dashed','-.','dashdot','.','dotted',None,' ','') valid_types = ('line','scatter','bar', 'ohlc', 'candle','step') valid_stepwheres = ('pre','post','mid') valid_edgecolors = ('face', 'none', None) vkwargs = { 'scatter' : ...
def _valid_addplot_kwargs():
valid_linestyles = ('-','solid','--','dashed','-.','dashdot','.','dotted',None,' ','') valid_types = ('line','scatter','bar', 'ohlc', 'candle','step') valid_stepwheres = ('pre','post','mid') valid_edgecolors = ('face', 'none', None) vkwargs = { 'scatter' : { 'Default' : False, ...
line_width'] if mavc: ax.plot(xdates, mavprices, linewidth=lw, color=next(mavc)) else: ax.plot(xdates, mavprices, linewidth=lw) mavp_list.append(mavprices) return mavp_list def _auto_secondary_y( panels, panid, ylo, yhi ): # If mag(nitude) for...
256
256
927
7
248
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
_valid_addplot_kwargs
_valid_addplot_kwargs
1,042
1,123
1,042
1,043
e3e7878fbdae3e6cbb8135f40af4e9e00d914349
bigcode/the-stack
train
80b3970ec894364185fde2b6
train
function
def plot( data, **kwargs ): """ Given a Pandas DataFrame containing columns Open,High,Low,Close and optionally Volume with a DatetimeIndex, plot the data. Available plots include ohlc bars, candlestick, and line plots. Also provide visually analysis in the form of common technical studies, such as: ...
def plot( data, **kwargs ):
""" Given a Pandas DataFrame containing columns Open,High,Low,Close and optionally Volume with a DatetimeIndex, plot the data. Available plots include ohlc bars, candlestick, and line plots. Also provide visually analysis in the form of common technical studies, such as: moving averages, renko, ...
' : 1.0, # Issue#193 'Validator' : lambda value: _scale_padding_validator(value) }, 'ax' : { 'Default' : None, 'Validator' : lambda value: isinstance(value,mpl_axes.Axes) }, 'volume_ex...
256
256
5,193
8
247
LeonardoHMS/imobi
venv/Lib/site-packages/mplfinance/plotting.py
Python
plot
plot
286
787
286
286
ccfbe9f68e05d4b11721a104c760520f0a89e256
bigcode/the-stack
train
d9710e2fa375da576df1c5f6
train
function
@pytest.mark.parametrize("shape",[(1,1,28,28),(5,1,28,28)]) @pytest.mark.parametrize("dtype",[float,int,bool]) def test_init_and_run(shape,dtype): score_mnist.init() x_new = np.ones(shape,dtype=dtype) # Convert the array to a serializable list in a JSON document input_json = json.dumps({"data": x_new.to...
@pytest.mark.parametrize("shape",[(1,1,28,28),(5,1,28,28)]) @pytest.mark.parametrize("dtype",[float,int,bool]) def test_init_and_run(shape,dtype):
score_mnist.init() x_new = np.ones(shape,dtype=dtype) # Convert the array to a serializable list in a JSON document input_json = json.dumps({"data": x_new.tolist()}) res = json.loads(score_mnist.run(input_json)) assert len(res) == shape[0] assert isinstance(res[0], dict) assert tuple(r...
from src.cloud import score_mnist import torch import json import numpy as np import pytest @pytest.mark.parametrize("shape",[(1,1,28,28),(5,1,28,28)]) @pytest.mark.parametrize("dtype",[float,int,bool]) def test_init_and_run(shape,dtype):
64
64
158
42
21
ChristianHinge/ml_ops_project_lectures
tests/deployment/test_score.py
Python
test_init_and_run
test_init_and_run
8
21
8
10
7d07be09f008730cfa793266bd6a091a182dd6cd
bigcode/the-stack
train
b0b8744ca129ff54733b2a60
train
class
class SqlFixture(fixtures.Fixture): # flag to indicate that the models have been loaded _TABLES_ESTABLISHED = False def setUp(self): super(SqlFixture, self).setUp() # Register all data models engine = db_api.get_engine() if not SqlFixture._TABLES_ESTABLISHED: mo...
class SqlFixture(fixtures.Fixture): # flag to indicate that the models have been loaded
_TABLES_ESTABLISHED = False def setUp(self): super(SqlFixture, self).setUp() # Register all data models engine = db_api.get_engine() if not SqlFixture._TABLES_ESTABLISHED: model_base.BASE.metadata.create_all(engine) SqlFixture._TABLES_ESTABLISHED = True ...
under the License. import fixtures from apmec.common import config from apmec.db import api as db_api from apmec.db import model_base from apmec.tests.unit import base class SqlFixture(fixtures.Fixture): # flag to indicate that the models have been loaded
64
64
134
20
43
pineunity/apmec
apmec/tests/unit/db/base.py
Python
SqlFixture
SqlFixture
24
43
24
26
d7bea70e144381b59c3499954aa76d0ace7b7d3d
bigcode/the-stack
train
6b3c776c2c7ff262386782be
train
class
class SqlTestCase(base.TestCase): def setUp(self): config.set_db_defaults() super(SqlTestCase, self).setUp() self.useFixture(SqlFixture())
class SqlTestCase(base.TestCase):
def setUp(self): config.set_db_defaults() super(SqlTestCase, self).setUp() self.useFixture(SqlFixture())
.create_all(engine) SqlFixture._TABLES_ESTABLISHED = True def clear_tables(): with engine.begin() as conn: for table in reversed( model_base.BASE.metadata.sorted_tables): conn.execute(table.delete()) self.addCleanup(cl...
64
64
38
8
56
pineunity/apmec
apmec/tests/unit/db/base.py
Python
SqlTestCase
SqlTestCase
46
51
46
47
41ab748545e8f24af1df01f8bb6ade73ffe355e2
bigcode/the-stack
train
daab0398d6f14dd2474b2db7
train
class
class HelperNode(): """ Helper for dealing with the nodes. # Methods - get_last_ledger_transaction_on_nodes - get_token_req_handler """ def __init__(self, nodes): self._nodes = nodes def get_last_ledger_transaction_on_nodes(self, ledger_id): """ Return last transaction...
class HelperNode():
""" Helper for dealing with the nodes. # Methods - get_last_ledger_transaction_on_nodes - get_token_req_handler """ def __init__(self, nodes): self._nodes = nodes def get_last_ledger_transaction_on_nodes(self, ledger_id): """ Return last transaction stored on ledger fr...
from plenum.common.constants import DOMAIN_LEDGER_ID from sovtoken.constants import TOKEN_LEDGER_ID class HelperNode():
25
64
209
4
20
dastardlychimp/token-plugin
sovtoken/sovtoken/test/helpers/helper_node.py
Python
HelperNode
HelperNode
5
33
5
5
e0309752c5b32ff865dcbb0b406aad3a75a367fd
bigcode/the-stack
train
b589a1e71b8dc90711b1432b
train
class
class IronicHostManagerChangedNodesTestCase(test.NoDBTestCase): """Test case for IronicHostManager class.""" @mock.patch.object(host_manager.HostManager, '_init_instance_info') @mock.patch.object(host_manager.HostManager, '_init_aggregates') def setUp(self, mock_init_agg, mock_init_inst): super...
class IronicHostManagerChangedNodesTestCase(test.NoDBTestCase):
"""Test case for IronicHostManager class.""" @mock.patch.object(host_manager.HostManager, '_init_instance_info') @mock.patch.object(host_manager.HostManager, '_init_aggregates') def setUp(self, mock_init_agg, mock_init_inst): super(IronicHostManagerChangedNodesTestCase, self).setUp() se...
, mock_get_all, mock_get_by_binary): mock_get_all.return_value = ironic_fakes.COMPUTE_NODES mock_get_by_binary.return_value = ironic_fakes.SERVICES context = 'fake_context' self.host_manager.get_all_host_states(context) self.assertEqual(0, mock_g...
256
256
1,553
15
241
ebalduf/nova-backports
nova/tests/unit/scheduler/test_ironic_host_manager.py
Python
IronicHostManagerChangedNodesTestCase
IronicHostManagerChangedNodesTestCase
97
248
97
97
d7720f810cdf5d08c30352755c6887e0a6e8f780
bigcode/the-stack
train
27e7be41503397a8e09a314b
train
class
class IronicHostManagerTestFilters(test.NoDBTestCase): """Test filters work for IronicHostManager.""" @mock.patch.object(host_manager.HostManager, '_init_instance_info') @mock.patch.object(host_manager.HostManager, '_init_aggregates') def setUp(self, mock_init_agg, mock_init_inst): super(Ironic...
class IronicHostManagerTestFilters(test.NoDBTestCase):
"""Test filters work for IronicHostManager.""" @mock.patch.object(host_manager.HostManager, '_init_instance_info') @mock.patch.object(host_manager.HostManager, '_init_aggregates') def setUp(self, mock_init_agg, mock_init_inst): super(IronicHostManagerTestFilters, self).setUp() self.flag...
_node) self.assertIsNone(host.updated) spec_obj = objects.RequestSpec( flavor=objects.Flavor(root_gb=20, ephemeral_gb=0, memory_mb=2048, vcpus=2)) host.consume_from_request(spec_obj) self.assertEqual(1, host.vcpus_used) self.assertE...
256
256
2,236
13
243
ebalduf/nova-backports
nova/tests/unit/scheduler/test_ironic_host_manager.py
Python
IronicHostManagerTestFilters
IronicHostManagerTestFilters
251
511
251
251
ad52b8928cd56d34d425e54bf066f5d11fcacd42
bigcode/the-stack
train
3699a954e6b7e754266d58a4
train
class
class FakeFilterClass2(filters.BaseHostFilter): def host_passes(self, host_state, filter_properties): pass
class FakeFilterClass2(filters.BaseHostFilter):
def host_passes(self, host_state, filter_properties): pass
_manager from nova import test from nova.tests.unit.scheduler import ironic_fakes from nova.tests import uuidsentinel as uuids class FakeFilterClass1(filters.BaseHostFilter): def host_passes(self, host_state, filter_properties): pass class FakeFilterClass2(filters.BaseHostFilter):
64
64
26
10
53
ebalduf/nova-backports
nova/tests/unit/scheduler/test_ironic_host_manager.py
Python
FakeFilterClass2
FakeFilterClass2
38
40
38
38
da8d869dbfa8681e60c14a32b6c83b6f1d2e0179
bigcode/the-stack
train
c22d74d2c357264feee727b7
train
class
class IronicHostManagerTestCase(test.NoDBTestCase): """Test case for IronicHostManager class.""" @mock.patch.object(host_manager.HostManager, '_init_instance_info') @mock.patch.object(host_manager.HostManager, '_init_aggregates') def setUp(self, mock_init_agg, mock_init_inst): super(IronicHostM...
class IronicHostManagerTestCase(test.NoDBTestCase):
"""Test case for IronicHostManager class.""" @mock.patch.object(host_manager.HostManager, '_init_instance_info') @mock.patch.object(host_manager.HostManager, '_init_aggregates') def setUp(self, mock_init_agg, mock_init_inst): super(IronicHostManagerTestCase, self).setUp() self.host_mana...
and limitations # under the License. """ Tests For IronicHostManager """ import mock from nova import exception from nova import objects from nova.objects import base as obj_base from nova.scheduler import filters from nova.scheduler import host_manager from nova.scheduler import ironic_host_manager from nova imp...
152
152
507
13
138
ebalduf/nova-backports
nova/tests/unit/scheduler/test_ironic_host_manager.py
Python
IronicHostManagerTestCase
IronicHostManagerTestCase
43
94
43
43
f6d7060e4042057c1406588baac72b14de44147e
bigcode/the-stack
train
d5416a47aecbbf51ac990bbf
train
class
class FakeFilterClass1(filters.BaseHostFilter): def host_passes(self, host_state, filter_properties): pass
class FakeFilterClass1(filters.BaseHostFilter):
def host_passes(self, host_state, filter_properties): pass
.objects import base as obj_base from nova.scheduler import filters from nova.scheduler import host_manager from nova.scheduler import ironic_host_manager from nova import test from nova.tests.unit.scheduler import ironic_fakes from nova.tests import uuidsentinel as uuids class FakeFilterClass1(filters.BaseHostFilter):...
64
64
26
10
53
ebalduf/nova-backports
nova/tests/unit/scheduler/test_ironic_host_manager.py
Python
FakeFilterClass1
FakeFilterClass1
33
35
33
33
97f4093a6cf7fe817a7bb057c62072fe675b0666
bigcode/the-stack
train
5d85dc2b057b29a83c5df050
train
function
def getUnvisitedNeighbors(i, j, matrix, visited): unvisitedNeighbors = [] if i > 0 and not visited[i - 1][j]: unvisitedNeighbors.append([i - 1, j]) if i < len(matrix) - 1 and not visited[i + 1][j]: unvisitedNeighbors.append([i + 1, j]) if j > 0 and not visited[i][j - 1]: unvisite...
def getUnvisitedNeighbors(i, j, matrix, visited):
unvisitedNeighbors = [] if i > 0 and not visited[i - 1][j]: unvisitedNeighbors.append([i - 1, j]) if i < len(matrix) - 1 and not visited[i + 1][j]: unvisitedNeighbors.append([i + 1, j]) if j > 0 and not visited[i][j - 1]: unvisitedNeighbors.append([i, j - 1]) if j < len(matri...
1 unvisitedNeighbors = getUnvisitedNeighbors(i, j, matrix, visited) for neighbor in unvisitedNeighbors: nodesToExplore.append(neighbor) if currentRiverSize > 0: sizes.append(currentRiverSize) def getUnvisitedNeighbors(i, j, matrix, visited):
64
64
151
13
51
rickylaufitness/minialgos
graphs/riverSizes.py
Python
getUnvisitedNeighbors
getUnvisitedNeighbors
53
64
53
53
1f4f1edd4052722c5495b96585d0cc04ddeb4276
bigcode/the-stack
train
1642c5d9e04c2e385fa97680
train
function
def riverSizes(matrix): sizes = [] visited = [[False for value in row] for row in matrix] for i in range(len(matrix)): for j in range(len(matrix[i])): if visited[i][j]: continue traverseNode(i, j, matrix, visited, sizes) return sizes
def riverSizes(matrix):
sizes = [] visited = [[False for value in row] for row in matrix] for i in range(len(matrix)): for j in range(len(matrix[i])): if visited[i][j]: continue traverseNode(i, j, matrix, visited, sizes) return sizes
1,0,1,0,0], [0,0,1,0,1], [1,0,1,0,1], [1,0,1,1,0], ] Output: [1,2,2,2,5] ''' def riverSizes(matrix):
63
64
68
5
58
rickylaufitness/minialgos
graphs/riverSizes.py
Python
riverSizes
riverSizes
21
29
21
21
56073088b7bc8ada12d344de83052c6ad0424fdf
bigcode/the-stack
train
93e71af1dc29fcf38a4661c9
train
function
def traverseNode(i, j, matrix, visited, sizes): currentRiverSize = 0 nodesToExplore = [[i, j]] while len(nodesToExplore): currentNode = nodesToExplore.pop() i = currentNode[0] j = currentNode[1] if visited[i][j]: continue visited[i][j] = True if m...
def traverseNode(i, j, matrix, visited, sizes):
currentRiverSize = 0 nodesToExplore = [[i, j]] while len(nodesToExplore): currentNode = nodesToExplore.pop() i = currentNode[0] j = currentNode[1] if visited[i][j]: continue visited[i][j] = True if matrix[i][j] == 0: continue c...
row] for row in matrix] for i in range(len(matrix)): for j in range(len(matrix[i])): if visited[i][j]: continue traverseNode(i, j, matrix, visited, sizes) return sizes def traverseNode(i, j, matrix, visited, sizes):
64
64
153
13
50
rickylaufitness/minialgos
graphs/riverSizes.py
Python
traverseNode
traverseNode
32
50
32
32
74727bba71af24979581e906678166dab4045616
bigcode/the-stack
train
ed552278bbba7aa002455cad
train
class
class configuration(object): def __init__(self): self.TESTRUN = False self.NFORMANTS = 6 self.NZEROS = 1 self.DIFFWEIGHT = 0.15 self.SAMPLERATE = 16000.0 self.MAX_ANALYSIS_FREQ = self.SAMPLERATE / 2.0 self.MAXFREQ = 8000.0 self.MINFREQ = 0.0 ...
class configuration(object):
def __init__(self): self.TESTRUN = False self.NFORMANTS = 6 self.NZEROS = 1 self.DIFFWEIGHT = 0.15 self.SAMPLERATE = 16000.0 self.MAX_ANALYSIS_FREQ = self.SAMPLERATE / 2.0 self.MAXFREQ = 8000.0 self.MINFREQ = 0.0 self.MAXBW = 5000.0 s...
#!/usr/bin/env python # coding: utf-8 # # FormantNet Configuration Code # This code is used to parse the configuration file, if one exists, and save the global variables used by FormantNet into one object, referred to as **cfg** in the other scripts and passed around from function to function. # In[ ]: import conf...
81
256
2,404
4
76
NemoursResearch/FormantTracking
User/FN_configuration.py
Python
configuration
configuration
13
177
13
14
17654dcc30ab02ff6bb7875fc59637a2655ffb03
bigcode/the-stack
train
e519242b431acba2269c0f3b
train
class
class DeconzTampering(DeconzDevice, BinarySensorEntity): """Representation of a deCONZ tampering sensor.""" TYPE = DOMAIN @property def unique_id(self) -> str: """Return a unique identifier for this device.""" return f"{self.serial}-tampered" @callback def async_update_callbac...
class DeconzTampering(DeconzDevice, BinarySensorEntity):
"""Representation of a deCONZ tampering sensor.""" TYPE = DOMAIN @property def unique_id(self) -> str: """Return a unique identifier for this device.""" return f"{self.serial}-tampered" @callback def async_update_callback(self, force_update: bool = False) -> None: """U...
[ATTR_ORIENTATION] = self._device.orientation attr[ATTR_TILTANGLE] = self._device.tiltangle attr[ATTR_VIBRATIONSTRENGTH] = self._device.vibrationstrength return attr class DeconzTampering(DeconzDevice, BinarySensorEntity):
67
67
224
16
50
mikan-megane/core
homeassistant/components/deconz/binary_sensor.py
Python
DeconzTampering
DeconzTampering
125
155
125
125
a2008a80caa10bf5711a49a81bdac84a85495eec
bigcode/the-stack
train
fa4cbf76bfd4dcea36e23652
train
function
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the deCONZ binary sensor.""" gateway = get_gateway_from_config_entry(hass, config_entry) gateway.entities[DOMAIN] = set() @callback def async_add_sensor(sensors=gateway.api.sensors.values()): """Add binary sensor...
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the deCONZ binary sensor.""" gateway = get_gateway_from_config_entry(hass, config_entry) gateway.entities[DOMAIN] = set() @callback def async_add_sensor(sensors=gateway.api.sensors.values()): """Add binary sensor from deCONZ.""" entities = [] for sensor in sensors...
STRENGTH = "vibrationstrength" DEVICE_CLASS = { CarbonMonoxide: DEVICE_CLASS_GAS, Fire: DEVICE_CLASS_SMOKE, OpenClose: DEVICE_CLASS_OPENING, Presence: DEVICE_CLASS_MOTION, Vibration: DEVICE_CLASS_VIBRATION, Water: DEVICE_CLASS_MOISTURE, } async def async_setup_entry(hass, config_entry, async_ad...
85
85
285
15
70
mikan-megane/core
homeassistant/components/deconz/binary_sensor.py
Python
async_setup_entry
async_setup_entry
37
76
37
37
2382d85629e8d0bb7bf4357deb1d7b6a88d425eb
bigcode/the-stack
train
be7382eaf33790da978b0b08
train
class
class DeconzBinarySensor(DeconzDevice, BinarySensorEntity): """Representation of a deCONZ binary sensor.""" TYPE = DOMAIN @callback def async_update_callback(self, force_update=False): """Update the sensor's state.""" keys = {"on", "reachable", "state"} if force_update or self....
class DeconzBinarySensor(DeconzDevice, BinarySensorEntity):
"""Representation of a deCONZ binary sensor.""" TYPE = DOMAIN @callback def async_update_callback(self, force_update=False): """Update the sensor's state.""" keys = {"on", "reachable", "state"} if force_update or self._device.changed_keys.intersection(keys): super()...
.append(new_tampering_sensor) if entities: async_add_entities(entities) config_entry.async_on_unload( async_dispatcher_connect( hass, gateway.async_signal_new_device(NEW_SENSOR), async_add_sensor ) ) async_add_sensor( [gateway.api.sensors[key] for k...
96
96
322
16
80
mikan-megane/core
homeassistant/components/deconz/binary_sensor.py
Python
DeconzBinarySensor
DeconzBinarySensor
79
122
79
79
b58b2edb7002cbb612930ea32471313891bf6cc3
bigcode/the-stack
train
757952dadb93a3ba5079bc65
train
class
class S3LogAccumulator(object): """Aggregates total downloaded bytes per file from S3 logs. Helps us track which binaries our S3 bandwidth costs are being spent on. To run, first download S3 access logs. For example, to download all logs for 4/2018, you can use something like: aws s3 sync s3://logs.pantsbu...
class S3LogAccumulator(object):
"""Aggregates total downloaded bytes per file from S3 logs. Helps us track which binaries our S3 bandwidth costs are being spent on. To run, first download S3 access logs. For example, to download all logs for 4/2018, you can use something like: aws s3 sync s3://logs.pantsbuild.org/binaries/ /tmp/s3logs --...
# coding=utf-8 # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os import sys from builtins import object, open from collections import defaultdic...
181
191
638
7
173
StephanErb/pants
src/python/pants/util/s3_log_aggregator.py
Python
S3LogAccumulator
S3LogAccumulator
29
97
29
29
33955698df8dd71ae9e1c059751a7b0cee36bb87
bigcode/the-stack
train
5640ef68dd06b4f5344d6a2f
train
class
class Measure(object): def __init__(self, init_count=0, init_bytes=0): self.count = init_count self.bytes = init_bytes def __add__(self, other): return self.__class__(self.count + other.count, self.bytes + other.bytes) def __iadd__(self, other): self.count += other.count self.bytes += other....
class Measure(object):
def __init__(self, init_count=0, init_bytes=0): self.count = init_count self.bytes = init_bytes def __add__(self, other): return self.__class__(self.count + other.count, self.bytes + other.bytes) def __iadd__(self, other): self.count += other.count self.bytes += other.bytes return self
License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os import sys from builtins import object, open from collections import defaultdict from s3logparse.s3logparse import parse_log_lines class Measure(object):
64
64
90
4
59
StephanErb/pants
src/python/pants/util/s3_log_aggregator.py
Python
Measure
Measure
15
26
15
15
e01bbb5dc98f4c1488b9189e2cf9971c6ee67238
bigcode/the-stack
train
a4f6de94725bbbf9c471d73e
train
function
@pytest.fixture() def measurement_model(): return LinearGaussian(ndim_state=4, mapping=[0, 2], noise_covar=CovarianceMatrix(np.diag([1, 1])))
@pytest.fixture() def measurement_model():
return LinearGaussian(ndim_state=4, mapping=[0, 2], noise_covar=CovarianceMatrix(np.diag([1, 1])))
.measurement.linear import LinearGaussian from ...types.array import CovarianceMatrix from ...models.transition.linear import ConstantVelocity, CombinedLinearGaussianTransitionModel from ...predictor.kalman import KalmanPredictor from ...updater.kalman import ExtendedKalmanUpdater @pytest.fixture() def measurement_mode...
64
64
41
7
56
Red-Portal/Stone-Soup-1
stonesoup/dataassociator/tests/conftest.py
Python
measurement_model
measurement_model
15
18
15
16
4a9e860672fd0d56fdba00f564c1eb8ac5a136c3
bigcode/the-stack
train
568af34153c888b8d58de15e
train
function
@pytest.fixture() def updater(measurement_model): return ExtendedKalmanUpdater(measurement_model)
@pytest.fixture() def updater(measurement_model):
return ExtendedKalmanUpdater(measurement_model)
noise_covar=CovarianceMatrix(np.diag([1, 1]))) @pytest.fixture() def predictor(): transition_model = CombinedLinearGaussianTransitionModel([ConstantVelocity(1), ConstantVelocity(1)]) return KalmanPredictor(transition_model) @pytest.fixture() def u...
64
64
21
10
54
Red-Portal/Stone-Soup-1
stonesoup/dataassociator/tests/conftest.py
Python
updater
updater
28
30
28
29
544130bc3ae2d7cb24aa0da967852f70d6322d06
bigcode/the-stack
train
5852cda56c82d0458e88faf7
train
function
@pytest.fixture() def distance_hypothesiser(predictor, updater): return DistanceHypothesiser(predictor, updater, Mahalanobis(), 10)
@pytest.fixture() def distance_hypothesiser(predictor, updater):
return DistanceHypothesiser(predictor, updater, Mahalanobis(), 10)
ypothesiser(predictor, updater): return PDAHypothesiser(predictor, updater, clutter_spatial_density=1.2e-2, prob_detect=0.9, prob_gate=0.99) @pytest.fixture() def distance_hypothesiser(predictor, updater):
64
64
34
15
49
Red-Portal/Stone-Soup-1
stonesoup/dataassociator/tests/conftest.py
Python
distance_hypothesiser
distance_hypothesiser
40
42
40
41
a8f11d3cbb7449b9203ee9cd0cd31a15504bac51
bigcode/the-stack
train
bbfee32d3a7d93b5b95b6fa6
train
function
@pytest.fixture() def probability_hypothesiser(predictor, updater): return PDAHypothesiser(predictor, updater, clutter_spatial_density=1.2e-2, prob_detect=0.9, prob_gate=0.99)
@pytest.fixture() def probability_hypothesiser(predictor, updater):
return PDAHypothesiser(predictor, updater, clutter_spatial_density=1.2e-2, prob_detect=0.9, prob_gate=0.99)
= CombinedLinearGaussianTransitionModel([ConstantVelocity(1), ConstantVelocity(1)]) return KalmanPredictor(transition_model) @pytest.fixture() def updater(measurement_model): return ExtendedKalmanUpdater(measurement_model) @pytest.fixture() def pr...
64
64
55
15
49
Red-Portal/Stone-Soup-1
stonesoup/dataassociator/tests/conftest.py
Python
probability_hypothesiser
probability_hypothesiser
33
37
33
34
7e9deb40342caf5a420c73234c67efebcabc8c4b
bigcode/the-stack
train
33726daea774f3aa4513819f
train
function
@pytest.fixture() def predictor(): transition_model = CombinedLinearGaussianTransitionModel([ConstantVelocity(1), ConstantVelocity(1)]) return KalmanPredictor(transition_model)
@pytest.fixture() def predictor():
transition_model = CombinedLinearGaussianTransitionModel([ConstantVelocity(1), ConstantVelocity(1)]) return KalmanPredictor(transition_model)
Predictor from ...updater.kalman import ExtendedKalmanUpdater @pytest.fixture() def measurement_model(): return LinearGaussian(ndim_state=4, mapping=[0, 2], noise_covar=CovarianceMatrix(np.diag([1, 1]))) @pytest.fixture() def predictor():
63
64
37
6
57
Red-Portal/Stone-Soup-1
stonesoup/dataassociator/tests/conftest.py
Python
predictor
predictor
21
25
21
22
9b185df3ed8328caf130df434b940018de4c6036
bigcode/the-stack
train
d44bb9fd4a8d6f235b559dc4
train
function
def plotly_page(*args, **kwargs) -> pn.Column: fig = plotly_fig() return pn.Column(pn.pane.Markdown("# Plotly"), fig, name="Plotly", sizing_mode="stretch_both",)
def plotly_page(*args, **kwargs) -> pn.Column:
fig = plotly_fig() return pn.Column(pn.pane.Markdown("# Plotly"), fig, name="Plotly", sizing_mode="stretch_both",)
)) fig.layout.paper_bgcolor = "rgba(0,0,0,0)" fig.layout.plot_bgcolor = "rgba(0,0,0,0)" fig.layout.width = 1000 return fig def plotly_page(*args, **kwargs) -> pn.Column:
64
64
50
14
49
philippjfr/awesome-panel
scripts/issues/issue840_plotly_does_not_show.py
Python
plotly_page
plotly_page
69
71
69
69
a0952966794436f08564d9761320876acc0d73d4
bigcode/the-stack
train
18b270f63fabeb5009461413
train
function
def plotly_fig(): fig = px.line(get_chart_data(), x="Day", y="Orders") fig.update_traces(mode="lines+markers", marker=dict(size=10), line=dict(width=4)) fig.layout.paper_bgcolor = "rgba(0,0,0,0)" fig.layout.plot_bgcolor = "rgba(0,0,0,0)" fig.layout.width = 1000 return fig
def plotly_fig():
fig = px.line(get_chart_data(), x="Day", y="Orders") fig.update_traces(mode="lines+markers", marker=dict(size=10), line=dict(width=4)) fig.layout.paper_bgcolor = "rgba(0,0,0,0)" fig.layout.plot_bgcolor = "rgba(0,0,0,0)" fig.layout.width = 1000 return fig
return fig def holoviews_page() -> pn.Column: fig = holoviews_fig() return pn.Column( pn.pane.Markdown("# Holoviews"), fig, name="Holoviews", sizing_mode="stretch_both", ) def plotly_fig():
64
64
94
5
59
philippjfr/awesome-panel
scripts/issues/issue840_plotly_does_not_show.py
Python
plotly_fig
plotly_fig
60
66
60
60
a60b9a22391a35583eaa3ec8ece9011425ad5119
bigcode/the-stack
train
6cf1d08cf2de43c736e2e983
train
function
def holoviews_page() -> pn.Column: fig = holoviews_fig() return pn.Column( pn.pane.Markdown("# Holoviews"), fig, name="Holoviews", sizing_mode="stretch_both", )
def holoviews_page() -> pn.Column:
fig = holoviews_fig() return pn.Column( pn.pane.Markdown("# Holoviews"), fig, name="Holoviews", sizing_mode="stretch_both", )
responsive=True, toolbar=None, yticks=list(range(12000, 26000, 2000)), ylim=(12000, 26000), gridstyle=gridstyle, show_grid=True, ) return fig def holoviews_page() -> pn.Column:
64
64
55
11
52
philippjfr/awesome-panel
scripts/issues/issue840_plotly_does_not_show.py
Python
holoviews_page
holoviews_page
53
57
53
53
c25b9a29c982ea4080c0448a4844a21f8964f8f7
bigcode/the-stack
train
1f9f770979a04a5be6d1a840
train
function
def get_chart_data(): chart_data = { "Day": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",], "Orders": [15539, 21345, 18483, 24003, 23489, 24092, 12034], } return pd.DataFrame(chart_data)
def get_chart_data():
chart_data = { "Day": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",], "Orders": [15539, 21345, 18483, 24003, 23489, 24092, 12034], } return pd.DataFrame(chart_data)
/panel/issues/840 def navigation_button(page, page_outlet): button = pn.widgets.Button(name=page.name) def navigate_to_page(event): page_outlet.clear() page_outlet.append(page) button.on_click(navigate_to_page) return button def get_chart_data():
64
64
78
5
58
philippjfr/awesome-panel
scripts/issues/issue840_plotly_does_not_show.py
Python
get_chart_data
get_chart_data
23
28
23
23
b49447b8f41a05e2a52531650049debcda05c216
bigcode/the-stack
train
05566a6470cac57533513a0e
train
function
def holoviews_fig(): data = get_chart_data() line_plot = data.hvplot.line( x="Day", y="Orders", width=None, line_color="#007BFF", line_width=6, ) scatter_plot = data.hvplot.scatter(x="Day", y="Orders", width=None).opts( marker="o", size=10, color="#007BFF" ) fig = line_plot * sca...
def holoviews_fig():
data = get_chart_data() line_plot = data.hvplot.line( x="Day", y="Orders", width=None, line_color="#007BFF", line_width=6, ) scatter_plot = data.hvplot.scatter(x="Day", y="Orders", width=None).opts( marker="o", size=10, color="#007BFF" ) fig = line_plot * scatter_plot gridsty...
Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",], "Orders": [15539, 21345, 18483, 24003, 23489, 24092, 12034], } return pd.DataFrame(chart_data) def holoviews_fig():
64
64
186
7
57
philippjfr/awesome-panel
scripts/issues/issue840_plotly_does_not_show.py
Python
holoviews_fig
holoviews_fig
31
50
31
31
176249c4a696e380c088392c3672c9a210f402d2
bigcode/the-stack
train