code stringlengths 281 23.7M |
|---|
class AsyncRelationalParent(models.Model):
done = models.BooleanField(default=True)
many_to_many = models.ManyToManyField(AsyncRelationalChild, related_name='many_to_many')
one_to_one = models.OneToOneField(AsyncRelationalChild, related_name='one_to_one', on_delete=models.SET_NULL, null=True) |
class WholePQPixelCNN(nn.Module):
def __init__(self, m, k, channel, withGroup, withAtt, target, alias, ema):
super().__init__()
self._levels = len(k)
self._compressor = PQCompressorBig(m, k, channel, withGroup, withAtt, False, alias, ema)
self._cLoss = nn.CrossEntropyLoss()
s... |
def get_faces_in_selection_bounds(bm):
faces = [f for f in bm.faces if f.select]
normal = faces[0].normal.copy()
(L, R) = (normal.cross(VEC_UP), normal.cross(VEC_DOWN))
faces = sort_faces(faces, R)
(start, finish) = (faces[0].calc_center_median(), faces[(- 1)].calc_center_median())
faces_left = ... |
class VisualGenomeCaptions():
def __init__(self, ann_dir):
super().__init__()
escapes = ''.join([chr(char) for char in range(0, 32)])
self.translator = str.maketrans('', '', escapes)
self.caps = self.parse_annotations(Path(ann_dir))
def combination(l1, l2):
return [' '.jo... |
class InliningTracer(torch.fx.Tracer):
FNS_TO_INLINE = [add_lowp]
def create_node(self, kind, target, args, kwargs, name=None, type_expr=None):
if ((kind == 'call_function') and (target in self.FNS_TO_INLINE)):
tracer = torch.fx.proxy.GraphAppendingTracer(self.graph)
proxy_args =... |
def get_mypyc_attrs(stmt: (ClassDef | Decorator)) -> dict[(str, Any)]:
attrs: dict[(str, Any)] = {}
for dec in stmt.decorators:
d = get_mypyc_attr_call(dec)
if d:
for (name, arg) in zip(d.arg_names, d.args):
if (name is None):
if isinstance(arg, St... |
class ParsedItem(dict):
def __init__(self, json_object, name, required, level):
super(ParsedItem, self).__init__()
self['name'] = name
self['title'] = json_object.get('title', '')
self['type'] = json_object.get('type')
self['description'] = json_object.get('description', '')
... |
class TestProcedure(Procedure):
iterations = IntegerParameter('Loop Iterations', default=100)
delay = FloatParameter('Delay Time', units='s', default=0.2)
seed = Parameter('Random Seed', default='12345')
DATA_COLUMNS = ['Iteration', 'Random Number']
def startup(self):
log.info('Setting up ra... |
class PrepareTFirstQuantizationWithProj(Bloq):
num_bits_p: int
num_bits_n: int
eta: int
num_bits_rot_aa: int = 8
adjoint: bool = False
_property
def signature(self) -> Signature:
return Signature.build(w=2, w_mean=2, r=self.num_bits_n, s=self.num_bits_n)
def build_call_graph(self... |
class Migration(migrations.Migration):
dependencies = [('schedule', '0005_scheduleitem_highlight_color')]
operations = [migrations.AlterField(model_name='scheduleitem', name='highlight_color', field=models.CharField(blank=True, choices=[('blue', 'blue'), ('yellow', 'yellow'), ('orange', 'orange'), ('cinderella'... |
def parse_test_result(lines: LineStream) -> TestResult:
consume_non_diagnostic(lines)
if ((not lines) or (not parse_tap_header(lines))):
return TestResult(TestStatus.FAILURE_TO_PARSE_TESTS, [], lines)
expected_test_suite_num = parse_test_plan(lines)
if (expected_test_suite_num == 0):
ret... |
class IWICBitmapEncoder(com.pIUnknown):
_methods_ = [('Initialize', com.STDMETHOD(IWICStream, WICBitmapEncoderCacheOption)), ('GetContainerFormat', com.STDMETHOD()), ('GetEncoderInfo', com.STDMETHOD()), ('SetColorContexts', com.STDMETHOD()), ('SetPalette', com.STDMETHOD()), ('SetThumbnail', com.STDMETHOD()), ('SetP... |
def range_len(slc):
from pytensor.tensor import and_, gt, lt, switch
(start, stop, step) = tuple((as_index_constant(a) for a in [slc.start, slc.stop, slc.step]))
return switch(and_(gt(step, 0), lt(start, stop)), (1 + (((stop - 1) - start) // step)), switch(and_(lt(step, 0), gt(start, stop)), (1 + (((start -... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
norm_func = (ll.FrozenBatchNorm2d if config.MODEL.FIXNORM else ll.BatchNorm2d)
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False... |
(eq=False, repr=False)
class MemoryReceiveChannel(ReceiveChannel[ReceiveType], metaclass=NoPublicConstructor):
_state: MemoryChannelState[ReceiveType] = attr.ib()
_closed: bool = attr.ib(default=False)
_tasks: set[trio._core._run.Task] = attr.ib(factory=set)
def __attrs_post_init__(self) -> None:
... |
def call_tox(toxenv: str, *args: str, python: pathlib.Path=pathlib.Path(sys.executable), debug: bool=False) -> None:
env = os.environ.copy()
env['PYTHON'] = str(python)
env['PATH'] = ((os.environ['PATH'] + os.pathsep) + str(python.parent))
if debug:
env['PYINSTALLER_DEBUG'] = '1'
subprocess.... |
def access_handler(args):
combine_secret_key()
selectors = get_selectors()
try:
db = get_db()
spec = {'$or': [{s.enc_mongo: {'$exists': True}} for s in selectors]}
printed_header = (not args.audit_trail)
for (keys, dct, tuples) in decrypt_iterator(db.clients.find(spec), ('_id... |
def cdelt_derivative(crval, cdelt, intype, outtype, linear=False, rest=None):
if (intype == outtype):
return cdelt
elif (set((outtype, intype)) == set(('length', 'frequency'))):
return (((- constants.c) / (crval ** 2)) * cdelt).to(PHYS_UNIT_DICT[outtype])
elif ((outtype in ('frequency', 'len... |
def compute_validation_result(args, best_metric, epoch):
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.FATAL)
logging.getLogger().setLevel(logging.INFO)
filter_keras_warnings()
tf.compat.v1.disable_eager_execution()
evaluation = create_evaluation(args, best_metric)
return ValidationRes... |
class TestElementBase(unittest.TestCase):
def test_remove_csrf_checks(self):
token = 'token'
e = pywebcopy.parsers.ElementBase('link')
e.set('href', '#')
e.set('crossorigin', token)
self.assertEqual(e.attrib.get('crossorigin'), token)
e.remove_csrf_checks()
se... |
.tf2
class TransformerQuantizationAcceptanceTests(unittest.TestCase):
def test_hf_bert_with_tokenizer(self):
tf.compat.v1.reset_default_graph()
tokenizer = BertTokenizer.from_pretrained('./data/huggingface/bert-base-uncased')
configuration = BertConfig(num_hidden_layers=1)
model = TF... |
class ViTFeatureExtractionTester(unittest.TestCase):
def __init__(self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=18, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5]):
self.parent = parent
self.batch_size... |
class CmdUnconnectedHelp(MuxCommand):
key = 'help'
aliases = ['h', '?']
locks = 'cmd:all()'
def func(self):
string = '\nYou are not yet logged into the game. Commands available at this point:\n |wcreate, connect, look, help, quit|n\n\nTo login to the system, you need to do one of the following:... |
class PreReleaseFilter(FilterReleasePlugin):
name = 'prerelease_release'
PRERELEASE_PATTERNS = ('.+rc\\d+$', '.+a(lpha)?\\d+$', '.+b(eta)?\\d+$', '.+dev\\d+$')
patterns: list[Pattern] = []
package_names: list[str] = []
def initialize_plugin(self) -> None:
if (not self.patterns):
... |
def get_example_reana_yaml_file_path(example, workflow_engine, compute_backend):
reana_yaml_filename = EXAMPLE_NON_STANDARD_REANA_YAML_FILENAME.get(example, {}).get(workflow_engine, {}).get(compute_backend, {})
if (not reana_yaml_filename):
reana_yaml_filename = 'reana{workflow_engine}{compute_backend}.... |
def main():
bench_name = os.environ['PYBENCH_NAME']
func = load_by_object_ref(os.environ['PYBENCH_ENTRYPOINT'])
params = json.loads(os.environ['PYBENCH_PARAMS'])
benchmark_plan = func(*params)
gc.collect()
runner = pyperf.Runner()
runner.bench_func(bench_name, benchmark_plan.func, *benchmark... |
class Datasets(Dataset):
def __init__(self, config, train=False):
if train:
self.data_dir = config.train_data_dir
(_, self.im_height, self.im_width) = config.image_dims
transforms_list = [transforms.RandomCrop((self.im_height, self.im_width)), transforms.ToTensor()]
... |
def freeze_except_bn(model):
for module in model.modules():
if isinstance(module, torch.nn.BatchNorm2d):
if hasattr(module, 'weight'):
module.weight.requires_grad_(True)
if hasattr(module, 'bias'):
module.bias.requires_grad_(True)
module.tr... |
def colorize_strings(l):
p = l.find("'")
if (p >= 0):
(yield l[:p])
l = l[(p + 1):]
p = l.find("'")
if (p >= 0):
(yield ((((CYA + "'") + subst_path(l[:p])) + "'") + RST))
for x in colorize_strings(l[(p + 1):]):
(yield x)
else:
... |
def cli_run():
print('\nFreesurfer QC module')
from visualqc.utils import run_common_utils_before_starting
run_common_utils_before_starting()
wf = make_workflow_from_user_options()
if (wf.vis_type is not None):
import matplotlib
matplotlib.interactive(True)
wf.run()
else:... |
def test_ResultBase_repr():
class TestResult(ResultABC):
_skcriteria_result_series = 'foo'
def _validate_result(self, values):
pass
method = 'test_method'
alternatives = ['a', 'b', 'c']
rank = [1, 2, 3]
extra = {'alfa': 1}
result = TestResult(method=method, alternativ... |
def detect_compute_compatibility(CUDA_HOME, so_file):
try:
cuobjdump = os.path.join(CUDA_HOME, 'bin', 'cuobjdump')
if os.path.isfile(cuobjdump):
output = subprocess.check_output("'{}' --list-elf '{}'".format(cuobjdump, so_file), shell=True)
output = output.decode('utf-8').str... |
class YieldFromCollector(FuncCollectorBase):
def __init__(self) -> None:
super().__init__()
self.in_assignment = False
self.yield_from_expressions: list[tuple[(YieldFromExpr, bool)]] = []
def visit_assignment_stmt(self, stmt: AssignmentStmt) -> None:
self.in_assignment = True
... |
def make_md(lst, method, split='train', image_size=126, **kwargs):
if (split == 'train'):
SPLIT = learning_spec.Split.TRAIN
elif (split == 'val'):
SPLIT = learning_spec.Split.VALID
elif (split == 'test'):
SPLIT = learning_spec.Split.TEST
ALL_DATASETS = lst
all_dataset_specs =... |
.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
.parametrize('loss_class', [BCConvexGIoULoss, ConvexGIoULoss, KLDRepPointsLoss])
def test_convex_regression_losses(loss_class):
pred = torch.rand((10, 18)).cuda()
target = torch.rand((10, 8)).cuda()
weight = torch.rand((10,)).cuda()
... |
.parametrize('filename,feedback_to_output', [('bol_eol.txt', False), ('characterclass.txt', False), ('dotstar.txt', False), ('extension_notation.txt', False), ('from_cmdloop.txt', True), ('multiline_no_regex.txt', False), ('multiline_regex.txt', False), ('no_output.txt', False), ('no_output_last.txt', False), ('regex_s... |
def default_setup(cfg, args):
output_dir = cfg.OUTPUT_DIR
if output_dir:
mkdir(output_dir)
rank = comm.get_rank()
logger = setup_logger(output_dir, rank, file_name='log_{}.txt'.format(cfg.START_TIME))
logger.info('Using {} GPUs'.format(args.num_gpus))
logger.info('Collecting environment ... |
def transform_func_def(builder: IRBuilder, fdef: FuncDef) -> None:
(func_ir, func_reg) = gen_func_item(builder, fdef, fdef.name, builder.mapper.fdef_to_sig(fdef))
if func_reg:
builder.assign(get_func_target(builder, fdef), func_reg, fdef.line)
maybe_insert_into_registry_dict(builder, fdef)
build... |
def make_optimizer(model: nn.Module) -> Optimizer:
if (configs.optimizer.name == 'sgd'):
optimizer = torch.optim.SGD(model.parameters(), lr=configs.optimizer.lr, momentum=configs.optimizer.momentum, weight_decay=configs.optimizer.weight_decay, nesterov=configs.optimizer.nesterov)
elif (configs.optimizer... |
class XWBOExchangeCalendar(TradingCalendar):
name = 'XWBO'
tz = timezone('Europe/Vienna')
open_times = ((None, time(9, 1)),)
close_times = ((None, time(17, 30)),)
def regular_holidays(self):
return HolidayCalendar([NewYearsDay, Epiphany, GoodFriday, EasterMonday, AscensionDay, WhitMonday, Co... |
(scope='module')
def venue():
return Venue(TestVenueBase.location, TestVenueBase.title, TestVenueBase.address, foursquare_id=TestVenueBase.foursquare_id, foursquare_type=TestVenueBase.foursquare_type, google_place_id=TestVenueBase.google_place_id, google_place_type=TestVenueBase.google_place_type) |
def sub_new():
if (len(sys.argv) < 3):
print('*** Error, missing argument.\n')
print(subcommands_help['new'])
return 1
session = sys.argv[2]
if (len(sys.argv) > 3):
playlist_file = sys.argv[3]
else:
playlist_file = None
fs.new_session(session, playlist_file)
... |
def extract_smis(library, smiles_col=0, title_line=True) -> List:
if (Path(library).suffix == '.gz'):
open_ = partial(gzip.open, mode='rt')
else:
open_ = open
with open_(library) as fid:
reader = csv.reader(fid)
if title_line:
next(reader)
smis = []
... |
class ToyDiscriminator(nn.Module):
def __init__(self):
super(ToyDiscriminator, self).__init__()
self.conv0 = nn.Conv2d(3, 4, 3, 1, 1, bias=True)
self.bn0 = nn.BatchNorm2d(4, affine=True)
self.conv1 = nn.Conv2d(4, 4, 3, 1, 1, bias=True)
self.bn1 = nn.BatchNorm2d(4, affine=True... |
def process_npy():
if (not os.path.exists(os.path.join(config.save_dir, 'npy'))):
os.makedirs(os.path.join(config.save_dir, 'npy'))
for tag in ['Tr', 'Va']:
img_ids = []
for path in tqdm(glob.glob(os.path.join(config.base_dir, f'images{tag}', '*.nii.gz'))):
print(path)
... |
class Proxy(BaseType):
def __init__(self, *, none_ok: bool=False, completions: _Completions=None) -> None:
super().__init__(none_ok=none_ok, completions=completions)
self.valid_values = ValidValues(('system', 'Use the system wide proxy.'), ('none', "Don't use any proxy"), others_permitted=True)
... |
class CertificateSigningRequestBuilder():
def __init__(self, subject_name: (Name | None)=None, extensions: list[Extension[ExtensionType]]=[], attributes: list[tuple[(ObjectIdentifier, bytes, (int | None))]]=[]):
self._subject_name = subject_name
self._extensions = extensions
self._attributes... |
class LogHandler(Handler):
class Emitter(QtCore.QObject):
record = QtCore.Signal(object)
def __init__(self):
super().__init__()
self.emitter = self.Emitter()
def connect(self, *args, **kwargs):
return self.emitter.record.connect(*args, **kwargs)
def emit(self, record):
... |
def test_no_ub_terms_default(methanol):
assert (methanol.UreyBradleyForce.n_parameters == 0)
ff = methanol._build_forcefield().getroot()
force = ff.find('AmoebaUreyBradleyForce')
assert (force is None)
for angle in methanol.angles:
methanol.UreyBradleyForce.create_parameter(angle, k=1, d=2)
... |
class ResidualAttentionNet_56(nn.Module):
def __init__(self, feature_dim=512, drop_ratio=0.4):
super(ResidualAttentionNet_56, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True))
self.mpool1 =... |
class Dereferer(SimpleDecrypter):
__name__ = 'Dereferer'
__type__ = 'decrypter'
__version__ = '0.27'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('folder_per_package', 'Default;Yes... |
def readFile(handle, firstBytesOnly=False):
logging.debug('Getting data on given handle (firstBytesOnly == {0})'.format(firstBytesOnly))
BUFSIZE = 5242880
data = b''
buf = create_string_buffer(BUFSIZE)
bytesRead = c_uint()
while True:
retVal = ReadFile(handle, byref(buf), sizeof(buf), by... |
class TestRandomAccessIntVectorVectorReader(_TestRandomAccessReaders, unittest.TestCase, IntVectorVectorExampleMixin):
def checkRead(self, reader):
self.assertEqual([[1]], reader['one'])
self.assertEqual([], reader['three'])
self.assertEqual([[1, 2], [3, 4]], reader['two'])
with self... |
.parametrize('file', ['CEUTrio.20.21.gatk3.4.g.vcf.bgz', 'CEUTrio.20.21.gatk3.4.g.vcf.bgz.tbi'])
.parametrize('is_path', [True, False])
def test_read_csi__invalid_csi(shared_datadir, file, is_path):
with pytest.raises(ValueError, match='File not in CSI format.'):
read_csi(path_for_test(shared_datadir, file,... |
.parametrize('key', FUNCTION_METHODS)
def test_given_function_set_then_autorange_enabled(resetted_dmm6500, key):
if (key[(- 2):] == 'ac'):
getattr(resetted_dmm6500, FUNCTION_METHODS[key])(ac=True)
elif (key[(- 2):] == '4W'):
getattr(resetted_dmm6500, FUNCTION_METHODS[key])(wires=4)
else:
... |
def test_feature_no_src_layout(hatch, helpers, config_file, temp_dir):
config_file.model.template.plugins['default']['src-layout'] = False
config_file.save()
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', project_name)
path = (temp_dir / 'my-app')
expected_files = ... |
class CustomColorizationTrain(CustomBase):
def __init__(self, size, test_images_list_file):
super().__init__()
with open(test_images_list_file, 'r') as f:
paths = f.read().splitlines()
self.data = ColorizationImagePaths(paths=paths, size=size, random_crop=False) |
_metaclass(ABCMeta)
class RepositoryDataInterface(object):
def get_repo(self, namespace_name, repository_name, user, include_tags=True, max_tags=500):
def repo_exists(self, namespace_name, repository_name):
def create_repo(self, namespace, name, creating_user, description, visibility='private', repo_kind='i... |
class Color(BaseOption):
def validate(self, value, **kwargs):
return validatorfuncs.color(value, option_key=self.key, **kwargs)
def display(self, **kwargs):
return f'{self.value} - |{self.value}this|n'
def deserialize(self, save_data):
if ((not save_data) or (len(strip_ansi(f'|{save_... |
def get_model(p):
if ('VOCSegmentation' in p['train_db_name']):
if (('use_fcn' in p['model_kwargs']) and p['model_kwargs']['use_fcn']):
print('Using FCN for PASCAL')
from models.fcn_model import Model
return Model(get_backbone(p), (p['num_classes'] + int(p['has_bg'])))
... |
class TestPEP673(TestNameCheckVisitorBase):
_passes()
def test_instance_attribute(self):
from typing_extensions import Self
class X():
parent: Self
def prop(self) -> Self:
raise NotImplementedError
class Y(X):
pass
def capybara(... |
def test_simple_while_no_else() -> None:
src = '\n while n > 10:\n print(n)\n '
cfg = build_cfg(src)
expected_blocks = [['n > 10'], ['print(n)'], []]
assert (expected_blocks == _extract_blocks(cfg))
expected_edges = [[['n > 10'], ['print(n)']], [['print(n)'], ['n > 10']], [['n > 10'], [... |
class TestCloneReplace():
def test_cloning_no_replace_strict_copy_inputs(self):
x = vector('x')
y = vector('y')
z = shared(0.25)
f1 = ((z * ((x + y) ** 2)) + 5)
f2 = clone_replace(f1, replace=None, rebuild_strict=True, copy_inputs_over=True)
f2_inp = graph_inputs([f2]... |
class CocoaDisplay(Display):
def get_screens(self):
maxDisplays = 256
activeDisplays = (CGDirectDisplayID * maxDisplays)()
count = c_uint32()
quartz.CGGetActiveDisplayList(maxDisplays, activeDisplays, byref(count))
return [CocoaScreen(self, displayID) for displayID in list(ac... |
class ModFile(AudioFile):
format = 'MOD/XM/IT'
def __init__(self, filename):
with translate_errors():
data = open(filename, 'rb').read()
f = _modplug.ModPlug_Load(data, len(data))
if (not f):
raise OSError(('%r not a valid MOD file' % filename))
... |
class GroupBoardListManager(CRUDMixin, RESTManager):
_path = '/groups/{group_id}/boards/{board_id}/lists'
_obj_cls = GroupBoardList
_from_parent_attrs = {'group_id': 'group_id', 'board_id': 'id'}
_create_attrs = RequiredOptional(exclusive=('label_id', 'assignee_id', 'milestone_id'))
_update_attrs = ... |
def mat2euler(M, cy_thresh=None):
M = np.asarray(M)
if (cy_thresh is None):
try:
cy_thresh = (np.finfo(M.dtype).eps * 4)
except ValueError:
cy_thresh = _FLOAT_EPS_4
(r11, r12, r13, r21, r22, r23, r31, r32, r33) = M.flat
cy = math.sqrt(((r33 * r33) + (r23 * r23)))
... |
class TokenClassificationArgumentHandler(ArgumentHandler):
def __call__(self, inputs: Union[(str, List[str])], **kwargs):
if ((inputs is not None) and isinstance(inputs, (list, tuple)) and (len(inputs) > 0)):
inputs = list(inputs)
batch_size = len(inputs)
elif isinstance(inpu... |
class PeptidesFunctionalDataset(InMemoryDataset):
def __init__(self, root='datasets', smiles2graph=smiles2graph, transform=None, pre_transform=None):
self.original_root = root
self.smiles2graph = smiles2graph
self.folder = osp.join(root, 'peptides-functional')
self.url = '
se... |
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {'question': question, 'error_message': "You di... |
def _date_range_in_single_index(dt1, dt2):
assert (isinstance(dt1, date) and isinstance(dt2, date))
dt = (dt2 - dt1)
if ((not isinstance(dt1, datetime)) and (not isinstance(dt2, datetime))):
return (dt == timedelta(days=1))
if ((dt < timedelta(days=1)) and (dt >= timedelta(days=0))):
ret... |
class TestDataloaderAsyncGPUWrapper(unittest.TestCase):
(torch.cuda.is_available(), 'This test needs a gpu to run')
def test_dataset_async(self):
NUM_SAMPLES = 1024
dataset = ZeroImageDataset(crop_size=224, num_channels=3, num_classes=1000, num_samples=NUM_SAMPLES)
base_dataloader = Data... |
class Trainer(Base):
def __init__(self, cfg):
self.cfg = cfg
super(Trainer, self).__init__(cfg.log_dir, log_name='train_logs.txt')
def get_optimizer(self, model):
base_params = list(map(id, model.module.backbone.parameters()))
other_params = filter((lambda p: (id(p) not in base_p... |
def get_global(key: _GLOBAL_KEY) -> Mapping[(str, Any)]:
global _global_data
if (_global_data is None):
dirname = os.path.join(os.path.dirname(__file__))
filename = os.path.join(dirname, 'global.dat')
if (not os.path.isfile(filename)):
_raise_no_data_error()
with open... |
class InspectCommand(BaseGraphCommand):
handler = staticmethod(bonobo.inspect)
def add_arguments(self, parser):
super(InspectCommand, self).add_arguments(parser)
parser.add_argument('--graph', '-g', dest='format', action='store_const', const='graph')
def parse_options(self, **options):
... |
class L1Loss(nn.Module):
def __init__(self, args):
super(L1Loss, self).__init__()
self.args = args
self.loss = L1()
self.loss_labels = ['L1', 'EPE']
def forward(self, output, target):
lossvalue = self.loss(output, target)
epevalue = EPE(output, target)
ret... |
class CUDACallback(Callback):
def on_train_epoch_start(self, trainer, pl_module):
torch.cuda.reset_peak_memory_stats(trainer.root_gpu)
torch.cuda.synchronize(trainer.root_gpu)
self.start_time = time.time()
def on_train_epoch_end(self, trainer, pl_module):
torch.cuda.synchronize(t... |
def noisy_dense(inputs, units, bias_shape, c_names, w_i, b_i=None, activation=tf.nn.relu, noisy_distribution='factorised'):
def f(e_list):
return tf.multiply(tf.sign(e_list), tf.pow(tf.abs(e_list), 0.5))
if (not isinstance(inputs, ops.Tensor)):
inputs = ops.convert_to_tensor(inputs, dtype='float... |
class RuncodeWizardPage1(BasePyzoWizardPage):
_title = translate('wizard', 'Running code')
_image_filename = 'pyzo_run1.png'
_descriptions = [translate('wizard', "Pyzo supports several ways to run source code in the editor. (see the 'Run' menu)."), translate('wizard', '*Run selection:* if there is no select... |
def _try_get_string(dev, index, langid=None, default_str_i0='', default_access_error='Error Accessing String'):
if (index == 0):
string = default_str_i0
else:
try:
if (langid is None):
string = util.get_string(dev, index)
else:
string = uti... |
def get_egress_cmd(execution, test_interface, mod, vallst, duration=30):
tc_set = tc_unset = tc_ls = ''
param_map = {'latency': 'delay', 'loss': 'loss', 'bandwidth': 'rate'}
for i in test_interface:
tc_set = '{0} tc qdisc add dev {1} root netem'.format(tc_set, i)
tc_unset = '{0} tc qdisc del... |
class TestEntityCrawler():
def test_crawl_wiki_entity(self):
url = '
res = entity.crawl_wiki_entity(url, label=Label['PERSON'])
assert isinstance(res, Entity)
def test_crawl_wiki_entity_urls(self):
category_url = '
urls = [url for url in entity.crawl_wiki_entity_urls(cate... |
def get_f1(model: BiRecurrentConvCRF4NestedNER, mode: str, file_path: str=None) -> float:
with torch.no_grad():
model.eval()
(pred_all, pred, recall_all, recall) = (0, 0, 0, 0)
gold_cross_num = 0
pred_cross_num = 0
if (mode == 'dev'):
batch_zip = zip(dev_token_bat... |
class VanLargeKernelAttention(nn.Module):
def __init__(self, hidden_size: int):
super().__init__()
self.depth_wise = nn.Conv2d(hidden_size, hidden_size, kernel_size=5, padding=2, groups=hidden_size)
self.depth_wise_dilated = nn.Conv2d(hidden_size, hidden_size, kernel_size=7, dilation=3, padd... |
class PluginConfigMixin():
CONFIG_SECTION = ''
def _config_key(cls, name):
return cls._get_config_option(name)
def _get_config_option(cls, option):
prefix = cls.CONFIG_SECTION
if (not prefix):
prefix = cls.PLUGIN_ID.lower().replace(' ', '_')
return f'{prefix}_{opt... |
def download_manifest_entry(manifest_entry: ManifestEntry, token_holder: Optional[Dict[(str, Any)]]=None, table_type: TableType=TableType.PYARROW, column_names: Optional[List[str]]=None, include_columns: Optional[List[str]]=None, file_reader_kwargs_provider: Optional[ReadKwargsProvider]=None, content_type: Optional[Con... |
class DistributedGPUTest(unittest.TestCase):
_if_not_gpu
_if_not_distributed
def test_gather_uneven_multidim_nccl(self) -> None:
spawn_multi_process(2, 'nccl', self._test_ddp_gather_uneven_tensors_multidim_nccl)
def _test_ddp_gather_uneven_tensors_multidim_nccl() -> None:
rank = dist.get... |
_type_check
def decrypt(secret, hash, data):
if (not CRYPTO_INSTALLED):
raise RuntimeError('To use Telegram Passports, PTB must be installed via `pip install "python-telegram-bot[passport]"`.')
digest = Hash(SHA512(), backend=default_backend())
digest.update((secret + hash))
secret_hash_hash = d... |
class XBKKExchangeCalendar(TradingCalendar):
name = 'XBKK'
tz = timezone('Asia/Bangkok')
open_times = ((None, time(10, 1)),)
close_times = ((None, time(16, 30)),)
def regular_holidays(self):
return HolidayCalendar([NewYearsDay, ChakriMemorialDay, SongkranFestival1, SongkranFestival2, Songkra... |
def listify_value(arg, split=None):
out = []
if (not isinstance(arg, (list, tuple))):
arg = [arg]
for val in arg:
if (val is None):
continue
if isinstance(val, (list, tuple)):
out.extend(listify_value(val, split=split))
continue
out.extend(... |
def test_unused_tcp_port_factory_selects_unused_port(pytester: Pytester):
pytester.makepyfile(dedent(' .asyncio\n async def test_unused_port_factory_fixture(unused_tcp_port_factory):\n async def closer(_, writer):\n writer.close()\n\n port1, por... |
def read_nonterminals(filename):
ans = [line.strip(' \t\r\n') for line in open(filename, 'r', encoding='latin-1')]
if (len(ans) == 0):
raise RuntimeError('The file {0} contains no nonterminals symbols.'.format(filename))
for nonterm in ans:
if (nonterm[:9] != '#nonterm:'):
raise ... |
def base_js():
base_js_files = []
for file in ['base.js-2022-02-04.gz', 'base.js-2022-04-15.gz']:
file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mocks', file)
with gzip.open(file_path, 'rb') as f:
base_js_files.append(f.read().decode('utf-8'))
return base_... |
class ComponentPascalLexer(RegexLexer):
name = 'Component Pascal'
aliases = ['componentpascal', 'cp']
filenames = ['*.cp', '*.cps']
mimetypes = ['text/x-component-pascal']
url = '
version_added = '2.1'
flags = (re.MULTILINE | re.DOTALL)
tokens = {'root': [include('whitespace'), include('... |
class BaseEvent():
def __init__(self, client):
self.client = client
self.logger = logging.getLogger(__name__)
def to_string(self, data):
raise NotImplementedError
def capture(self, **kwargs):
return {}
def transform(self, value):
return self.client.transform(value... |
class VariationalGPModel(gpytorch.models.ApproximateGP):
def __init__(self, inducing_points, mean_module=None, covar_module=None, streaming=False, likelihood=None, feat_extractor=None, beta=1.0, learn_inducing_locations=True):
data_dim = ((- 2) if (inducing_points.dim() > 1) else (- 1))
variational_... |
class ForwardTafel(BaseKinetics):
def __init__(self, param, domain, reaction, options, phase='primary'):
super().__init__(param, domain, reaction, options, phase)
def _get_kinetics(self, j0, ne, eta_r, T, u):
alpha = self.phase_param.alpha_bv
Feta_RT = ((self.param.F * eta_r) / (self.par... |
def extract_warnings_from_single_artifact(artifact_path, targets):
selected_warnings = set()
buffer = []
def parse_line(fp):
for line in fp:
if isinstance(line, bytes):
line = line.decode('UTF-8')
if ('warnings summary (final)' in line):
contin... |
class AdaptiveAvgMaxPool2d(nn.Module):
def __init__(self):
super(AdaptiveAvgMaxPool2d, self).__init__()
self.gap = FastGlobalAvgPool2d()
self.gmp = nn.AdaptiveMaxPool2d(1)
def forward(self, x):
avg_feat = self.gap(x)
max_feat = self.gmp(x)
feat = (avg_feat + max_f... |
def _weights_init(m):
if isinstance(m, nn.Conv2d):
torch.nn.init.xavier_uniform_(m.weight)
if (m.bias is not None):
torch.nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.