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
92924657359d89605b25a7e4
train
class
class MySQLBrowserResource(_DAVResource): """Represents a single existing DAV resource instance. See also DAVResource and MySQLBrowserProvider. """ def __init__(self, provider, path, is_collection, environ): super(MySQLBrowserResource, self).__init__(path, is_collection, environ) self....
class MySQLBrowserResource(_DAVResource):
"""Represents a single existing DAV resource instance. See also DAVResource and MySQLBrowserProvider. """ def __init__(self, provider, path, is_collection, environ): super(MySQLBrowserResource, self).__init__(path, is_collection, environ) self._cache = None def _init(self): ...
. The code uses a numeric or string comparison that may not hold up if the primary key is a date or some other datatype. - There is no handling for cases like BLOBs as primary keys or such. Well, there is no handling for BLOBs in general. - When returning contents, it buffers the entire cont...
256
256
1,696
9
247
Scottpedia/seafdav
wsgidav/samples/mysql_dav_provider.py
Python
MySQLBrowserResource
MySQLBrowserResource
80
302
80
80
26e70920f9ab211845483b46aba156b43468a860
bigcode/the-stack
train
a4ee810797f84cc60641c59d
train
function
def ccsd(ham,ampfile="none"): if (ham.hamtype != 'Hubbard'): print("This routine should only be used for Hubbard in the spin-orbital basis.") if (ham.wfn_type == 'uhf'): print("converting One-electron Integrals to spin-orbital basis") #We build the 2-e integrals on the fly, #so will only build the spin-or...
def ccsd(ham,ampfile="none"):
if (ham.hamtype != 'Hubbard'): print("This routine should only be used for Hubbard in the spin-orbital basis.") if (ham.wfn_type == 'uhf'): print("converting One-electron Integrals to spin-orbital basis") #We build the 2-e integrals on the fly, #so will only build the spin-orbital Fock matrix and MO coeff...
#Module cGSSD implements complex generalized CCSD for the Hubbard Hamiltonian in N^5 scaling #by exploiting the sparsity of the two-electron integrals for Hubbard. Derivation and factorization #of the spin-orbital CCSD equations were worked out by Tom Henderson. import numpy as np #import cCCutils import CCDutils impo...
108
256
5,667
12
95
jag20/HubCCD
cGCCSD.py
Python
ccsd
ccsd
13
298
13
13
a5946565c6f28856eb6f418870920e402d78cbeb
bigcode/the-stack
train
d63eccd83aaf00a52a885319
train
class
class Cmd(Base, CmdImp): """ Base emulator class """ def __init__(self, logger=None, **kwargs): """ Args: logger (logging, default None): Custom logger. New logger will be created when None. Keyword args: __emulator_replace_keys__ (dict): Keys with data ...
class Cmd(Base, CmdImp):
""" Base emulator class """ def __init__(self, logger=None, **kwargs): """ Args: logger (logging, default None): Custom logger. New logger will be created when None. Keyword args: __emulator_replace_keys__ (dict): Keys with data to replace in Emulator te...
# All rights reserved by forest fairy. # You cannot modify or share anything without sacrifice. # If you don't agree, keep calm and don't look at code bellow! __author__ = "VirtualV <https://github.com/virtualvfix>" __date__ = "03/18/18 15:00" import re import types from string import Template from ..base.base import...
224
256
981
7
216
VirtualVFix/AndroidTestFramework
src/libs/cmd/implement/emulator/cmd.py
Python
Cmd
Cmd
40
160
40
40
7c92fd5589da496188180c0bcaa4e55cdcff7729
bigcode/the-stack
train
1449fd47afcfb44730f66fc8
train
class
class Command: """ Emulate command output """ def __init__(self, logger=None, **kwargs): self._command = None self._code = None self._error = None self._output = '' @property def lastcommand(self): return self._command @property def returncode(self): ...
class Command:
""" Emulate command output """ def __init__(self, logger=None, **kwargs): self._command = None self._code = None self._error = None self._output = '' @property def lastcommand(self): return self._command @property def returncode(self): return sel...
/virtualvfix>" __date__ = "03/18/18 15:00" import re import types from string import Template from ..base.base import Base from libs.cmd.interface.cmd import Cmd as CmdImp from libs.core.logger import getLogger, getSysLogger class Command:
64
64
110
3
60
VirtualVFix/AndroidTestFramework
src/libs/cmd/implement/emulator/cmd.py
Python
Command
Command
16
37
16
16
c7cd061660c691d3df8f50d3d430f87fd526e271
bigcode/the-stack
train
15e57b85a948eb171e66bf33
train
class
class ComputeStat: """Maintain statistics on measurement data.""" def __init__(self, quiet): self.referenced = set() self.already_warned = set() self.errcount = 0 self.errors = set() self.prev_errors = set() self.mismeasured = set() self.prev_mismeasured =...
class ComputeStat:
"""Maintain statistics on measurement data.""" def __init__(self, quiet): self.referenced = set() self.already_warned = set() self.errcount = 0 self.errors = set() self.prev_errors = set() self.mismeasured = set() self.prev_mismeasured = set() self...
lex']) def geoadd(l): return math.sqrt(sum([x**2 for x in l])) # DEPRECATED # use geomean of stddevs and minimum of multiplex ratios for combining # XXX better way to combine multiplex ratios? def deprecated_combine_valstat(l): if not l: return [] return ValStat(geoadd([x.stddev for x in l]), min(...
109
109
366
4
104
patinnc/60secs
pmu-tools-master/tl_stat.py
Python
ComputeStat
ComputeStat
35
71
35
35
c35dd2a3d0de1c4572813435a3c945e55cea2d9b
bigcode/the-stack
train
bc5eafeba6bcf28ebdb6b7c9
train
function
def isnan(x): return x != x
def isnan(x):
return x != x
minimum of multiplex ratios for combining # XXX better way to combine multiplex ratios? def deprecated_combine_valstat(l): if not l: return [] return ValStat(geoadd([x.stddev for x in l]), min([x.multiplex for x in l])) def isnan(x):
64
64
11
5
59
patinnc/60secs
pmu-tools-master/tl_stat.py
Python
isnan
isnan
32
33
32
32
75cf43400d90622e6a47dcceaf976fb8346e815a
bigcode/the-stack
train
56a69a3d081c3d51b9e94be7
train
function
def geoadd(l): return math.sqrt(sum([x**2 for x in l]))
def geoadd(l):
return math.sqrt(sum([x**2 for x in l]))
See the GNU General Public License for # more details. # # Maintain error data on perf measurements from __future__ import print_function import sys import math from collections import namedtuple ValStat = namedtuple('ValStat', ['stddev', 'multiplex']) def geoadd(l):
64
64
19
5
59
patinnc/60secs
pmu-tools-master/tl_stat.py
Python
geoadd
geoadd
21
22
21
21
84a5bc252eb000fd3400ee3a562c73b3f6596b76
bigcode/the-stack
train
8dac43a8dee4bf3177b0337d
train
function
def deprecated_combine_valstat(l): if not l: return [] return ValStat(geoadd([x.stddev for x in l]), min([x.multiplex for x in l]))
def deprecated_combine_valstat(l):
if not l: return [] return ValStat(geoadd([x.stddev for x in l]), min([x.multiplex for x in l]))
stddev', 'multiplex']) def geoadd(l): return math.sqrt(sum([x**2 for x in l])) # DEPRECATED # use geomean of stddevs and minimum of multiplex ratios for combining # XXX better way to combine multiplex ratios? def deprecated_combine_valstat(l):
64
64
43
8
56
patinnc/60secs
pmu-tools-master/tl_stat.py
Python
deprecated_combine_valstat
deprecated_combine_valstat
27
30
27
27
cb67f14d52af8cea2205de51e1876db8f9035ef3
bigcode/the-stack
train
1bdd4be8211d396662650649
train
function
def downgrade(migrate_engine): meta.bind = migrate_engine t = Table("demographics_request_data_response", meta, autoload=True) t.c.sex.drop()
def downgrade(migrate_engine):
meta.bind = migrate_engine t = Table("demographics_request_data_response", meta, autoload=True) t.c.sex.drop()
, NVARCHAR, ) meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine t = Table("demographics_request_data_response", meta, autoload=True) sex = Column("sex", NVARCHAR(10)) sex.create(t) def downgrade(migrate_engine):
64
64
36
6
58
LCBRU/identity
migrations/versions/029_DemographicsRequestDataResponse_Add_Sex.py
Python
downgrade
downgrade
20
23
20
20
3bb3fce1ee0014807c79c407a75c9c6c2f8d78cb
bigcode/the-stack
train
c56ce532c791eaf5fff7f1ac
train
function
def upgrade(migrate_engine): meta.bind = migrate_engine t = Table("demographics_request_data_response", meta, autoload=True) sex = Column("sex", NVARCHAR(10)) sex.create(t)
def upgrade(migrate_engine):
meta.bind = migrate_engine t = Table("demographics_request_data_response", meta, autoload=True) sex = Column("sex", NVARCHAR(10)) sex.create(t)
from sqlalchemy import ( MetaData, Table, Column, NVARCHAR, ) meta = MetaData() def upgrade(migrate_engine):
30
64
47
6
24
LCBRU/identity
migrations/versions/029_DemographicsRequestDataResponse_Add_Sex.py
Python
upgrade
upgrade
11
17
11
11
ad431addd4f61912c347e7d94d87b2515fa09ec3
bigcode/the-stack
train
88ec3b3081a64ba573f5535c
train
class
class TestFlexbox_FlowColumnWrap(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'flexbox_flow-column-wrap'))
class TestFlexbox_FlowColumnWrap(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'flexbox_flow-column-wrap'))
from tests.utils import W3CTestCase class TestFlexbox_FlowColumnWrap(W3CTestCase):
22
64
33
13
8
jonboland/colosseum
tests/web_platform/css_flexbox_1/test_flexbox_flow_column_wrap.py
Python
TestFlexbox_FlowColumnWrap
TestFlexbox_FlowColumnWrap
4
5
4
4
e240128a2488fe68ac1bb62190c6c539a12f93e7
bigcode/the-stack
train
e10418af032a64f0c410c903
train
function
def main(): args = parse_args() ck = torch.load(args.checkpoint, map_location=torch.device('cpu')) output_dict = dict(state_dict=dict(), author='OpenSelfSup') for key, value in ck.items(): if key.startswith('head'): continue else: output_dict['state_dict'][key] = ...
def main():
args = parse_args() ck = torch.load(args.checkpoint, map_location=torch.device('cpu')) output_dict = dict(state_dict=dict(), author='OpenSelfSup') for key, value in ck.items(): if key.startswith('head'): continue else: output_dict['state_dict'][key] = value to...
torch import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( '--save-path', type=str, required=True, help='destination file name') args = parser.parse_args() return args def main():
64
64
84
3
60
youqingxiaozhua/OpenSelfSup
tools/upgrade_models.py
Python
main
main
14
23
14
14
5dd5b37f7703872a59d6333f516bc2303c96ece5
bigcode/the-stack
train
6c5364378830421bd31b5ca4
train
function
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( '--save-path', type=str, required=True, help='destination file name') args = parser.parse_args() return args
def parse_args():
parser = argparse.ArgumentParser() parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( '--save-path', type=str, required=True, help='destination file name') args = parser.parse_args() return args
import torch import argparse def parse_args():
10
64
56
4
5
youqingxiaozhua/OpenSelfSup
tools/upgrade_models.py
Python
parse_args
parse_args
5
11
5
5
d2208194793d0311424e2cc714f9e4ab1d7ac8f0
bigcode/the-stack
train
058baddd8b1996e64141972c
train
class
class S_BERT_Regression(pl.LightningModule): def __init__(self, hparams): super(S_BERT_Regression, self).__init__() # not the best model... self.hparams = hparams self.l1 = torch.nn.Linear(768, 256) self.l2 = torch.nn.Linear(256, 1) def forward(self, x): f1 = to...
class S_BERT_Regression(pl.LightningModule):
def __init__(self, hparams): super(S_BERT_Regression, self).__init__() # not the best model... self.hparams = hparams self.l1 = torch.nn.Linear(768, 256) self.l2 = torch.nn.Linear(256, 1) def forward(self, x): f1 = torch.relu(self.l1(x.view(x.size(0), -1))) ...
import os import torch, numpy as np, pandas as pd from torch.nn import functional as F from torch.utils.data import DataLoader, Dataset from argparse import ArgumentParser import h5py from transformers import ( PreTrainedModel, PreTrainedTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer...
96
202
675
11
84
lunayach/funnyAgain
baselines/s_bert_only_train/s_bert.py
Python
S_BERT_Regression
S_BERT_Regression
17
98
17
18
95aa4ae4c5522c3c80cd209ebaa09cbc383cee00
bigcode/the-stack
train
3057df9d15329e6ca547d41a
train
class
class S_bert_not_finetuend_Data(Dataset): def __init__(self, train=True): super(S_bert_not_finetuend_Data, self).__init__() self.train = train self.split = 'train' if self.train: data_file = '../../data/s_bert_not_finetuned_TRAIN.hdf5' else: data_fil...
class S_bert_not_finetuend_Data(Dataset):
def __init__(self, train=True): super(S_bert_not_finetuend_Data, self).__init__() self.train = train self.split = 'train' if self.train: data_file = '../../data/s_bert_not_finetuned_TRAIN.hdf5' else: data_file = '../../data/s_bert_not_finetuned_DEV.hd...
=0.02, type=float) parser.add_argument('--batch_size', default=32, type=int) # training specific (for this model) parser.add_argument('--max_nb_epochs', default=2, type=int) return parser class S_bert_not_finetuend_Data(Dataset):
65
65
219
13
51
lunayach/funnyAgain
baselines/s_bert_only_train/s_bert.py
Python
S_bert_not_finetuend_Data
S_bert_not_finetuend_Data
101
130
101
102
a956dd0c755ee5ef2826c9bcc4739e7e4fe1007f
bigcode/the-stack
train
9b9fd63a8936fecc6af9dcec
train
function
def format_stack_frame(stack_frame, project: 'projects.Project') -> dict: """ Formats a raw stack frame into a dictionary formatted for render templating and enriched with information from the currently open project. :param stack_frame: A raw stack frame to turn into an enriched version for te...
def format_stack_frame(stack_frame, project: 'projects.Project') -> dict:
""" Formats a raw stack frame into a dictionary formatted for render templating and enriched with information from the currently open project. :param stack_frame: A raw stack frame to turn into an enriched version for templating. :param project: The currently open project, which is...
if test_filename.startswith(resources_path): return False return True while len(frames) > 1 and is_cauldron_code(frames[0].filename): frames.pop(0) return frames def format_stack_frame(stack_frame, project: 'projects.Project') -> dict:
64
64
187
16
47
DanMayhew/cauldron
cauldron/render/stack.py
Python
format_stack_frame
format_stack_frame
37
64
37
37
428677af30f343d93b5c0f36af7075940de155a5
bigcode/the-stack
train
058985bb2cb5f13259b764a1
train
function
def get_stack_frames(error_stack: bool = True) -> list: """ Returns a list of the current stack frames, which are pruned focus on the Cauldron code where the relevant information resides. """ cauldron_path = environ.paths.package() resources_path = environ.paths.resources() frames = ( ...
def get_stack_frames(error_stack: bool = True) -> list:
""" Returns a list of the current stack frames, which are pruned focus on the Cauldron code where the relevant information resides. """ cauldron_path = environ.paths.package() resources_path = environ.paths.resources() frames = ( list(traceback.extract_tb(sys.exc_info()[-1])) ...
import sys import traceback from cauldron import environ from cauldron.session import projects def get_stack_frames(error_stack: bool = True) -> list:
35
64
180
14
20
DanMayhew/cauldron
cauldron/render/stack.py
Python
get_stack_frames
get_stack_frames
8
34
8
8
3ce3d186473de79ae12cdd7251a9bb6959bc0032
bigcode/the-stack
train
54589559ec3bb125362aada4
train
function
def get_formatted_stack_frame( project: 'projects.Project', error_stack: bool = True ) -> list: """ Returns a list of the stack frames formatted for user display that has been enriched by the project-specific data. :param project: The currently open project used to enrich t...
def get_formatted_stack_frame( project: 'projects.Project', error_stack: bool = True ) -> list:
""" Returns a list of the stack frames formatted for user display that has been enriched by the project-specific data. :param project: The currently open project used to enrich the stack data. :param error_stack: Whether or not to return the error stack. When True the stack of ...
': location = None return dict( filename=filename, location=location, line_number=stack_frame.lineno, line=stack_frame.line ) def get_formatted_stack_frame( project: 'projects.Project', error_stack: bool = True ) -> list:
64
64
157
26
38
DanMayhew/cauldron
cauldron/render/stack.py
Python
get_formatted_stack_frame
get_formatted_stack_frame
67
87
67
70
d31eecb0d408ba09ac1d9c7ca5c4b715996b8cb9
bigcode/the-stack
train
6c8712ae468b2d36398db481
train
function
def create(kernel): result = Static() result.template = "object/static/structure/naboo/shared_nboo_imprv_pristine_wall_sml_s03.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
def create(kernel):
result = Static() result.template = "object/static/structure/naboo/shared_nboo_imprv_pristine_wall_sml_s03.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel):
46
64
75
4
42
obi-two/GameServer
data/scripts/templates/object/static/structure/naboo/shared_nboo_imprv_pristine_wall_sml_s03.py
Python
create
create
7
17
7
7
87dd392813210f3117bef3fd5f0fb3d544581933
bigcode/the-stack
train
54c9e6011cea8048300141cc
train
function
def check(count, input): for checksum in itertools.combinations(input, count): checksum_sum = sum(checksum) if checksum_sum == 2020: total = 1 for i in checksum: total = total * i return total
def check(count, input):
for checksum in itertools.combinations(input, count): checksum_sum = sum(checksum) if checksum_sum == 2020: total = 1 for i in checksum: total = total * i return total
import itertools def check(count, input):
9
64
57
6
2
icecreampuppy44/advent2020
shart/python/libs/checksum/checksum.py
Python
check
check
3
10
3
3
4c83fe54b48dac4bb062816c100eed875ad934ef
bigcode/the-stack
train
71f8024e8e2d90200d8f257d
train
class
class Conv2d(nn.Conv2d): r""" A Conv2d module attached with FakeQuantize modules for weight, used for quantization aware training. We adopt the same interface as `torch.nn.Conv2d`, please see https://pytorch.org/docs/stable/nn.html?highlight=conv2d#torch.nn.Conv2d for documentation. Simila...
class Conv2d(nn.Conv2d):
r""" A Conv2d module attached with FakeQuantize modules for weight, used for quantization aware training. We adopt the same interface as `torch.nn.Conv2d`, please see https://pytorch.org/docs/stable/nn.html?highlight=conv2d#torch.nn.Conv2d for documentation. Similar to `torch.nn.Conv2d`, w...
from __future__ import absolute_import, division, print_function, unicode_literals import torch.nn as nn from torch.nn.intrinsic import ConvReLU2d class Conv2d(nn.Conv2d):
44
157
525
9
34
AndreasKaratzas/stonne
pytorch-frontend/torch/nn/qat/modules/conv.py
Python
Conv2d
Conv2d
5
56
5
5
876a82ac8b794302a09e209c687b09b497294cf2
bigcode/the-stack
train
d44b095c45c8e46fdc612d0f
train
class
class Test_Main(unittest.TestCase): def test_mains(self): fileName = "Tabular Atmosphere.xlsx" print ( "===================Tabular Atmosphere start======================" ) fileName = os.path.dirname(__file__) + os.path.sep + fileName print ( fileName ) w...
class Test_Main(unittest.TestCase):
def test_mains(self): fileName = "Tabular Atmosphere.xlsx" print ( "===================Tabular Atmosphere start======================" ) fileName = os.path.dirname(__file__) + os.path.sep + fileName print ( fileName ) workbook = xlsxwriter.Workbook(fileNam...
3 * cas * cas) / ( 2 * pressureMSLpascals) tas = math.pow(tas , 1.0 / mu) - 1.0 tas = 1 + (pressureMSLpascals / pressurePascals) * (tas) tas = math.pow(tas, mu) - 1.0 tas = ( 2 * pressurePascals)/ (mu * densityKgm3) * tas tas = math.pow(tas , 0.5) return tas cl...
125
126
422
7
117
RobertPastor/flight-profile
trajectory/Environment/Atmosphere.py
Python
Test_Main
Test_Main
348
401
348
349
89419d5b9708d403b5a2464cb4542c30e1f1a5c3
bigcode/the-stack
train
11025f9ae65954ef9c35f8f4
train
class
class Atmosphere(): ''' The standard sea level conditions are as follows: Temperature (T0) = 288.15 K = 150C Pressure (p0) = 101325 N/m2 = 760 mm of Hg ''' SeaLevelTemperatureDegrees = 15.0 SeaLevelPressureNewtonsSquareMeters = 101325.0 ''' MSL Mean Sea Level ''' StandardAtmo...
class Atmosphere():
''' The standard sea level conditions are as follows: Temperature (T0) = 288.15 K = 150C Pressure (p0) = 101325 N/m2 = 760 mm of Hg ''' SeaLevelTemperatureDegrees = 15.0 SeaLevelPressureNewtonsSquareMeters = 101325.0 ''' MSL Mean Sea Level ''' StandardAtmosphericTemperatureMs...
< robert [--DOT--] pastor0691 (--AT--) orange [--DOT--] fr > @http://trajectoire-predict.monsite-orange.fr/ @copyright: Copyright 2015 Robert PASTOR This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published...
256
256
5,493
4
251
RobertPastor/flight-profile
trajectory/Environment/Atmosphere.py
Python
Atmosphere
Atmosphere
40
343
40
40
497270b13d1a23c2e0a301584ba7288b0575961d
bigcode/the-stack
train
9f4eb7996bdb3f4615635654
train
class
class ConvolutionalOccupancyNetwork(nn.Module): ''' Occupancy Network class. Args: decoder (nn.Module): decoder network encoder (nn.Module): encoder network device (device): torch device ''' def __init__(self, decoder, encoder=None, device=None): super().__init__() ...
class ConvolutionalOccupancyNetwork(nn.Module):
''' Occupancy Network class. Args: decoder (nn.Module): decoder network encoder (nn.Module): encoder network device (device): torch device ''' def __init__(self, decoder, encoder=None, device=None): super().__init__() self.decoder = decoder.to(device) ...
import torch import torch.nn as nn from torch import distributions as dist from src.conv_onet.models import decoder # Decoder dictionary decoder_dict = { 'simple_local': decoder.LocalDecoder, 'simple_local_crop': decoder.PatchLocalDecoder, 'simple_local_point': decoder.LocalPointDecoder } class Convolution...
76
171
572
10
66
tangjiapeng/SA-ConvONet
src/conv_onet/models/__init__.py
Python
ConvolutionalOccupancyNetwork
ConvolutionalOccupancyNetwork
14
110
14
14
9698b8091f295bc32e6697f37d98d1d60b1ba6ec
bigcode/the-stack
train
192414ce7efcf223ef5c25e4
train
function
def write_temporary_ascii(num_halos, temp_fname): d = OrderedDict() with NumpyRNGContext(fixed_seed): d['halo_spin_bullock'] = np.random.random(num_halos).astype('f4') d['halo_id'] = np.arange(num_halos).astype('i8') d['halo_upid'] = np.random.randint(-1, 6, num_halos).astype('i8') ...
def write_temporary_ascii(num_halos, temp_fname):
d = OrderedDict() with NumpyRNGContext(fixed_seed): d['halo_spin_bullock'] = np.random.random(num_halos).astype('f4') d['halo_id'] = np.arange(num_halos).astype('i8') d['halo_upid'] = np.random.randint(-1, 6, num_halos).astype('i8') d['halo_x'] = np.random.random(num_halos).astyp...
arin' detected_home = _find_home() if aph_home == detected_home: APH_MACHINE = True else: APH_MACHINE = False __all__ = ('TestRockstarHlistReader', ) fixed_seed = 43 def write_temporary_ascii(num_halos, temp_fname):
64
64
186
12
51
mclaughlin6464/halotools_old
halotools/sim_manager/tests/test_rockstar_hlist_reader.py
Python
write_temporary_ascii
write_temporary_ascii
44
55
44
44
07a50a9f26a486f50003ea982d4d715969047f9f
bigcode/the-stack
train
20d81c2eeb7ed70884e4968c
train
class
class TestRockstarHlistReader(TestCase): def setUp(self): self.tmpdir = os.path.join(_find_home(), '.tmp_testingdir') try: os.makedirs(self.tmpdir) except OSError: pass basename = 'abc.txt' self.dummy_fname = os.path.join(self.tmpdir, basename) ...
class TestRockstarHlistReader(TestCase):
def setUp(self): self.tmpdir = os.path.join(_find_home(), '.tmp_testingdir') try: os.makedirs(self.tmpdir) except OSError: pass basename = 'abc.txt' self.dummy_fname = os.path.join(self.tmpdir, basename) _t = Table({'x': [0]}) _t.writ...
aph_home = '/Users/aphearin' detected_home = _find_home() if aph_home == detected_home: APH_MACHINE = True else: APH_MACHINE = False __all__ = ('TestRockstarHlistReader', ) fixed_seed = 43 def write_temporary_ascii(num_halos, temp_fname): d = OrderedDict() with NumpyRNGContext(fixed_seed): ...
256
256
2,974
10
246
mclaughlin6464/halotools_old
halotools/sim_manager/tests/test_rockstar_hlist_reader.py
Python
TestRockstarHlistReader
TestRockstarHlistReader
58
353
58
59
ccd2281f074ff9d7267f8ddb4b7fabaa3d2a2447
bigcode/the-stack
train
d463f4c685315ecd73782a7a
train
class
class Graph: def __init__(self, vertex): self.vertex = vertex self.graph = [[0] * vertex for i in range(vertex) ] def add_edge(self, u, v): self.graph[u - 1][v - 1] = 1 self.graph[v - 1][u - 1] = 1 def show(self): for i in self.graph: for j in i: ...
class Graph:
def __init__(self, vertex): self.vertex = vertex self.graph = [[0] * vertex for i in range(vertex) ] def add_edge(self, u, v): self.graph[u - 1][v - 1] = 1 self.graph[v - 1][u - 1] = 1 def show(self): for i in self.graph: for j in i: pri...
from __future__ import print_function class Graph:
11
64
107
3
7
joeyzhou85/python
graphs/graph_matrix.py
Python
Graph
Graph
4
19
4
5
78e0a21a1927fcdd268971716cd66b59db328e8c
bigcode/the-stack
train
eb20d7be9f8a0d4f63f73013
train
class
class OpenTests(TranspileTestCase): pass
class OpenTests(TranspileTestCase):
pass
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class OpenTests(TranspileTestCase):
24
64
12
9
14
akubera/batavia
tests/builtins/test_open.py
Python
OpenTests
OpenTests
4
5
4
4
c21fa589795629fd0b7f7aee33ad402b614560af
bigcode/the-stack
train
bca43dccaf1a2043c038ed17
train
class
class BuiltinOpenFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): function = "open" not_implemented = [ 'test_noargs', 'test_bool', 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_float', 'test_fr...
class BuiltinOpenFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
function = "open" not_implemented = [ 'test_noargs', 'test_bool', 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_float', 'test_frozenset', 'test_int', 'test_list', 'test_None', ...
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class OpenTests(TranspileTestCase): pass class BuiltinOpenFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
44
64
127
17
26
akubera/batavia
tests/builtins/test_open.py
Python
BuiltinOpenFunctionTests
BuiltinOpenFunctionTests
8
30
8
8
79f393163ff846829aca53af71bd477023b0e149
bigcode/the-stack
train
0f79248d3c181f9d1469ec84
train
function
def main(): QR_Generator = QRCode_generator.QRCode_Generator('https://yagi-404.github.io/', 'My Website') QR_Generator.generate_QR_code() QR_Generator = QRCode_generator.QRCode_Generator('https://lapcoder.github.io/4U-Programming-language/', '4U Programming Language') QR_Generator.generate_QR_code()
def main():
QR_Generator = QRCode_generator.QRCode_Generator('https://yagi-404.github.io/', 'My Website') QR_Generator.generate_QR_code() QR_Generator = QRCode_generator.QRCode_Generator('https://lapcoder.github.io/4U-Programming-language/', '4U Programming Language') QR_Generator.generate_QR_code()
import QRCode_generator def main():
8
64
81
3
4
Yagi-404/PY-QR
src/main.py
Python
main
main
3
8
3
3
ed2fd2e3b6457882a892902422cf1cd0fe427d8f
bigcode/the-stack
train
8c90efee1dcdd572ee4785d7
train
function
@click.command() @click.argument('model_list') @click.option('--output_file', '-o', nargs=1, type=str, default='trained_models.json') @click.option('--hash-type', '-H', type=click.Choice(['md5', 'sha1']), default='sha1') def main(model_list, *, output_file, hash_type): """Trains models s...
@click.command() @click.argument('model_list') @click.option('--output_file', '-o', nargs=1, type=str, default='trained_models.json') @click.option('--hash-type', '-H', type=click.Choice(['md5', 'sha1']), default='sha1') def main(model_list, *, output_file, hash_type):
"""Trains models speficied in the supplied `model_list` file output is a dictionary of trained model metadata keyed by model_key := {algorithm}_{dataset}_{run_number}, where: dataset: name of dataset to use algorithm: name of algorithm (estimator) to run on the dataset run_numb...
find_dotenv, load_dotenv from ..logging import logger from ..utils import save_json from ..paths import model_path, trained_model_path from .model_list import build_models @click.command() @click.argument('model_list') @click.option('--output_file', '-o', nargs=1, type=str, default='trained_models.json'...
112
112
375
72
39
dorbat01/mammogram
src/models/train_models.py
Python
main
main
13
65
13
19
c41f9cdb85ad171b3ad27f507113bfacc9820ee1
bigcode/the-stack
train
5976dfff83a7e16a180dcf70
train
class
class MacaccessctrlCommandProcessor(BaseCommandProcessor): __name__ = 'macAccessCtrl' management_functions = ('main', 'cfgm', 'fm', 'status') access_points = () from .macaccessctrlManagementFunctions import main from .macaccessctrlManagementFunctions import cfgm from .macaccessctrlManagementFun...
class MacaccessctrlCommandProcessor(BaseCommandProcessor):
__name__ = 'macAccessCtrl' management_functions = ('main', 'cfgm', 'fm', 'status') access_points = () from .macaccessctrlManagementFunctions import main from .macaccessctrlManagementFunctions import cfgm from .macaccessctrlManagementFunctions import fm from .macaccessctrlManagementFunctions...
- Alexander Dincher <https://github.com/Dinker1996> # # License: https://github.com/inexio/NESi/LICENSE.rst from nesi import exceptions from nesi.vendors.KeyMile.baseCommandProcessor import BaseCommandProcessor class MacaccessctrlCommandProcessor(BaseCommandProcessor):
64
64
214
10
53
inexio/NESi
nesi/vendors/KeyMile/accessPoints/root/services/macaccessctrlCommandProcessor.py
Python
MacaccessctrlCommandProcessor
MacaccessctrlCommandProcessor
17
39
17
17
4b66ee3086b42b99353f8b4fa19ab0ea982d4639
bigcode/the-stack
train
6abd8dc9d3919500e3bf98ce
train
class
class JSONWebTokenMixin(BaseJSONWebTokenMixin): def __init_subclass__(cls, **kwargs): cls.init_fields( cls, {"token": {"is_optional": True}, "refresh_token": {"is_optional": True}}, )
class JSONWebTokenMixin(BaseJSONWebTokenMixin):
def __init_subclass__(cls, **kwargs): cls.init_fields( cls, {"token": {"is_optional": True}, "refresh_token": {"is_optional": True}}, )
"refresh_token", str, **field_options.get("refresh_token", {}) ) ) # field.base_resolver.wrapped_func = strip_kwargs(field.base_resolver.wrapped_func, # ...
63
64
53
11
52
kozickikarol/strawberry-django-jwt
strawberry_django_jwt/mixins.py
Python
JSONWebTokenMixin
JSONWebTokenMixin
55
60
55
55
63b2d541d6811725bc07a2935f40ce910d8a5198
bigcode/the-stack
train
450b2bc3854cbc563294e472
train
class
class RefreshMixin(base_class, JSONWebTokenMixin): # type: ignore """RefreshMixin"""
class RefreshMixin(base_class, JSONWebTokenMixin): # type: ignore
"""RefreshMixin"""
( payload, token, new_refresh_token, refresh_expires_in=0 ) base_class = ( RefreshTokenMixin if settings.jwt_settings.JWT_LONG_RUNNING_REFRESH_TOKEN else KeepAliveRefreshMixin ) class RefreshMixin(base_class, JSONWebTokenMixin): # type: ignore
64
64
22
17
47
kozickikarol/strawberry-django-jwt
strawberry_django_jwt/mixins.py
Python
RefreshMixin
RefreshMixin
152
153
152
152
a5a9994b4c35d87f906931f34414c69ba99876af
bigcode/the-stack
train
bc1114699c19be7dc1386acd
train
class
class BaseJSONWebTokenMixin: @staticmethod def init_fields(cls, field_options: Dict[str, Dict[str, Any]]): if not settings.jwt_settings.JWT_HIDE_TOKEN_FIELDS: for (__, field) in inspect.getmembers( cls, lambda f: isinstance(f, StrawberryField) ): f...
class BaseJSONWebTokenMixin: @staticmethod
def init_fields(cls, field_options: Dict[str, Dict[str, Any]]): if not settings.jwt_settings.JWT_HIDE_TOKEN_FIELDS: for (__, field) in inspect.getmembers( cls, lambda f: isinstance(f, StrawberryField) ): field.arguments.append( Stra...
_token.shortcuts import get_refresh_token from .refresh_token.shortcuts import refresh_token_lazy from .signals import token_refreshed from .utils import get_payload, get_context from .utils import get_user_by_payload from .utils import maybe_thenable class BaseJSONWebTokenMixin: @staticmethod
64
64
142
11
52
kozickikarol/strawberry-django-jwt
strawberry_django_jwt/mixins.py
Python
BaseJSONWebTokenMixin
BaseJSONWebTokenMixin
30
50
30
31
0e9aee06a664db3e1824ebcc77a3f6c3e6130b50
bigcode/the-stack
train
6eec368f9b7230fe9484accc
train
class
class RefreshTokenMixin(JSONWebTokenMixin): @strawberry.mutation @setup_jwt_cookie @csrf_rotation @refresh_expiration @ensure_refresh_token def refresh(self, info, refresh_token: Optional[str]) -> RefreshedTokenType: context = get_context(info) old_refresh_token = get_refresh_tok...
class RefreshTokenMixin(JSONWebTokenMixin): @strawberry.mutation @setup_jwt_cookie @csrf_rotation @refresh_expiration @ensure_refresh_token
def refresh(self, info, refresh_token: Optional[str]) -> RefreshedTokenType: context = get_context(info) old_refresh_token = get_refresh_token(refresh_token, context) if old_refresh_token.is_expired(context): raise exceptions.JSONWebTokenError(_("Refresh token is expired")) ...
token_refreshed.send(sender=RefreshMixin, request=context, user=user) result = TokenDataType(payload, token, refresh_expires_in) return maybe_thenable((result, token), on_resolve) class RefreshTokenMixin(JSONWebTokenMixin): @strawberry.mutation @setup_jwt_cookie @csrf_rotation @refresh...
86
86
289
41
45
kozickikarol/strawberry-django-jwt
strawberry_django_jwt/mixins.py
Python
RefreshTokenMixin
RefreshTokenMixin
99
142
99
104
1fc8a36e61e7f93df84c409967da514a3bab4373
bigcode/the-stack
train
fe1e6049cf37e7242d4fdedf
train
class
class KeepAliveRefreshMixin(JSONWebTokenMixin): @strawberry.mutation @setup_jwt_cookie @csrf_rotation @ensure_token def refresh(self, info, token: Optional[str]) -> TokenDataType: def on_resolve(values): payload, token = values payload.token = token return...
class KeepAliveRefreshMixin(JSONWebTokenMixin): @strawberry.mutation @setup_jwt_cookie @csrf_rotation @ensure_token
def refresh(self, info, token: Optional[str]) -> TokenDataType: def on_resolve(values): payload, token = values payload.token = token return payload context = get_context(info) payload = get_payload(token, context) user = get_user_by_payload(paylo...
(BaseJSONWebTokenMixin): def __init_subclass__(cls, **kwargs): cls.init_fields( cls, {"token": {"is_optional": True}, "refresh_token": {"is_optional": True}}, ) class KeepAliveRefreshMixin(JSONWebTokenMixin): @strawberry.mutation @setup_jwt_cookie @csrf_rotation ...
83
83
277
35
48
kozickikarol/strawberry-django-jwt
strawberry_django_jwt/mixins.py
Python
KeepAliveRefreshMixin
KeepAliveRefreshMixin
63
96
63
67
5a1cc4033a753282992ff51b320205449ce23bab
bigcode/the-stack
train
ac240b68dce601a1a703a22d
train
class
class TestDiffTripleOBuilds(unittest.TestCase): def setUp(self): self.diff = diff_builds.DiffBuilds() # from get_logs, nice_list self.control_list = {'fribidi-1.0.4-8.el8', 'fribidi-1.0.5-9.el8', 'fribidi-1.0.5-11.el8', ...
class TestDiffTripleOBuilds(unittest.TestCase):
def setUp(self): self.diff = diff_builds.DiffBuilds() # from get_logs, nice_list self.control_list = {'fribidi-1.0.4-8.el8', 'fribidi-1.0.5-9.el8', 'fribidi-1.0.5-11.el8', 'python3-pyasn1-modules-0.4.6-3.e...
import json import os import unittest import mock from diff_tripleo_builds import diff_builds # execute w/ python -m unittest # sys.path.append(os.path.abspath('..')) class TestDiffTripleOBuilds(unittest.TestCase):
54
256
2,205
11
43
fuzzball81/ci-config
ci-scripts/infra-setup/roles/rrcockpit/files/compare_rpms/tests/test_diff_tripleo_builds.py
Python
TestDiffTripleOBuilds
TestDiffTripleOBuilds
13
215
13
14
4e5a17ef70a77635cf4d2a4b196f608728c40864
bigcode/the-stack
train
73387409889a8aa7c2af5c13
train
class
class X509(object): """ This class represents an X.509 certificate. :vartype bytes: bytearray :ivar bytes: The DER-encoded ASN.1 certificate :vartype publicKey: ~tlslite.utils.rsakey.RSAKey :ivar publicKey: The subject public key from the certificate. :vartype subject: bytearray :ivar...
class X509(object):
""" This class represents an X.509 certificate. :vartype bytes: bytearray :ivar bytes: The DER-encoded ASN.1 certificate :vartype publicKey: ~tlslite.utils.rsakey.RSAKey :ivar publicKey: The subject public key from the certificate. :vartype subject: bytearray :ivar subject: The DER-en...
# Authors: # Trevor Perrin # Google - parsing subject field # # See the LICENSE file for legal information regarding use of this file. """Class representing an X.509 certificate.""" from .utils.asn1parser import ASN1Parser from .utils.cryptomath import * from .utils.keyfactory import _createPublicRSAKey from .ut...
86
256
992
5
81
zak905/scalyr-agent-2
scalyr_agent/third_party_tls/tlslite/x509.py
Python
X509
X509
15
135
15
15
4bf0e74ab0482a0125e7d9cfa1a37f0510e49a98
bigcode/the-stack
train
9e95bff216bdfd67c696a99b
train
function
def add_parser(subparsers): parser = subparsers.add_parser('Serve-Data', aliases=['poke', 'sd', 'serve-data']) parser.add_argument('-f', '--freshness', metavar='FRESHNESS', default=60000, type=int, help='the freshness period of the Data packet') parser.add_argument('-o', '--output', ...
def add_parser(subparsers):
parser = subparsers.add_parser('Serve-Data', aliases=['poke', 'sd', 'serve-data']) parser.add_argument('-f', '--freshness', metavar='FRESHNESS', default=60000, type=int, help='the freshness period of the Data packet') parser.add_argument('-o', '--output', metavar='FILE', ...
implied. # See the License for the specific language governing permissions and # limitations under the License. # ----------------------------------------------------------------------------- import os import sys import argparse from ...encoding import Name, MetaInfo from ...app import NDNApp from ...security import K...
64
64
164
7
56
tianyuan129/python-ndn
src/ndn/bin/tools/cmd_serve_data.py
Python
add_parser
add_parser
26
37
26
26
67999622bb13d4971e12d0ab9428532e09982e28
bigcode/the-stack
train
7e5303ef933b91263d0c6e27
train
function
def execute(args: argparse.Namespace): fresh = args.freshness try: name = Name.from_str(args.name) except (ValueError, IndexError): print(f'Invalid name: {args.name}') return -1 try: if args.file == '-': text = sys.stdin.read().encode() else: ...
def execute(args: argparse.Namespace):
fresh = args.freshness try: name = Name.from_str(args.name) except (ValueError, IndexError): print(f'Invalid name: {args.name}') return -1 try: if args.file == '-': text = sys.stdin.read().encode() else: with open(os.path.expandvars(args.f...
'--output', metavar='FILE', help='write the AppParam into a file') # More to be added parser.add_argument('name', metavar='NAME', help='the name of the Data packet') parser.add_argument('file', metavar='FILE', nargs='?', default='-', h...
97
97
326
7
90
tianyuan129/python-ndn
src/ndn/bin/tools/cmd_serve_data.py
Python
execute
execute
40
79
40
40
2a57692cd44af5a5eaf96636e9c0fb071f665d2e
bigcode/the-stack
train
1301c6336e22d7184831b8b3
train
function
def requirements_from_file(filename): """Parses a pip requirements file into a list.""" return [line.strip() for line in open(filename, 'r') if line.strip() and not line.strip().startswith('--')]
def requirements_from_file(filename):
"""Parses a pip requirements file into a list.""" return [line.strip() for line in open(filename, 'r') if line.strip() and not line.strip().startswith('--')]
#an amazing project import re import sys from codecs import open # To use a consistent encoding from os import path from setuptools import setup # Always prefer setuptools over distutils def requirements_from_file(filename):
48
64
46
6
41
sumitsisodiya/MechanicalSoup
setup.py
Python
requirements_from_file
requirements_from_file
11
14
11
11
b3d02c036a56b84470b4d13f800c6127dc777d35
bigcode/the-stack
train
92ccd726a63abe0628e791bf
train
function
def read(fname, URL, URLImage): """Read the content of a file.""" readme = open(path.join(path.dirname(__file__), fname)).read() if hasattr(readme, 'decode'): # In Python 3, turn bytes into str. readme = readme.decode('utf8') # turn relative links into absolute ones readme = re.sub(r...
def read(fname, URL, URLImage):
"""Read the content of a file.""" readme = open(path.join(path.dirname(__file__), fname)).read() if hasattr(readme, 'decode'): # In Python 3, turn bytes into str. readme = readme.decode('utf8') # turn relative links into absolute ones readme = re.sub(r'`<([^>]*)>`__', ...
# Always prefer setuptools over distutils def requirements_from_file(filename): """Parses a pip requirements file into a list.""" return [line.strip() for line in open(filename, 'r') if line.strip() and not line.strip().startswith('--')] def read(fname, URL, URLImage):
63
64
145
9
54
sumitsisodiya/MechanicalSoup
setup.py
Python
read
read
17
29
17
17
99a820a323c76887c9fc3e036ac1f14b9377293f
bigcode/the-stack
train
4b3a31d262a5bb4ed42684eb
train
function
def test_compliant_1(): assert is_complaint([1,2,3], List[int]) assert is_complaint({"a":1}, Dict[str, int]) assert not is_complaint({"a": "b"}, Dict[str, int])
def test_compliant_1():
assert is_complaint([1,2,3], List[int]) assert is_complaint({"a":1}, Dict[str, int]) assert not is_complaint({"a": "b"}, Dict[str, int])
from redbean.dobject.utils import is_complaint from dataclasses import dataclass from typing import List, Dict, Union, _GenericAlias, get_args, get_origin def test_compliant_1():
46
64
57
7
38
lcgong/redbean
tests/dobject/test_compliant.py
Python
test_compliant_1
test_compliant_1
7
11
7
7
d6bfc6909f9b8e6056b306ea61c33ae49de0dfce
bigcode/the-stack
train
f113fe5592d409312f29931d
train
function
def test_compliant_1(): @dataclass class A: a: str assert is_complaint(A("a"), A)
def test_compliant_1(): @dataclass
class A: a: str assert is_complaint(A("a"), A)
1(): assert is_complaint([1,2,3], List[int]) assert is_complaint({"a":1}, Dict[str, int]) assert not is_complaint({"a": "b"}, Dict[str, int]) def test_compliant_1(): @dataclass
64
64
33
12
52
lcgong/redbean
tests/dobject/test_compliant.py
Python
test_compliant_1
test_compliant_1
14
19
14
15
043613cf3baad12b470d7bd9eb40dfaad711ec3f
bigcode/the-stack
train
7d02d7e7393fbaa79a5eb553
train
class
class Swarm: def __init__(self, ec2_client: boto3.client, docker_client: docker.APIClient): self.docker_client = docker_client self.ec2_client = ec2_client self.manager_nodes = [] self.manager_instances = [] self.nodes = [] @staticmethod def running_managers(nodes): ...
class Swarm:
def __init__(self, ec2_client: boto3.client, docker_client: docker.APIClient): self.docker_client = docker_client self.ec2_client = ec2_client self.manager_nodes = [] self.manager_instances = [] self.nodes = [] @staticmethod def running_managers(nodes): """Fo...
import boto3 import docker from docker.errors import APIError import click class Swarm:
21
256
1,716
4
16
jaredvacanti/swarm-controller
swarm_controller/swarm.py
Python
Swarm
Swarm
7
236
7
7
a90c473671d2fcde61570726e27489c9fd9eff28
bigcode/the-stack
train
c361e26a7ceb8209e35a9dfe
train
class
class XlsReader(Reader): def __init__(self, base_dir: str): super().__init__() self.base_dir = base_dir def read(self, file_name: str, options: dict = None) -> pd.DataFrame: return pd.read_excel(os.path.join(self.base_dir, file_name), **options if options is not None else {})
class XlsReader(Reader):
def __init__(self, base_dir: str): super().__init__() self.base_dir = base_dir def read(self, file_name: str, options: dict = None) -> pd.DataFrame: return pd.read_excel(os.path.join(self.base_dir, file_name), **options if options is not None else {})
import os import pandas as pd from reader.reader import Reader class XlsReader(Reader):
21
64
77
7
13
jbinder/csv-merge
reader/xls_reader.py
Python
XlsReader
XlsReader
8
14
8
8
b990cfe8670847f27ff4fbfde3e96cb015ac86a1
bigcode/the-stack
train
bbfa1c2721f45d90c2f969d4
train
class
class TestRunner: def __init__(self): self.case_dirs = [] def add_case_dir(self, dir_path): """添加测试用例文件夹,多次调用可以添加多个文件夹,会按照文件夹的添加顺序执行用例 runner = TestRunner() runner.add_case_dir(r"testcase\chat") runner.add_case_dir(r"testcase\battle") runner.run...
class TestRunner:
def __init__(self): self.case_dirs = [] def add_case_dir(self, dir_path): """添加测试用例文件夹,多次调用可以添加多个文件夹,会按照文件夹的添加顺序执行用例 runner = TestRunner() runner.add_case_dir(r"testcase\chat") runner.add_case_dir(r"testcase\battle") runner.run_test(report_title=...
"跳过" result_data['testResult'].append(case_data) result_data["testPass"] = result.success_count result_data["testAll"] = result.success_count + result.failure_count + result.error_count + result.skip_count result_data["testFail"] = result.failure_count result_data["test...
91
91
304
4
86
ZhangshTest/unittest-
utx/runner.py
Python
TestRunner
TestRunner
187
225
187
188
db42b9a1af73519f278af160b9ea21b5c9188a64
bigcode/the-stack
train
e5fb0e2980d79e2c7d4526ef
train
class
class _TestRunner: def __init__(self, report_title, report_dir, verbosity=1, description=""): self.report_dir = report_dir self.verbosity = verbosity self.title = report_title self.description = description self.start_time = datetime.datetime.now() self.stop_time = No...
class _TestRunner:
def __init__(self, report_title, report_dir, verbosity=1, description=""): self.report_dir = report_dir self.verbosity = verbosity self.title = report_title self.description = description self.start_time = datetime.datetime.now() self.stop_time = None def run(sel...
addSuccess(test) output = self.complete_output() self.result.append((0, test, output, '', self._case_run_time)) def addError(self, test, err): self.error_count += 1 super().addError(test, err) _, _exc_str = self.errors[-1] output = self.complete_output() self...
256
256
876
5
251
ZhangshTest/unittest-
utx/runner.py
Python
_TestRunner
_TestRunner
94
184
94
94
2004fc0e921b3461f4c3a19cd594dbe8cda7ea7f
bigcode/the-stack
train
38e7e516d2e633261c76776c
train
class
class _TestResult(unittest.TestResult): def __init__(self, verbosity=1): super().__init__(verbosity) self.outputBuffer = io.StringIO() self.raw_stdout = None self.raw_stderr = None self.success_count = 0 self.failure_count = 0 self.skip_count = 0 self....
class _TestResult(unittest.TestResult):
def __init__(self, verbosity=1): super().__init__(verbosity) self.outputBuffer = io.StringIO() self.raw_stdout = None self.raw_stderr = None self.success_count = 0 self.failure_count = 0 self.skip_count = 0 self.error_count = 0 self.verbosity =...
#! /usr/bin/env python # -*- coding: UTF-8 -*- import time import os import io import datetime import sys import unittest from utx.core import Tool from . import log, setting result_data = dict() result_data['testResult'] = [] current_class_name = "" STATUS = { 0: 'Pass', 1: 'Fail', 2: 'Error', 3: 'Ski...
105
163
546
8
97
ZhangshTest/unittest-
utx/runner.py
Python
_TestResult
_TestResult
23
91
23
23
5625f311accb1eafffdbce2f1952da2accdcd086
bigcode/the-stack
train
1eccad354dd727b6ee8fd040
train
function
def senet(classes,epochs, steps_per_epoch, validation_steps,input_shape): # 加载数据 train_batches, valid_batches= load_data(input_shape) model = SEResNeXt(classes,input_shape[0]).model if classes==1: model.compile(optimizer=Adam(lr=0.0001), loss='binary_crossentropy', me...
def senet(classes,epochs, steps_per_epoch, validation_steps,input_shape): # 加载数据
train_batches, valid_batches= load_data(input_shape) model = SEResNeXt(classes,input_shape[0]).model if classes==1: model.compile(optimizer=Adam(lr=0.0001), loss='binary_crossentropy', metrics=['accuracy']) else: model.compile(optimizer=Adam(lr=0.0001), loss='...
= self.initial_layer(inputs) x = self.residual_layer(x, out_dim=64) x = self.residual_layer(x, out_dim=128) x = self.residual_layer(x, out_dim=256) x = GlobalAveragePooling2D()(x) if num_classes==1: print("sigmoid") x = Dense(units=num_classes,...
136
136
454
22
114
Hiwyl/keras_cnn_finetune
models/senet.py
Python
senet
senet
198
237
198
199
209fb82747baddb4a740299a58d6d1072f64263a
bigcode/the-stack
train
ae2a0ad2c05fd2e0e022fcc7
train
class
class SEResNeXt(object): def __init__(self, num_classes=10, size=96, depth=64, reduction_ratio=4, num_split=8, num_block=3): self.depth = depth # number of channels self.ratio = reduction_ratio # ratio of channel reduction in SE module self.num_split = num_split # number of splitting ...
class SEResNeXt(object):
def __init__(self, num_classes=10, size=96, depth=64, reduction_ratio=4, num_split=8, num_block=3): self.depth = depth # number of channels self.ratio = reduction_ratio # ratio of channel reduction in SE module self.num_split = num_split # number of splitting trees for ResNeXt (so call...
.backend.tensorflow_backend import set_session # os.environ["CUDA_VISIBLE_DEVICES"] = "0,1" # # config = tf.ConfigProto(intra_op_parallelism_threads=18, inter_op_parallelism_threads=18, device_count={'CPU': 9}) # config = tf.ConfigProto() # # config.gpu_options.per_process_gpu_memory_fraction = 0.4 # config.gpu_...
256
256
1,108
7
248
Hiwyl/keras_cnn_finetune
models/senet.py
Python
SEResNeXt
SEResNeXt
51
196
51
51
2d4865d9da16209be3f6f26ac36d22430807f885
bigcode/the-stack
train
ec970b733f917ffa11abd528
train
class
class ExternalCommandError(Exception): """Exception for command failure in ExternalCommandHandler sub-classes.""" #pylint: disable=unnecessary-pass pass
class ExternalCommandError(Exception):
"""Exception for command failure in ExternalCommandHandler sub-classes.""" #pylint: disable=unnecessary-pass pass
pcmd: print line print('grep returned %d' % grepcmd.rc) """ import sys import os import shutil import subprocess import tempfile from contextlib import contextmanager from . import utility from . import shell from . import console class ExternalCommandError(Exception):
64
64
35
6
57
wijjo/scriptbase
scriptbase/command.py
Python
ExternalCommandError
ExternalCommandError
98
101
98
98
dc42512d5f7bb8dfa6a4ad01df1ea928c02ef224
bigcode/the-stack
train
e2f3b641695204f2673d0a1a
train
class
class Command(object): """ Run a single command with various methods for accessing results. A Command object must be used in a "with" statement to assure proper clean-up. Once inside the "with" statement methods can be called to iterate output, run to completion with output on the console, or read ...
class Command(object):
""" Run a single command with various methods for accessing results. A Command object must be used in a "with" statement to assure proper clean-up. Once inside the "with" statement methods can be called to iterate output, run to completion with output on the console, or read output lines into a lis...
if _get_option('dry_run'): sys.stdout.write('>>> ') sys.stdout.write(_command_text()) sys.stdout.write(os.linesep) return 0 if _get_option('verbose'): console.display_messages(_command_text(), tag='TRACE') elif _get_option('pause'): ...
256
256
1,466
4
252
wijjo/scriptbase
scriptbase/command.py
Python
Command
Command
185
383
185
185
262e13b3511d7f77591fe60877dc0306ab571510
bigcode/the-stack
train
a65fd2f252bdfa1f38b50aa5
train
class
class ExternalCommandHandler(object): """ Base class for command runners. Provides surrounding logic for running external commands. Handles options, including dry-run, verbose, and pause. Used by the Command, Runner, and Batch classes in this module. Not generally useful externally. """ ...
class ExternalCommandHandler(object):
""" Base class for command runners. Provides surrounding logic for running external commands. Handles options, including dry-run, verbose, and pause. Used by the Command, Runner, and Batch classes in this module. Not generally useful externally. """ def __init__(self, **options): ...
222','abc','333']) as grepcmd: for line in grepcmd: print line print('grep returned %d' % grepcmd.rc) # Pipe file stream into command. with Command('grep', 'abc').pipe_in(open('/path/to/file')) as grepcmd: for line in grepcmd: print line print('grep returned %d' % grepcmd.rc) """ import sys im...
168
168
563
6
161
wijjo/scriptbase
scriptbase/command.py
Python
ExternalCommandHandler
ExternalCommandHandler
104
182
104
104
38c7005d6e7c5e2c38abaf28f6702f8e03a62a32
bigcode/the-stack
train
1f5116979edc77bfe83a3ea3
train
class
class CommandContext(utility.DictObject): """Local data with console methods enhanced with automatic formatting.""" def info(self, *msgs, **symbols): """Display informational message(s).""" msgs2 = [self.format(msg, **symbols) for msg in msgs] console.info(*msgs2) def verbose_info(...
class CommandContext(utility.DictObject):
"""Local data with console methods enhanced with automatic formatting.""" def info(self, *msgs, **symbols): """Display informational message(s).""" msgs2 = [self.format(msg, **symbols) for msg in msgs] console.info(*msgs2) def verbose_info(self, *msgs, **symbols): """Displa...
_input_source_from_strings(cls, add_line_separators, *input_strs): # Spool strings or bytes through a temporary file. input_source = tempfile.SpooledTemporaryFile() for input_str in input_strs: if isinstance(input_str, bytes): input_source.write(input_str) ...
115
115
384
8
106
wijjo/scriptbase
scriptbase/command.py
Python
CommandContext
CommandContext
386
427
386
386
c788bc7727edb3bcb8071fa55d3625f90b0bad03
bigcode/the-stack
train
c62460ffed6c3b05fab604a9
train
class
class Batch(object): """Build and execute a batch of shell commands (blocking).""" #=== Batch nested classes. class Error(Exception): """Exception for batch errors prior to execution.""" #pylint: disable=unnecessary-pass pass class Failure(Exception): """Exception for ...
class Batch(object):
"""Build and execute a batch of shell commands (blocking).""" #=== Batch nested classes. class Error(Exception): """Exception for batch errors prior to execution.""" #pylint: disable=unnecessary-pass pass class Failure(Exception): """Exception for batch errors during e...
_user=False, expand_env=False): """ Expand string or path using internal symbols. If expand_user is True replace '~' with the user HOME. (default=False) if expand_env is True expand environment variables. (default=False) Return the expanded string. """ str_out ...
256
256
959
4
252
wijjo/scriptbase
scriptbase/command.py
Python
Batch
Batch
620
742
620
620
8543789d6a33012cb62a723d8fd6f54e46303499
bigcode/the-stack
train
eaa70efde6aed955c83e70cf
train
class
class Runner(object): """ Command runner. Runner objects are passed by the "cli" module to all call-back functions, but can also be used independently for the command execution and or template expansion functionality. """ #=== Runner nested classes. class VarNamespace(utility.DictObje...
class Runner(object):
""" Command runner. Runner objects are passed by the "cli" module to all call-back functions, but can also be used independently for the command execution and or template expansion functionality. """ #=== Runner nested classes. class VarNamespace(utility.DictObject): """Variab...
msgs2 = [self.format(msg, **symbols) for msg in msgs] console.debug(*msgs2) def warning(self, *msgs, **symbols): """Display warning message(s).""" msgs2 = [self.format(msg, **symbols) for msg in msgs] console.warning(*msgs2) def error(self, *msgs, **symbols): ""...
256
256
1,430
4
252
wijjo/scriptbase
scriptbase/command.py
Python
Runner
Runner
430
617
430
430
d22d766b41c17bcba3ae6c31bdcce5c8d0482b0a
bigcode/the-stack
train
230ed6c64faec35b1a593634
train
class
class Application(object): ''' This is the base class of every program based on deepin-ui. Every program should realize it. ''' def __init__(self, app_support_colormap=True, resizable=True, window_type=gtk.WINDOW_TOPLEVEL, destroy_...
class Application(object):
''' This is the base class of every program based on deepin-ui. Every program should realize it. ''' def __init__(self, app_support_colormap=True, resizable=True, window_type=gtk.WINDOW_TOPLEVEL, destroy_func=None, ...
(C) 2011 ~ 2012 Deepin, Inc. # 2011 ~ 2012 Wang Yong # # Author: Wang Yong <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # ...
256
256
1,950
4
251
Jianwei-Wang/python2.7_lib
dist-packages/dtk/ui/application.py
Python
Application
Application
33
303
33
33
7c5b5b1d2d34e9e5eae339f506eb084f9930f271
bigcode/the-stack
train
68ba4949606b75eea9aabda5
train
class
class NfsDriver(driver.ExtendVD, remotefs.RemoteFSDriver): """NFS based cinder driver. Creates file on NFS share for using it as block device on hypervisor. """ driver_volume_type = 'nfs' driver_prefix = 'nfs' volume_backend_name = 'Generic_NFS' VERSION = VERSION def __init__(self, ex...
class NfsDriver(driver.ExtendVD, remotefs.RemoteFSDriver):
"""NFS based cinder driver. Creates file on NFS share for using it as block device on hypervisor. """ driver_volume_type = 'nfs' driver_prefix = 'nfs' volume_backend_name = 'Generic_NFS' VERSION = VERSION def __init__(self, execute=putils.execute, *args, **kwargs): self._remot...
[ cfg.StrOpt('nfs_shares_config', default='/etc/cinder/nfs_shares', help='File with the list of available NFS shares'), cfg.BoolOpt('nfs_sparsed_volumes', default=True, help=('Create volumes as sparsed files which take no space.' ...
256
256
3,393
15
241
HybridF5/cinder
cinder/volume/drivers/nfs.py
Python
NfsDriver
NfsDriver
66
442
66
66
faa8234e0fc5a5cd4b2142c9c49c50188e6cba82
bigcode/the-stack
train
7dbb4355757a294af527f33b
train
function
def test_wrapped_observation(mocker, env: LlvmEnv): """Test using an ObservationWrapper that returns the length of the Ir string.""" class MyWrapper(ObservationWrapper): def __init__(self, env): super().__init__(env) self.observation_space = "Ir" def convert_observation...
def test_wrapped_observation(mocker, env: LlvmEnv):
"""Test using an ObservationWrapper that returns the length of the Ir string.""" class MyWrapper(ObservationWrapper): def __init__(self, env): super().__init__(env) self.observation_space = "Ir" def convert_observation(self, observation): return len(observat...
(env, "action") env.reset() env.step(1) env.step(2) assert env.action.call_count == 2 # pylint: disable=no-member assert env.actions == [0, 1] def test_wrapped_observation(mocker, env: LlvmEnv):
64
64
114
15
49
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_observation
test_wrapped_observation
264
280
264
264
ad446ddb03cdbe882543682816cce8b5effd6d2f
bigcode/the-stack
train
4f03cef1ee15fb8ccdd235c9
train
function
def test_wrapped_set_benchmark(env: LlvmEnv, wrapper_type): """Test that the benchmark attribute can be set on wrapped classes.""" class MyWrapper(wrapper_type): def convert_observation(self, observation): return observation # pass thru env = MyWrapper(env) # Set the benchmark at...
def test_wrapped_set_benchmark(env: LlvmEnv, wrapper_type):
"""Test that the benchmark attribute can be set on wrapped classes.""" class MyWrapper(wrapper_type): def convert_observation(self, observation): return observation # pass thru env = MyWrapper(env) # Set the benchmark attribute and check that it propagates. env.benchmark = "b...
(benchmark="benchmark://cbench-v1/qsort") assert env.benchmark == "benchmark://cbench-v1/qsort" # Check that the observations for different benchmarks are different. assert ir_a != ir_b def test_wrapped_set_benchmark(env: LlvmEnv, wrapper_type):
64
64
183
16
47
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_set_benchmark
test_wrapped_set_benchmark
168
189
168
168
0f7db8aa1480ebe47da7756aff2ce0f8455652a6
bigcode/the-stack
train
12d57fb98d64575ab413b6cd
train
function
def test_wrapped_observation_missing_definition(env: LlvmEnv): with pytest.raises(TypeError): env = CoreObservationWrapper(env)
def test_wrapped_observation_missing_definition(env: LlvmEnv):
with pytest.raises(TypeError): env = CoreObservationWrapper(env)
def convert_observation(self, observation): return len(observation) env = MyWrapper(env) assert env.reset() > 0 observation, _, _, _ = env.step(0) assert observation > 0 def test_wrapped_observation_missing_definition(env: LlvmEnv):
64
64
29
14
49
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_observation_missing_definition
test_wrapped_observation_missing_definition
283
285
283
283
535d0a078343e828020692e42dedb10c4ed72fc2
bigcode/the-stack
train
571fc341b94e65f7f637fa01
train
function
def test_wrapped_action(mocker, env: LlvmEnv): class MyWrapper(ActionWrapper): def action(self, action): return action - 1 def reverse_action(self, action): return action + 1 env = MyWrapper(env) mocker.spy(env, "action") env.reset() env.step(1) env.ste...
def test_wrapped_action(mocker, env: LlvmEnv):
class MyWrapper(ActionWrapper): def action(self, action): return action - 1 def reverse_action(self, action): return action + 1 env = MyWrapper(env) mocker.spy(env, "action") env.reset() env.step(1) env.step(2) assert env.action.call_count == 2 # ...
ophase" env.reward_space = "IrInstructionCount" assert env.observation_space.shape == (56,) assert env.observation_space_spec.id == "Autophase" assert env.reward_space.name == "IrInstructionCount" def test_wrapped_action(mocker, env: LlvmEnv):
64
64
110
14
50
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_action
test_wrapped_action
245
261
245
245
36db270b88715e0732e9ef0ef8a71d46f21ea19b
bigcode/the-stack
train
96a266d3e3aad251b3544e9f
train
function
def test_wrapped_fork_type(env: LlvmEnv, wrapper_type): """Test forking a wrapper.""" env = wrapper_type(env) fkd = env.fork() try: assert isinstance(fkd, wrapper_type) finally: fkd.close()
def test_wrapped_fork_type(env: LlvmEnv, wrapper_type):
"""Test forking a wrapper.""" env = wrapper_type(env) fkd = env.fork() try: assert isinstance(fkd, wrapper_type) finally: fkd.close()
(env: LlvmEnv, wrapper_type): """Test accessing the non-standard properties.""" with wrapper_type(env) as env: assert env.actions == [] assert env.benchmark assert isinstance(env.datasets, Datasets) def test_wrapped_fork_type(env: LlvmEnv, wrapper_type):
64
64
59
16
48
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_fork_type
test_wrapped_fork_type
63
71
63
63
18b50df283c427bc2398cb2aa6c2b67a738dea00
bigcode/the-stack
train
94decf0341739576074d8a2d
train
function
@pytest.fixture( scope="module", params=[ ActionWrapper, CompilerEnvWrapper, ObservationWrapper, RewardWrapper, ], ) def wrapper_type(request): """A test fixture that yields one of the CompilerGym wrapper types.""" return request.param
@pytest.fixture( scope="module", params=[ ActionWrapper, CompilerEnvWrapper, ObservationWrapper, RewardWrapper, ], ) def wrapper_type(request):
"""A test fixture that yields one of the CompilerGym wrapper types.""" return request.param
def __init__(self, env): super().__init__(env) def convert_reward(self, reward): return reward @pytest.fixture( scope="module", params=[ ActionWrapper, CompilerEnvWrapper, ObservationWrapper, RewardWrapper, ], ) def wrapper_type(request):
64
64
56
36
27
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
wrapper_type
wrapper_type
35
46
35
44
021e2fede83ff6be1067400f1ead03eed76355a0
bigcode/the-stack
train
114f333e1705cf273c66e7e8
train
function
def test_wrapped_benchmark(env: LlvmEnv, wrapper_type): """Test that benchmark property has expected values.""" class MyWrapper(wrapper_type): def convert_observation(self, observation): return observation # pass thru env.observation_space = "Ir" env = MyWrapper(env) ir_a = e...
def test_wrapped_benchmark(env: LlvmEnv, wrapper_type):
"""Test that benchmark property has expected values.""" class MyWrapper(wrapper_type): def convert_observation(self, observation): return observation # pass thru env.observation_space = "Ir" env = MyWrapper(env) ir_a = env.reset(benchmark="benchmark://cbench-v1/dijkstra") ...
isinstance(icr, float) assert isinstance(icroz, float) assert env.unwrapped.observation.spaces["Ir"].space.contains(ir) assert env.unwrapped.observation.spaces["IrInstructionCount"].space.contains(ic) def test_wrapped_benchmark(env: LlvmEnv, wrapper_type):
64
64
153
15
49
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_benchmark
test_wrapped_benchmark
148
165
148
148
b1c78a815ac8001f04df17e45bc587f912bf5846
bigcode/the-stack
train
91e7bf9f750b3fe6741d7120
train
function
def test_wrapped_env_in_episode(env: LlvmEnv, wrapper_type): class MyWrapper(wrapper_type): def convert_observation(self, observation): return observation env = MyWrapper(env) assert not env.in_episode env.reset() assert env.in_episode
def test_wrapped_env_in_episode(env: LlvmEnv, wrapper_type):
class MyWrapper(wrapper_type): def convert_observation(self, observation): return observation env = MyWrapper(env) assert not env.in_episode env.reset() assert env.in_episode
effect until reset\(\) is called", ): env.benchmark = "benchmark://cbench-v1/crc32" env.reset() assert env.benchmark == "benchmark://cbench-v1/crc32" def test_wrapped_env_in_episode(env: LlvmEnv, wrapper_type):
64
64
60
16
48
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_env_in_episode
test_wrapped_env_in_episode
192
201
192
192
9bae3b4824988ddf276071bc3f6c551cd809a859
bigcode/the-stack
train
218dfac6789a60ffd6e7a2d1
train
function
def test_wrapped_env_custom_close(env: LlvmEnv): """Test that a custom close() method is called on wrapped environments.""" class MyWrapper(CompilerEnvWrapper): def __init__(self, env: LlvmEnv): super().__init__(env) self.custom_close = False def close(self): ...
def test_wrapped_env_custom_close(env: LlvmEnv):
"""Test that a custom close() method is called on wrapped environments.""" class MyWrapper(CompilerEnvWrapper): def __init__(self, env: LlvmEnv): super().__init__(env) self.custom_close = False def close(self): self.custom_close = True self.env.c...
env.episode_reward == -10 def test_wrapped_env_close(env: LlvmEnv): wrapped = CompilerEnvWrapper(env) wrapped.reset() assert wrapped.service is not None wrapped.close() assert wrapped.service is None def test_wrapped_env_custom_close(env: LlvmEnv):
64
64
105
13
50
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_env_custom_close
test_wrapped_env_custom_close
314
330
314
314
5b98208655d7f68c6f4f632c02286edc10f2caee
bigcode/the-stack
train
2a1c63dbb36b5e97a370281f
train
class
class RewardWrapper(CoreRewardWrapper): def __init__(self, env): super().__init__(env) def convert_reward(self, reward): return reward
class RewardWrapper(CoreRewardWrapper):
def __init__(self, env): super().__init__(env) def convert_reward(self, reward): return reward
Wrapper from tests.test_main import main pytest_plugins = ["tests.pytest_plugins.llvm"] class ObservationWrapper(CoreObservationWrapper): def __init__(self, env): super().__init__(env) def convert_observation(self, observation): return observation class RewardWrapper(CoreRewardWrapper):
64
64
35
7
56
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
RewardWrapper
RewardWrapper
27
32
27
27
a823c2b1ad76492bff8fdedd968f163b1fe7a8f4
bigcode/the-stack
train
f361cdf6040de70e344df652
train
class
class ObservationWrapper(CoreObservationWrapper): def __init__(self, env): super().__init__(env) def convert_observation(self, observation): return observation
class ObservationWrapper(CoreObservationWrapper):
def __init__(self, env): super().__init__(env) def convert_observation(self, observation): return observation
import ActionWrapper, CompilerEnvWrapper from compiler_gym.wrappers import ObservationWrapper as CoreObservationWrapper from compiler_gym.wrappers import RewardWrapper as CoreRewardWrapper from tests.test_main import main pytest_plugins = ["tests.pytest_plugins.llvm"] class ObservationWrapper(CoreObservationWrapper):...
63
64
36
7
56
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
ObservationWrapper
ObservationWrapper
19
24
19
19
8bc83054741fa27bfbb0adcc1de4bd42d7fd4677
bigcode/the-stack
train
10cc18877b6609c03d09d351
train
function
def test_wrapped_fork_subtype(env: LlvmEnv, wrapper_type): """Test forking a wrapper subtype.""" class MyWrapper(wrapper_type): def __init__(self, env): super().__init__(env) env = MyWrapper(env) fkd = env.fork() try: assert isinstance(fkd, MyWrapper) finally: ...
def test_wrapped_fork_subtype(env: LlvmEnv, wrapper_type):
"""Test forking a wrapper subtype.""" class MyWrapper(wrapper_type): def __init__(self, env): super().__init__(env) env = MyWrapper(env) fkd = env.fork() try: assert isinstance(fkd, MyWrapper) finally: fkd.close()
, wrapper_type): """Test forking a wrapper.""" env = wrapper_type(env) fkd = env.fork() try: assert isinstance(fkd, wrapper_type) finally: fkd.close() def test_wrapped_fork_subtype(env: LlvmEnv, wrapper_type):
64
64
84
17
47
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_fork_subtype
test_wrapped_fork_subtype
74
86
74
74
0dad7ce4082434bd27658174ed2343ddc3f6558e
bigcode/the-stack
train
411167fa3325997d7a48c45b
train
function
def test_wrapped_step_custom_args(env: LlvmEnv, wrapper_type): """Test passing the custom CompilerGym step() keyword arguments.""" class MyWrapper(wrapper_type): def convert_observation(self, observation): return observation # pass thru def action(self, action): return...
def test_wrapped_step_custom_args(env: LlvmEnv, wrapper_type):
"""Test passing the custom CompilerGym step() keyword arguments.""" class MyWrapper(wrapper_type): def convert_observation(self, observation): return observation # pass thru def action(self, action): return action # pass thru def convert_reward(self, reward):...
a list of actions to step().""" env = CompilerEnvWrapper(env) env.reset() env.multistep([0, 0, 0]) assert env.actions == [0, 0, 0] def test_wrapped_step_custom_args(env: LlvmEnv, wrapper_type):
64
64
216
16
48
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_step_custom_args
test_wrapped_step_custom_args
119
145
119
119
5812620deffeb005711972665739894d2f278fba
bigcode/the-stack
train
5c6f3a1d97fb491ba26e5bfd
train
function
def test_wrapped_properties(env: LlvmEnv, wrapper_type): """Test accessing the non-standard properties.""" with wrapper_type(env) as env: assert env.actions == [] assert env.benchmark assert isinstance(env.datasets, Datasets)
def test_wrapped_properties(env: LlvmEnv, wrapper_type):
"""Test accessing the non-standard properties.""" with wrapper_type(env) as env: assert env.actions == [] assert env.benchmark assert isinstance(env.datasets, Datasets)
A test fixture that yields one of the CompilerGym wrapper types.""" return request.param def test_wrapped_close(env: LlvmEnv, wrapper_type): env = wrapper_type(env) env.close() assert env.service is None def test_wrapped_properties(env: LlvmEnv, wrapper_type):
64
64
53
14
49
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_properties
test_wrapped_properties
55
60
55
55
eab5f571429a380ad0701017a6139169c79234c1
bigcode/the-stack
train
bb6d6cf98bdb3c8e8fbce0c9
train
function
def test_wrapped_close(env: LlvmEnv, wrapper_type): env = wrapper_type(env) env.close() assert env.service is None
def test_wrapped_close(env: LlvmEnv, wrapper_type):
env = wrapper_type(env) env.close() assert env.service is None
module", params=[ ActionWrapper, CompilerEnvWrapper, ObservationWrapper, RewardWrapper, ], ) def wrapper_type(request): """A test fixture that yields one of the CompilerGym wrapper types.""" return request.param def test_wrapped_close(env: LlvmEnv, wrapper_type):
64
64
32
14
49
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_close
test_wrapped_close
49
52
49
49
f3a3350066b77b3d82f27ea1cf66bcdbe3c16d61
bigcode/the-stack
train
4210a9e273c826a97bdc8a99
train
function
def test_wrapped_reward(env: LlvmEnv): class MyWrapper(RewardWrapper): def convert_reward(self, reward): return -5 env.reward_space = "IrInstructionCount" env = MyWrapper(env) env.reset() _, reward, _, _ = env.step(0) assert reward == -5 assert env.episode_reward == -5 ...
def test_wrapped_reward(env: LlvmEnv):
class MyWrapper(RewardWrapper): def convert_reward(self, reward): return -5 env.reward_space = "IrInstructionCount" env = MyWrapper(env) env.reset() _, reward, _, _ = env.step(0) assert reward == -5 assert env.episode_reward == -5 _, reward, _, _ = env.step(0) ...
() > 0 observation, _, _, _ = env.step(0) assert observation > 0 def test_wrapped_observation_missing_definition(env: LlvmEnv): with pytest.raises(TypeError): env = CoreObservationWrapper(env) def test_wrapped_reward(env: LlvmEnv):
64
64
111
11
53
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_reward
test_wrapped_reward
288
303
288
288
b301a248230e2f9ee1dc1d21e94e022b61d615ab
bigcode/the-stack
train
c440c3e011c6f5019b081068
train
function
def test_wrapped_fork_subtype_custom_constructor(env: LlvmEnv, wrapper_type): """Test forking a wrapper with a custom constructor. This requires a custom fork() implementation.""" class MyWrapper(wrapper_type): def __init__(self, env, foo): super().__init__(env) self.foo = f...
def test_wrapped_fork_subtype_custom_constructor(env: LlvmEnv, wrapper_type):
"""Test forking a wrapper with a custom constructor. This requires a custom fork() implementation.""" class MyWrapper(wrapper_type): def __init__(self, env, foo): super().__init__(env) self.foo = foo def fork(self): return MyWrapper(self.env.fork(), foo=...
, env): super().__init__(env) env = MyWrapper(env) fkd = env.fork() try: assert isinstance(fkd, MyWrapper) finally: fkd.close() def test_wrapped_fork_subtype_custom_constructor(env: LlvmEnv, wrapper_type):
64
64
138
19
45
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_fork_subtype_custom_constructor
test_wrapped_fork_subtype_custom_constructor
89
107
89
89
9ad5bdbad82566bfb3a324234d9d24b655331426
bigcode/the-stack
train
d55a3ea5e09ee994a9946395
train
function
def test_wrapped_step_multi_step(env: LlvmEnv): """Test passing a list of actions to step().""" env = CompilerEnvWrapper(env) env.reset() env.multistep([0, 0, 0]) assert env.actions == [0, 0, 0]
def test_wrapped_step_multi_step(env: LlvmEnv):
"""Test passing a list of actions to step().""" env = CompilerEnvWrapper(env) env.reset() env.multistep([0, 0, 0]) assert env.actions == [0, 0, 0]
=self.foo) env = MyWrapper(env, foo=1) fkd = env.fork() try: assert isinstance(fkd, MyWrapper) assert fkd.foo == 1 finally: fkd.close() def test_wrapped_step_multi_step(env: LlvmEnv):
64
64
65
13
51
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_step_multi_step
test_wrapped_step_multi_step
110
116
110
110
5f17cbafa2912d81d27e92a45e65542e3419a606
bigcode/the-stack
train
0cb3bec505f8a01494c5af5f
train
function
def test_wrapped_env_change_spaces(env: LlvmEnv, wrapper_type): """Test changing the observation and reward spaces on a wrapped environment.""" class MyWrapper(wrapper_type): def convert_observation(self, observation): return observation # pass thru def convert_reward(self, reward...
def test_wrapped_env_change_spaces(env: LlvmEnv, wrapper_type):
"""Test changing the observation and reward spaces on a wrapped environment.""" class MyWrapper(wrapper_type): def convert_observation(self, observation): return observation # pass thru def convert_reward(self, reward): return reward # pass thru env = MyWrapper(e...
_space.shape == (56,) assert env.observation_space_spec.id == "Autophase" assert env.reward_space.name == "IrInstructionCount" observation = env.reset() assert env.observation_space.contains(observation) def test_wrapped_env_change_spaces(env: LlvmEnv, wrapper_type):
64
64
135
16
48
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_env_change_spaces
test_wrapped_env_change_spaces
225
242
225
225
a4d491f8b37c69f0f70d00bc17928021744892ea
bigcode/the-stack
train
5a49b70c3b630c8f051353be
train
function
def test_wrapped_env_changes_default_spaces(env: LlvmEnv, wrapper_type): """Test when an environment wrapper changes the default observation and reward spaces.""" class MyWrapper(wrapper_type): def __init__(self, env: LlvmEnv): super().__init__(env) self.env.observation_space = ...
def test_wrapped_env_changes_default_spaces(env: LlvmEnv, wrapper_type):
"""Test when an environment wrapper changes the default observation and reward spaces.""" class MyWrapper(wrapper_type): def __init__(self, env: LlvmEnv): super().__init__(env) self.env.observation_space = "Autophase" self.env.reward_space = "IrInstructionCount" ...
wrapper_type): class MyWrapper(wrapper_type): def convert_observation(self, observation): return observation env = MyWrapper(env) assert not env.in_episode env.reset() assert env.in_episode def test_wrapped_env_changes_default_spaces(env: LlvmEnv, wrapper_type):
64
64
159
17
46
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_env_changes_default_spaces
test_wrapped_env_changes_default_spaces
204
222
204
204
d1c9ba4fe6703126221499d8cf77753815906070
bigcode/the-stack
train
cbf973d29f5de92d9acc453d
train
function
def test_wrapped_env_close(env: LlvmEnv): wrapped = CompilerEnvWrapper(env) wrapped.reset() assert wrapped.service is not None wrapped.close() assert wrapped.service is None
def test_wrapped_env_close(env: LlvmEnv):
wrapped = CompilerEnvWrapper(env) wrapped.reset() assert wrapped.service is not None wrapped.close() assert wrapped.service is None
= env.step(0) assert reward == -5 assert env.episode_reward == -5 _, reward, _, _ = env.step(0) assert reward == -5 assert env.episode_reward == -10 def test_wrapped_env_close(env: LlvmEnv):
64
64
43
12
51
thecoblack/CompilerGym
tests/wrappers/core_wrappers_test.py
Python
test_wrapped_env_close
test_wrapped_env_close
306
311
306
306
c65067db2029ac37b3559e8575383537c5a24d02
bigcode/the-stack
train
8428ec015821ba050b74c2ab
train
class
class TopicIndexer(Cog): def __init__(self, bot: Bot): self.bot = bot self.ignore_categories = [816030924872613888] self.index_embed_title = "𝐓𝐨𝐩𝐢𝐜 𝐨𝐟 𝐂𝐡𝐚𝐧𝐧𝐞𝐥𝐬" @Cog.listener() async def on_ready(self): self.guild = self.bot.get_guild(ID_GUILD) self.ch...
class TopicIndexer(Cog):
def __init__(self, bot: Bot): self.bot = bot self.ignore_categories = [816030924872613888] self.index_embed_title = "𝐓𝐨𝐩𝐢𝐜 𝐨𝐟 𝐂𝐡𝐚𝐧𝐧𝐞𝐥𝐬" @Cog.listener() async def on_ready(self): self.guild = self.bot.get_guild(ID_GUILD) self.ch_index = self.bot.get_cha...
from datetime import datetime, timezone from const import ID_CH_INDEX, ID_GUILD from discord import Embed, TextChannel from discord.ext.commands import Bot, Cog class TopicIndexer(Cog):
41
117
390
6
34
tenzyu/Chimera
cogs/topic_indexer.py
Python
TopicIndexer
TopicIndexer
8
60
8
8
522d57fbf3324f3867fd71a67b1b8afbce728ad6
bigcode/the-stack
train
00bf4cf4b41917090957c2c5
train
function
def setup(bot: Bot): bot.add_cog(TopicIndexer(bot))
def setup(bot: Bot):
bot.add_cog(TopicIndexer(bot))
self.create_index_embed() await (index.edit(embed=embed) if index else self.ch_index.send(embed=embed)) @Cog.listener() async def on_guild_channel_update(self, before, after): if isinstance(after, TextChannel): await self.update_index() def setup(bot: Bot):
64
64
16
6
58
tenzyu/Chimera
cogs/topic_indexer.py
Python
setup
setup
63
64
63
63
2987dd2e2375cc225113c730a1de4306fb8818f9
bigcode/the-stack
train
8c938a90187486c6bb5269c8
train
class
class TestRewritings(TestCase): def test_prenex_basic(self): a,b,c = (Symbol(x) for x in "abc") f = Not(And(a, Exists([b], And(a, b)), ForAll([c], Or(a, c)))) prenex = prenex_normal_form(f) # Two prenex normal forms are possible my_prenex_1 = Exists([c], ForAll([b], Not(And(...
class TestRewritings(TestCase):
def test_prenex_basic(self): a,b,c = (Symbol(x) for x in "abc") f = Not(And(a, Exists([b], And(a, b)), ForAll([c], Or(a, c)))) prenex = prenex_normal_form(f) # Two prenex normal forms are possible my_prenex_1 = Exists([c], ForAll([b], Not(And(a, And(a, b), Or(a, c))))) ...
copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License fo...
256
256
1,559
9
246
cogrpar/qcpuWARE
QCPU_Setup/DWave-library/dist-packages/PySMT-0.7.0-py3.7.egg/pysmt/test/test_rewritings.py
Python
TestRewritings
TestRewritings
32
180
32
33
a6685263e55c86ee781fbd20ddd80f12597a525d
bigcode/the-stack
train
f0d2664cb0b68c1053d0028b
train
class
class SystemStatus: TEMP_FILE = '/sys/class/thermal/thermal_zone{}/temp' MAXIMUM_CORE = 16 @classmethod def using_mem(cls) -> int: return psutil.virtual_memory().used @classmethod def num_proc(cls) -> int: return len(psutil.pids()) @classmethod def temperature(cls) -> ...
class SystemStatus:
TEMP_FILE = '/sys/class/thermal/thermal_zone{}/temp' MAXIMUM_CORE = 16 @classmethod def using_mem(cls) -> int: return psutil.virtual_memory().used @classmethod def num_proc(cls) -> int: return len(psutil.pids()) @classmethod def temperature(cls) -> List[float]: ...
except OSError: return cls.DIST_ERR @classmethod def serialize(cls) -> SystemInfoType: return { 'rpi': cls.rpi(), 'cpu': cls.cpu(), 'total_mem': cls.total_mem(), 'dist': cls.dist() } class SystemStatus:
66
66
221
4
62
rubycho/webpi
api/utils/system.py
Python
SystemStatus
SystemStatus
57
92
57
57
04c5af1546f3c29b119583f640a84774221f1497
bigcode/the-stack
train
8f68e7c16b6dc8cfcc90ac90
train
class
class SystemInfo: RPI_FILE = '/proc/device-tree/model' CPU_FILE = '/proc/cpuinfo' DIST_FILE = '/etc/os-release' RPI_ERR = 'NOT a RPi System.' CPU_ERR = 'Unavailable' DIST_ERR = 'Unavailable' @classmethod def rpi(cls) -> str: try: with open(cls.RPI_FILE, 'r') as f: ...
class SystemInfo:
RPI_FILE = '/proc/device-tree/model' CPU_FILE = '/proc/cpuinfo' DIST_FILE = '/etc/os-release' RPI_ERR = 'NOT a RPi System.' CPU_ERR = 'Unavailable' DIST_ERR = 'Unavailable' @classmethod def rpi(cls) -> str: try: with open(cls.RPI_FILE, 'r') as f: ret...
import time import psutil from typing import List from .types import SystemInfoType, SystemStatusType from .common import find_line, find_value class SystemInfo:
38
93
310
4
33
rubycho/webpi
api/utils/system.py
Python
SystemInfo
SystemInfo
9
54
9
9
dd738b4c592c68ba0fb5f4fa1a0a8c343659675e
bigcode/the-stack
train
06f0b2198df7890e9e198c5b
train
class
class GetListEntries(Api): API_METHOD = ApiMethod.LIST_ENTRIES class ApiParams(Enum): PER_PAGE = "perPage" ORDER = "order" ARCHIVE = "archive" STARRED = "starred" TAGS = "tags" DETAIL = "detail" class ApiValues(Enum): class ORDER(Enum): ...
class GetListEntries(Api):
API_METHOD = ApiMethod.LIST_ENTRIES class ApiParams(Enum): PER_PAGE = "perPage" ORDER = "order" ARCHIVE = "archive" STARRED = "starred" TAGS = "tags" DETAIL = "detail" class ApiValues(Enum): class ORDER(Enum): ASC = "asc" class D...
# -*- coding: utf-8 -*- from enum import Enum from wallabag.api.api import Api, ApiMethod class Params(Enum): COUNT = "count" FILTER_READ = "filter_read" FILTER_STARRED = "filter_starred" OLDEST = "oldest" TAGS = "tags" class GetListEntries(Api):
73
117
391
6
67
artur-shaik/wallabag-client
src/wallabag/api/get_list_entries.py
Python
GetListEntries
GetListEntries
16
72
16
17
a16260462afea585c573c5d1bead6ee21e536960
bigcode/the-stack
train
3940f27822ddcc13d2ac8355
train
class
class Params(Enum): COUNT = "count" FILTER_READ = "filter_read" FILTER_STARRED = "filter_starred" OLDEST = "oldest" TAGS = "tags"
class Params(Enum):
COUNT = "count" FILTER_READ = "filter_read" FILTER_STARRED = "filter_starred" OLDEST = "oldest" TAGS = "tags"
# -*- coding: utf-8 -*- from enum import Enum from wallabag.api.api import Api, ApiMethod class Params(Enum):
28
64
43
4
23
artur-shaik/wallabag-client
src/wallabag/api/get_list_entries.py
Python
Params
Params
8
13
8
8
ad740ada541207c86d99fca996aa89b6a9fbd91e
bigcode/the-stack
train
936a800fc2067c245e8654fc
train
function
@pytest.mark.parametrize("enable_checkpointing", (False, True)) @pytest.mark.parametrize("fn", ("validate", "test", "predict")) def test_tested_checkpoint_path_best(tmpdir, enable_checkpointing, fn): class TestModel(BoringModel): def validation_step(self, batch, batch_idx): self.log("foo", -batc...
@pytest.mark.parametrize("enable_checkpointing", (False, True)) @pytest.mark.parametrize("fn", ("validate", "test", "predict")) def test_tested_checkpoint_path_best(tmpdir, enable_checkpointing, fn):
class TestModel(BoringModel): def validation_step(self, batch, batch_idx): self.log("foo", -batch_idx) return super().validation_step(batch, batch_idx) def test_step(self, *args): return self.validation_step(*args) def predict_step(self, batch, *_): ...
() ) trainer_fn(ckpt_path=ckpt_path) assert getattr(trainer, "ckpt_path") == ckpt_path trainer_fn(model, ckpt_path=ckpt_path) assert getattr(trainer, "ckpt_path") == ckpt_path @pytest.mark.parametrize("enable_checkpointing", (False, True)) @pytest.mark.parame...
104
104
347
44
59
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
test_tested_checkpoint_path_best
test_tested_checkpoint_path_best
739
779
739
741
a7c68af4283cc557026893c4b03a048df74ac011
bigcode/the-stack
train
ef01eb4636cd5e5fb82ca48b
train
function
def predict( tmpdir, strategy=None, accelerator=None, devices=None, model=None, plugins=None, datamodule=True, enable_progress_bar=True, use_callbacks=True, ): dataloaders = [torch.utils.data.DataLoader(RandomDataset(32, 2)), torch.utils.data.DataLoader(RandomDataset(32, 2))] ...
def predict( tmpdir, strategy=None, accelerator=None, devices=None, model=None, plugins=None, datamodule=True, enable_progress_bar=True, use_callbacks=True, ):
dataloaders = [torch.utils.data.DataLoader(RandomDataset(32, 2)), torch.utils.data.DataLoader(RandomDataset(32, 2))] model = model or BoringModel() dm = TestLightningDataModule(dataloaders) cb = CustomPredictionWriter(tmpdir, write_interval="batch") cb_1 = CustomPredictionWriter(tmpdir, write_inte...
if trainer._accelerator_connector.is_distributed: for idx in range(2): assert isinstance(trainer.predict_dataloaders[idx].batch_sampler.sampler, UnrepeatedDistributedSampler) assert isinstance(trainer.predict_dataloaders[idx].batch_sampler, IndexBatchSamplerWrapper) ...
121
121
406
45
76
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
predict
predict
1,304
1,355
1,304
1,314
4520a7a87d76059fc2b9e8f71ae0232442184662
bigcode/the-stack
train
1a4395e7212d253a1ce78c2f
train
function
def test_module_current_fx_attributes_reset(tmpdir): """Ensure that lightning module's attributes related to current fx are reset at the end of execution.""" model = BoringModel() trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=1, enable_checkpointing=False, logger=False) trainer.fit(model) ...
def test_module_current_fx_attributes_reset(tmpdir):
"""Ensure that lightning module's attributes related to current fx are reset at the end of execution.""" model = BoringModel() trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=1, enable_checkpointing=False, logger=False) trainer.fit(model) assert model._current_fx_name is None trainer.t...
LoadCheckpoint()]) trainer.fit(model) trainer = Trainer(default_root_dir=tmpdir, max_epochs=5) with pytest.warns(UserWarning, match="CustomCallbackOnLoadCheckpoint"): trainer.fit(model, ckpt_path=chk.last_model_path) def test_module_current_fx_attributes_reset(tmpdir):
64
64
92
10
54
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
test_module_current_fx_attributes_reset
test_module_current_fx_attributes_reset
1,736
1,745
1,736
1,736
b1d3fc2f10bdcd12a74d86039c6c0d8f4e961476
bigcode/the-stack
train
c4ba8590e420994c06a9e049
train
function
@pytest.mark.parametrize(["max_steps", "max_epochs", "global_step"], [(10, 5, 10), (20, None, 20)]) def test_repeated_fit_calls_with_max_epochs_and_steps(tmpdir, max_steps, max_epochs, global_step): """Ensure that the training loop is bound by `max_steps` and `max_epochs` for repeated calls of `trainer.fit`, an...
@pytest.mark.parametrize(["max_steps", "max_epochs", "global_step"], [(10, 5, 10), (20, None, 20)]) def test_repeated_fit_calls_with_max_epochs_and_steps(tmpdir, max_steps, max_epochs, global_step):
"""Ensure that the training loop is bound by `max_steps` and `max_epochs` for repeated calls of `trainer.fit`, and disabled if the limit is reached.""" dataset_len = 200 batch_size = 10 train_data = DataLoader(RandomDataset(32, dataset_len), batch_size=batch_size) model = BoringModel() t...
training_epoch_end` {error_string}" @pytest.mark.parametrize(["max_steps", "max_epochs", "global_step"], [(10, 5, 10), (20, None, 20)]) def test_repeated_fit_calls_with_max_epochs_and_steps(tmpdir, max_steps, max_epochs, global_step):
63
64
186
55
8
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
test_repeated_fit_calls_with_max_epochs_and_steps
test_repeated_fit_calls_with_max_epochs_and_steps
1,510
1,526
1,510
1,511
87d5fd6d6e0f953654fed332582fbd46c7f5e875
bigcode/the-stack
train
d60d0471284282aa31c31ad0
train
function
@pytest.mark.parametrize( "running_stage", [RunningStage.TRAINING, RunningStage.VALIDATING, RunningStage.TESTING, RunningStage.PREDICTING] ) def test_dataloaders_are_not_loaded_if_disabled_through_limit_batches(running_stage): dl_prefix = running_stage.dataloader_prefix trainer_kwargs = {f"limit_{dl_prefix}...
@pytest.mark.parametrize( "running_stage", [RunningStage.TRAINING, RunningStage.VALIDATING, RunningStage.TESTING, RunningStage.PREDICTING] ) def test_dataloaders_are_not_loaded_if_disabled_through_limit_batches(running_stage):
dl_prefix = running_stage.dataloader_prefix trainer_kwargs = {f"limit_{dl_prefix}_batches": 0} trainer = Trainer(**trainer_kwargs) model = BoringModel() trainer._data_connector.attach_data(model) reset_dataloader = getattr(trainer, f"reset_{dl_prefix}_dataloader") reset_dataloader(model) ...
_kwargs.get("num_nodes", 1) @pytest.mark.parametrize( "running_stage", [RunningStage.TRAINING, RunningStage.VALIDATING, RunningStage.TESTING, RunningStage.PREDICTING] ) def test_dataloaders_are_not_loaded_if_disabled_through_limit_batches(running_stage):
64
64
177
55
9
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
test_dataloaders_are_not_loaded_if_disabled_through_limit_batches
test_dataloaders_are_not_loaded_if_disabled_through_limit_batches
2,121
2,137
2,121
2,124
9a77c870a39be5ecb048545d2e7162dbbb085d87
bigcode/the-stack
train
7685bf05a265899f063f1175
train
class
class TrainerStagesModel(BoringModel): def on_train_start(self) -> None: assert self.trainer.model.training assert self.training def on_validation_start(self) -> None: assert not self.trainer.model.training assert not self.training def on_test_start(self) -> None: a...
class TrainerStagesModel(BoringModel):
def on_train_start(self) -> None: assert self.trainer.model.training assert self.training def on_validation_start(self) -> None: assert not self.trainer.model.training assert not self.training def on_test_start(self) -> None: assert not self.trainer.model.training ...
TrainerFn.TESTING with pytest.raises(MisconfigurationException, match=r"with `fast_dev_run=True`. .* pass an exact checkpoint path"): trainer._Trainer__set_ckpt_path(ckpt_path="best", model_provided=False, model_connected=True) class TrainerStagesModel(BoringModel):
64
64
106
8
56
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
TrainerStagesModel
TrainerStagesModel
1,663
1,678
1,663
1,663
fe9bb189e6c7bd02be64d1c9d808d4ee3e015af6
bigcode/the-stack
train
f4e01a1b7e0c14b571a75f18
train
function
@RunIf(skip_windows=True) def test_trainer_predict_ddp_spawn(tmpdir): predict(tmpdir, strategy="ddp_spawn", accelerator="auto", devices=2)
@RunIf(skip_windows=True) def test_trainer_predict_ddp_spawn(tmpdir):
predict(tmpdir, strategy="ddp_spawn", accelerator="auto", devices=2)
, kwargs): predict(tmpdir, accelerator="gpu", **kwargs) @RunIf(min_gpus=1) def test_trainer_predict_1_gpu(tmpdir): predict(tmpdir, accelerator="gpu", devices=1) @RunIf(skip_windows=True) def test_trainer_predict_ddp_spawn(tmpdir):
64
64
36
17
47
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
test_trainer_predict_ddp_spawn
test_trainer_predict_ddp_spawn
1,408
1,410
1,408
1,409
a28c10716165f6081a7fbf3f933a2e09415dcac0
bigcode/the-stack
train
a8da353677ef2670e745e4ee
train
function
def test_train_loop_system(tmpdir): """ Test the following methods are called in the order in automatic optimization. 1. optimizer.step (skip when gradient accumulation) 2. model.training_step 3. optimizer.zero_grad (run when the first batch of gradient accumulation) 4. model.backward Note ...
def test_train_loop_system(tmpdir):
""" Test the following methods are called in the order in automatic optimization. 1. optimizer.step (skip when gradient accumulation) 2. model.training_step 3. optimizer.zero_grad (run when the first batch of gradient accumulation) 4. model.backward Note that the order is NOT `training_step...
the correct device.""" class TestModel(BoringModel): def setup(self, stage: str) -> None: self.new_layer = torch.nn.Linear(2, 2) def training_step(self, batch, batch_idx): output = self.layer(batch) # will crash if not moved to correct device output...
163
163
545
8
155
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
test_train_loop_system
test_train_loop_system
1,567
1,647
1,567
1,567
a4dff8f2ac4eddaff028c2fcb76db154e0a8f20e
bigcode/the-stack
train
1e6648518499a89dafde3b35
train
class
class TrainerStagesErrorsModel(BoringModel): def on_train_start(self) -> None: raise Exception("Error during train") def on_validation_start(self) -> None: raise Exception("Error during validation") def on_test_start(self) -> None: raise Exception("Error during test") def on_p...
class TrainerStagesErrorsModel(BoringModel):
def on_train_start(self) -> None: raise Exception("Error during train") def on_validation_start(self) -> None: raise Exception("Error during validation") def on_test_start(self) -> None: raise Exception("Error during test") def on_predict_start(self) -> None: raise Exc...
_loss"].device == torch.device("cpu") assert current_memory() <= initial deepcopy(trainer) assert current_memory() <= initial trainer_2 = Trainer(**trainer_kwargs) trainer_2.fit(model) assert current_memory() <= initial class TrainerStagesErrorsModel(BoringModel):
64
64
81
9
54
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
TrainerStagesErrorsModel
TrainerStagesErrorsModel
1,845
1,856
1,845
1,845
454f38a57a877c42a271c6b1cbc2a708a70d4e02
bigcode/the-stack
train
d9ab45a14706ddc0878d9150
train
function
@pytest.mark.parametrize("return_predictions", [None, False, True]) @pytest.mark.parametrize("precision", [32, 64]) def test_predict_return_predictions_cpu(return_predictions, precision, tmpdir): """Test that `return_predictions=True`.""" seed_everything(42) model = BoringModel() trainer = Trainer(defa...
@pytest.mark.parametrize("return_predictions", [None, False, True]) @pytest.mark.parametrize("precision", [32, 64]) def test_predict_return_predictions_cpu(return_predictions, precision, tmpdir):
"""Test that `return_predictions=True`.""" seed_everything(42) model = BoringModel() trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=True, precision=precision) preds = trainer.predict(model, dataloaders=model.train_dataloader(), return_predictions=return_predictions) if return_predictio...
be set to `False`"): trainer.predict(model, dataloaders=model.train_dataloader(), return_predictions=True) @pytest.mark.parametrize("return_predictions", [None, False, True]) @pytest.mark.parametrize("precision", [32, 64]) def test_predict_return_predictions_cpu(return_predictions, precision, tmpdir):
64
64
163
40
24
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
test_predict_return_predictions_cpu
test_predict_return_predictions_cpu
1,443
1,455
1,443
1,445
90663b3fc4fc5534b8e0807410069522ace441e3
bigcode/the-stack
train
4a346e03bed40199b1ab0b96
train
function
def test_disabled_training(tmpdir): """Verify that `limit_train_batches=0` disables the training loop unless `fast_dev_run=True`.""" class CurrentModel(BoringModel): training_step_invoked = False training_epoch_end_invoked = False def training_step(self, *args, **kwargs): ...
def test_disabled_training(tmpdir):
"""Verify that `limit_train_batches=0` disables the training loop unless `fast_dev_run=True`.""" class CurrentModel(BoringModel): training_step_invoked = False training_epoch_end_invoked = False def training_step(self, *args, **kwargs): self.training_step_invoked = True ...
that a warning is raised if best ckpt callback is used for evaluation configured with multiple checkpoints.""" ckpt_callback1 = ModelCheckpoint() ckpt_callback1.best_model_path = "foo_best_model.ckpt" ckpt_callback2 = ModelCheckpoint() ckpt_callback2.best_model_path = "bar_best_model.ckpt" tra...
148
148
494
7
141
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
test_disabled_training
test_disabled_training
797
856
797
797
6b1dc02e97483fa476cc398d9a6e541bd684fa33
bigcode/the-stack
train
9d4ae147a569069103cd17dd
train
function
@RunIf(min_gpus=2, standalone=True) def test_ddp_terminate_when_deadlock_is_detected(tmpdir): """Test that DDP kills the remaining processes when only one rank is throwing an exception.""" class TestModel(BoringModel): def training_step(self, batch, batch_idx): if batch_idx == 1 and self.tr...
@RunIf(min_gpus=2, standalone=True) def test_ddp_terminate_when_deadlock_is_detected(tmpdir):
"""Test that DDP kills the remaining processes when only one rank is throwing an exception.""" class TestModel(BoringModel): def training_step(self, batch, batch_idx): if batch_idx == 1 and self.trainer.is_global_zero: # rank 0: raises an exception # rank 1: ...
.*test"): trainer.test() with pytest.raises(MisconfigurationException, match=r"`model` must be provided.*predict"): trainer.predict() class CustomException(Exception): pass @RunIf(min_gpus=2, standalone=True) def test_ddp_terminate_when_deadlock_is_detected(tmpdir):
65
65
217
26
38
catalys1/pytorch-lightning
tests/trainer/test_trainer.py
Python
test_ddp_terminate_when_deadlock_is_detected
test_ddp_terminate_when_deadlock_is_detected
1,763
1,789
1,763
1,764
fca152a989b28b702812479a39a7ca00e38873c7
bigcode/the-stack
train