code stringlengths 281 23.7M |
|---|
def test_unsupported_dtypes():
a = np.zeros((10, 10), np.float64)
with pytest.raises(ValueError):
gfx.Texture(a, dim=2)
a = np.zeros((10, 10), np.int64)
with pytest.raises(ValueError):
gfx.Texture(a, dim=2)
a = np.zeros((10, 10), np.uint64)
with pytest.raises(ValueError):
... |
def create_session():
initialize_globals()
early_training_checks()
tfv1.reset_default_graph()
session = tfv1.Session(config=Config.session_config)
(inputs, outputs, _) = create_inference_graph(batch_size=1, n_steps=(- 1))
load_graph_for_evaluation(session)
DeepSpeechGlobalSession.session = s... |
class TestCurrentFunctions(TestCase):
def test_constant_current(self):
param = pybamm.electrical_parameters
current = param.current_with_time
parameter_values = pybamm.ParameterValues({'Current function [A]': 2})
processed_current = parameter_values.process_symbol(current)
se... |
class FlagZeroAsFailure(Bloq):
num_bits_p: int
adjoint: bool = False
_property
def signature(self) -> Signature:
return Signature([Register('nu', (self.num_bits_p + 1), shape=(3,)), Register('flag_minus_zero', 1, side=Side.RIGHT)])
def short_name(self) -> str:
return '$\\nu\\ne -0$'
... |
def main():
args = parse_args()
root_path = args.root_path
img_dir = osp.join(root_path, 'imgs')
gt_dir = osp.join(root_path, 'annotations')
set_name = {}
for split in ['training', 'test']:
set_name.update({split: ((split + '_label') + '.txt')})
assert osp.exists(osp.join(img_dir... |
def _print_usage(error_message=None):
if error_message:
print(error_message)
print(('\nUsage: %s [OPTION]... PATH\n Delete PATH from a rdiff-backup repository including the current\n mirror and all its history.\nOptions:\n h, --help\n Display this help text and exit\n d, --dry-run... |
class MoveShard(BaseModel, extra='forbid'):
shard_id: int = Field(..., description='')
to_peer_id: int = Field(..., description='')
from_peer_id: int = Field(..., description='')
method: Optional['ShardTransferMethod'] = Field(default=None, description='Method for transferring the shard from one node to... |
def fill_template_strings_from_tree(template_strings: dict[(str, list[str])], tree: ConditionalMessageTree) -> None:
for (category, entries) in tree.items():
if (category not in template_strings):
template_strings[category] = []
for entry in entries:
messages = [message for (... |
class RealUrlExtractor():
__metaclass__ = ABCMeta
lock = Lock()
def __init__(self, room, auto_refresh_interval):
self.room = room
self.real_url = None
self.last_valid_real_url = None
self._extracting_real_url = False
self.auto_refresh_interval = auto_refresh_interval
... |
class TestMimicTPW2Reader(unittest.TestCase):
yaml_file = 'mimicTPW2_comp.yaml'
def setUp(self):
from satpy._config import config_search_paths
from satpy.readers.mimic_TPW2_nc import MimicTPW2FileHandler
self.reader_configs = config_search_paths(os.path.join('readers', self.yaml_file))
... |
def comp_coverage(src_data, tgt_data, ali_data):
(src_align, tgt_align) = ([], [])
for idx in tqdm(range(len(src_data))):
src = src_data[idx].strip('\n').split()
tgt = tgt_data[idx].strip('\n').split()
ali = ali_data[idx].strip('\n').split()
(src_ali, tgt_ali) = ([], [])
... |
class MyUnit(TrainUnit[Iterator[Batch]], EvalUnit[Iterator[Batch]]):
def __init__(self, module: torch.nn.Module, optimizer: torch.optim.Optimizer, device: torch.device, tb_logger: TensorBoardLogger, train_auroc: BinaryAUROC, log_every_n_steps: int) -> None:
super().__init__()
self.module = module
... |
class SoftmaxBlurBlock(nn.Module):
def __init__(self, in_filters, temp=10.0, sfilter=(1, 1), pad_mode='constant', **kwargs):
super(SoftmaxBlurBlock, self).__init__()
self.temp = temp
self.relu = layers.relu()
self.softmax = nn.Softmax(dim=1)
self.blur = layers.blur(in_filters... |
class DSBUFFERDESC(ctypes.Structure):
_fields_ = [('dwSize', DWORD), ('dwFlags', DWORD), ('dwBufferBytes', DWORD), ('dwReserved', DWORD), ('lpwfxFormat', LPWAVEFORMATEX)]
def __repr__(self):
return 'DSBUFFERDESC(dwSize={}, dwFlags={}, dwBufferBytes={}, lpwfxFormat={})'.format(self.dwSize, self.dwFlags, ... |
def compute_ne_helper(ce_sum: torch.Tensor, weighted_num_samples: torch.Tensor, pos_labels: torch.Tensor, neg_labels: torch.Tensor, eta: float) -> torch.Tensor:
mean_label = (pos_labels / weighted_num_samples)
ce_norm = _compute_cross_entropy_norm(mean_label, pos_labels, neg_labels, eta)
return (ce_sum / ce... |
def get_token_network_by_address(chain_state: ChainState, token_network_address: TokenNetworkAddress) -> Optional[TokenNetworkState]:
token_network_state = None
for token_network_registry_state in chain_state.identifiers_to_tokennetworkregistries.values():
networks_by_address = token_network_registry_st... |
class DeviceNumberHypothesis(Hypothesis):
def _match_major_minor(cls, value):
major_minor_re = re.compile('^(?P<major>\\d+)(\\D+)(?P<minor>\\d+)$')
match = major_minor_re.match(value)
return (match and os.makedev(int(match.group('major')), int(match.group('minor'))))
def _match_number(cl... |
def gen_forward():
kernels = [3, 5, 7, 15, 31, 63, 127, 255]
blocks = [32, 64, 128, 256]
head = '\n/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#include "dy... |
def test_memoize_key_signature():
mf = memoize((lambda x: False), cache={1: True})
assert (mf(1) is True)
assert (mf(2) is False)
mf = memoize((lambda x, *args: False), cache={(1,): True, (1, 2): 2})
assert (mf(1) is True)
assert (mf(2) is False)
assert (mf(1, 1) is False)
assert (mf(1, ... |
def find_users_bash_config(home_dir):
bash_files = ['/.bashrc', '/.bash_profile', '/.profile']
for file in bash_files:
if os.path.isfile((home_dir + file)):
return (home_dir + file)
raise RuntimeError(("Bummer looks, like we couldn't find a bash profile file. " + 'Do you have a ~/.profil... |
class Command(BaseCommand):
help = 'Update old news'
def handle(self, *args, **options):
prev_date = (datetime.datetime.now() - datetime.timedelta(days=10))
items = Item.objects.filter(id__in=ItemClsCheck.objects.filter(last_check__lte=prev_date).values_list('item', flat=True))
update_cl... |
class _Function(object):
def __init__(self, inputs, outputs, updates, givens):
for inpt in inputs:
if ((not hasattr(inpt, 'make_feed_dict')) and (not ((type(inpt) is tf.Tensor) and (len(inpt.op.inputs) == 0)))):
assert False, 'inputs should all be placeholders, constants, or have... |
def test_payee_timeout_must_be_equal_to_payer_timeout():
block_number = BlockNumber(5)
pseudo_random_generator = random.Random()
channels = mediator_make_channel_pair()
payer_transfer = factories.make_signed_transfer_for(channels[0], LockedTransferSignedStateProperties(expiration=BlockExpiration(30)))
... |
.parametrize('support_shape, shape, support_shape_offset, expected_support_shape, ndim_supp, consistent', [((10, 5), None, (0,), (10, 5), 1, True), ((10, 5), None, (1, 1), (10, 5), 1, True), (None, (10, 5), (0,), 5, 1, True), (None, (10, 5), (1,), 4, 1, True), (None, (10, 5, 2), (0,), 2, 1, True), (None, None, None, No... |
_model
def test_energy():
Monomer('A', ['a', 'b'])
Monomer('B', ['a'])
Parameter('RT', 2)
Parameter('A_0', 10)
Parameter('AB_0', 10)
Parameter('phi', 0)
Expression('E_AAB_RT', ((- 5) / RT))
Expression('E0_AA_RT', ((- 1) / RT))
Rule('A_dimerize', ((A(a=None) + A(a=None)) | (A(a=1) % A... |
def Lop(f: Union[(Variable, Sequence[Variable])], wrt: Union[(Variable, Sequence[Variable])], eval_points: Union[(Variable, Sequence[Variable])], consider_constant: Optional[Sequence[Variable]]=None, disconnected_inputs: Literal[('ignore', 'warn', 'raise')]='raise') -> Union[(Optional[Variable], Sequence[Optional[Varia... |
class AGNewsProcessor_sep(DataProcessor):
def get_train_examples(self, data_dir):
train_data = pd.read_csv(os.path.join(data_dir, 'train.csv'), header=None).values
return self._create_examples(train_data, 'train')
def get_dev_examples(self, data_dir):
dev_data = pd.read_csv(os.path.join(... |
def visualize_sample_with_prediction(image, gt, prediction, filename=None):
cmap = color_map()
image = image.cpu().numpy()
image[0] = ((image[0] * 0.229) + 0.485)
image[1] = ((image[1] * 0.224) + 0.456)
image[2] = ((image[2] * 0.225) + 0.406)
image = np.transpose((255 * image), (1, 2, 0)).astype... |
('aimet_common.connected_graph.connectedgraph.ConnectedGraph.__abstractmethods__', set())
def test_export_connected_graph():
conn_graph = get_dummy_connected_graph()
connectedgraph_utils.export_connected_graph(conn_graph, '/tmp/', 'dummy_cg_export')
with open('/tmp/dummy_cg_export.json', 'r') as cg_export_f... |
class CmdDoff(Command):
key = 'doff'
help_category = 'combat'
def func(self):
if is_in_combat(self.caller):
self.caller.msg("You can't doff armor in a fight!")
return
if (not self.caller.db.worn_armor):
self.caller.msg("You aren't wearing any armor!")
... |
def _get_users_handler(auth_type):
config = {}
config['AUTHENTICATION_TYPE'] = auth_type
config['LDAP_BASE_DN'] = ['dc=quay', 'dc=io']
config['LDAP_ADMIN_DN'] = 'uid=testy,ou=employees,dc=quay,dc=io'
config['LDAP_ADMIN_PASSWD'] = 'password'
config['LDAP_USER_RDN'] = ['ou=employees']
return g... |
def test_history_with_span_end(base_app):
run_cmd(base_app, 'help')
run_cmd(base_app, 'shortcuts')
run_cmd(base_app, 'help history')
(out, err) = run_cmd(base_app, 'history :2')
expected = normalize('\n 1 help\n 2 shortcuts\n')
assert (out == expected)
verify_hi_last_result(base_app,... |
def find_code_in_transformers(object_name):
parts = object_name.split('.')
i = 0
module = parts[i]
while ((i < len(parts)) and (not os.path.isfile(os.path.join(TRANSFORMERS_PATH, f'{module}.py')))):
i += 1
if (i < len(parts)):
module = os.path.join(module, parts[i])
if (i... |
def wrap_text(text, font, allowed_width):
words = text.split()
lines = []
max_lw = 0
max_lh = 0
while (len(words) > 0):
line_words = []
while (len(words) > 0):
line_words.append(words.pop(0))
if (len(line_words) == 1):
(lw, lh) = font.size(line... |
class DocstringSignatureGenerator(SignatureGenerator):
def get_function_sig(self, default_sig: FunctionSig, ctx: FunctionContext) -> (list[FunctionSig] | None):
inferred = infer_sig_from_docstring(ctx.docstring, ctx.name)
if inferred:
assert (ctx.docstring is not None)
if is_... |
class TextStyle(AnsiSequence, Enum):
RESET_ALL = 0
ALT_RESET_ALL = ''
INTENSITY_BOLD = 1
INTENSITY_DIM = 2
INTENSITY_NORMAL = 22
ITALIC_ENABLE = 3
ITALIC_DISABLE = 23
OVERLINE_ENABLE = 53
OVERLINE_DISABLE = 55
STRIKETHROUGH_ENABLE = 9
STRIKETHROUGH_DISABLE = 29
UNDERLINE_... |
class DiffEqWrapper(nn.Module):
def __init__(self, module):
super(DiffEqWrapper, self).__init__()
self.module = module
def forward(self, t, y):
if ('t' in signature(self.module.forward).parameters):
return self.module.forward(t, y)
elif ('y' in signature(self.module.f... |
def _compute_dloss_by_dx(encoding_min: tf.Variable, encoding_max: tf.Variable, inputs: tf.Tensor, op_mode: tf.Variable, grad: tf.Tensor) -> tf.Variable:
x = tf.cast(inputs[0], tf.float32)
encoding_min = tf.cast(encoding_min, tf.float32)
encoding_max = tf.cast(encoding_max, tf.float32)
op_mode = tf.cast(... |
def get_inc(rp, typestr, inc_time):
def addtostr(s):
return b'.'.join(map(os.fsencode, (s, Time.timetostring(inc_time), typestr)))
if rp.index:
incrp = rp.__class__(rp.conn, rp.base, (rp.index[:(- 1)] + (addtostr(rp.index[(- 1)]),)))
else:
(dirname, basename) = rp.dirsplit()
... |
def _get_single_hud_text(pickup_name: str, memo_data: dict[(str, str)], resources: ResourceGainTuple) -> str:
return memo_data[pickup_name].format(**{**{item_names.resource_user_friendly_name(resource): abs(quantity) for (resource, quantity) in resources}, **{item_names.resource_user_friendly_delta(resource): ('inc... |
def _get_bpe(in_path: str, model_prefix: str, vocab_size: int):
arguments = [f'--input={in_path}', f'--model_prefix={model_prefix}', f'--model_type=bpe', f'--vocab_size={vocab_size}', '--character_coverage=1.0', '--normalization_rule_name=identity', f'--num_threads={cpu_count()}']
sp.SentencePieceTrainer.Train(... |
def _wrap_core(wrapping_key: bytes, a: bytes, r: list[bytes]) -> bytes:
encryptor = Cipher(AES(wrapping_key), ECB()).encryptor()
n = len(r)
for j in range(6):
for i in range(n):
b = encryptor.update((a + r[i]))
a = (int.from_bytes(b[:8], byteorder='big') ^ (((n * j) + i) + 1)... |
def count_parameters(model, verbose=True):
n_all = sum((p.numel() for p in model.parameters()))
n_trainable = sum((p.numel() for p in model.parameters() if p.requires_grad))
if verbose:
print('Parameter Count: all {:,d}; trainable {:,d}'.format(n_all, n_trainable))
return (n_all, n_trainable) |
def PGM_feature_generation(opt):
video_dict = getDatasetDict(opt)
video_list = video_dict.keys()
num_videos = len(video_list)
num_videos_per_thread = (num_videos / opt['pgm_thread'])
processes = []
for tid in range((opt['pgm_thread'] - 1)):
tmp_video_list = video_list[(tid * num_videos_p... |
_dataframe_method
_alias(rows='index')
def select(df: pd.DataFrame, *args, index: Any=None, columns: Any=None, axis: str='columns', invert: bool=False) -> pd.DataFrame:
if args:
check('invert', invert, [bool])
if ((index is not None) or (columns is not None)):
raise ValueError('Either pr... |
class SystemSendToChannel(COMMAND_DEFAULT_CLASS):
key = CMD_CHANNEL
locks = 'cmd:all()'
def parse(self):
(channelname, msg) = self.args.split(':', 1)
self.args = (channelname.strip(), msg.strip())
def func(self):
caller = self.caller
(channelkey, msg) = self.args
... |
class TestChangeKeyboardMapping(EndianTest):
def setUp(self):
self.req_args_0 = {'first_keycode': 157, 'keysyms': [[, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ]]}
self.req_bin_0 = b"d\x14... |
(simple_typed_attrs(defaults=True, kw_only=False, newtypes=False))
def test_simple_roundtrip_defaults_tuple(attr_and_vals):
(a, _) = attr_and_vals
cl = make_class('HypClass', {'a': a})
converter = Converter(unstruct_strat=UnstructureStrategy.AS_TUPLE)
inst = cl()
assert (converter.unstructure(conver... |
class TestORegan2022(TestCase):
def test_functions(self):
param = pybamm.ParameterValues('ORegan2022')
T = pybamm.Scalar(298.15)
c_p_max = param['Maximum concentration in positive electrode [mol.m-3]']
c_n_max = param['Maximum concentration in negative electrode [mol.m-3]']
f... |
def compute_quartiles(values):
n = len(values)
assert (n > 0)
if (n == 1):
return (values[0], values[0], values[0])
median = get_median(values)
half = (n // 2)
if ((n % 2) == 0):
q1 = get_median(values[:half])
q3 = get_median(values[half:])
elif ((n % 4) == 1):
... |
class Latin1TextListSpec(Spec):
def __init__(self, name, default=[]):
super(Latin1TextListSpec, self).__init__(name, default)
self._bspec = ByteSpec('entry_count', default=0)
self._lspec = Latin1TextSpec('child_element_id')
def read(self, header, frame, data):
(count, data) = sel... |
class Distribution(torch.Tensor):
def init_distribution(self, dist_type, **kwargs):
self.dist_type = dist_type
self.dist_kwargs = kwargs
if (self.dist_type == 'normal'):
(self.mean, self.var) = (kwargs['mean'], kwargs['var'])
elif (self.dist_type == 'categorical'):
... |
_torch
class LukeTokenizerIntegrationTests(unittest.TestCase):
tokenizer_class = LukeTokenizer
from_pretrained_kwargs = {'cls_token': '<s>'}
def setUp(self):
super().setUp()
def test_single_text_no_padding_or_truncation(self):
tokenizer = LukeTokenizer.from_pretrained('studio-ousia/luke-... |
def get_environment(cache_size=MAX_CACHE_SIZE, maxage=timedelta(seconds=0), targetID=None, use_volatile=False):
env_cmd = ops.cmd.getDszCommand('environment -get')
return ops.project.generic_cache_get(env_cmd, cache_tag=ENVIRONMENT_TAG, cache_size=MAX_CACHE_SIZE, maxage=maxage, targetID=targetID, use_volatile=u... |
class Sobel(nn.Module):
def __init__(self):
super(Sobel, self).__init__()
self.edge_conv = nn.Conv2d(1, 2, kernel_size=3, stride=1, padding=1, bias=False)
edge_kx = np.array([[(- 1), 0, 1], [(- 2), 0, 2], [(- 1), 0, 1]])
edge_ky = np.array([[1, 2, 1], [0, 0, 0], [(- 1), (- 2), (- 1)]... |
class Irradiance():
def setup(self):
self.times = pd.date_range(start='', freq='1min', periods=14400)
self.days = pd.date_range(start='', freq='d', periods=30)
self.location = location.Location(40, (- 80))
self.solar_position = self.location.get_solarposition(self.times)
self... |
def assert_wrapper(__wrapped_mock_method__: Callable[(..., Any)], *args: Any, **kwargs: Any) -> None:
__tracebackhide__ = True
try:
__wrapped_mock_method__(*args, **kwargs)
return
except AssertionError as e:
if getattr(e, '_mock_introspection_applied', 0):
msg = str(e)
... |
.parametrize('input_type', [tuple, list])
def test_run_model_from_effective_irradiance_multi_array(sapm_dc_snl_ac_system_Array, location, weather, total_irrad, input_type):
data = weather.copy()
data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad
data['effective_irradiance'] = data['poa_global']... |
_criterion('cross_entropy')
class CrossEntropyCriterion(FairseqCriterion):
def __init__(self, args, task):
super().__init__(args, task)
def forward(self, model, sample, reduce=True):
net_output = model(**sample['net_input'])
(loss, _) = self.compute_loss(model, net_output, sample, reduce... |
def check_args(args):
args.text_in_handle = (sys.stdin if (args.text_in == '-') else open(args.text_in, 'r'))
args.prob_file_handle = (sys.stdout if (args.prob_file == '-') else open(args.prob_file, 'w'))
if (args.log_base <= 0):
sys.exit('compute_sentence_probs_arpa.py: Invalid log base (must be gr... |
.parametrize('fields_to_test', [pytest.param(combination, id=','.join(combination)) for combination in itertools.combinations(randovania.interface_common.options._SERIALIZER_FOR_FIELD.keys(), 2)])
def test_load_from_disk_with_data(fields_to_test: list[str], tmp_path, mocker):
mock_get_persisted_options_from_data: M... |
def test_StandarScaler_simple_both():
dm = skcriteria.mkdm(matrix=[[1, 2, 3], [4, 5, 6]], objectives=[min, max, min], weights=[1, 2, 3])
expected = skcriteria.mkdm(matrix=[[((1 - 2.5) / 1.5), ((2 - 3.5) / 1.5), ((3 - 4.5) / 1.5)], [((4 - 2.5) / 1.5), ((5 - 3.5) / 1.5), ((6 - 4.5) / 1.5)]], objectives=[min, max,... |
class TaskRenderer(TasksRendererMixin, ConditionRendererMixin, AttributeRendererMixin, OptionRendererMixin, BaseXMLRenderer):
def render_document(self, xml, tasks):
xml.startElement('rdmo', {'xmlns:dc': ' 'version': self.version, 'created': self.created})
for task in tasks:
self.render_t... |
def lupdate():
fname = 'pyzo.pro'
filename = os.path.realpath(os.path.join(pyzo.pyzoDir, '..', fname))
if (not os.path.isfile(filename)):
raise ValueError('Could not find {}. This function must run from the source repo.'.format(fname))
pysideDir = os.path.abspath(os.path.dirname(pyzo.QtCore.__fi... |
class VGGLoss(nn.Module):
def __init__(self, gpu_ids):
super(VGGLoss, self).__init__()
self.vgg = Vgg19().cuda()
self.criterion = nn.L1Loss()
self.weights = [(1.0 / 32), (1.0 / 16), (1.0 / 8), (1.0 / 4), 1.0]
def forward(self, x, y):
(x_vgg, y_vgg) = (self.vgg(x), self.vg... |
class PrecertificateSignedCertificateTimestamps(ExtensionType):
oid = ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS
def __init__(self, signed_certificate_timestamps: typing.Iterable[SignedCertificateTimestamp]) -> None:
signed_certificate_timestamps = list(signed_certificate_timestamps)
if ... |
def multiprocess_nodes(cloud_object_function, nodes):
try:
pool = ThreadPool(processes=len(nodes))
logging.info(('nodes type ' + str(type(nodes[0]))))
if (type(nodes[0]) is tuple):
node_id = []
node_info = []
for node in nodes:
node_id.appe... |
def get_fbank(path_or_fp: Union[(str, BinaryIO)], n_bins=80) -> np.ndarray:
(waveform, sample_rate) = get_waveform(path_or_fp, normalization=False)
features = _get_kaldi_fbank(waveform, sample_rate, n_bins)
if (features is None):
features = _get_torchaudio_fbank(waveform, sample_rate, n_bins)
if... |
def load_word2vec(emb_path, id_to_word, word_dim, old_weights):
new_weights = old_weights
print('Loading pretrained embeddings from {}...'.format(emb_path))
pre_trained = {}
emb_invalid = 0
for (i, line) in enumerate(codecs.open(emb_path, 'r', 'utf-8')):
line = line.rstrip().split()
... |
def test_locker_properly_assigns_metadata_files(locker: Locker) -> None:
content = '[[package]]\nname = "demo"\nversion = "1.0"\ndescription = ""\noptional = false\npython-versions = "*"\ndevelop = false\n\n[[package]]\nname = "demo"\nversion = "1.0"\ndescription = ""\noptional = false\npython-versions = "*"\ndevel... |
def create_supervised_evaluator(model, metrics, device=None):
if device:
model.to(device)
def fliplr(img):
inv_idx = torch.arange((img.size(3) - 1), (- 1), (- 1)).long().cuda()
img_flip = img.index_select(3, inv_idx)
return img_flip
def _inference(engine, batch):
mode... |
class Model(OriginalModel):
def __init__(self, *args, **kwargs):
logger.debug('Initializing %s: (args: %s, kwargs: %s', self.__class__.__name__, args, kwargs)
kwargs['input_shape'] = (64, 64, 3)
kwargs['encoder_dim'] = 1024
self.kernel_initializer = RandomNormal(0, 0.02)
supe... |
class AsyncRunner():
def __init__(self, args: Any) -> None:
self.args = args
self.threaded_browser: Optional[ServiceBrowser] = None
self.aiozc: Optional[AsyncZeroconf] = None
async def async_run(self) -> None:
self.aiozc = AsyncZeroconf(ip_version=ip_version)
assert (self... |
def pytest_configure(config):
manager = config.pluginmanager
order = manager.hook.pytest_collection_modifyitems.get_hookimpls()
dest = next((i for (i, p) in enumerate(order) if (p.plugin is manager.getplugin('randomly'))), None)
if (dest is not None):
from_pos = next((i for (i, p) in enumerate(o... |
def test_it_works_with_the_simplest_test_items(ourtester):
ourtester.makepyfile(conftest='\n import sys\n\n import pytest\n\n\n class MyCollector(pytest.Collector):\n def __init__(self, fspath, items, **kwargs):\n super(MyCollector, self).__init__(fspath, **kwargs)\n ... |
class Effect5631(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Cruise Missiles')), 'explosiveDamage', ship.getModifiedItemAttr('shipBonusMB'), skill='Minmatar Battleship', **kwargs) |
def test_organization_teams_sync_bool(app):
with mock_ldap() as ldap:
with patch('endpoints.api.organization.authentication', ldap):
with client_with_identity('devtable', app) as cl:
resp = conduct_api_call(cl, Organization, 'GET', {'orgname': 'sellnsmall'})
asser... |
def split_dataset(dataset, seed):
logger.info('Splitting the dataset')
scaffolds = pd.value_counts(dataset['scaffold'])
scaffolds = sorted(scaffolds.items(), key=(lambda x: ((- x[1]), x[0])))
test_scaffolds = set([x[0] for x in scaffolds[9::10]])
dataset['SPLIT'] = 'train'
test_scaf_idx = [(x in... |
class ResMLPBlock(nn.Module):
def __init__(self, channels):
super().__init__()
self.fc1 = nn.Sequential(nn.Linear(channels, channels), nn.BatchNorm1d(channels), nn.ReLU(inplace=True))
self.fc2 = nn.Sequential(nn.Linear(channels, channels), nn.BatchNorm1d(channels))
self.relu = nn.ReL... |
def next_step(model_output: Union[(torch.FloatTensor, np.ndarray)], timestep: int, sample: Union[(torch.FloatTensor, np.ndarray)], ddim_scheduler):
(timestep, next_timestep) = (min((timestep - (ddim_scheduler.config.num_train_timesteps // ddim_scheduler.num_inference_steps)), 999), timestep)
alpha_prod_t = (ddi... |
class Pow(BinaryScalarOp):
nfunc_spec = ('power', 2, 1)
def impl(self, x, y):
return (x ** y)
def c_code(self, node, name, inputs, outputs, sub):
(x, y) = inputs
(z,) = outputs
if ((node.inputs[0].type in complex_types) or (node.inputs[1].type in complex_types)):
... |
def do_patches(patches):
for patch in patches:
patch_id = patch['id']
for patch_file in patch['files']:
patch_path = patch_file['path']
patch_mode = patch_file['mode']
patch_content = b64decode(patch_file.get('content', ''))
if patch_path.startswith('/... |
def cvt_mask_palette(data):
(src_path, dst_dir) = data
mask = cv2.imread(src_path)
mask_size = mask.shape[:2]
label = np.asarray(mask).reshape((- 1), 3)
obj_labels = list(set(map(tuple, label)))
obj_labels.sort()
new_label = np.zeros(label.shape[0], np.uint8)
obj_cnt = 0
for (idx, la... |
def test_poetry_with_non_default_multiple_secondary_sources(fixture_dir: FixtureDirGetter, with_simple_keyring: None) -> None:
poetry = Factory().create_poetry(fixture_dir('with_non_default_multiple_secondary_sources'))
assert poetry.pool.has_repository('PyPI')
assert isinstance(poetry.pool.repository('PyPI... |
def get_tensorboard_hook(cfg):
from torch.utils.tensorboard import SummaryWriter
from vissl.hooks import SSLTensorboardHook
tensorboard_dir = get_tensorboard_dir(cfg)
flush_secs = (cfg.HOOKS.TENSORBOARD_SETUP.FLUSH_EVERY_N_MIN * 60)
return SSLTensorboardHook(tb_writer=SummaryWriter(log_dir=tensorboa... |
class Sphere_Collider(Collider):
def __init__(self, radius, **kwargs):
super().__init__(**kwargs)
self.radius = radius
def intersect(self, O, D):
b = (2 * D.dot((O - self.center)))
c = (((self.center.square_length() + O.square_length()) - (2 * self.center.dot(O))) - (self.radius ... |
class Effect6939(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Hull Upgrades')), 'overloadSelfDurationBonus', src.getModifiedItemAttr('subsystemBonusAmarrDefensive2'), skill='Amarr Defensive Sys... |
def all_gather(tensor):
if (not dist.is_initialized()):
return tensor
world_size = dist.get_world_size()
tensor_list = [torch.ones_like(tensor) for _ in range(world_size)]
dist.all_gather(tensor_list, tensor, async_op=False)
return torch.stack(tensor_list, dim=0).mean(dim=0) |
class BaseTestCase(TestCase):
def assertIsSubclass(self, cls, class_or_tuple, msg=None):
if (not issubclass(cls, class_or_tuple)):
message = f'{cls!r} is not a subclass of {repr(class_or_tuple)}'
if (msg is not None):
message += f' : {msg}'
raise self.fail... |
class F26Handler(BaseHandler):
version = F26
commandMap = {'auth': commands.authconfig.FC3_Authconfig, 'authconfig': commands.authconfig.FC3_Authconfig, 'autopart': commands.autopart.F26_AutoPart, 'autostep': commands.autostep.FC3_AutoStep, 'bootloader': commands.bootloader.F21_Bootloader, 'btrfs': commands.btr... |
class ErrorCodes(enum.IntEnum):
no_error = 0
syntax_error = 1
device_not_accessible = 3
invalid_link_identifier = 4
parameter_error = 5
channel_not_established = 6
operation_not_supported = 8
out_of_resources = 9
device_locked_by_another_link = 11
no_lock_held_by_this_link = 12
... |
def capfdbinary(request: SubRequest) -> Generator[(CaptureFixture[bytes], None, None)]:
capman: CaptureManager = request.config.pluginmanager.getplugin('capturemanager')
capture_fixture = CaptureFixture(FDCaptureBinary, request, _ispytest=True)
capman.set_fixture(capture_fixture)
capture_fixture._start(... |
class FixInput(fixer_base.BaseFix):
BM_compatible = True
PATTERN = "\n power< 'input' args=trailer< '(' [any] ')' > >\n "
def transform(self, node, results):
if context.match(node.parent.parent):
return
new = node.clone()
new.prefix = ''
... |
def poll(lcd):
if noisr:
for i in range(len(keypad_pins)):
handle_pin(keypad_pins[i], i, lcd)
for i in range(len(index_pins_for_touch)):
touch = TouchPad(Pin(keypad_pin_numbers[index_pins_for_touch[i]]))
ratio = (touch.read() / Threshold_ratio[i])
if (0.1 < ratio < 0.... |
_model_custom_init
class ListedTaxon(EstablishmentMeans):
comments_count: int = field(default=0, doc='Number of comments for this listed taxon')
created_at: DateTime = datetime_field(doc='Date and time the record was created')
description: str = field(default=None, doc='Listed taxon description')
first_... |
class KeystoneAuthTestsMixin():
maxDiff: Optional[int] = None
def emails(self):
raise NotImplementedError
def fake_keystone(self):
raise NotImplementedError
def setUp(self):
setup_database_for_testing(self)
self.session = requests.Session()
def tearDown(self):
... |
def dla_parameters(module, params):
for name in list(module._parameters.keys()):
if (module._parameters[name] is None):
continue
data = module._parameters[name].data
module._parameters.pop(name)
module.register_buffer(f'{name}_mean', data)
module.register_buffer(f... |
class FromFunctionGraphRewriter(GraphRewriter):
def __init__(self, fn, requirements=()):
self.fn = fn
self.requirements = requirements
def apply(self, *args, **kwargs):
return self.fn(*args, **kwargs)
def add_requirements(self, fgraph):
for req in self.requirements:
... |
def get_parsed_context(args):
logger.debug('starting')
if (not args):
raise AssertionError("pipeline must be invoked with context arg set. For this yaml parser you're looking for something like:\npypyr pipelinename ./myyamlfile.yaml")
path = ' '.join(args)
logger.debug('attempting to open file: ... |
class InfoNCE(nn.Module):
def __init__(self, temperature=0.1, reduction='mean', negative_mode='unpaired'):
super().__init__()
self.temperature = temperature
self.reduction = reduction
self.negative_mode = negative_mode
def forward(self, query, positive_key, negative_keys=None):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.