code stringlengths 281 23.7M |
|---|
def xtype_from_derivation(derivation: str) -> str:
bip32_indices = convert_bip32_strpath_to_intpath(derivation)
if (len(bip32_indices) >= 1):
if (bip32_indices[0] == (84 + BIP32_PRIME)):
return 'p2wpkh'
elif (bip32_indices[0] == (49 + BIP32_PRIME)):
return 'p2wpkh-p2sh'
... |
class SEResNeXtUnit(nn.Module):
def __init__(self, in_channels, out_channels, stride, cardinality, bottleneck_width):
super(SEResNeXtUnit, self).__init__()
self.resize_identity = ((in_channels != out_channels) or (stride != 1))
self.body = ResNeXtBottleneck(in_channels=in_channels, out_chann... |
class UpBlock2D(nn.Module):
def __init__(self, in_channels: int, prev_output_channel: int, out_channels: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_groups: int=32, resnet_pre_norm: bool=True, out... |
(config_path='config', config_name='train_tracking_default')
def main(cfg: DictConfig) -> None:
print(os.getcwd())
os.mkdir('checkpoints')
datamodule = SparseUnet3DTrackingDataModule2(**cfg.datamodule)
batch_size = datamodule.kwargs['batch_size']
pipeline_model = GarmentTrackingPipeline(batch_size=b... |
def save_config_file_for_per_channel_quantization():
quantsim_config = {'defaults': {'ops': {'is_output_quantized': 'True', 'is_symmetric': 'False'}, 'params': {'is_quantized': 'True', 'is_symmetric': 'True'}, 'per_channel_quantization': 'True'}, 'params': {'bias': {'is_quantized': 'False'}}, 'op_type': {}, 'superg... |
def require_files(*name_patterns: str) -> None:
cwd = Path.cwd()
matches = 0
for pattern in name_patterns:
if list(cwd.glob(pattern)):
matches += 1
if (matches == len(name_patterns)):
return
frame = inspect.currentframe()
if (not frame):
raise Exception('workf... |
def _induce_cliques(adjtable, clique_to_members, fill_value=1):
adj_across_clique = adjtable.merge(clique_to_members['input_index'], left_on='focal', right_index=True).explode('input_index').rename(columns={'input_index': 'subclique_focal'}).merge(clique_to_members['input_index'], left_on='neighbor', right_index=Tr... |
def call_func(t):
import numpy as N
import random
N.random.seed(random.randint(0, ))
if ('func' in t):
assert ('module' not in t)
assert ('method' not in t)
func = t['func']
else:
modu = importlib.import_module(t['module'])
func = getattr(modu, t['method'])
... |
class Configure(object):
def get_file_cfg(file):
cfgargs = Args()
parser = configparser.ConfigParser()
parser.read(file)
for section in parser.sections():
setattr(cfgargs, section, Args())
for item in parser.items(section):
setattr(getattr(cfga... |
def _get_via_file_cache(cls, app_data, path, exe, env):
path_text = str(path)
try:
path_modified = path.stat().st_mtime
except OSError:
path_modified = (- 1)
if (app_data is None):
app_data = AppDataDisabled()
(py_info, py_info_store) = (None, app_data.py_info(path))
with... |
class Pool(base.Pool):
def __init__(self, url, loop, init=None, bakery=None, prebake=True, **kwargs):
self._url = url
self._loop = loop
self._kwargs = kwargs
self._pool = None
self._conn_init = init
self._bakery = bakery
self._prebake = prebake
async def _... |
class TestExcitationPreserving(QiskitNatureTestCase):
def setUp(self):
super().setUp()
self.seed = 50
algorithm_globals.random_seed = self.seed
self.reference_energy = (- 1.)
_test
((not _optionals.HAS_PYSCF), 'pyscf not available.')
def test_excitation_preserving(self):
... |
class QlLoaderPE_UEFI(QlLoader):
def __init__(self, ql: Qiling):
super().__init__(ql)
self.ql = ql
self.modules = []
self.events = {}
self.notify_list = []
self.dxe_context: DxeContext
self.smm_context: SmmContext
self.context: UefiContext
__save_m... |
def test_attrs(fake_manager):
obj = helpers.FakeObject(fake_manager, {'foo': 'bar'})
assert ('bar' == obj.foo)
with pytest.raises(AttributeError):
getattr(obj, 'bar')
obj.bar = 'baz'
assert ('baz' == obj.bar)
assert ({'foo': 'bar'} == obj._attrs)
assert ({'bar': 'baz'} == obj._update... |
def set_literal_values(builder: IRBuilder, items: Sequence[Expression]) -> (list[object] | None):
values: list[object] = []
for item in items:
const_value = constant_fold_expr(builder, item)
if (const_value is not None):
values.append(const_value)
continue
if isin... |
def create_COCO_img_mask(data):
(img_id, dst_img_dir, dst_mask_dir) = data
img_info = coco.loadImgs(img_id)[0]
h = img_info['height']
w = img_info['width']
mask_all = np.zeros((h, w), np.uint8)
anno_ids = coco.getAnnIds(imgIds=img_info['id'])
anno_list = coco.loadAnns(anno_ids)
obj_cnt =... |
def build_from_path(in_dir, out_dir):
index = 1
texts = []
with open(os.path.join(in_dir, 'metadata.csv'), encoding='utf-8') as f:
for line in f.readlines():
if ((index % 100) == 0):
print('{:d} Done'.format(index))
parts = line.strip().split('|')
... |
def test_get_current_tag_with_single_existing_tag(initialized_db):
repo = model.repository.create_repository('devtable', 'newrepo', None)
(manifest, _) = create_manifest_for_testing(repo, '1')
t = manifest.tag_set.get()
tag = get_current_tag(repo.id, t.name)
assert (tag.id == t.id) |
.parametrize('token_lifetime, time_since', [('1m', '2m'), ('2m', '1m'), ('1h', '1m')])
def test_validation_code(token_lifetime, time_since, initialized_db):
user = create_user_noverify('foobar', '', email_required=False)
created = (datetime.now() - convert_to_timedelta(time_since))
(verification_code, unhas... |
_fixtures(WebFixture, InputGroupFixture)
def test_input_group(web_fixture, input_group_fixture):
fixture = input_group_fixture
tester = WidgetTester(fixture.input_group)
[outer_div] = tester.xpath('//div')
assert (outer_div.attrib['class'] == 'has-validation input-group')
if fixture.expects_before_h... |
_REGISTRY.register()
def build_p37_fcos_dla_bifpn_backbone(cfg, input_shape: ShapeSpec):
bottom_up = dla34(cfg)
in_features = cfg.MODEL.FPN.IN_FEATURES
out_channels = cfg.MODEL.BIFPN.OUT_CHANNELS
num_repeats = cfg.MODEL.BIFPN.NUM_BIFPN
assert (cfg.MODEL.BIFPN.NUM_LEVELS == 5)
top_levels = 2
... |
def main(argv):
global LOG
LOG = file(WRAPPER_LOG, 'a+')
if LOG_OPTIONS['argv']:
((print >> LOG), ' '.join(argv))
(flags, argv) = make_flags(argv)
new_argv = compiler_argv(flags, argv)
start_time = time.time()
ret = subprocess.call(new_argv)
end_time = time.time()
if LOG_OPTI... |
('pypyr.steps.filewrite.Path')
def test_filewrite_pass_with_non_string_substitutions(mock_path):
context = Context({'k1': 'v1', 'p': '/arb/path', 'intkey': 123, 'is_bin': False, 'is_append': 0, 'fileWrite': {'path': '{p}', 'payload': '{intkey}', 'binary': '{is_bin}', 'append': '{is_append}'}})
with io.StringIO(... |
def rename_key(orig_key):
if ('model' in orig_key):
orig_key = orig_key.replace('model.', '')
if ('norm1' in orig_key):
orig_key = orig_key.replace('norm1', 'attention.output.LayerNorm')
if ('norm2' in orig_key):
orig_key = orig_key.replace('norm2', 'output.LayerNorm')
if ('norm'... |
.parametrize('numeric_type_funcs', _calcparams_correct_Python_type_numeric_type_cases())
def test_calcparams_desoto_returns_correct_Python_type(numeric_type_funcs, cec_module_params):
numeric_args = dict(effective_irradiance=numeric_type_funcs[0](800.0), temp_cell=numeric_type_funcs[1](25))
out = pvsystem.calcp... |
def load_args(filename):
with open(filename, 'r') as f:
args = json.load(f)
if ('data_distribution' not in args):
args['data_distribution'] = None
(probl, *dist) = args['problem'].split('_')
if (probl == 'op'):
args['problem'] = probl
args['data_distributi... |
class TargetProfileNameValidator(BaseValidator):
def __init__(self):
BaseValidator.__init__(self)
def Clone(self):
return TargetProfileNameValidator()
def Validate(self, win):
entityEditor = win.Parent.parent
textCtrl = self.GetWindow()
text = textCtrl.GetValue().stri... |
def batch_sample_anchors(node_vec, ratio, node_mask=None, device=None):
idx = []
num_anchors = []
max_num_anchors = 0
for i in range(node_vec.size(0)):
tmp_num_nodes = int(node_mask[i].sum().item())
tmp_num_anchors = int((ratio * tmp_num_nodes))
g_idx = torch.randperm(tmp_num_nod... |
_cache()
def setup_logger(output=None, distributed_rank=0, *, color=True, name='log', abbrev_name=None):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.propagate = False
if (abbrev_name is None):
abbrev_name = name
plain_formatter = logging.Formatter('[%(asctime)s] %(... |
def make_valid_identifier(string: str) -> str:
string = str(string).strip()
string = string.replace('-', '_')
string = string.replace(' ', '_')
string = re.sub('[^_a-zA-Z0-9]', '', string)
string = string.lower()
if is_valid_identifier(string):
return string
raise InvalidIdentifier('... |
class SetInitialGoal():
def __init__(self, obj_position, class_name_size, init_pool_tasks, task_name, same_room=True, goal_template=None, rand=None):
self.task_name = task_name
self.init_pool_tasks = init_pool_tasks
self.obj_position = obj_position
self.class_name_size = class_name_s... |
class TestSolve():
def op_numpy(self, A, b):
return np.linalg.solve(A, b)
def _gen_op(self, N, dtype):
return qutip.rand_unitary(N, dtype=dtype).data
def _gen_ket(self, N, dtype):
return qutip.rand_ket(N, dtype=dtype).data
.parametrize(['method', 'opt'], [('spsolve', {}), ('splu'... |
class RegWalk(Task):
def __init__(self, file):
Task.__init__(self, file, 'RegistryWalk')
def CreateCommandLine(self):
key = ''
self.RootKey = self.RootKey.strip('"')
if (self.RootKey == 'HKEY_LOCAL_MACHINE'):
key = 'L'
elif (self.RootKey == 'HKEY_USERS'):
... |
class up_conv(nn.Module):
def __init__(self, ch_in, ch_out):
super(up_conv, self).__init__()
self.up = nn.Sequential(nn.Upsample(scale_factor=2), nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1, bias=True), nn.BatchNorm2d(ch_out), nn.ReLU(inplace=True))
def forward(self, x):
... |
class DuplicatesTreeModel(Gtk.TreeStore):
def i(x):
return x
TAG_MAP = [('artist', i), ('title', i), ('album', i), ('~#length', (lambda s: util.format_time_display(int(s)))), ('~#filesize', (lambda s: util.format_size(int(s)))), ('~#bitrate', i), ('~filename', i)]
tag_functions = {}
for (t, f) i... |
class TestFastLayerNorm(unittest.TestCase):
def assertAll(self, l):
if (not all(l)):
print(l)
for x in l:
self.assertTrue(x)
def test_all_configs(self):
hidden_sizes = [768, 1024, 1536, 2048, 2304, 3072, 3840, 4096, 5120, 6144, 8192, 10240, 12288, 12800, 15360, 16... |
def initialize_config(root, cli_opts, scaling_factor, pathcache, statusbar, session):
global _CONFIG
if (_CONFIG is not None):
return
logger.debug('Initializing config: (root: %s, cli_opts: %s, tk_vars: %s, pathcache: %s, statusbar: %s, session: %s)', root, cli_opts, scaling_factor, pathcache, statu... |
def rb_cnotdihedral_execution(rb_opts: dict, shots: int):
backend = qiskit.Aer.get_backend('qasm_simulator')
basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']
(rb_cnotdihedral_z_circs, xdata, rb_cnotdihedral_x_circs) = rb.randomized_benchmarking_seq(**rb_opts)
noise_model = create_depolarizing_noise_model()
... |
class L2Norm(Func):
def __init__(self, mult=1.0):
self.mult = mult
def _eval(self, x):
return (self.mult * euclid_norm(x))
def _prox(self, x, step):
return L2_prox(x=x, mult=(self.mult * step))
def is_smooth(self):
return False
def is_proximable(self):
return ... |
class Style():
def __init__(self, style: Dict[(str, str)]=None, css_class: str=None):
self.style = (style if (style is not None) else dict())
self.css_class = (css_class.split() if (css_class is not None) else [])
self.logger = qf_logger.getChild(self.__class__.__name__)
def add_css_clas... |
def argparser():
parser = argparse.ArgumentParser(description='Ape-X')
parser.add_argument('--seed', type=int, default=1122, help='Random seed')
parser.add_argument('--n_steps', type=int, default=3, help='Number of steps in multi-step learning')
parser.add_argument('--gamma', type=float, default=0.99, h... |
def create_terminal_writer(config: Config, file: Optional[TextIO]=None) -> TerminalWriter:
tw = TerminalWriter(file=file)
if (config.option.color == 'yes'):
tw.hasmarkup = True
elif (config.option.color == 'no'):
tw.hasmarkup = False
if (config.option.code_highlight == 'yes'):
tw... |
def data_for_url(url: QUrl) -> Tuple[(str, bytes)]:
norm_url = url.adjusted((QUrl.UrlFormattingOption.NormalizePathSegments | QUrl.UrlFormattingOption.StripTrailingSlash))
if (norm_url != url):
raise Redirect(norm_url)
path = url.path()
host = url.host()
query = url.query()
log.misc.debu... |
def spectral_normed_weight(W, u=None, num_iters=1, update_collection=None, with_sigma=False):
W_shape = W.shape.as_list()
W_reshaped = tf.reshape(W, [(- 1), W_shape[(- 1)]])
if (u is None):
u = tf.get_variable('u', [1, W_shape[(- 1)]], initializer=tf.truncated_normal_initializer(), trainable=False)
... |
def view_route(f):
def decorator(*args, **kwargs):
rv = f(*args, **kwargs)
if isinstance(rv, (int, float)):
res = ResMsg()
res.update(data=rv)
return jsonify(res.data)
elif isinstance(rv, tuple):
if (len(rv) >= 3):
return (jsoni... |
class ValidEpoch(Epoch):
def __init__(self, model, loss, metrics, device='cpu', verbose=True):
super().__init__(model=model, loss=loss, metrics=metrics, stage_name='valid', device=device, verbose=verbose)
def on_epoch_start(self):
self.model.eval()
def batch_update(self, x, y):
with ... |
.parametrize('line', ['text/plain', 'text/markdown', 'text/csv', 'text/rtf', 'text/javascript', 'text/html', 'text/xml'])
def test_validate_content_type_invalid(line: str):
warnings = [warning for (_, warning) in check_peps._validate_content_type(1, line)]
assert (warnings == ["Content-Type must be 'text/x-rst'... |
def test_drop_event(tmpdir, qtbot):
output_dir = str(tmpdir.mkdir('tmpdir'))
filename = str(os.path.join(output_dir, 'tmp.vtk'))
mesh = pyvista.Cone()
mesh.save(filename)
assert os.path.isfile(filename)
plotter = BackgroundPlotter(update_app_icon=False)
with qtbot.wait_exposed(plotter.app_wi... |
def main():
parser = argparse.ArgumentParser(description='Read and write COLMAP binary and text models')
parser.add_argument('input_model', help='path to input model folder')
parser.add_argument('input_format', choices=['.bin', '.txt'], help='input model format')
parser.add_argument('--output_model', me... |
def binary_search(level, cand, low, high):
if (low > high):
return (- 1)
while (low <= high):
mid = int(((low + high) / 2))
if (cand == freArr[(level - 1)][mid][0:(level - 1)]):
s_low = low
s_high = mid
if (cand == freArr[(level - 1)][low][0:(level - 1... |
_ordering
class Parse(entity):
str2int = {'w': '1', 's': '2'}
def __init__(self, meter, totalSlots):
self.positions = []
self.meter = meter
self.constraints = meter.constraints
self.constraintScores = {}
for constraint in self.constraints:
self.constraintScore... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = conv3x3(planes, planes)
self.bn2 = ... |
def test_upload(requests_mock):
requests_mock.post(f'{API_V1}/observation_photos', json=SAMPLE_DATA['post_observation_photos'], status_code=200)
requests_mock.post(f'{API_V1}/observation_sounds', json=SAMPLE_DATA['post_observation_sounds'], status_code=200)
response = upload(1234, BytesIO(), BytesIO(), acce... |
def test_scenarios(testdir):
p = testdir.makepyfile('\n from reahl.tofu import Fixture, scenario\n from reahl.tofu.pytestsupport import with_fixtures\n class Scenarios(Fixture):\n \n def one(self):\n self.n = 1\n \n def two(self):\n self.n = 2\n\n Scenar... |
('iM_product_vect_jvp_translation')
def _iM_product_vect_jvp_translation(c, q, vect, q_tan, vect_tan):
(type_in, size_xla, dims_spec) = check_dim_imputs((q, vect, q_tan, vect_tan), c)
op_name = (b'iM_prod_vect_jvp_wrapper_f32' if (type_in == np.float32) else b'iM_prod_vect_jvp_wrapper_f64')
return xops.Cust... |
class TestWeightedAverageControlCurve():
def test_constant(self, three_storage_model):
m = three_storage_model
m.nodes['Storage 0'].max_volume = 16.0
curve0 = ConstantParameter(three_storage_model, 0.25)
curve1 = ConstantParameter(three_storage_model, 0.7)
storages = [m.nodes... |
def _update_config_from_file(config, cfg_file):
config.defrost()
with open(cfg_file, 'r') as f:
yaml_cfg = yaml.load(f, Loader=yaml.FullLoader)
for cfg in yaml_cfg.setdefault('BASE', ['']):
if cfg:
_update_config_from_file(config, os.path.join(os.path.dirname(cfg_file), cfg))
... |
def _query_attribute(program_id: int, index: int):
asize = GLint()
atype = GLenum()
buf_size = 192
aname = create_string_buffer(buf_size)
try:
glGetActiveAttrib(program_id, index, buf_size, None, asize, atype, aname)
return (aname.value.decode(), atype.value, asize.value)
except ... |
class SelecSLSBlock(nn.Module):
def __init__(self, in_chs, skip_chs, mid_chs, out_chs, is_first, stride, dilation=1):
super(SelecSLSBlock, self).__init__()
self.stride = stride
self.is_first = is_first
assert (stride in [1, 2])
self.conv1 = conv_bn(in_chs, mid_chs, 3, stride,... |
.parametrize(('name', 'expected'), [('foo', 'foo'), ('Foo', 'foo'), ('fOo', 'foo'), ('foo.bar', 'foo-bar'), ('Foo.Bar', 'foo-bar'), ('Foo.....Bar', 'foo-bar'), ('foo_bar', 'foo-bar'), ('foo___bar', 'foo-bar'), ('foo-bar', 'foo-bar'), ('foo----bar', 'foo-bar')])
def test_is_normalized_name(name, expected):
assert is... |
class RenameFiles(Gtk.VBox):
title = _('Rename Files')
FILTERS = [SpacesToUnderscores, ReplaceColons, StripWindowsIncompat, StripDiacriticals, StripNonASCII, Lowercase]
handler = RenameFilesPluginHandler()
IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'bmp']
def init_plugins(cls):
PluginManager.... |
def resolve_logger_callbacks(loggers, defined_loggers) -> List[Callback]:
init_loggers = {JsonLoggerCallback(), CSVLoggerCallback()}
if (loggers is None):
return list(init_loggers)
if (not isinstance(loggers, list)):
raise TypeError('`loggers` must be a list of str or tune logger callbacks.'... |
def test_edit_units(data, runner):
inputfile = str(data.join('RGB.byte.tif'))
result = runner.invoke(main_group, ['edit-info', inputfile, '--bidx', '1', '--units', 'DN'], catch_exceptions=False)
assert (result.exit_code == 0)
with rasterio.open(inputfile) as src:
assert (src.units[0] == 'DN') |
def convert_examples_to_features(examples, seq_length, tokenizer):
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
if tokens_b:... |
_to_zarr_if('cache_sensor_angles', sanitize_args_func=_sanitize_observer_look_args)
def _get_sensor_angles_from_sat_pos(sat_lon, sat_lat, sat_alt, start_time, area_def, chunks):
(lons, lats) = _get_valid_lonlats(area_def, chunks)
res = da.map_blocks(_get_sensor_angles_ndarray, lons, lats, start_time, sat_lon, s... |
class SplitTransformDataset(Dataset):
def __init__(self, root, in_memory=False, need_name=False, perturb=True, img_suffix='_im.jpg'):
self.root = root
self.need_name = need_name
self.in_memory = in_memory
self.perturb = perturb
self.img_suffix = img_suffix
imgs = os.l... |
def check_win(board: dict[(int, str)]) -> bool:
return any(((board[1] == board[2] == board[3]), (board[4] == board[5] == board[6]), (board[7] == board[8] == board[9]), (board[1] == board[4] == board[7]), (board[2] == board[5] == board[8]), (board[3] == board[6] == board[9]), (board[1] == board[5] == board[9]), (boa... |
class FeatureFlagsConfiguration(BaseModel):
features: Optional[dict[(str, Any)]]
_validator('features', mode='before')
def validate_features(cls, value):
validator = SchemaValidator(value)
try:
validator.validate()
except Exception as exc:
raise ValueError(str... |
class MaxxVit(nn.Module):
def __init__(self, cfg: MaxxVitCfg, img_size: Union[(int, Tuple[(int, int)])]=224, in_chans: int=3, num_classes: int=1000, global_pool: str='avg', drop_rate: float=0.0, drop_path_rate: float=0.0):
super().__init__()
img_size = to_2tuple(img_size)
transformer_cfg = c... |
.parametrize('mean, scale, size', [(np.array(10, dtype=config.floatX), np.array(1, dtype=config.floatX), None), (np.array(10, dtype=config.floatX), np.array(1, dtype=config.floatX), []), (np.array(10, dtype=config.floatX), np.array(1, dtype=config.floatX), [2, 3]), (np.full((1, 2), 10, dtype=config.floatX), np.array(1,... |
class Character(Object):
def from_dict(self):
super().from_dict()
self.name = self._data.get('name')
self.team_id = self._data.get('teamId')
self.health = self._data.get('health')
self.location = Location(self._data.get('location', {}))
self.ranking = self._data.get('... |
def setup(opt):
if (opt.caption_model == 'fc'):
model = FCModel(opt)
elif (opt.caption_model == 'language_model'):
model = LMModel(opt)
elif (opt.caption_model == 'newfc'):
model = NewFCModel(opt)
elif (opt.caption_model == 'show_tell'):
model = ShowTellModel(opt)
eli... |
class Reader():
def __init__(self, instance_name):
if True:
file = open(os.path.join(os.path.dirname(__file__), '../../instances.json'), 'r')
data = json.load(file)
instance = [inst for inst in data if (inst['name'] == instance_name)]
if (len(instance) == 0):
... |
def env_settings():
env_module_name = 'ltr.admin.local'
try:
env_module = importlib.import_module(env_module_name)
return env_module.EnvironmentSettings()
except:
env_file = os.path.join(os.path.dirname(__file__), 'local.py')
create_default_local_file()
raise RuntimeE... |
class HflixIn(SimpleDecrypter):
__name__ = 'HflixIn'
__type__ = 'decrypter'
__version__ = '0.12'
__status__ = 'testing'
__pattern__ = '
__description__ = 'Hflix.in decrypter plugin'
__license__ = 'GPLv3'
__authors__ = [('GammaC0de', 'nitzo2001[AT]yahoo[DOT]com')]
def decrypt(self, py... |
def train_image_diffusion(cfg):
training_steps = 50000
image = imread(f'./images/{cfg.image_name}')
crop_size = int((min(image[0].shape[(- 2):]) * 0.95))
train_dataset = CropSet(image=image, crop_size=crop_size, use_flip=False)
train_loader = DataLoader(train_dataset, batch_size=1, num_workers=4, sh... |
def test_varyings_remove2():
code1 = '\n fn vs_main() -> Varyings {\n var varyings : Varyings;\n varyings.foo = f32(something1);\n varyings.bar = vec2<f32>(something2);\n varyings.spam = vec3<f32>(something3);\n return varyings;\n }\n\n fn fs_main(varyings : Varyings) {\n... |
class R2RBatch(object):
def __init__(self, feat_db, instr_data, connectivity_dir, batch_size=64, angle_feat_size=4, seed=0, name=None, sel_data_idxs=None, is_reverie=False, anno_dir=None):
self.env = EnvBatch(connectivity_dir, feat_db=feat_db, batch_size=batch_size)
self.is_reverie = is_reverie
... |
def short_platform(r=None, p=None):
if (r is None):
r = platform.release()
if (p is None):
p = platform.platform()
sp = r.split('-')
if (len(sp) < 2):
return p
kernel_version = sp[0].split('.')
if (len(kernel_version) <= 2):
return p
sp[0] = '.'.join(kernel_ve... |
def get_openssl_cnf_path(opts):
global generated_cnf_file
try:
if path.exists(generated_cnf_file):
return generated_cnf_file
except TypeError:
pass
cn = opts.common_name
client_alt_name = (opts.client_alt_name or opts.common_name)
server_alt_name = (opts.server_alt_na... |
def _do_check_version(current_version: Union[(Version, LegacyVersion)], raiden: 'RaidenService') -> bool:
content = requests.get(LATEST).json()
if ('tag_name' not in content):
click.secho('Error while contacting github for latest version. API rate limit exceeded?', fg='red')
return False
lat... |
def test_set_defaults_pass_no_substitutions():
context = Context({'key1': 'value1', 'key2': 'value2', 'key3': 'value3'})
add_me = {'key2': 'value4', 'key4': 'value5'}
context.set_defaults(add_me)
assert (context['key1'] == 'value1')
assert (context['key2'] == 'value2')
assert (context['key3'] ==... |
class AppEngineServer(ServerAdapter):
quiet = True
def run(self, handler):
from google.appengine.ext.webapp import util
module = sys.modules.get('__main__')
if (module and (not hasattr(module, 'main'))):
module.main = (lambda : util.run_wsgi_app(handler))
util.run_wsg... |
def suggest_mlp_params(trial):
params = {}
params['lr'] = trial.suggest_loguniform('lr', 5e-05, 0.005)
params['dropout'] = _suggest_optional(trial, 'uniform', 'dropout', 0.0, 0.5)
params['weight_decay'] = _suggest_optional(trial, 'loguniform', 'weight_decay', 1e-06, 0.01)
params['d_layers'] = _sugge... |
def load_bin_vec(fname, vocab):
word_vecs = {}
with open(fname, 'rb') as f:
header = f.readline()
(vocab_size, layer1_size) = map(int, header.split())
binary_len = (np.dtype('float32').itemsize * layer1_size)
for line in xrange(vocab_size):
word = []
while... |
class OptaxStatePartitionRules():
_RULES = {amos.ScaleByAmosState: amos_helper.state_partition_rule, optax.AddNoiseState: (lambda state, params_axes: optax.AddNoiseState(count=None, rng_key=None)), optax.DifferentiallyPrivateAggregateState: (lambda state, params_axes: optax.DifferentiallyPrivateAggregateState(rng_k... |
def get_trainer(args, return_trainer_only=True):
ckpt_path = os.path.abspath(args.downstream_model_dir)
os.makedirs(ckpt_path, exist_ok=True)
checkpoint_callback = ModelCheckpoint(dirpath=ckpt_path, save_top_k=args.save_top_k, monitor=args.monitor.split()[1], mode=args.monitor.split()[0], filename='{epoch}-... |
def test_bn_reestimation():
tf.keras.backend.clear_session()
np.random.seed(0)
input_data = np.random.randn(1024, 32, 32, 3).astype(np.float32)
batch_size = 4
dataset = tf.data.Dataset.from_tensor_slices(input_data)
dataset = dataset.batch(batch_size=batch_size)
it = iter(dataset)
dummy_... |
class TestHarness(Component):
def construct(s, dut_class, src_msgs, sink_msgs, latency, src_lat, sink_lat):
s.src = TestSrcCL(None, src_msgs, 0, src_lat)
s.dut = dut_class(latency)
s.sink = TestSinkCL(None, sink_msgs, 0, sink_lat)
connect(s.src.send, s.dut.enq)
if (dut_class ... |
class EpisodicDataset():
def __init__(self, data, num_classes, transforms=[], episode_size=args.batch_size, device=args.dataset_device, use_hd=False):
if torch.is_tensor(data):
self.length = data.shape[0]
self.data = data.to(device)
else:
self.data = data
... |
def pair_within_simultaneously_binned(binned_majoranas: list) -> tuple:
iterators = [pair_within_simultaneously(bn) for bn in binned_majoranas]
for pairing in _parallel_iter(iterators, flatten=True):
(yield pairing)
num_bins = len(binned_majoranas)
if ((max([len(bn) for bn in binned_majoranas]) ... |
class _MockBase():
public_proxy = ('example',)
def __init__(self, name, fields=()):
self.test_data = {}
self.name = name
self.fields = fields
def track_call(func):
def wrapped(self, *args, **kwargs):
self.test_data[func.__name__] = True
return func(sel... |
def dump_pages(asinlist, filelist, mf, dirpath, fil, is_verbose):
row = get_pages(dirpath, fil, is_verbose)
if (row is None):
return
if (row[0] in asinlist):
return
if (row[6] in filelist):
return
with open(mf, 'ab') as o:
print('* Updating book pages CSV file...')
... |
def main(args):
qas = load_qas_(args.qas)
collection = load_collection_(args.collection, retain_titles=True)
rankings = load_ranking(args.ranking)
parallel_pool = Pool(30)
print_message('#> Tokenize the answers in the Q&As in parallel...')
qas = list(parallel_pool.map(tokenize_all_answers, qas))... |
def test_charclass_fsm_2() -> None:
bc = from_charclass(Charclass('bc'))
assert (bc.alphabet == {Charclass('bc'), (~ Charclass('bc'))})
assert (bc.map == {0: {Charclass('bc'): 1, (~ Charclass('bc')): 2}, 1: {Charclass('bc'): 2, (~ Charclass('bc')): 2}, 2: {Charclass('bc'): 2, (~ Charclass('bc')): 2}})
a... |
class Logger(object):
def __init__(self, log_dir):
if LOG:
self.writer = tf.summary.FileWriter(log_dir)
self.f = open((log_dir + '/log.txt'), 'w')
else:
os.mkdir(log_dir)
self.f = open((log_dir + '/log.txt'), 'w')
def write(self, txt):
self... |
class QuantSimConfigurator(AimetCommonQuantSimConfigurator):
def __init__(self, connected_graph: ConnectedGraph, quant_scheme: Union[(QuantScheme, str)], rounding_mode: str, default_output_bw: int, default_param_bw: int, default_data_type: QuantizationDataType=QuantizationDataType.int, config_file: str=None):
... |
class TestDataset(object):
def check_keys_contain(result_keys, target_keys):
return set(target_keys).issubset(set(result_keys))
def setup_class(cls):
cls.data_prefix = osp.join(osp.dirname(osp.dirname(__file__)), 'data')
cls.frame_ann_file = osp.join(cls.data_prefix, 'frame_test_list.txt... |
class TestWasserstein1D(MetricClassTester):
def _get_scipy_equivalent(self, x: torch.Tensor, y: torch.Tensor, x_weights: Optional[torch.Tensor]=None, y_weights: Optional[torch.Tensor]=None, device: str='cpu') -> torch.Tensor:
x_np = x.numpy().flatten()
y_np = y.numpy().flatten()
if (x_weight... |
class BatchedFusedEmbeddingBag(BaseBatchedEmbeddingBag[torch.Tensor], FusedOptimizerModule):
def __init__(self, config: GroupedEmbeddingConfig, pg: Optional[dist.ProcessGroup]=None, device: Optional[torch.device]=None) -> None:
super().__init__(config, pg, device)
managed: List[EmbeddingLocation] = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.