code stringlengths 281 23.7M |
|---|
class DFN(nn.Module):
def __init__(self, num_class=19):
super(DFN, self).__init__()
self.num_class = num_class
self.resnet_features = resnet101(pretrained=False)
self.layer0 = nn.Sequential(self.resnet_features.conv1, self.resnet_features.bn1, self.resnet_features.relu)
self.... |
def draw_text_onimage(text, image, color=(255, 0, 0)):
if (image.dtype == np.float32):
image = (image * 255.0).astype(np.uint8)
assert (image.dtype == np.uint8)
text_image = Image.fromarray(image)
draw = ImageDraw.Draw(text_image)
draw.text((4, 0), text, fill=color)
return (np.array(text... |
class SunZenithReducer(SunZenithCorrectorBase):
def __init__(self, correction_limit=80.0, max_sza=90, strength=1.3, **kwargs):
self.correction_limit = correction_limit
self.strength = strength
super(SunZenithReducer, self).__init__(max_sza=max_sza, **kwargs)
if (self.max_sza is None)... |
def hdf5_read(filepath: (pathlib.Path | str), dataset_name: str) -> cunumeric.ndarray:
filepath = pathlib.Path(filepath)
annotations = SingleHdf5ToZarr(filepath, inline_threshold=0).translate()
zarr_group = zarr.open(fsspec.get_mapper('reference://', fo=annotations))
zarr_ary: zarr.Array = zarr_group[da... |
def test_load_previous_state_previous_layout_not_layout(tmp_path: Path, default_echoes_configuration):
tmp_path.joinpath('preset.rdvpreset').write_text(json.dumps({'trick_level': 'foo'}))
tmp_path.joinpath('state.json').write_text('[]')
result = tracker_window._load_previous_state(tmp_path, default_echoes_c... |
_loss('simclr_info_nce_loss')
class SimclrInfoNCELoss(ClassyLoss):
def __init__(self, loss_config: AttrDict, device: str='gpu'):
super(SimclrInfoNCELoss, self).__init__()
self.loss_config = loss_config
self.temperature = self.loss_config.temperature
self.buffer_params = self.loss_con... |
class GenerationConfig(PushToHubMixin):
def __init__(self, **kwargs):
self.max_length = kwargs.pop('max_length', 20)
self.max_new_tokens = kwargs.pop('max_new_tokens', None)
self.min_length = kwargs.pop('min_length', 0)
self.min_new_tokens = kwargs.pop('min_new_tokens', None)
... |
class positive_int(click.ParamType):
name = 'N'
def convert(self, value, param, ctx):
msg = 'must be a positive integer'
if isinstance(value, str):
try:
value = int(value)
except ValueError:
self.fail(msg, param, ctx)
if (not (value... |
.end_to_end()
def test_more_nested_pytree_and_python_node_as_return(runner, snapshot_cli, tmp_path):
source = '\n from pathlib import Path\n from typing import Any\n from typing_extensions import Annotated\n from pytask import PythonNode\n from typing import Dict\n\n nodes = [\n PythonNode(... |
def parse_flag_from_env(key, default=False):
try:
value = os.environ[key]
except KeyError:
_value = default
else:
try:
_value = strtobool(value)
except ValueError:
raise ValueError(f'If set, {key} must be yes or no.')
return _value |
def asdict(inst, recurse=True, filter=None, dict_factory=dict, retain_collection_types=False, value_serializer=None):
attrs = fields(inst.__class__)
rv = dict_factory()
for a in attrs:
v = getattr(inst, a.name)
if ((filter is not None) and (not filter(a, v))):
continue
if... |
def _perform_login(user_obj, service_name):
(success, _) = common_login(user_obj.uuid)
if success:
if model.user.has_user_prompts(user_obj):
return redirect(url_for('web.updateuser', _scheme=app.config['PREFERRED_URL_SCHEME'], _external=True))
else:
return redirect(url_fo... |
def _generate_primal(graph, gdf_network, fields, multigraph, oneway_column=None):
graph.graph['approach'] = 'primal'
msg = ' This can lead to unexpected behaviour. The intended usage of the conversion function is with networks made of LineStrings only.'
if ('LineString' not in gdf_network.geom_type.unique()... |
class CoreAudioDecoder(MediaDecoder):
def get_file_extensions(self):
return ('.aac', '.ac3', '.aif', '.aiff', '.aifc', '.caf', '.mp3', '.mp4', '.m4a', '.snd', '.au', '.sd2', '.wav')
def decode(self, filename, file, streaming=True):
if streaming:
return CoreAudioSource(filename, file)... |
def patch_ptq_techniques(bn_folded_acc, cle_acc, adaround_acc):
def bn_folding(session, *_, **__):
session = deepcopy_tf_session(session)
_tf_session_set_flag(session, 'applied_bn_folding')
return (session, list())
def cle(session, *_, **__):
session = deepcopy_tf_session(session... |
def test_async_subproc_maximal():
cmd = Command('arb', is_shell=True, cwd='cwd', is_save=True, is_text=True, encoding='enc', append=True)
assert (cmd.cmd == 'arb')
assert (cmd.is_shell is True)
assert (cmd.cwd == 'cwd')
assert (cmd.is_save is True)
assert (cmd.is_text is True)
assert (cmd.st... |
def add_seqformer_config(cfg):
cfg.MODEL.SeqFormer = CN()
cfg.MODEL.SeqFormer.NUM_CLASSES = 80
cfg.INPUT.PRETRAIN_TYPE = 'v1'
cfg.INPUT.SAMPLING_FRAME_NUM = 1
cfg.INPUT.SAMPLING_FRAME_RANGE = 10
cfg.INPUT.SAMPLING_INTERVAL = 1
cfg.INPUT.SAMPLING_FRAME_SHUFFLE = False
cfg.INPUT.AUGMENTATI... |
class RoIPoolFunction(Function):
def forward(ctx, features, rois, out_size, spatial_scale):
assert features.is_cuda
(out_h, out_w) = _pair(out_size)
assert (isinstance(out_h, int) and isinstance(out_w, int))
ctx.save_for_backward(rois)
num_channels = features.size(1)
... |
def concat_guess_data(stock_column, data):
print('stock_column:', stock_column)
tmp_dic = {}
for col in stock_column:
if (col == 'date'):
tmp_dic[col] = data['date']
elif (col == 'code'):
tmp_dic[col] = data['code']
else:
tmp_dic[col] = data['lates... |
def test_new_type_value() -> None:
nt1 = NewType('nt1', int)
nt1_val = value.NewTypeValue(nt1)
nt2 = NewType('nt2', int)
nt2_val = value.NewTypeValue(nt2)
assert_can_assign(nt1_val, nt1_val)
assert_cannot_assign(nt1_val, nt2_val)
assert_can_assign(nt1_val, TypedValue(int))
assert_can_ass... |
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(feature_size, 300)
self.fc2 = nn.Linear(300, 3)
def forward(self, x):
x = x.view((- 1), feature_size)
emb = F.relu(self.fc1(x))
(nn.Dropout(0.5),)
x = self.fc2(emb)
... |
class HelpCategories(cmd2.Cmd):
START_TIMES = ['now', 'later', 'sometime', 'whenever']
CMD_CAT_CONNECTING = 'Connecting'
CMD_CAT_APP_MGMT = 'Application Management'
CMD_CAT_SERVER_INFO = 'Server Information'
def __init__(self):
super().__init__()
def do_connect(self, _):
self.pou... |
class BezierCurve(QQuickItem):
p1Changed = pyqtSignal(QPointF)
(QPointF, notify=p1Changed)
def p1(self):
return self._p1
.setter
def p1(self, p):
if (self._p1 != p):
self._p1 = QPointF(p)
self.p1Changed.emit(p)
self.update()
p2Changed = pyqtSig... |
def modifyModlist(old_entry, new_entry, ignore_attr_types=None, ignore_oldexistent=0, case_ignore_attr_types=None):
ignore_attr_types = {v.lower() for v in (ignore_attr_types or [])}
case_ignore_attr_types = {v.lower() for v in (case_ignore_attr_types or [])}
modlist = []
attrtype_lower_map = {}
for... |
def object_len(node, context: (InferenceContext | None)=None):
from astroid.objects import FrozenSet
inferred_node = real_safe_infer(node, context=context)
node_frame = node.frame()
if (isinstance(node_frame, scoped_nodes.FunctionDef) and (node_frame.name == '__len__') and isinstance(inferred_node, base... |
def _convert_list_type_from_XML(vs):
vlist = (vs.findall('ListItem') + vs.findall('ConfigListItem'))
l = []
for xconfig in vlist:
v = xconfig.text
if (xconfig.get('type') in CONVERT_TYPE_FROM_XML):
v = CONVERT_TYPE_FROM_XML[xconfig.get('type')](xconfig)
l.append(v)
re... |
def create_virtual_interfaces(kubecli: KrknKubernetes, nummber: int, node: str, pod_template) -> None:
pod_body = yaml.safe_load(pod_template.render(nodename=node))
kubecli.create_pod(pod_body, 'default', 300)
logging.info('Creating {0} virtual interfaces on node {1} using a pod'.format(nummber, node))
... |
def main():
os.chdir(top_dir)
collect_interval = get_setting('schedule:collect_interval')
submit_interval = get_setting('schedule:submit_interval')
collect_stamp_file = os.path.join(var_dir, 'collect-stamp')
submit_stamp_file = os.path.join(var_dir, 'submit-stamp')
do_collect = check_stamp(colle... |
class Migration(migrations.Migration):
dependencies = [('schedule', '0033_new_schedule_item_type_talk')]
operations = [migrations.AddField(model_name='scheduleitem', name='attendees_total_capacity', field=models.PositiveIntegerField(blank=True, help_text='Maximum capacity for this event. Leave blank to not limi... |
class ResBlock(nn.Module):
def __init__(self, dim, seq_len, mlp_ratio=4, mlp_layer=Mlp, norm_layer=Affine, act_layer=nn.GELU, init_values=0.0001, drop=0.0, drop_path=0.0):
super().__init__()
channel_dim = int((dim * mlp_ratio))
self.norm1 = norm_layer(dim)
self.linear_tokens = nn.Lin... |
class RepBlock(nn.Module):
def __init__(self, in_channels, out_channels, n=1, block=RepVGGBlock, basic_block=RepVGGBlock):
super().__init__()
self.conv1 = block(in_channels, out_channels)
self.block = (nn.Sequential(*(block(out_channels, out_channels) for _ in range((n - 1)))) if (n > 1) els... |
def format_item(format_spec, item, defaults=None):
template_engine = getattr(format_spec, '__engine__', None)
if ((template_engine == 'tempita') or ((not template_engine) and format_spec.startswith('{{'))):
namespace = dict(headers=(not bool(item)))
if item:
namespace['d'] = item
... |
def distros_for_location(location, basename, metadata=None):
if basename.endswith('.egg.zip'):
basename = basename[:(- 4)]
if (basename.endswith('.egg') and ('-' in basename)):
return [Distribution.from_location(location, basename, metadata)]
if (basename.endswith('.whl') and ('-' in basenam... |
def test_cannot_send_a_grant_if_grants_deadline_do_not_exists(graphql_client, user, conference, grant_factory):
assert (list(conference.deadlines.all()) == [])
graphql_client.force_login(user)
response = _send_grant(graphql_client, grant_factory, conference)
assert (not response.get('errors'))
asser... |
class MF(BaseEstimator, TransformerMixin):
def __init__(self, num_users, num_items, pretrain_flag, hidden_factor, epoch, batch_size, learning_rate, lamda_bilinear, optimizer_type, verbose, layers, activation_function, keep_prob, save_file, random_seed=2016):
self.batch_size = batch_size
self.learnin... |
class ServiceHandler(AbstractServiceHandler):
_search_base = '
_recent_list = '
def __init__(self):
super().__init__('nyaa', 'Nyaa', True)
def get_all_episodes(self, stream, **kwargs):
info('Getting live episodes for Nyaa/{}'.format(stream.show_key))
episode_datas = self._get_fee... |
class EG3DDataset(BaseDataset):
def __init__(self, root_dir, file_format='zip', annotation_path=None, annotation_meta=None, annotation_format='json', max_samples=(- 1), mirror=False, transform_kwargs=None, use_label=True, num_classes=None, use_pose=True, pose_meta='dataset.json'):
super().__init__(root_dir=... |
def uniform_points_on_sphere(angle_sampling, radius=1):
elevation = np.linspace((- 90), 90, angle_sampling)
azimuth = np.linspace((- 180), 180, angle_sampling, endpoint=False)
(elevation, azimuth) = np.meshgrid(elevation, azimuth)
keep = (elevation != (- 90))
keep[np.argmin(keep)] = True
azimuth... |
class CortexMScb(QlPeripheral):
def enable(self, IRQn):
if (IRQn == IRQ.USAGE_FAULT):
self.instance.SHCSR |= (1 << 18)
if (IRQn == IRQ.BUS_FAULT):
self.instance.SHCSR |= (1 << 17)
if (IRQn == IRQ.MEMORY_MANAGEMENT_FAULT):
self.instance.SHCSR |= (1 << 16)
... |
class PerFutureTrade(PerContract):
def __init__(self, cost=DEFAULT_MINIMUM_COST_PER_FUTURE_TRADE):
super(PerFutureTrade, self).__init__(cost=0, exchange_fee=cost, min_trade_cost=0)
self._cost_per_trade = self._exchange_fee
def __repr__(self):
if isinstance(self._cost_per_trade, DummyMapp... |
class ChangeObjectStates(StateChanger):
def __init__(self, properties_data):
self.properties_data = properties_data
def apply_changes(self, state: EnvironmentState, **kwargs):
for node in state.get_nodes():
for p in (node.properties & _PROPERTY_STATES.keys()):
possibl... |
def get_norm(norm, out_channels):
if (norm is None):
return None
if isinstance(norm, str):
if (len(norm) == 0):
return None
norm = {'BN': BatchNorm2d, 'SyncBN': (NaiveSyncBatchNorm if (env.TORCH_VERSION <= (1, 5)) else nn.SyncBatchNorm), 'FrozenBN': FrozenBatchNorm2d, 'GN': (... |
_datapipe('load_from_bz2')
class Bz2FileLoaderIterDataPipe(IterDataPipe[Tuple[(str, BufferedIOBase)]]):
def __init__(self, datapipe: Iterable[Tuple[(str, BufferedIOBase)]], length: int=(- 1)) -> None:
super().__init__()
self.datapipe: Iterable[Tuple[(str, BufferedIOBase)]] = datapipe
self.le... |
def pyrocko_station_from_channels(nsl, channels, inconsistencies='warn'):
pos = (lat, lon, elevation, depth) = channels[0].position_values
if (not all(((pos == x.position_values) for x in channels))):
info = '\n'.join(((' %s: %s' % (x.code, x.position_values)) for x in channels))
mess = ('enc... |
def get_parser(**parser_kwargs):
def str2bool(v):
if isinstance(v, bool):
return v
if (v.lower() in ('yes', 'true', 't', 'y', '1')):
return True
elif (v.lower() in ('no', 'false', 'f', 'n', '0')):
return False
else:
raise argparse.Argum... |
def delete_vm(call, vm_name):
refresh_token = user_dict[call.from_user.id].refresh_token
subscription_id = user_dict[call.from_user.id].subscription_id
bot.edit_message_text(text=f''' <b> VM</b>
<code>{vm_name}</code> ...''', chat_id=call.from_user.id, message_id=call.message.message_id, parse_mode='HTML')... |
def strain_calculation_parameters(substrate_material, layer_material, should_print=False, SO=False):
sub = substrate_material
mat = layer_material
k = State()
k.av = abs(mat.a_v)
k.ac = mat.a_c
k.b = mat.b
k.C11 = mat.c11
k.C12 = mat.c12
if should_print:
print(sub, mat)
k... |
def test_starting_location_world_select(skip_qtbot, preset_manager):
base = preset_manager.default_preset_for_game(RandovaniaGame.METROID_PRIME_ECHOES).get_preset()
preset = dataclasses.replace(base, uuid=uuid.UUID('b41fde84-1f57-4b79-8cd6-3e5a78077fa6'))
options = MagicMock()
editor = PresetEditor(pres... |
class ExperimentPlanner2D(ExperimentPlanner):
def __init__(self, folder_with_cropped_data, preprocessed_output_folder):
super(ExperimentPlanner2D, self).__init__(folder_with_cropped_data, preprocessed_output_folder)
self.data_identifier = (default_data_identifier + '_2D')
self.plans_fname = ... |
class TestSpatialSvdLayerSplitandSVDPrunner():
.parametrize('model_type', ['Sequential', 'Functional'])
.parametrize('rank', [1024, 512])
def test_split_layer(self, model_type, rank):
model = get_model(model_type)
orig_conv_op = _get_layers(model, model_type)[2]
org_conv_op_shape = o... |
_torch
_vision
class ViTImageProcessingTest(ImageProcessingSavingTestMixin, unittest.TestCase):
image_processing_class = (ViTImageProcessor if is_vision_available() else None)
def setUp(self):
self.image_processor_tester = ViTImageProcessingTester(self)
def image_processor_dict(self):
return... |
def _validate_child_key_integrity(value: Any) -> None:
if (hasattr(value, '__iter__') and (not hasattr(value, '__len__'))):
warn(f'Did not verify key-path integrity of children in generator {value} - pass a sequence (i.e. list of finite length) in order to verify')
else:
for child in value:
... |
class TestBuildDependenciesInstalled():
def test_default_all(self, hatch, temp_dir, helpers):
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code == 0), result.output
path = (temp_dir / 'my-app')
(path /... |
class BaseModel():
def __init__(self, opt):
self.opt = opt
self.device = torch.device(('cuda' if (opt.get('gpu_ids', None) is not None) else 'cpu'))
self.is_train = opt['is_train']
self.schedulers = []
self.optimizers = []
self.scaler = None
def feed_data(self, da... |
def _builtin_filter_predicate(node, builtin_name) -> bool:
if ((builtin_name == 'type') and (node.root().name == 're') and isinstance(node.func, nodes.Name) and (node.func.name == 'type') and isinstance(node.parent, nodes.Assign) and (len(node.parent.targets) == 1) and isinstance(node.parent.targets[0], nodes.Assig... |
def get_ytplayer_config(html: str) -> Any:
logger.debug('finding initial function name')
config_patterns = ['ytplayer\\.config\\s*=\\s*', 'ytInitialPlayerResponse\\s*=\\s*']
for pattern in config_patterns:
try:
return parse_for_object(html, pattern)
except HTMLParseError as e:
... |
def convert_sentence_and_mention_to_features(sentence, mention, max_seq_length, tokenizer):
sentence = tokenizer.tokenize(sentence)
mention = tokenizer.tokenize(mention)
_truncate_seq_pair(sentence, mention, (max_seq_length - 3))
tokens = []
segment_ids = []
tokens.append('[CLS]')
segment_id... |
def save_checkpoint(args, epoch, model, optimizer):
checkpoint_path = os.path.join(args.path2saved_checkpoints, f'checkpoint_{epoch}.pt')
save_num = 0
while (save_num < 10):
try:
if False:
torch.save({'epoch': epoch, 'model_state_dict': model.module.state_dict(), 'optimiz... |
class PartialFCAdamW(torch.nn.Module):
def __init__(self, margin_loss: Callable, embedding_size: int, num_classes: int, sample_rate: float=1.0, fp16: bool=False):
super(PartialFCAdamW, self).__init__()
assert distributed.is_initialized(), 'must initialize distributed before create this'
self... |
class vgg16(torch.nn.Module):
def __init__(self, requires_grad=False, pretrained=True):
super(vgg16, self).__init__()
vgg_pretrained_features = tv.vgg16(pretrained=pretrained).features
self.slice1 = torch.nn.Sequential()
self.slice2 = torch.nn.Sequential()
self.slice3 = torch... |
def color_jitter_rand(image, brightness=0, contrast=0, saturation=0, hue=0):
with tf.name_scope('distort_color'):
def apply_transform(i, x):
def brightness_foo():
if (brightness == 0):
return x
else:
return tf.image.random_b... |
def min_weight_simple_path_greedy(graph: nx.Graph, n: int, weight_fun: Callable[([nx.Graph, List], float)]=path_weight):
def _grow_path_lowest_weight(path, partial_graph):
adjacent_edges = sorted(list(partial_graph.edges([path[0], path[(- 1)]], data='weight')), key=(lambda e: e[2]))
if (len(adjacent... |
def command_dnone(command, args):
def setup(parser):
add_source_options(parser)
add_double_options(parser)
(parser, opts, args) = cl_parse(command, args, setup=setup)
(dir1, dir2, smin, smax) = verify_arguements('dnone', 4, args)
opts['rel_lowpass_frequency'] = None
opts['rel_highpas... |
def rally_count(rawfile, predict_file, savefile, clipinfo_file):
data = pd.read_csv(rawfile)
predict_result = pd.read_csv(predict_file)
clipinfo_data = pd.read_excel(clipinfo_file)
needed_data = data[['set', 'rally', 'hit_area', 'getpoint_player', 'lose_reason', 'type']]
clipinfo_data = clipinfo_dat... |
class SE_OBJECT_TYPE(enum.Enum):
SE_UNKNOWN_OBJECT_TYPE = 0
SE_FILE_OBJECT = 1
SE_SERVICE = 2
SE_PRINTER = 3
SE_REGISTRY_KEY = 4
SE_LMSHARE = 5
SE_KERNEL_OBJECT = 6
SE_WINDOW_OBJECT = 7
SE_DS_OBJECT = 8
SE_DS_OBJECT_ALL = 9
SE_PROVIDER_DEFINED_OBJECT = 10
SE_WMIGUID_OBJEC... |
def test_includes_with_inline_table() -> None:
poetry = Factory().create_poetry(project('with_include_inline_table'))
builder = SdistBuilder(poetry)
builder.build()
sdist = (((fixtures_dir / 'with_include_inline_table') / 'dist') / 'with_include-1.2.3.tar.gz')
assert sdist.exists()
with tarfile.... |
def main():
logs_dir = path.Path('logs')
data = []
for log_dir in sorted(logs_dir.listdir()):
if (not log_dir.isdir()):
continue
for eval_dir in log_dir.glob('eval*'):
m = re.match('^eval-noise_(.*)-miss_(.*)$', eval_dir.basename())
(noise, miss) = [float(... |
class ConcatOptimizer(FairseqOptimizer):
def __init__(self, args, optimizer_list):
self.optimizer_list = optimizer_list
self.scaler = None
self.is_fpl6 = None
self.check_optimizer()
if self.is_fpl6:
for optimizer in optimizer_list:
if (self.scaler ... |
class DescribeStyles():
def it_supports_the_in_operator_on_style_name(self, in_fixture):
(styles, name, expected_value) = in_fixture
assert ((name in styles) is expected_value)
def it_knows_its_length(self, len_fixture):
(styles, expected_value) = len_fixture
assert (len(styles) ... |
def mobilenet_v1_arg_scope(is_training=True, stddev=0.09):
batch_norm_params = {'is_training': False, 'center': True, 'scale': True, 'decay': 0.9997, 'epsilon': 0.001, 'trainable': False}
weights_init = tf.truncated_normal_initializer(stddev=stddev)
regularizer = tf.contrib.layers.l2_regularizer(cfg.MOBILEN... |
class TestAcoustics():
.benchmark(group='ComplexCepstrum')
.parametrize('num_samps', [(2 ** 8), (2 ** 14)])
.parametrize('n', [123, 256])
class TestComplexCepstrum():
def cpu_version(self, sig, n):
return complex_cepstrum(sig, n)
def gpu_version(self, sig, n):
wit... |
def map_errors_and_warnings(objs, error_container=code_to_error, warning_container=code_to_warning):
for obj in objs:
if (not issubclass(type(obj), (type(Warning), type(Error)))):
continue
code = getattr(obj, 'code', None)
if (code is None):
continue
if issubc... |
def validate(val_loader, model, criterion, epoch, args):
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('', ':6.2f')
top5 = AverageMeter('', ':6.2f')
progress = ProgressMeter(len(val_loader), batch_time, losses, top1, top5, prefix='Test: ')
m... |
class CLIP(nn.Module):
def __init__(self, embed_dim: int, vision_cfg: CLIPVisionCfg, text_cfg: CLIPTextCfg, quick_gelu: bool=False, cast_dtype: Optional[torch.dtype]=None):
super().__init__()
self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype)
text = _build_text_... |
def random_neuron_single_bit_inj_batched(pfi: core.FaultInjection, layer_ranges, batch_random=True):
pfi.set_conv_max(layer_ranges)
locations = ([random_neuron_location(pfi) for _ in range(pfi.batch_size)] if batch_random else ([random_neuron_location(pfi)] * pfi.batch_size))
(random_layers, random_c, rando... |
class PlaybackTimer():
def __init__(self) -> None:
self._elapsed = 0.0
self._started_at = None
def start(self) -> None:
if (self._started_at is None):
self._started_at = time.perf_counter()
def pause(self) -> None:
self._elapsed = self.get_time()
self._sta... |
def init_detector(config, checkpoint=None, device='cuda:0', cfg_options=None):
if isinstance(config, str):
config = mmcv.Config.fromfile(config)
elif (not isinstance(config, mmcv.Config)):
raise TypeError(f'config must be a filename or Config object, but got {type(config)}')
if (cfg_options ... |
class TestSequenceGetItem(TestNameCheckVisitorBase):
_passes()
def test_list(self):
from typing import List
def capybara(lst: List[int], i: int, s: slice, unannotated) -> None:
assert_is_value(lst[0], TypedValue(int))
assert_is_value(lst[(- 1)], TypedValue(int))
... |
def mpi_mean(x, axis=0, comm=None, keepdims=False):
x = np.asarray(x)
assert (x.ndim > 0)
if (comm is None):
comm = MPI.COMM_WORLD
xsum = x.sum(axis=axis, keepdims=keepdims)
n = xsum.size
localsum = np.zeros((n + 1), x.dtype)
localsum[:n] = xsum.ravel()
localsum[n] = x.shape[axis... |
def compress_session(sess, compressible_ops):
layer_a = sess.graph.get_operation_by_name(compressible_ops[0])
list_of_module_comp_ratio_pairs = [ModuleCompRatioPair(layer_a, 0.5)]
manual_params = SpatialSvdParameters.ManualModeParams(list_of_module_comp_ratio_pairs=list_of_module_comp_ratio_pairs)
param... |
def bbc_prepDefaultLex(outFile):
if (not os.environ.get('MAKE_SPEECH_ROM', 0)):
return
sd = open(os.environ['SPEECH_DISK'])
d = getBuf(sd).read()
i = d.index((((((as_utf8('LO') + chr(128)) + as_utf8('LP')) + chr(128)) + chr(130)) + chr(17)))
j = d.index(as_utf8('>OUS_'), i)
assert ((j - ... |
def default_hp_space_wandb(trial) -> Dict[(str, float)]:
from .integrations import is_wandb_available
if (not is_wandb_available()):
raise ImportError('This function needs wandb installed: `pip install wandb`')
return {'method': 'random', 'metric': {'name': 'objective', 'goal': 'minimize'}, 'paramet... |
class TARGET_LSTM(object):
def __init__(self, config, params):
self.num_emb = config.num_emb
self.batch_size = config.gen_batch_size
self.emb_dim = config.emb_dim
self.hidden_dim = config.hidden_dim
self.sequence_length = config.sequence_length
self.start_token = tf.c... |
class SecondPage(Gtk.Box):
def __init__(self, parent_window):
super().__init__(spacing=10)
self.__parent_window = parent_window
self.grid = Gtk.Grid()
vbox = Gtk.VBox()
vbox_container = Gtk.VBox()
scroller = Gtk.ScrolledWindow()
scroller.set_policy(Gtk.PolicyT... |
class TextDataset(Dataset):
def __init__(self, txt_list, tokenizer, max_length):
self.labels = []
self.input_ids = []
self.attn_masks = []
for txt in txt_list:
encodings_dict = tokenizer(txt, truncation=True, max_length=max_length, pad_to_max_length=False)
sel... |
class GUDevMonitorObserver(GObject.Object, _ObserverMixin):
_action_signal_map = {'add': 'device-added', 'remove': 'device-removed', 'change': 'device-changed', 'move': 'device-moved'}
__gsignals__ = {str('device-event'): (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_STRING, GObject.TYPE_PYOBJECT))... |
def test_draw_trajectory() -> None:
on_image = np.zeros((224, 244, 3), dtype=np.uint8)
positions = np.asarray([(0, 0), (0, 10), (0, 20)])
draw_trajectory(on_image, positions, (255, 255, 255))
assert np.all((on_image[(0, 0)] == (255, 255, 255)))
assert np.all((on_image[(10, 0)] == (255, 255, 255)))
... |
def get_vehiclerouting_solution(instance: np.ndarray, n: int, K: int, result: MinimumEigensolverResult) -> List[int]:
del instance, K
v = result.eigenstate
N = ((n - 1) * n)
index_value = [x for x in range(len(v)) if (v[x] == max(v))][0]
string_value = '{0:b}'.format(index_value)
while (len(stri... |
def test_rtf_footer():
t = ''
result = format_rtf(t)
expected = ''
msg = "RTF documents are expected to end with '{expected}'\n\t\tEnds intead with '{result}'\n\t(WARNING: Partial Output of Result!)".format(expected=_escape(expected), result=_escape(result[(- len(expected)):]))
assert result.endswit... |
class DenseSimpleUnit(nn.Module):
def __init__(self, in_channels, out_channels, dropout_rate):
super(DenseSimpleUnit, self).__init__()
self.use_dropout = (dropout_rate != 0.0)
inc_channels = (out_channels - in_channels)
self.conv = pre_conv3x3_block(in_channels=in_channels, out_chann... |
def test_aggregated_node_min_flow(model):
A = Input(model, 'A', max_flow=20.0, cost=1)
B = Input(model, 'B', max_flow=20.0, cost=100)
Z = Output(model, 'Z', max_flow=100, cost=0)
A.connect(Z)
B.connect(Z)
agg = AggregatedNode(model, 'agg', [A, B])
agg.min_flow = 15.0
model.run()
asse... |
class fastPredictBertMrc(fastPredict):
def __init__(self, model_path, config):
self.orig_test_file = os.path.join(config.get('data_dir'), config.get('orig_test'))
super(fastPredictBertMrc, self).__init__(model_path, config)
def init_data_loader(self, config):
vocab_file_path = os.path.jo... |
def run_dummyrunner(number_of_dummies):
number_of_dummies = (str(int(number_of_dummies)) if number_of_dummies else 1)
cmdstr = [sys.executable, EVENNIA_DUMMYRUNNER, '-N', number_of_dummies]
config_file = os.path.join(SETTINGS_PATH, 'dummyrunner_settings.py')
if os.path.exists(config_file):
cmdst... |
class MAEMetricTest(unittest.TestCase):
clazz: Type[RecMetric] = MAEMetric
task_name: str = 'mae'
def test_unfused_mae(self) -> None:
rec_metric_value_test_launcher(target_clazz=MAEMetric, target_compute_mode=RecComputeMode.UNFUSED_TASKS_COMPUTATION, test_clazz=TestMAEMetric, metric_name='mae', task... |
def target_df_without_window(spark_context, spark_session):
data = [{'id': 1, 'timestamp': '2016-04-11 12:03:21', 'feature1__avg': 350, 'feature2__count': 4}]
df = spark_session.read.json(spark_context.parallelize(data, 1))
df = df.withColumn(TIMESTAMP_COLUMN, df.timestamp.cast(DataType.TIMESTAMP.spark))
... |
class Migration(migrations.Migration):
dependencies = [('projects', '0047_continuation')]
operations = [migrations.AlterField(model_name='membership', name='project', field=models.ForeignKey(help_text='The project for this membership.', on_delete=django.db.models.deletion.CASCADE, related_name='memberships', to... |
class ImportOrganizer():
def __init__(self, project):
self.project = project
self.import_tools = ImportTools(self.project)
def organize_imports(self, resource, offset=None):
return self._perform_command_on_import_tools(self.import_tools.organize_imports, resource, offset)
def expand_... |
class _ProtocolEncoder(json.JSONEncoder):
def default(self, o: Any):
if isinstance(o, Performed):
return {'tag': 'Performed', 'contents': o.state}
elif isinstance(o, Stale):
return {'tag': 'Stale'}
elif isinstance(o, Timeout):
return {'tag': 'Timeout', 'co... |
def _topk_helper(g, input, k, dim, largest=True, sorted=False, out=None):
if (out is not None):
_unimplemented('TopK', 'Out parameter is not supported')
if (not _is_value(k)):
k = g.op('Constant', value_t=torch.tensor([k], dtype=torch.int64))
else:
k = g.op('Reshape', k, g.op('Consta... |
class RCNN(nn.Module):
def __init__(self, archi, device='cuda', checkpoint_path=None, share_memory=False, load_heads=False):
super().__init__()
self.device = device
self.feat_layer = '3'
if (archi == 'maskrcnn'):
self.model = models.detection.maskrcnn_resnet50_fpn(pretrai... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.