code stringlengths 281 23.7M |
|---|
class Conditional_Distortion_Loss(Conditional_Unfolding_Loss):
def __init__(self, window_length, hop_length, **kwargs):
super().__init__(window_length, hop_length)
def criterion(self, target_signal_hat, target_signal):
s_target = ((((target_signal_hat * target_signal).sum((- 1), keepdims=True) +... |
def load_voc_instances(dirname: str, split: str, class_names: Union[(List[str], Tuple[(str, ...)])]):
with PathManager.open(os.path.join(dirname, 'ImageSets', 'Main', (split + '.txt'))) as f:
fileids = np.loadtxt(f, dtype=np.str)
annotation_dirname = PathManager.get_local_path(os.path.join(dirname, 'Ann... |
class ConstantElementwiseInputModel(torch.nn.Module):
def __init__(self):
super(ConstantElementwiseInputModel, self).__init__()
self.add = elementwise_ops.Add()
self.mul = elementwise_ops.Multiply()
def forward(self, inp):
x = self.add(inp, torch.tensor(2.0))
x = self.mul... |
class BinaryBinnedPrecisionRecallCurve(Metric[Tuple[(torch.Tensor, torch.Tensor, torch.Tensor)]]):
def __init__(self: TBinaryBinnedPrecisionRecallCurve, *, threshold: Union[(int, List[float], torch.Tensor)]=100, device: Optional[torch.device]=None) -> None:
super().__init__(device=device)
threshold ... |
class CommandSpecSchema(marshmallow.Schema):
name = fields.String(metadata={'description': 'Name of the new command.'})
help = fields.String(default=None, missing=None, metadata={'description': 'Long-form documentation of the command. Will be interpreted as ReStructuredText markup.'})
short_help = fields.St... |
def get_dropout(**kwargs):
(backend, layers, models, keras_utils) = get_submodules_from_kwargs(kwargs)
class FixedDropout(layers.Dropout):
def _get_noise_shape(self, inputs):
if (self.noise_shape is None):
return self.noise_shape
symbolic_shape = backend.shape(inp... |
class TransformerDecoderScriptable(TransformerDecoder):
def extract_features(self, prev_output_tokens, encoder_out: Optional[Dict[(str, List[Tensor])]]=None, incremental_state: Optional[Dict[(str, Dict[(str, Optional[Tensor])])]]=None, full_context_alignment: bool=False, alignment_layer: Optional[int]=None, alignme... |
def create_src_table(primary_keys: Set[str], sort_keys: Optional[List[Any]], partition_keys: Optional[List[PartitionKey]], ds_mock_kwargs: Optional[Dict[(str, Any)]]):
source_namespace: str = BASE_TEST_SOURCE_NAMESPACE
source_table_name: str = BASE_TEST_SOURCE_TABLE_NAME
source_table_version: str = BASE_TES... |
def test_star_advanced() -> None:
starred = Fsm(alphabet={Charclass('a'), Charclass('b'), (~ Charclass('ab'))}, states={0, 1, 2, 3}, initial=0, finals={2}, map={0: {Charclass('a'): 0, Charclass('b'): 1, (~ Charclass('ab')): 3}, 1: {Charclass('a'): 2, Charclass('b'): 3, (~ Charclass('ab')): 3}, 2: {Charclass('a'): 3... |
def pytest_collectstart(collector: pytest.Collector) -> None:
if ('django' not in sys.modules):
return
if (not isinstance(collector, pytest.Class)):
return
tags = getattr(collector.obj, 'tags', ())
if (not tags):
return
from django.test import SimpleTestCase
if (not issub... |
class QlikLexer(RegexLexer):
name = 'Qlik'
aliases = ['qlik', 'qlikview', 'qliksense', 'qlikscript']
filenames = ['*.qvs', '*.qvw']
url = '
version_added = '2.12'
flags = re.IGNORECASE
tokens = {'comment': [('\\*/', Comment.Multiline, '#pop'), ('[^*]+', Comment.Multiline)], 'numerics': [('\\... |
class MUSX(object):
def __init__(self, formula, solver='m22', verbosity=1):
(topv, self.verbose) = (formula.nv, verbosity)
(self.sels, self.vmap) = ([], {})
self.oracle = Solver(name=solver, bootstrap_with=formula.hard, use_timer=True)
if (isinstance(formula, WCNFPlus) and formula.at... |
class IPResolver(IPResolverInterface):
def __init__(self, app):
self.app = app
path = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(path, 'GeoLite2-Country.mmdb')
self.geoip_db = geoip2.database.Reader(file_path)
self.amazon_ranges: Dict[(str, IPSet)] = ... |
def test_parse_basic_multiline_command(parser):
line = 'multiline foo\nbar\n\n'
statement = parser.parse(line)
assert (statement.multiline_command == 'multiline')
assert (statement.command == 'multiline')
assert (statement == 'foo bar')
assert (statement.args == statement)
assert (statement.... |
class ReferenceGraph(object):
def __init__(self, objects, reduce=False):
self.objects = list(objects)
self.count = len(self.objects)
self.num_in_cycles = 'N/A'
self.edges = None
if reduce:
self.num_in_cycles = self._reduce_to_cycles()
self._reduced = s... |
_fixtures(PartyAccountFixture)
def test_registration_application_help(party_account_fixture):
fixture = party_account_fixture
account_management_interface = fixture.account_management_interface
assert account_management_interface.is_login_active()
fixture.account_management_interface.new_email = 'new_'
... |
def add_radiobuttongroup(menu, menudef, target, default=None):
group = qw.QActionGroup(menu)
group.setExclusive(True)
menuitems = []
for (name, value, *shortcut) in menudef:
action = menu.addAction(name)
action.setCheckable(True)
action.setActionGroup(group)
if shortcut:
... |
def subgraph(graph, radius=5, distance=None, meshedness=True, cds_length=True, mode='sum', degree='degree', length='mm_len', mean_node_degree=True, proportion={3: True, 4: True, 0: True}, cyclomatic=True, edge_node_ratio=True, gamma=True, local_closeness=True, closeness_weight=None, verbose=True):
netx = graph.copy... |
_grad()
def predict(dataloader, model, mu, S, apply_sigm=True, delta=1):
py = []
for (x, y) in dataloader:
(x, y) = ((delta * x.cuda()), y.cuda())
m = len(x)
phi = torch.cat([torch.ones(m, 1, device='cuda'), model.features(x)], dim=1)
mu_pred = (phi mu)
var_pred = torch.... |
def test_wheel_install_pep_503():
project_name = 'Foo_Bar'
version = '1.0'
with build_wheel(name=project_name, version=version) as filename, tempdir() as install_dir:
new_filename = filename.replace(project_name, canonicalize_name(project_name))
shutil.move(filename, new_filename)
_c... |
def _align_column(strings, alignment, minwidth=0, has_invisible=True):
if (alignment == 'right'):
strings = [s.strip() for s in strings]
padfn = _padleft
elif (alignment == 'center'):
strings = [s.strip() for s in strings]
padfn = _padboth
elif (alignment == 'decimal'):
... |
def ffmpeg_reduce_noise(input_file_path: str, output_file: str) -> None:
print(f"{ULTRASINGER_HEAD} Reduce noise from vocal audio with {blue_highlighted('ffmpeg')}.")
try:
ffmpeg.input(input_file_path).output(output_file, af='afftdn=nr=70:nf=-80:tn=1').overwrite_output().run(capture_stdout=True, capture... |
def dataset_entry(config, world_size, rank, evaluate=False, test_img=False):
img_h = config.img_h
img_w = config.img_w
transform_train = transforms.Compose([transforms.Resize((img_h, img_w)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
transform_val = tran... |
class SudsStatident(SudsStructBase, namedtuple('SudsStatident', 'network, st_name, component, inst_type')):
def nslc(self):
return (str(self.network.rstrip(b'\x00 ').decode('ascii')), str(self.st_name.rstrip(b'\x00 ').decode('ascii')), '', str(self.component.rstrip(b'\x00 ').decode('ascii')))
__slots__ ... |
class PulpILPVisitor(ILPVisitor):
def __init__(self, model):
super().__init__()
self.model = model
def var(self, name):
return pulp.LpVariable(f'visitor_{name}', lowBound=0, upBound=1, cat='Binary')
def eq(self, expression):
self.model += (expression == 0)
def le(self, ex... |
def _init_weights(module, name='', zero_init_last=False):
if isinstance(module, nn.Conv2d):
fan_out = ((module.kernel_size[0] * module.kernel_size[1]) * module.out_channels)
fan_out //= module.groups
module.weight.data.normal_(0, math.sqrt((2.0 / fan_out)))
if (module.bias is not Non... |
class PyTorchModel(torch.nn.Module):
def __init__(self, input_size, hidden_units, num_classes):
super().__init__()
all_layers = []
for hidden_unit in hidden_units:
layer = torch.nn.Linear(input_size, hidden_unit, bias=False)
all_layers.append(layer)
all_la... |
class TestRFC2047Encoding():
def test_attrfc2047token(self, header_checker):
header_checker.check_ignored('attachment; filename==?ISO-8859-1?Q?foo-=E4.html?=')
_STDLIB_XFAIL
def test_attrfc2047quoted(self, header_checker):
header_checker.check_filename('attachment; filename="=?ISO-8859-1?Q?f... |
def prompt_comparation(reference, output1, output2):
template = "\n Reference: {reference}\n \n\n\n output1: {output1}\n \n\n\n output2: {output2}\n \n\n\n According to the drug recommendation result in reference output, which output is a better match? If the output1 is better match, output '1'. If the outpu... |
def prepare(args):
res_root = args.results_dir
cur_time = time.strftime('%Y-%m-%d %H.%M', time.localtime())
cur_time2 = time.strftime('%m%d_%H.%M', time.localtime())
mask = ''.join(random.sample(string.ascii_letters, 5))
if (not args.save_pred):
results_raw_dir = os.path.join(res_root, f'raw... |
class FourChanOrg(BaseDecrypter):
__name__ = 'FourChanOrg'
__type__ = 'decrypter'
__version__ = '0.38'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('folder_per_package', 'Default;Y... |
class TestAlmostAssertEqual(TestCase):
def test_simple(self):
self.assertAlmostEqual(100, klm)
self.assertAlmostEqual(456, (aaa and bbb))
self.assertAlmostEqual(789, (ccc or ddd))
self.assertAlmostEqual(123, (True if You else False))
def test_simple_msg(self):
self.assert... |
class TestMultiTrajResult():
def _fill_trajectories(self, multiresult, N, ntraj, collapse=False, noise=0, dm=False):
np.random.seed(1)
for _ in range(ntraj):
result = Result(multiresult._raw_ops, multiresult.options)
result.collapse = []
for t in range(N):
... |
def findAllFilesWithSpecifiedSuffix(target_dir, target_suffix='txt'):
find_res = []
walk_generator = os.walk(target_dir)
for (root_path, dirs, files) in walk_generator:
if (len(files) < 1):
continue
for file in files:
if file.endswith(target_suffix):
f... |
class CommonParams(FairseqDataclass):
no_progress_bar: bool = field(default=False, metadata={'help': 'disable progress bar'})
log_interval: int = field(default=100, metadata={'help': 'log progress every N batches (when progress bar is disabled)'})
log_format: Optional[LOG_FORMAT_CHOICES] = field(default=Non... |
def test_find_signals():
sys = ct.rss(states=['x[1]', 'x[2]', 'x[3]', 'x[4]', 'x4', 'x5'], inputs=['u[0]', 'u[1]', 'u[2]', 'v[0]', 'v[1]'], outputs=['y[0]', 'y[1]', 'y[2]', 'z[0]', 'z1'], name='sys')
assert (sys.find_states('x[1]') == [0])
assert (sys.find_states('x') == [0, 1, 2, 3])
assert (sys.find_s... |
class RegExtract(Extract):
def extract(raw_response: str, **kwargs: Any) -> str:
if (('extraction_regex' in kwargs) and (kwargs['extraction_regex'] is not None)):
extraction_regex = kwargs['extraction_regex']
answer = re.match(extraction_regex, raw_response)
if (answer is... |
def compute_timestep(model, total_length=40000, transient_fraction=0.2, num_iters=20, pts_per_period=1000, visualize=False, return_period=True):
base_freq = (1 / pts_per_period)
cutoff = int((transient_fraction * total_length))
step_history = [np.copy(model.dt)]
for i in range(num_iters):
sol = ... |
def parse_export_file(p):
with open(p, 'r') as f:
for l in f.read().split('\n'):
l = l.strip()
if (l and ('#' not in l)):
(x, y) = l.split()
if (x == 'linux_version'):
(yield {'linux_version': y})
else:
... |
class ScenarioObject(VersionBase):
def __init__(self, name, entityobject, controller=None):
self.name = name
if (not (isinstance(entityobject, CatalogReference) or isinstance(entityobject, Vehicle) or isinstance(entityobject, Pedestrian) or isinstance(entityobject, MiscObject) or ((not self.isVersio... |
class TestAllSignalsAndArgs():
def test_empty_when_no_signal(self, qtbot, signaller):
signals = get_mixed_signals_with_guaranteed_name(signaller)
with qtbot.waitSignals(signals=signals, timeout=200, check_params_cbs=None, order='none', raising=False) as blocker:
pass
assert (bloc... |
_time('2020-02-02')
.parametrize('test_input, expected', [(NOW, 'now'), ((NOW - dt.timedelta(seconds=1)), 'a second ago'), ((NOW - dt.timedelta(seconds=30)), '30 seconds ago'), ((NOW - dt.timedelta(minutes=1, seconds=30)), 'a minute ago'), ((NOW - dt.timedelta(minutes=2)), '2 minutes ago'), ((NOW - dt.timedelta(hours=1... |
def test_combine_dicts_close():
from satpy.dataset.metadata import combine_metadata
attrs = {'raw_metadata': {'a': 1, 'b': 'foo', 'c': [1, 2, 3], 'd': {'e': np.str_('bar'), 'f': datetime(2020, 1, 1, 12, 15, 30), 'g': np.array([1, 2, 3])}, 'h': np.array([datetime(2020, 1, 1), datetime(2020, 1, 1)])}}
attrs_c... |
def get_scene_rec_names(scene_recs_keys):
scene_recs_names = []
for k in scene_recs_keys:
(room, k) = k.split('-')
rn = preprocess(k)
rn = rn.replace(' ', '_')
room = room.split('_')
room = '_'.join(room[:(- 1)])
if (rn not in scene_recs_names):
scene_... |
def map_object(object_map, obj):
oid = obj['object_id']
obj['id'] = oid
del obj['object_id']
if (oid in object_map):
object_ = object_map[oid]
else:
if ('attributes' in obj):
attrs = obj['attributes']
del obj['attributes']
else:
attrs = []
... |
class TargetMixin():
(target=send_secret_requests, source=consumes(send_locked_transfers))
def process_send_locked_transfer(self, source: utils.SendLockedTransferInNode) -> utils.SendSecretRequestInNode:
target_address = source.event.recipient
target_client = self.address_to_client[target_addres... |
_model
def resnest200e(pretrained=False, **kwargs):
model_kwargs = dict(block=ResNestBottleneck, layers=[3, 24, 36, 3], stem_type='deep', stem_width=64, avg_down=True, base_width=64, cardinality=1, block_args=dict(radix=2, avd=True, avd_first=False), **kwargs)
return _create_resnest('resnest200e', pretrained=pr... |
class RTM_SepBNHead(nn.Module):
def __init__(self, in_channels, out_channels, reg_max=16, num_classes=3, stage=3, stacked_convs_number=2, num_anchors=1, share_conv=True):
super(RTM_SepBNHead, self).__init__()
self.cls_convs = nn.ModuleList()
self.reg_convs = nn.ModuleList()
self.rtm_... |
class EuclideanCodebook(nn.Module):
def __init__(self, dim: int, codebook_size: int, kmeans_init: int=False, kmeans_iters: int=10, decay: float=0.99, epsilon: float=1e-05, threshold_ema_dead_code: int=2):
super().__init__()
self.decay = decay
init_fn: tp.Union[(tp.Callable[(..., torch.Tensor... |
class SemanticGroup():
def __init__(self, contents):
self.contents = contents
while (self.contents[(- 1)].__class__ == self.__class__):
self.contents = (self.contents[:(- 1)] + self.contents[(- 1)].contents)
def __str__(self):
return '{}({})'.format(self.label, ' '.join([((is... |
.parametrize('dc_handle', [GET_DC_SUCCESS, GET_DC_FAILURE], indirect=True)
.parametrize('release_result', [RELEASE_DC_SUCCESS], indirect=True)
def test_device_context_calls_get_dc(patched_get_dc, dc_handle, patched_release_dc):
try:
with context_managers.device_context() as dc:
pass
finally:... |
class Effect6534(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.requiresSkill('Skirmish Command') or mod.item.requiresSkill('Shield Command'))), 'warfareBuff3Value', src.getModifiedItemAttr('shipBonusForceAuxi... |
def test_it_resets_the_random_seed_at_the_end_of_test_classes(ourtester):
ourtester.makepyfile(test_one="\n import random\n from unittest import TestCase\n\n\n class A(TestCase):\n\n def test_fake(self):\n assert True\n\n \n def tearDownClass(cls)... |
def test_sar_encoder():
with pytest.raises(AssertionError):
SAREncoder(enc_bi_rnn='bi')
with pytest.raises(AssertionError):
SAREncoder(enc_do_rnn=2)
with pytest.raises(AssertionError):
SAREncoder(enc_gru='gru')
with pytest.raises(AssertionError):
SAREncoder(d_model=512.5)... |
def read_trace_data(filename):
global current_max_cpu
global sample_num, last_sec_cpu, last_usec_cpu, start_time
try:
data = open(filename, 'r').read()
except:
print('Error opening ', filename)
sys.exit(2)
for line in data.splitlines():
search_obj = re.search('(^(.*?)... |
class Meta_Arch(nn.Module):
def __init__(self, out_dim, criterion, name='meta', **Cell_Config):
super(Meta_Arch, self).__init__()
self.arch_name = name
self.out_dim = out_dim
self.criterion = criterion
self.cell_config = Cell_Config
self.arch_depth = Cell_Config['dept... |
(frozen=True)
class HasAttrExtension(Extension):
attribute_name: Value
attribute_type: Value
def substitute_typevars(self, typevars: TypeVarMap) -> Extension:
return HasAttrExtension(self.attribute_name.substitute_typevars(typevars), self.attribute_type.substitute_typevars(typevars))
def walk_va... |
def _get_svd_uv0(func, x0):
from xitorch.linalg import svd
fjac = jac(func, (x0.clone().requires_grad_(),), idxs=[0])[0]
(u, s, vh) = svd(fjac, k=1, mode='lowest', method='davidson', min_eps=0.001)
sinv_sqrt = (1.0 / torch.sqrt(torch.clamp(s, min=0.1)))
uv0 = ((sinv_sqrt * vh.squeeze((- 2))), (sinv_... |
def test_spawn_densitydist_bound_method():
N = 100
with pm.Model() as model:
mu = pm.Normal('mu', 0, 1)
def logp(x, mu):
normal_dist = pm.Normal.dist(mu, 1, size=N)
out = pm.logp(normal_dist, x)
return out
obs = pm.CustomDist('density_dist', mu, logp=l... |
def unsbox(str_arg):
v1 = [15, 35, 29, 24, 33, 16, 1, 38, 10, 9, 19, 31, 40, 27, 22, 23, 25, 13, 6, 11, 39, 18, 20, 8, 14, 21, 32, 26, 2, 30, 7, 4, 17, 5, 3, 28, 34, 37, 12, 36]
v2 = ['' for _ in v1]
for idx in range(0, len(str_arg)):
v3 = str_arg[idx]
for idx2 in range(len(v1)):
... |
def test_super_inference_of_abstract_property() -> None:
code = '\n from abc import abstractmethod\n\n class A:\n \n def test(self):\n return "super"\n\n class C:\n \n \n def test(self):\n "abstract method"\n\n class B(A, C):\n\n \n def test(... |
def main():
hive = 'L'
classkey = 'system\\currentcontrolset\\control\\class'
intkey = 'system\\currentcontrolset\\services\\tcpip\\parameters\\interfaces'
config_dict = getadapterkeys(hive, classkey)
key_list = ['Enabled', 'Name', 'IPAddress', 'SubnetMask', 'DefaultGateway', 'EnableDHCP', 'DhcpIPAd... |
def get_ads(page_url=None):
ads = Advertising.objects.filter(start_date__lte=datetime.datetime.now(), end_date__gte=datetime.datetime.now(), active=True)
if (page_url is not None):
to_remove = []
for ad in ads:
for ad_page in ad.pages.all():
if (ad_page.url == page_ur... |
def main():
args = parse_args()
root_path = args.root_path
out_dir = (args.out_dir if args.out_dir else root_path)
mmcv.mkdir_or_exist(out_dir)
anns = mmcv.load(osp.join(root_path, 'train1.json'))
data1 = convert_annotations(anns, 'syntext_word_eng', args.num_sample, args.nproc)
start_img_id... |
class YOLOv4Head(BaseHead):
def __init__(self, **kwargs):
super(YOLOv4Head, self).__init__(**kwargs)
self.y1 = Y(self.in_channels[(- 1)], self.out_channels[0], norm_type=self.norm_type, num_groups=self.num_groups)
self.y2 = Y(self.in_channels[(- 2)], self.out_channels[1], norm_type=self.norm... |
.xfail(reason='causing issues in CI, to be fixed later')
.spark_functions
def test_clean_names_case_type_preserve(spark_df):
spark_df = spark_df.clean_names(case_type='preserve')
expected_columns = ['a', 'Bell_Chart', 'decorated_elephant', '#$%^', 'cities']
assert (set(spark_df.columns) == set(expected_colu... |
class LogHelper():
def __init__(self, model_name, cache_root=None, quan_activation=False, resume=False):
self.model_name = model_name
self.log_cache = ''
self.ckpt_cache = ''
self.model_cache = ''
self.prepare_cache_root(cache_root)
self.clear_cache_root(resume)
... |
def get_log_level_for_setting(config: Config, *setting_names: str) -> Optional[int]:
for setting_name in setting_names:
log_level = config.getoption(setting_name)
if (log_level is None):
log_level = config.getini(setting_name)
if log_level:
break
else:
ret... |
('pypyr.cache.loadercache.Loader.get_pipeline')
def test_get_parsed_context_parser_not_found(mock_get_pipeline):
mock_get_pipeline.return_value = get_pipe_def({'context_parser': 'unlikelyblahmodulenameherexxssz'})
context = Context()
pipeline = Pipeline('arb')
with pytest.raises(PyModuleNotFoundError):
... |
class BaseModel(Composite):
def __init__(self, param, domain, options=None):
super().__init__(param, domain, options)
def get_fundamental_variables(self):
if (self.domain == 'separator'):
return {}
delta_phi_av = pybamm.Variable(f'X-averaged {self.domain} electrode surface po... |
class SegmentalSampling(object):
def __init__(self, num_per_seg, segments=3, interval=1, shuffle=False, fix_cursor=False, seed=0):
self.memory = {}
self.num_per_seg = num_per_seg
self.segments = segments
self.interval = (interval if (type(interval) == list) else [interval])
s... |
class PasswordPolicyControl(ValueLessRequestControl, ResponseControl):
controlType = '1.3.6.1.4.1.42.2.27.8.5.1'
def __init__(self, criticality=False):
self.criticality = criticality
self.timeBeforeExpiration = None
self.graceAuthNsRemaining = None
self.error = None
def decod... |
class Model(object):
def __init__(self, hidden_size=100, out_size=100, batch_size=100, nonhybrid=True):
self.hidden_size = hidden_size
self.out_size = out_size
self.batch_size = batch_size
self.mask = tf.placeholder(dtype=tf.float32)
self.alias = tf.placeholder(dtype=tf.int32... |
class DistFieldTextureGroup(pyglet.sprite.SpriteGroup):
def set_state(self):
glEnable(self.texture.target)
glBindTexture(self.texture.target, self.texture.id)
glPushAttrib(GL_COLOR_BUFFER_BIT)
if enable_shader:
glUseProgram(shader.program)
glUniform1i(shader['... |
.parametrize('kind', {kind for (kind, kind_method) in vars(dominance.DecisionMatrixDominanceAccessor).items() if ((not inspect.ismethod(kind_method)) and (not kind.startswith('_')))})
def test_DecisionMatrixDominanceAccessor_call(decision_matrix, kind):
dm = decision_matrix(seed=42, min_alternatives=3, max_alternat... |
class AudioNotificationCB(com.COMObject):
_interfaces_ = [IMMNotificationClient]
def __init__(self, audio_devices: 'Win32AudioDeviceManager'):
super().__init__()
self.audio_devices = audio_devices
self._lost = False
def OnDeviceStateChanged(self, pwstrDeviceId, dwNewState):
d... |
class MetaRLScreener_pro(torch.nn.Module):
def __init__(self, model, epochs=100, lr=0.01, log=True):
super(MetaRLScreener_pro, self).__init__()
self.model = model
self.model.to(device)
self.epochs = epochs
self.lr = lr
self.log = log
self.temperature = 0.2
... |
class TxInput():
prevout: TxOutpoint
script_sig: Optional[bytes]
nsequence: int
witness: Optional[bytes]
_is_coinbase_output: bool
def __init__(self, *, prevout: TxOutpoint, script_sig: bytes=None, nsequence: int=( - 1), witness: bytes=None, is_coinbase_output: bool=False):
self.prevout ... |
def main(local_rank, args):
if (local_rank == 0):
print("Initializing Distributed Training. This is in BETA mode and hasn't been tested thoroughly. Use at your own risk :)")
print('To get the maximum speed-up consider reducing evaluations on val set by setting --eval_every_epoch to greater than 50')... |
def lex(module=None, object=None, debug=0, optimize=0, lextab='lextab', reflags=0, nowarn=0, cls=Lexer):
global lexer
ldict = None
stateinfo = {'INITIAL': 'inclusive'}
error = 0
files = {}
lexobj = cls()
lexobj.lexdebug = debug
lexobj.lexoptimize = optimize
global token, input
if... |
class Solution():
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
def inorder(root, target):
stack = []
while ((root is not None) or (len(stack) > 0)):
while (root is not None):
stack.append(root)
... |
def test_single_and_tuple():
res = substitute_params('SELECT * FROM cust WHERE salesrep = %s AND id IN %s', (b'John Doe', (1, 2, 3)))
eq_(res, b"SELECT * FROM cust WHERE salesrep = 'John Doe' AND id IN (1,2,3)")
res = substitute_params('SELECT * FROM cust WHERE salesrep = %s AND id IN %s', ('John Doe', (1, ... |
def create_genotype_dosage_dataset(*, variant_contig_names: List[str], variant_contig: ArrayLike, variant_position: ArrayLike, variant_allele: ArrayLike, sample_id: ArrayLike, call_dosage: ArrayLike, call_genotype_probability: ArrayLike, variant_id: Optional[ArrayLike]=None) -> xr.Dataset:
data_vars: Dict[(Hashable... |
class CustomFactor(PositiveWindowLengthMixin, CustomTermMixin, Factor):
dtype = float64_dtype
def _validate(self):
try:
super(CustomFactor, self)._validate()
except UnsupportedDataType:
if (self.dtype in CLASSIFIER_DTYPES):
raise UnsupportedDataType(typena... |
def test_pdb_enabled(django_pytester: DjangoPytester) -> None:
django_pytester.create_test_module('\n import os\n\n from django.test import TestCase\n from django.conf import settings\n\n from .app.models import Item\n\n class TestPDBIsolation(TestCase):\n def setUp(sel... |
def looks_like_an_import(sexp):
if (not isinstance(sexp, values.W_Cons)):
return False
if (sexp.car() is not import_sym):
return False
if (not isinstance(sexp.cdr(), values.W_Cons)):
return False
if (not isinstance(sexp.cdr().cdr(), values.W_Cons)):
return False
if (n... |
def init_logger(log_file=None, log_file_level=logging.NOTSET):
log_format = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handle... |
def sessions_for_site(connection: Connection, sit_set_id: int) -> Iterator[Tuple[(int, datetime, datetime)]]:
result = api.execute(connection, '\n SELECT\n Tx_DtTm\n FROM Dose_Hst\n INNER JOIN\n Site ON Site.SIT_ID = Dose_Hst.SIT_ID\n WHERE\n Site.SIT_SET... |
class KwsIndexConstFst(_FstBase, _const_fst.KwsIndexConstFst):
_ops = _index_ops
_drawer_type = _KwsIndexFstDrawer
_printer_type = _KwsIndexFstPrinter
_weight_factory = KwsIndexWeight
_state_iterator_type = KwsIndexConstFstStateIterator
_arc_iterator_type = KwsIndexConstFstArcIterator
def __... |
class RandomDataProvider(BaseDataProvider):
def __init__(self, tickers: Optional[Union[(str, List[str])]]=None, start: datetime.datetime=datetime.datetime(2016, 1, 1), end: datetime.datetime=datetime.datetime(2016, 1, 30), seed: Optional[int]=None) -> None:
super().__init__()
if (not _HAS_PANDAS):
... |
def _is_file_modified(filename):
last_modified_file = ('cache/last-modified_' + os.path.basename(filename).rstrip('.yaml'))
def _update_modified_date(date):
with open(last_modified_file, 'wb') as fd:
pickle.dump(date, fd)
if (not os.path.exists(last_modified_file)):
last_modified... |
class Label():
action: str = 'action'
addr: str = 'addr'
any: str = 'any'
co_size: str = 'co size'
defaults: str = 'defaults'
di_size: str = 'di size'
hr_size: str = 'hr size'
increment: str = 'increment'
invalid: str = 'invalid'
ir_size: str = 'ir size'
kwargs: str = 'kwargs... |
def _resolve_assignment_parts(parts, assign_path, context):
assign_path = assign_path[:]
index = assign_path.pop(0)
for part in parts:
assigned = None
if isinstance(part, nodes.Dict):
try:
(assigned, _) = part.items[index]
except IndexError:
... |
class DeprecatedObserverTestBase(object):
def setup_method(self, method):
self.observer = None
self.no_emitted_signals = 0
self.setup()
def teardown_method(self, method):
if (self.observer is not None):
self.destroy_observer()
self.teardown()
def setup(sel... |
class CIFAR10(object):
def __init__(self, **options):
transform_train = transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor()])
transform = transforms.Compose([transforms.ToTensor()])
batch_size = options['batch_size']
data... |
def infer(valid_queue, model, criterion):
objs = utils.AvgrageMeter()
top1 = utils.AvgrageMeter()
top5 = utils.AvgrageMeter()
model.eval()
for (step, (input, target)) in enumerate(valid_queue):
input = input.cuda()
target = target.cuda(non_blocking=True)
logits = model(input)... |
def browser_login_with_discord(sa: ServerApp):
sid = flask.request.args.get('sid')
if (sid is not None):
if (not sa.get_server().rooms(sid)):
return (flask.render_template('unable_to_login.html', error_message='Invalid sid received from Randovania!'), 400)
flask.session['sid'] = sid
... |
class BaseAttributeSerializer(ElementModelSerializerMixin, ReadOnlyObjectPermissionSerializerMixin, serializers.ModelSerializer):
model = serializers.SerializerMethodField()
read_only = serializers.SerializerMethodField(read_only=True)
class Meta():
model = Attribute
fields = ('id', 'model',... |
def test_fold_effect():
effs = [Effect('a'), Effect('b'), Effect('c')]
dispatcher = [('a', (lambda i: 'Ei')), ('b', (lambda i: 'Bee')), ('c', (lambda i: 'Cee'))]
eff = fold_effect(operator.add, 'Nil', effs)
result = perform_sequence(dispatcher, eff)
assert (result == 'NilEiBeeCee') |
def G_arch(ch=64, attention='64', ksize='333333', dilation='111111'):
arch = {}
arch[512] = {'in_channels': [(ch * item) for item in [16, 16, 8, 8, 4, 2, 1]], 'out_channels': [(ch * item) for item in [16, 8, 8, 4, 2, 1, 1]], 'upsample': ([True] * 7), 'resolution': [8, 16, 32, 64, 128, 256, 512], 'attention': {(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.