code stringlengths 281 23.7M |
|---|
def run_hp_search_ray(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
import ray
def _objective(trial, local_trainer, checkpoint_dir=None):
try:
from transformers.utils.notebook import NotebookProgressCallback
if local_trainer.pop_callback(NotebookProgressCallback):... |
class PicklableWrapper(object):
def __init__(self, obj):
while isinstance(obj, PicklableWrapper):
obj = obj._obj
self._obj = obj
def __reduce__(self):
s = cloudpickle.dumps(self._obj)
return (cloudpickle.loads, (s,))
def __call__(self, *args, **kwargs):
re... |
class AzureMLCallback(TrainerCallback):
def __init__(self, azureml_run=None):
if (not is_azureml_available()):
raise RuntimeError('AzureMLCallback requires azureml to be installed. Run `pip install azureml-sdk`.')
self.azureml_run = azureml_run
def on_init_end(self, args, state, cont... |
class ReconstructionLoss(nn.Module):
def __init__(self, losstype='l2', eps=1e-06):
super(ReconstructionLoss, self).__init__()
self.losstype = losstype
self.eps = eps
def forward(self, x, target):
if (self.losstype == 'l2'):
return torch.mean(torch.sum(((x - target) **... |
def test_SimpleImputer_params_vs_sklearn():
result = sorted(impute.SimpleImputer._skcriteria_parameters)
ignore = ['verbose', 'add_indicator', 'copy']
alias = {'keep_empty_features': 'keep_empty_criteria'}
expected = sorted([alias.get(p, p) for p in sklimpute.SimpleImputer().get_params(deep=False) if (p... |
def preprocess_data(X, Y, num_init):
dataset_size = X.size(0)
(x_min, _) = X.min(0)
(x_max, _) = X.max(0)
x_range = (x_max - x_min)
X = (2 * (((X - x_min) / x_range) - 0.5))
tmean = Y.mean()
tstd = Y.std()
Y = ((Y - tmean) / tstd)
(init_x, X) = (X[:num_init], X[num_init:])
(init_... |
(frozen=True)
class _ExponentialSchedule():
learning_rate: float
decay_steps: int
decay_rate: float
staircase: bool = False
def value(self, t):
m = (t / self.decay_steps)
if self.staircase:
m = np.floor(m)
return (self.learning_rate * (self.decay_rate ** m)) |
.parametrize('search, documents, k', [pytest.param((((retriever_a * retriever_b) * retriever_c) + documents()), documents(), k, id=f'Union retrievers: {retriever_a.__class__.__name__} | {retriever_b.__class__.__name__} | {retriever_c.__class__.__name__} k: {k}') for k in [None, 3, 4] for retriever_c in cherche_retrieve... |
def test_text(args, device_id, pt, step):
device = ('cpu' if (args.visible_gpus == '-1') else 'cuda')
if (pt != ''):
test_from = pt
else:
test_from = args.test_from
logger.info(('Loading checkpoint from %s' % test_from))
checkpoint = torch.load(test_from, map_location=(lambda storage... |
def get_args():
usage = ' Python script to resolve overlaps in ctms. May be used with\n utils/data/subsegment_data_dir.sh. '
parser = argparse.ArgumentParser(usage)
parser.add_argument('segments', type=argparse.FileType('r'), help='use segments to resolve overlaps')
parser.add_argument('... |
def coords(obj):
if isinstance(obj, (tuple, list)):
coordinates = obj
elif ('geometry' in obj):
coordinates = obj['geometry']['coordinates']
else:
coordinates = obj.get('coordinates', obj)
for e in coordinates:
if isinstance(e, (float, int)):
(yield tuple(coor... |
class Effect6503(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Capital Energy Turret')), 'capacitorNeed', src.getModifiedItemAttr('shipBonusDreadnoughtA3'), skill='Amarr Dreadnought', **kwargs) |
def matching(ratio):
imgs = {}
result = []
img_set = []
true_image_set = []
img_snr10_true = img('true__out__images.pickle')
img_snr10_rotate = img('rotation_var__out__images.pickle')
for i in range(100):
img_set.append(img_snr10_rotate[i])
if (i < int((100 * ratio))):
... |
class SubprocessOutputPoller():
def __init__(self, process):
super().__init__()
self.process = process
self._lines = []
self._lines_lock = Lock()
self._last_seen = time.monotonic()
self.data_ready = Event()
self._polling_thread = Thread(target=self.poll_stdout... |
def get_freeman_coordination(img: np.ndarray, contour: [(int, int)]) -> [int]:
freeman_coordination_list = list()
(freeman_x_coordination_list, freeman_y_coordination_list) = __get_freeman_box_list(img=img)
for point in contour:
(x, y) = point
point_freeman_coordination = __get_freeman_coord... |
def populate_params():
params = {}
params['fps'] = get_param('~fps')
params['frame_id'] = get_param('~frame_id')
params['retry_on_fail'] = get_param('~retry_on_fail')
params['buffer_queue_size'] = get_param('~buffer_queue_size')
params['python_node'] = get_param('~python_node')
return params |
def get_optimizer_param_groups(model, model_config, optimizer_config, optimizer_schedulers):
if optimizer_config.construct_single_param_group_only:
return [{'params': list(model.parameters()), 'lr': optimizer_schedulers['lr'], 'weight_decay': optimizer_config.weight_decay}]
if (not optimizer_config.head... |
('beeref.widgets.welcome_overlay.BeeSettings.get_recent_files', return_value=[])
def test_welcome_overlay_when_no_recent_files(qapp):
parent = QtWidgets.QMainWindow()
view = BeeGraphicsView(qapp, parent)
overlay = WelcomeOverlay(view)
overlay.show()
assert (overlay.layout.indexOf(overlay.files_widge... |
def resample_and_save(predicted, target_shape, output_file, force_separate_z=False, interpolation_order=1, interpolation_order_z=0):
if isinstance(predicted, str):
assert isfile(predicted), 'If isinstance(segmentation_softmax, str) then isfile(segmentation_softmax) must be True'
del_file = deepcopy(... |
class _DenseBlock(nn.Module):
def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate, memory_efficient=False):
super(_DenseBlock, self).__init__()
for i in range(num_layers):
layer = _DenseLayer((num_input_features + (i * growth_rate)), growth_rate=growth_rate... |
class AppsfuelOAuth2(BaseOAuth2):
name = 'appsfuel'
ID_KEY = 'user_id'
AUTHORIZATION_URL = '
ACCESS_TOKEN_URL = '
ACCESS_TOKEN_METHOD = 'POST'
USER_DETAILS_URL = '
def get_user_details(self, response):
email = response.get('email', '')
username = (email.split('')[0] if email ... |
('/xml_add', methods=['POST'])
def xml_add():
if (not session.get('logged_in')):
return redirect(url_for('login'))
obj = [elem.replace('.xml', '') for elem in os.listdir(('../%s/' % request.form['para2']))]
if (request.form['para1'] in obj):
code = 201
msg = ''
elif (request.form... |
class Visitor(VisitorBase, ABC, Generic[_Leaf_T]):
def visit(self, tree: Tree[_Leaf_T]) -> Tree[_Leaf_T]:
for subtree in tree.iter_subtrees():
self._call_userfunc(subtree)
return tree
def visit_topdown(self, tree: Tree[_Leaf_T]) -> Tree[_Leaf_T]:
for subtree in tree.iter_subt... |
.parametrize('image_name', png_images)
def test_pil_saving(image_test, image_name):
try:
from PIL import Image
except ImportError:
pytest.skip('PIL not available')
from pyglet.image.codecs.pil import PILImageEncoder
image_test.test_image_saving(PILImageEncoder(), image_name) |
def define_config():
return {'horizon': 15, 'sequence_length': 50, 'update_steps': 100, 'pretrain_steps': 100, 'discount': 0.99, 'lambda_': 0.95, 'steps_per_update': 1000, 'steps_per_critic_clone': 1000, 'batch_size': 32, 'warmup_training_steps': 5000, 'kl_scale': 1.0, 'kl_mix': 0.8, 'free_nats': 3.0, 'deterministi... |
def get_memory_list(unit='G', number_only=False, init_pid=None):
from pyrl.utils.data import num_to_str
if (init_pid is None):
init_pid = os.getpid()
process = psutil.Process(init_pid)
ret = [num_to_str(process.memory_full_info().uss, unit, number_only=number_only)]
for proc in process.child... |
def _check_mopidy_extensions_service() -> Dict[(str, Tuple[(bool, str)])]:
log = subprocess.check_output(['sudo', '/usr/local/sbin/raveberry/read_mopidy_log'], universal_newlines=True)
error_handling = {'spotify': [((lambda line: (line.startswith('ERROR') and ('spotify.session' in line) and ('USER_NEEDS_PREMIUM... |
_kernel_api(params={'grp': POINTER, 'attr': POINTER})
def hook__lck_mtx_alloc_init(ql, address, params):
lck_addr = ql.os.heap.alloc(ctypes.sizeof(lck_mtx_t))
lck = lck_mtx_t(ql, lck_addr)
if (params['grp'] > 0):
grp = lck_grp_t(ql, params['grp'])
grp.loadFromMem()
else:
grp = No... |
def convert(filename, stream=None):
name = path.basename(filename)
if name.endswith('.vim'):
name = name[:(- 4)]
f = file(filename)
code = f.read()
f.close()
writer = StyleWriter(code, name)
if (stream is not None):
out = stream
else:
out = StringIO()
writer.w... |
def getIdxMap_torch(img, offset=False):
(C, H, W) = img.shape
import torch
idx = torch.stack(torch.where((~ torch.isnan(img[0]))))
if offset:
idx = (idx.float() + 0.5)
idx = idx.view(2, (H * W)).float().contiguous()
idx = idx.transpose(0, 1)
idx = ((idx / (H - 1)) if (not offset) els... |
_fixtures(SqlAlchemyFixture, AccessDomainFixture)
def test_collaborator_rights(sql_alchemy_fixture, access_domain_fixture):
account = access_domain_fixture.account
address_book = access_domain_fixture.address_book
other_address_book = access_domain_fixture.other_address_book
other_address_book.allow(acc... |
class Serializer(xml_serializer.Serializer):
def handle_tagfield(self, obj, field):
tag_string = str(getattr(obj, field.name))
fake_obj = FakeObject(field.name, tag_string)
fake_field = FakeField(field.name)
self.handle_field(fake_obj, fake_field)
def handle_fk_field(self, obj, f... |
('jsonpath_ready')
def jsonpath_ready(stage, depspec, stagespec):
log.debug('checking jsonpath ready predicate\n%s', depspec)
dependencies = depspec['expressions']
for x in dependencies:
depmatches = stage.view.query(x, stage.view.steps)
if (not depmatches):
log.debug('no query m... |
def readFragmentScores(name='fpscores'):
import gzip
global _fscores
if (name == 'fpscores'):
name = op.join(op.dirname(__file__), name)
_fscores = cPickle.load(gzip.open(('%s.pkl.gz' % name)))
outDict = {}
for i in _fscores:
for j in range(1, len(i)):
outDict[i[j]] =... |
class TestSwitchEncoder():
def test_switch_encoder_and_head(self):
model = FakeTrainableModelWithSwitchEncoder()
dataset = FakePairDataset()
data_loader = PairsSimilarityDataLoader(dataset, batch_size=3)
trainer_args = Quaterion.trainer_defaults(model, data_loader)
trainer_ar... |
def get_center(mask):
if isinstance(mask, torch.Tensor):
mask = mask.detach().detach().cpu().numpy()
if (len(mask.shape) > 2):
mask = mask.reshape(mask.shape[(- 2):])
mask = (mask > 0.5)
moment = cv2.moments(mask.astype('float'))
if (moment['m00'] != 0):
cx = int((moment['m10... |
class PythonImplementationRequirement(Requirement):
def __init__(self, implementation_name: str):
self.implementation_name = implementation_name
super().__init__()
def _evaluate(self) -> bool:
return (sys.implementation.name == self.implementation_name)
def fail_reason(self) -> str:
... |
def list_action():
parser = ArgumentParser(usage='mprof list\nThis command takes no argument.')
parser.add_argument('--version', action='version', version=mp.__version__)
args = parser.parse_args()
filenames = get_profile_filenames('all')
for (n, filename) in enumerate(filenames):
ts = osp.s... |
class ResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes=10, deconv=None, delinear=None, channel_deconv=None):
super(ResNet, self).__init__()
self.in_planes = 64
if deconv:
self.deconv = True
self.conv1 = deconv(3, 64, kernel_size=3, stride=1, paddin... |
def load_expert():
data_dir = os.path.join(covid_data_dir, 'test', 'expert')
experts = ['biomedical_expert', 'computer_science_expert']
final_result = {}
for expert in experts:
folder = os.path.join(data_dir, expert)
filenames = [f for f in os.listdir(folder) if ('.swp' not in f)]
... |
class EnsembleAgent(CustomAgent):
def get_ranks_greedy(self, obs, infos, input_quest, input_quest_mask, quest_id_list, previous_commands, previous_dynamics, previous_belief):
with torch.no_grad():
batch_size = len(obs)
if (self.not_finished_yet is None):
self.not_fini... |
_head('infer_links')
class InferLinksHead(torch.nn.Module):
def __init__(self, dim_in, dim_out):
super().__init__()
if (cfg.dataset.infer_link_label == 'edge'):
dim_out = 2
else:
raise ValueError(f'Infer-link task {cfg.dataset.infer_link_label} not available.')
... |
def prepare_locked_transfer(properties, defaults):
properties: LockedTransferProperties = create_properties(properties, defaults)
params = unwrap_canonical_identifier(properties.__dict__)
secrethash = sha256(params.pop('secret')).digest()
params['lock'] = Lock(amount=params.pop('amount'), expiration=par... |
def test_period_object_column():
range_index = pd.period_range(start='2000', periods=10, freq='B')
df = pd.DataFrame({'a': 5, 'b': range_index}, index=range_index)
view = QgridWidget(df=df)
view._handle_qgrid_msg_helper({'type': 'change_sort', 'sort_field': 'index', 'sort_ascending': True})
view._ha... |
((pgv is None), 'pygraphviz is not available')
class TestParallelWithPyGraphviz(TestParallel):
def setUp(self):
class PGVMachine(HierarchicalGraphMachine):
def __init__(self, *args, **kwargs):
kwargs['use_pygraphviz'] = True
super(PGVMachine, self).__init__(*args,... |
class GraphGather(torch.nn.Module):
def __init__(self, node_features: int, hidden_node_features: int, out_features: int, att_depth: int, att_hidden_dim: int, att_dropout_p: float, emb_depth: int, emb_hidden_dim: int, emb_dropout_p: float, big_positive: float) -> None:
super().__init__()
self.big_pos... |
class HGFilter(nn.Module):
def __init__(self, opt):
super(HGFilter, self).__init__()
self.num_modules = opt.num_stack
self.opt = opt
if (opt.input_type == 'RGB'):
self.input_channel = 3
print('input type: RGB')
elif (opt.input_type == 'RGBD'):
... |
class TestSink(ComponentLevel2):
def construct(s, Type, answer):
assert (type(answer) == list), 'TestSink only accepts a list of outputs!'
s.answer = deque([(x if (x == '*') else Type(x)) for x in answer])
s.in_ = InPort(Type)
def up_sink():
if (not s.answer):
... |
class TestNcNWCSAFPPS():
def test_start_time(self, nwcsaf_pps_cmic_filehandler):
assert (nwcsaf_pps_cmic_filehandler.start_time == read_nwcsaf_time(START_TIME_PPS))
def test_end_time(self, nwcsaf_pps_cmic_filehandler):
assert (nwcsaf_pps_cmic_filehandler.end_time == read_nwcsaf_time(END_TIME_PPS... |
class WideResNet(nn.Module):
def __init__(self, depth=34, num_classes=10, widen_factor=10, dropRate=0.0):
super(WideResNet, self).__init__()
nChannels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)]
assert (((depth - 4) % 6) == 0)
n = ((depth - 4) / 6)
b... |
_arg_scope
def one_hot_encoding(labels, num_classes, on_value=1.0, off_value=0.0, outputs_collections=None, scope=None):
with ops.name_scope(scope, 'OneHotEncoding', [labels, num_classes]) as sc:
labels = ops.convert_to_tensor(labels)
if (labels.dtype == dtypes.int32):
labels = standard_... |
class Pile(object):
def __init__(self, squirrel=None):
if (squirrel is None):
squirrel = psq.Squirrel()
self._squirrel = squirrel
self._listeners = []
self._squirrel.get_database().add_listener(self._notify_squirrel_to_pile)
def _notify_squirrel_to_pile(self, event, *... |
def test_kernel_regularization():
((x_train, y_train), (x_test, y_test)) = get_data()
for reg in [regularizers.l1(), regularizers.l2(), regularizers.l1_l2()]:
model = create_model(kernel_regularizer=reg)
model.compile(loss='categorical_crossentropy', optimizer='sgd')
assert (len(model.lo... |
def render_page_template(name, route_data=None, **kwargs):
main_scripts = _list_files('build', 'js', JS_BUNDLE_NAME)
use_cdn = app.config.get('USE_CDN', True)
if (request.args.get('use_cdn') is not None):
use_cdn = (request.args.get('use_cdn') == 'true')
external_styles = get_external_css(local=... |
class PresetEchoesGoal(PresetTab, Ui_PresetEchoesGoal):
def __init__(self, editor: PresetEditor, game_description: GameDescription, window_manager: WindowManager):
super().__init__(editor, game_description, window_manager)
self.setupUi(self)
self.goal_layout.setAlignment(QtCore.Qt.AlignmentF... |
def point_adjustment(y_true, y_score):
score = y_score.copy()
assert (len(score) == len(y_true))
splits = (np.where((y_true[1:] != y_true[:(- 1)]))[0] + 1)
is_anomaly = (y_true[0] == 1)
pos = 0
for sp in splits:
if is_anomaly:
score[pos:sp] = np.max(score[pos:sp])
is_... |
def voc_palette():
return [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0], [0, 64,... |
def replace_natural_gas_technology(df: pd.DataFrame):
mapping = {'Steam Turbine': 'CCGT', 'Combustion Engine': 'OCGT', 'NG': 'CCGT', 'Ng': 'CCGT', 'NG/FO': 'OCGT', 'Ng/Fo': 'OCGT', 'NG/D': 'OCGT', 'LNG': 'OCGT', 'CCGT/D': 'CCGT', 'CCGT/FO': 'CCGT', 'LCCGT': 'CCGT', 'CCGT/Fo': 'CCGT'}
fueltype = (df['Fueltype'] ... |
class LeafPrinter(Printer):
def process(self, output, pstate):
if (output in pstate.memo):
return pstate.memo[output]
if (output.name in greek):
r = greek[output.name]
else:
r = str(output)
pstate.memo[output] = r
return r |
class BaseOptions():
def __init__(self):
self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
self.initialized = False
def initialize(self):
self.parser.add_argument('--name', type=str, default=None, help='name of the experiment. It decides where ... |
class YOLOX(nn.Module):
def __init__(self, backbone=None, head=None):
super().__init__()
if (backbone is None):
backbone = DFPPAFPN()
if (head is None):
head = TALHead(20)
self.backbone = backbone
self.head = head
def forward(self, x, targets=None,... |
_module()
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
super(ResNet, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
... |
def get_parser(desc, default_task='translation'):
usr_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
usr_parser.add_argument('--user-dir', default=None)
(usr_args, _) = usr_parser.parse_known_args()
utils.import_user_module(usr_args)
parser = argparse.ArgumentParser(allow_abbre... |
class CLIPConverter(Converter):
def converted(self) -> Tokenizer:
vocab = self.original_tokenizer.encoder
merges = list(self.original_tokenizer.bpe_ranks.keys())
unk_token = self.original_tokenizer.unk_token
tokenizer = Tokenizer(BPE(vocab=vocab, merges=merges, dropout=None, continui... |
def test_extract_header_comment(monkeypatch, tmp_path):
pot_file = (tmp_path / 'temp.pot')
monkeypatch.chdir(project_dir)
cmdinst = configure_cli_command(f"extract . -o '{pot_file}' --header-comment 'Boing' ")
cmdinst.run()
pot_content = pot_file.read_text()
assert ('Boing' in pot_content) |
def _load_and_check_geolocation(scene, resolution, exp_res, exp_shape, has_res, check_callback=_check_shared_metadata):
scene.load(['longitude', 'latitude'], resolution=resolution)
lon_id = make_dataid(name='longitude', resolution=exp_res)
lat_id = make_dataid(name='latitude', resolution=exp_res)
if has... |
def gen_imgs_classifier(samples, patches_dir):
num_samples = len(samples)
print('gen_imgs_classifier ', num_samples)
for (counter, batch_sample) in samples.iterrows():
with openslide.open_slide(batch_sample.slide_path) as slide:
tiles = DeepZoomGenerator(slide, tile_size=256, overlap=0, ... |
class BaseProcessingNet(nn.Sequential):
def __init__(self, in_dim, mid_dim, out_dim, num_layers, block=FCBlock, final_activation=None, normalization='batch'):
super(BaseProcessingNet, self).__init__()
self.add_module('input', block(in_dim=in_dim, out_dim=mid_dim, normalization=None))
for i i... |
def _introspect_attributes(program_id: int) -> dict:
attributes = {}
for index in range(_get_number(program_id, GL_ACTIVE_ATTRIBUTES)):
(a_name, a_type, a_size) = _query_attribute(program_id, index)
loc = glGetAttribLocation(program_id, create_string_buffer(a_name.encode('utf-8')))
(coun... |
def main():
args = parser.get_args()
args.use_gpu = torch.cuda.is_available()
if args.use_gpu:
torch.backends.cudnn.benchmark = True
if (args.launcher == 'none'):
args.distributed = False
else:
args.distributed = True
dist_utils.init_dist(args.launcher)
(_, wo... |
class _job_state_monitor(threading.Thread):
def __init__(self, job_service):
self.logger = job_service._logger
self.js = job_service
self._term = threading.Event()
super(_job_state_monitor, self).__init__()
self.setDaemon(True)
def stop(self):
self._term.set()
... |
class ConditionalFix(BaseFix):
skip_on = None
def start_tree(self, *args):
super(ConditionalFix, self).start_tree(*args)
self._should_skip = None
def should_skip(self, node):
if (self._should_skip is not None):
return self._should_skip
pkg = self.skip_on.split('.'... |
class FakeDisplayItem(dict):
def get(self, key, default='', connector=' - '):
if ((key[:1] == '~') and ('~' in key[1:])):
return connector.join(map(self.get, util.tagsplit(key)))
elif ((key[:1] == '~') and (key[(- 4):(- 3)] == ':')):
func = key[(- 3):]
key = key[:... |
class DependenciesWidget(QtWidgets.QTableView):
def __init__(self):
super().__init__(None)
self.root_model = DependenciesModel(self)
self.proxy_model = QtCore.QSortFilterProxyModel(self)
self.proxy_model.setSourceModel(self.root_model)
self.proxy_model.setSortCaseSensitivity(... |
.unit()
.parametrize(('prefix_tree', 'full_tree', 'strict', 'expected'), [(1, 1, True, False), (1, 1, False, True), ({'a': 1, 'b': 1}, {'a': 1, 'b': {'c': 1, 'd': 1}}, False, True), ({'a': 1, 'b': 1}, {'a': 1, 'b': {'c': 1, 'd': 1}}, True, True)])
def test_is_prefix(prefix_tree, full_tree, strict, expected):
prefix... |
def test_affixes():
s = '\nspace-allowed-after-this |\nspace-allowed-before-this\nspace-allowed-after-this\n space-required-before-and-after-this |\nspace-required-before-and-after-this |\n space-required-before-and-after-this<= no space after\n'
assert (list(MyLexer().get_tokens(s)) == [(Token.Name, 'space-all... |
def _get_pak_name(locale_name: str) -> str:
if (locale_name in {'en', 'en-PH', 'en-LR'}):
return 'en-US'
elif locale_name.startswith('en-'):
return 'en-GB'
elif locale_name.startswith('es-'):
return 'es-419'
elif (locale_name == 'pt'):
return 'pt-BR'
elif locale_name.... |
def new_onion_packet(payment_path_pubkeys: Sequence[bytes], session_key: bytes, hops_data: Sequence[OnionHopsDataSingle], associated_data: bytes) -> OnionPacket:
num_hops = len(payment_path_pubkeys)
assert (num_hops == len(hops_data))
hop_shared_secrets = get_shared_secrets_along_route(payment_path_pubkeys,... |
class BaseEvaluator():
env: gym.Env
policy: BasePolicy
MAX_EPISODE_STEPS = 1000
def setup(self, env_id: str, policy_cls: Type[BasePolicy], env_kwargs=None):
self.env_id = env_id
self.env_kwargs = ({} if (env_kwargs is None) else env_kwargs)
obs_mode = policy_cls.get_obs_mode(env_... |
class PointCompoundSource(SandboxSource):
__implements__ = 'CompoundModel'
rotation_x = Float.T(help='Clockwise rotation of ellipsoid around x-axis in [deg]', default=0.0)
rotation_y = Float.T(help='Clockwise rotation of ellipsoid around y-axis in [deg]', default=0.0)
rotation_z = Float.T(help='Clockwis... |
class Invoice(TimeStampedModel):
sender = models.ForeignKey(Sender, verbose_name=_('Sender'), on_delete=models.PROTECT)
is_business = models.BooleanField(default=False)
invoice_number = models.CharField(_('Invoice number'), max_length=20)
invoice_type = models.CharField(_('Invoice type'), choices=INVOIC... |
def get_module_summary(module: torch.nn.Module, module_args: Optional[Tuple[(Any, ...)]]=None, module_kwargs: Optional[MutableMapping[(str, Any)]]=None) -> ModuleSummary:
module_summary_data = _ModuleSummaryData()
has_uninitialized_param = _has_uninitialized_param(module)
if (not has_uninitialized_param):
... |
class SwinUnet(nn.Module):
def __init__(self, config, img_size=224, num_classes=21843, zero_head=False, vis=False):
super(SwinUnet, self).__init__()
self.num_classes = num_classes
self.zero_head = zero_head
self.config = config
self.swin_unet = SwinTransformerSys(img_size=con... |
def delete_redundant_edges_and_ids(graph):
class_nodes_delete = ['wall', 'floor', 'ceiling', 'door', 'curtain', 'window', 'doorjamb']
ids_delete = [x['id'] for x in graph['nodes'] if (x['class_name'] in class_nodes_delete)]
graph['nodes'] = [x for x in graph['nodes'] if (x['id'] not in ids_delete)]
grap... |
def test_fips_hash_manager_md5(monkeypatch):
replaced_md5 = pretend.raiser(ValueError('fipsmode'))
monkeypatch.setattr(package_file.hashlib, 'md5', replaced_md5)
filename = 'tests/fixtures/twine-1.5.0-py2.py3-none-any.whl'
hasher = package_file.HashManager(filename)
hasher.hash()
hashes = TWINE_... |
def register_task(name, dataclass=None):
def register_task_cls(cls):
if (name in TASK_REGISTRY):
raise ValueError('Cannot register duplicate task ({})'.format(name))
if (not issubclass(cls, FairseqTask)):
raise ValueError('Task ({}: {}) must extend FairseqTask'.format(name, c... |
def get_platforms_filepath():
config_path = _get_config_path()
platform_file = os.path.join(config_path, 'platforms.txt')
if (not os.path.isfile(platform_file)):
platform_file = os.path.join(PKG_CONFIG_DIR, 'platforms.txt')
if (not os.path.isfile(platform_file)):
raise OSError('P... |
class Effect1035(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Shield Emission Systems')), 'capacitorNeed', src.getModifiedItemAttr('eliteBonusLogistics2'), skill='Logistics Cruisers', **kwargs) |
_cache
def load_ld_paths(root: str='/', prefix: str='') -> dict[(str, list[str])]:
ldpaths: dict = {'conf': [], 'env': [], 'interp': []}
env_ldpath = os.environ.get('LD_LIBRARY_PATH')
if (env_ldpath is not None):
if (root != '/'):
log.warning('ignoring LD_LIBRARY_PATH due to ROOT usage')... |
def rmepsilon(ifst, connect=True, reverse=False, queue_type='auto', delta=_weight.DELTA, weight=None, nstate=_fst.NO_STATE_ID):
try:
queue_type = _getters.GetQueueType(queue_type)
except ValueError:
raise ValueError('Unknown queue type: {!r}'.format(queue_type))
weight = _get_weight_or_defau... |
class SignalReference(XodrBase):
_usedIDs = {}
_IDCounter = {}
def __init__(self, s, t, id=None, orientation=Orientation.positive):
super().__init__()
self.s = s
self.t = t
self.orientation = orientation
self.validity = None
self.id = id
def __eq__(self, o... |
def Save_info(fun):
def work(*args, **kwargs):
result = fun(*args, **kwargs)
if result:
timetoken = str(int(time.time()))
filename = 'Output/{}_result_{}.rabbit'.format(fun.__name__, timetoken)
for i in result:
try:
fw = open(fi... |
class ForestToPyDotVisitor(ForestVisitor):
def __init__(self, rankdir='TB'):
super(ForestToPyDotVisitor, self).__init__(single_visit=True)
self.pydot = import_module('pydot')
self.graph = self.pydot.Dot(graph_type='digraph', rankdir=rankdir)
def visit(self, root, filename):
super... |
def downsample_avg(in_chs, out_chs, kernel_size=1, stride=1, dilation=1, norm_layer=None, preact=False):
norm_layer = (norm_layer or nn.BatchNorm2d)
avg_stride = (stride if (dilation == 1) else 1)
pool = nn.Identity()
if ((stride > 1) or (dilation > 1)):
avg_pool_fn = (AvgPool2dSame if ((avg_str... |
def test_utime_as_datetime():
the_utime =
actual_dt1 = qcore.utime_as_datetime(the_utime)
assert_eq(actual_dt1.tzname(), 'UTC')
assert_eq(actual_dt1, datetime(2022, 10, 31, 18, 2, 3, 123456, tzinfo=timezone.utc))
actual_dt2 = qcore.utime_as_datetime(the_utime, tz=PLUS_7_TZ)
assert_eq(actual_dt2... |
def test_matrix(hatch, helpers, temp_dir_data, config_file):
config_file.model.template.plugins['default']['tests'] = False
config_file.save()
project_name = 'My.App'
with temp_dir_data.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code == 0), result.output
project_pa... |
class SawyerPegUnplugSideV2Policy(Policy):
_fully_parsed
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'unused_gripper': obs[3], 'peg_pos': obs[4:7], 'unused_info': obs[7:]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_ef... |
class _Looks(BaseSprite):
def __init__(self):
super().__init__()
def looks_switchbackdropto(self, backdrop):
self.stage.costume_manager.switch_costume(backdrop)
def looks_nextbackdrop(self):
self.stage.costume_manager.next_costume()
def looks_seteffectto_color(self, value):
... |
_task('multilingual_masked_lm')
class MultiLingualMaskedLMTask(FairseqTask):
def add_args(parser):
parser.add_argument('data', help='colon separated path to data directories list, will be iterated upon during epochs in round-robin manner')
parser.add_argument('--sample-br... |
class MobileNetV3(nn.Module):
def __init__(self, model_mode='LARGE', num_classes=1000, multiplier=1.0, dropout_rate=0.0, output_layers=['default']):
super(MobileNetV3, self).__init__()
self.num_classes = num_classes
self.output_layers = output_layers
if (model_mode == 'LARGE'):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.