code stringlengths 281 23.7M |
|---|
class Effect6807(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
lvl = src.level
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Invulnerability Core Operation')), 'buffDuration', (src.getModifiedItemAttr('durationBonus') * lvl), **kwar... |
class Match():
def __init__(self, title: ((str | re.Pattern) | None)=None, wm_class: ((str | re.Pattern) | None)=None, role: ((str | re.Pattern) | None)=None, wm_type: ((str | re.Pattern) | None)=None, wm_instance_class: ((str | re.Pattern) | None)=None, net_wm_pid: (int | None)=None, func: (Callable[([base.Window]... |
def fmcw_rx():
angle = np.arange((- 90), 91, 1)
pattern = ((20 * np.log10((np.cos(((angle / 180) * np.pi)) + 0.01))) + 6)
rx_channel = {'location': (0, 0, 0), 'azimuth_angle': angle, 'azimuth_pattern': pattern, 'elevation_angle': angle, 'elevation_pattern': pattern}
return Receiver(fs=2000000.0, noise_f... |
class MultiReg(ScrimsButton):
def __init__(self, ctx: Context, letter: str):
super().__init__(emoji=ri(letter))
self.ctx = ctx
async def callback(self, interaction: Interaction):
(await interaction.response.defer())
self.view.record.multiregister = (not self.view.record.multiregi... |
class TestSimpleModule():
(autouse=True, scope='class')
def built(self, builder):
builder('pyexample', warningiserror=True, confoverrides={'exclude_patterns': ['manualapi.rst']})
def test_integration(self, parse):
self.check_integration(parse, '_build/html/autoapi/example/index.html')
... |
class MaxPoolingAggregator(Layer):
def __init__(self, input_dim, output_dim, model_size='small', neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs):
super(MaxPoolingAggregator, self).__init__(**kwargs)
self.dropout = dropout
self.bias = bias
... |
def L3(mu, C, r, m, n):
total_sum = 0
vals = []
for i in range(m):
numer = sum([(C[i][j] * mu[j]) for j in range(n)])
denom = sum([(C[h][j] * mu[j]) for j in range(n) for h in range(m)])
total_sum += (r[i] * numpy.log((numer / denom)))
vals.append((numer / denom))
return ... |
def is_staging_test(test_case):
if (not _run_staging):
return unittest.skip('test is staging test')(test_case)
else:
try:
import pytest
except ImportError:
return test_case
else:
return pytest.mark.is_staging_test()(test_case) |
_if_nothing_inferred
def instance_class_infer_binary_op(self: nodes.ClassDef, opnode: (nodes.AugAssign | nodes.BinOp), operator: str, other: InferenceResult, context: InferenceContext, method: SuccessfulInferenceResult) -> Generator[(InferenceResult, None, None)]:
return method.infer_call_result(self, context) |
class BNInception(nn.Module):
def __init__(self, channels, init_block_channels_list, mid1_channels_list, mid2_channels_list, bias=True, use_bn=True, in_channels=3, in_size=(224, 224), num_classes=1000):
super(BNInception, self).__init__()
self.in_size = in_size
self.num_classes = num_classes... |
class IterDataPipeQueueProtocolClient(ProtocolClient):
def request_reset_epoch(self, seed_generator, iter_reset_fn):
if (not self.can_take_request()):
raise Exception('Can not reset while we are still waiting response for previous request')
request = communication.messages.ResetEpochRequ... |
class BridgeTowerProcessor(ProcessorMixin):
attributes = ['image_processor', 'tokenizer']
image_processor_class = 'BridgeTowerImageProcessor'
tokenizer_class = ('RobertaTokenizer', 'RobertaTokenizerFast')
def __init__(self, image_processor, tokenizer):
super().__init__(image_processor, tokenizer... |
_fixtures(WebFixture)
def test_populating(web_fixture):
item_specs = [Bookmark('/', '/href1', 'description1'), Bookmark('/', '/go_to_href', 'description2')]
menu = Nav(web_fixture.view).with_bookmarks(item_specs)
tester = WidgetTester(menu)
[item1, item2] = menu.menu_items
assert (item1.a.href.path ... |
def _override_input_dist_forwards(pipelined_modules: List[ShardedModule]) -> None:
for module in pipelined_modules:
for (child_fqn, child_module) in module.named_modules():
if hasattr(child_module, '_has_uninitialized_input_dist'):
assert (not child_module._has_uninitialized_inpu... |
class SigmaPoint(object):
def __init__(self, sensor, down=False):
self.sensor = sensor
self.down = down
self.count = 1
self.time = time.monotonic()
def add_measurement(self, sensor, down):
self.count += 1
fac = max((1 / self.count), 0.01)
self.sensor = avg... |
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = None
def update(self, val):
if (self.val is None):
self.val = val
else:
self.val = ((self.val * 0.9) + (val * 0.1))
def __call__(self):
return self.val |
def Myrm(dirstring):
root_rp = rpath.RPath(Globals.local_connection, dirstring)
for rp in selection.Select(root_rp).get_select_iter():
if rp.isdir():
rp.chmod(448)
elif rp.isreg():
rp.chmod(384)
path = root_rp.path
if os.path.isdir(path):
shutil.rmtree(pat... |
def handle_long_project_repeating_form_request(**kwargs) -> Any:
headers = kwargs['headers']
data = kwargs['data']
resp = None
if ('data' in data):
repeat_forms = json.loads(data['data'][0])
resp = len(repeat_forms)
else:
resp = [{'form_name': 'testform', 'custom_form_label':... |
def write_and_fudge_mtime(content: str, target_path: str) -> None:
new_time = None
if os.path.isfile(target_path):
new_time = (os.stat(target_path).st_mtime + 1)
dir = os.path.dirname(target_path)
os.makedirs(dir, exist_ok=True)
with open(target_path, 'w', encoding='utf-8') as target:
... |
class Var():
def __init__(self, label, type, requires_grad=False, constant=None):
if (type == float):
type = float32
elif (type == int):
type = int32
self.label = label
self.type = type
self.requires_grad = requires_grad
self.constant = constan... |
.parametrize('meth', [pytest.param('signal', marks=have_sigalrm), 'thread'])
.parametrize('scope', ['function', 'class', 'module', 'session'])
def test_fix_finalizer(meth, scope, testdir):
testdir.makepyfile("\n import time, pytest\n\n class TestFoo:\n\n \n def fix(self, request)... |
class QuoSocket(socketio.AsyncClient):
bot: Quotient
def __init__(self, **kwargs):
super().__init__(**kwargs)
async def emit(self, event, data=None, namespace=None, callback=None):
return (await super().emit(('response__' + event), data=data, namespace=namespace, callback=callback))
asyn... |
def cmdutils_stub(monkeypatch, stubs):
return monkeypatch.setattr(objects, 'commands', {'quit': stubs.FakeCommand(name='quit', desc='quit qutebrowser'), 'open': stubs.FakeCommand(name='open', desc='open a url'), 'prompt-yes': stubs.FakeCommand(name='prompt-yes', deprecated=True), 'scroll': stubs.FakeCommand(name='s... |
def test_vectorize_test():
a = np.random.random((5, 5))
b = np.random.random((4, 4))
c = np.random.random((3, 3))
at = Tensor(tensor=a, name='a')
bt = Tensor(tensor=b, name='b')
ct = Tensor(tensor=c, name='c')
mt = MultiTensor([at, bt, ct])
vec = np.vstack((at.vectorize(), bt.vectorize()... |
class scan(object):
def __init__(self, job, timeout=None):
for field in self.get_data_fields():
setattr(self, field, '')
setattr(self, 'success', False)
self.job = job[0]
if (len(job) > 1):
self.target = job[1]
self.scan_type = _whats_your_name()
... |
class Attribute(MPTTModel):
uri = models.URLField(max_length=640, blank=True, verbose_name=_('URI'), help_text=_('The Uniform Resource Identifier of this attribute (auto-generated).'))
uri_prefix = models.URLField(max_length=256, verbose_name=_('URI Prefix'), help_text=_('The prefix for the URI of this attribut... |
def test_self_reference_infer_does_not_trigger_recursion_error() -> None:
code = "\n def func(elems):\n return elems\n\n class BaseModel(object):\n\n def __init__(self, *args, **kwargs):\n self._reference = func(*self._reference.split('.'))\n BaseModel()._reference\n "
node ... |
class Worker():
def __init__(self, target: typing.Callable, timeout: int=1) -> None:
self.target = target
self.timeout = timeout
(self.conn_sender, self.conn_receiver) = multiprocessing.Pipe()
self.worker = multiprocessing.Process(target=self.run_worker, args=(target, self.conn_recei... |
class NeuralTSDiag():
def __init__(self, input_dim, lamdba=1, nu=1, style='ucb', init_x=None, init_y=None, diagonalize=True):
self.diagonalize = diagonalize
torch.manual_seed(0)
torch.cuda.manual_seed(0)
self.func = extend(Network(input_dim).to(**tkwargs))
self.init_state_dic... |
def parse_options():
parser = argparse.ArgumentParser(description='Install SMT Solvers.\n\nThis script installs the solvers specified on the command line or in the environment variable PYSMT_SOLVER if not already instaled on the system.')
parser.add_argument('--version', action='version', version='%(prog)s {ver... |
def _check_multi_threading_and_problem_type(problem_type, **kwargs):
if (not isinstance(problem_type, SocpType.COLLOCATION)):
if ('n_thread' in kwargs):
if (kwargs['n_thread'] != 1):
raise ValueError('Multi-threading is not possible yet while solving a trapezoidal stochastic ocp.... |
class BLCBatchNorm(nn.BatchNorm1d):
def forward(self, x):
if (x.dim() == 2):
return super().forward(x)
if (x.dim() == 3):
x = rearrange(x, 'B L C -> B C L')
x = super().forward(x)
x = rearrange(x, 'B C L -> B L C')
return x
raise Va... |
class RealmTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, do_lowe... |
def test_softplus():
def softplus(x):
return np.log((np.ones_like(x) + np.exp(x)))
x = K.placeholder(ndim=2)
f = K.function([x], [activations.softplus(x)])
test_values = get_standard_values()
result = f([test_values])[0]
expected = softplus(test_values)
assert_allclose(result, expect... |
def test_window_transform():
with rasterio.open('tests/data/RGB.byte.tif') as src:
assert (src.window_transform(((0, None), (0, None))) == src.transform)
assert (src.window_transform(((None, None), (None, None))) == src.transform)
assert (src.window_transform(((1, None), (1, None))).c == (sr... |
def bmshj2018_factorized(quality, metric='mse', pretrained=False, progress=True, **kwargs):
if (metric not in ('mse', 'ms-ssim')):
raise ValueError(f'Invalid metric "{metric}"')
if ((quality < 1) or (quality > 8)):
raise ValueError(f'Invalid quality "{quality}", should be between (1, 8)')
re... |
(allow_output_mutation=True, suppress_st_warning=True)
def get_cached_mosaiq_connection_in_dict(hostname: str, port: int=1433, database: str='MOSAIQ', alias=None) -> Dict[(Literal['connection'], _connect.Connection)]:
return {'connection': get_uncached_mosaiq_connection(hostname=hostname, port=port, database=databa... |
class SyncStateControl(ResponseControl):
controlType = '1.3.6.1.4.1.4203.1.9.1.2'
opnames = ('present', 'add', 'modify', 'delete')
def decodeControlValue(self, encodedControlValue):
d = decoder.decode(encodedControlValue, asn1Spec=SyncStateValue())
state = d[0].getComponentByName('state')
... |
class BitStage(nn.Module):
def __init__(self, config, in_channels, out_channels, stride, dilation, depth, bottle_ratio=0.25, layer_dropout=None):
super().__init__()
first_dilation = (1 if (dilation in (1, 2)) else 2)
if (config.layer_type == 'bottleneck'):
layer_cls = BitBottlene... |
def break_long_words(data):
if verbose:
print(('#' * 10), 'Step - Break long words:')
temp_vocab = list(set([c for line in data for c in line.split()]))
temp_vocab = [k for k in temp_vocab if _check_replace(k)]
temp_vocab = [k for k in temp_vocab if (len(k) > 20)]
temp_dict = {}
for word... |
(Sponsorship)
class SponsorshipAdmin(ImportExportActionModelAdmin, admin.ModelAdmin):
change_form_template = 'sponsors/admin/sponsorship_change_form.html'
form = SponsorshipReviewAdminForm
inlines = [SponsorBenefitInline, AssetsInline]
search_fields = ['sponsor__name']
list_display = ['sponsor', 'st... |
def test_dielectric_constant_model(mocker):
mocker.patch('builtins.input', return_value='Y')
cauchy = Cauchy()
model = DielectricConstantModel(e_inf=0, oscillators=[cauchy])
assert (model.dielectric_constants(1000) == 0)
model.add_oscillator('drude', An=2, Brn=1)
assert (model.dielectric_constan... |
def compute_complexity(model: nn.Module, compute_fn: Callable, input_shape: Tuple[int], input_key: Optional[Union[(str, List[str])]]=None, patch_attr: str=None, compute_unique: bool=False) -> int:
assert isinstance(model, nn.Module)
if ((not isinstance(input_shape, abc.Sequence)) and (not isinstance(input_shape... |
class Effect553(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Large Hybrid Turret')), 'trackingSpeed', ship.getModifiedItemAttr('shipBonusGB'), skill='Gallente Battleship', **kwargs) |
(python=USE_PYTHON_VERSIONS)
('command_a', install_commands)
('command_b', install_commands)
def session_pkgutil(session, command_a, command_b):
session.install('--upgrade', 'setuptools', 'pip')
install_packages(session, 'pkgutil/pkg_a', 'pkgutil/pkg_b', command_a, command_b)
session.run('python', 'verify_p... |
class Adafactor(Optimizer):
def __init__(self, params, lr=None, eps=(1e-30, 0.001), clip_threshold=1.0, decay_rate=(- 0.8), beta1=None, weight_decay=0.0, scale_parameter=True, relative_step=True, warmup_init=False):
require_version('torch>=1.5.0')
if ((lr is not None) and relative_step):
... |
class NestedAsyncState(NestedState, AsyncState):
async def scoped_enter(self, event_data, scope=None):
self._scope = (scope or [])
(await self.enter(event_data))
self._scope = []
async def scoped_exit(self, event_data, scope=None):
self._scope = (scope or [])
(await self.... |
def main():
parser = argparse.ArgumentParser(description='Tooling to ease downloading of components from TaskCluster.')
parser.add_argument('--target', required=False, help='Where to put the native client binary files')
parser.add_argument('--arch', required=False, help='Which architecture to download binar... |
class TestTransformerPitch(unittest.TestCase):
def test_default(self):
tfm = new_transformer()
tfm.pitch(0.0)
actual_args = tfm.effects
expected_args = ['pitch', '0.000000']
self.assertEqual(expected_args, actual_args)
actual_log = tfm.effects_log
expected_log... |
class FileAudioDataset(RawAudioDataset):
def __init__(self, manifest_path, sample_rate, max_sample_size=None, min_sample_size=None, shuffle=True, min_length=0):
super().__init__(sample_rate=sample_rate, max_sample_size=max_sample_size, min_sample_size=min_sample_size, shuffle=shuffle, min_length=min_length)... |
class LogMatchStart(LogMatchEvent):
def from_dict(self):
super().from_dict()
self.blue_zone_custom_options = objects.BlueZoneCustomOptions(self._data.get('blueZoneCustomOptions'))
self.camera_view_behaviour = self._data.get('cameraViewBehaviour')
self.is_custom_game = self._data.get(... |
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super().__init__()
self.num_layers = num_layers
h = ([hidden_dim] * (num_layers - 1))
self.layers = nn.ModuleList((nn.Linear(n, k) for (n, k) in zip(([input_dim] + h), (h + [output_dim]))))
d... |
class MainWindow(QWidget):
STYLESHEET = "\n HintLabel {\n background-color: {{ conf.colors.hints.bg }};\n color: {{ conf.colors.hints.fg }};\n font: {{ conf.fonts.hints }};\n border: {{ conf.hints.border }};\n border-radius: {{ conf.hints.radius }}px;\n ... |
class DataTrainingArguments():
data_dir: Optional[str] = field(default=None, metadata={'help': 'Directory to a Universal Dependencies data folder.'})
max_seq_length: Optional[int] = field(default=196, metadata={'help': 'The maximum total input sequence length after tokenization. Sequences longer than this will ... |
class LogicalOrExpressionNode(ExpressionNode):
def __init__(self, left, right):
self.left = left
self.right = right
def evaluate(self, context):
return (self.left.evaluate(context) or self.right.evaluate(context))
def __str__(self):
return ('(%s || %s)' % (self.left, self.rig... |
def test_solver_can_resolve_sdist_dependencies(solver: Solver, repo: Repository, package: ProjectPackage, fixture_dir: FixtureDirGetter) -> None:
pendulum = get_package('pendulum', '2.0.3')
repo.add_package(pendulum)
path = (fixture_dir('distributions') / 'demo-0.1.0.tar.gz').as_posix()
package.add_depe... |
_bp.route(MANIFEST_DIGEST_ROUTE, methods=['GET'])
_for_account_recovery_mode
_repository_name()
_registry_jwt_auth(scopes=['pull'])
_repo_read(allow_for_superuser=True)
_protect
_registry_model()
def fetch_manifest_by_digest(namespace_name, repo_name, manifest_ref, registry_model):
try:
repository_ref = reg... |
def compute_sublist_prob(sub_list):
if (len(sub_list) == 0):
sys.exit('compute_sentence_probs_arpa.py: Ngram substring not found in arpa language model, please check.')
sub_string = ' '.join(sub_list)
if (sub_string in ngram_dict):
return (- float(ngram_dict[sub_string][0][1:]))
else:
... |
def send_request(path: string, method: string, body: string=None, token: string=None) -> dict:
current_time = str(int(time.time()))
nonce = ''.join(random.choices((string.ascii_lowercase + string.digits), k=32))
raw = ((((path + current_time) + nonce) + method) + api_key)
raw = raw.lower()
h = hmac.... |
def get_clients_at_depth(fgraph: FunctionGraph, node: Apply, depth: int) -> Generator[(Apply, None, None)]:
for var in node.outputs:
if (depth > 0):
for (out_node, _) in fgraph.clients[var]:
if (out_node == 'output'):
continue
(yield from get_c... |
.unit()
.parametrize(('expr', 'column', 'message'), [('(', 2, 'expected not OR left parenthesis OR identifier; got end of input'), (' (', 3, 'expected not OR left parenthesis OR identifier; got end of input'), (')', 1, 'expected not OR left parenthesis OR identifier; got right parenthesis'), (') ', 1, 'expected not OR ... |
def format_subnet(subnet):
try:
subnet_obj = ipaddress.ip_network(subnet)
except:
raise BadParam(('invalid subnet: %s' % subnet), msg_ch=(': %s' % subnet))
start_ip = subnet_obj.network_address
end_ip = subnet_obj.broadcast_address
is_ipv6 = (subnet_obj.version == 6)
return (str(... |
class VGG16_DM(nn.Module):
def __init__(self, load_weights=True):
super(VGG16_DM, self).__init__()
self.layer5 = self.VGG_make_layers([64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'])
self.reg_layer = nn.Sequential(nn.Conv2d(512, 256, kernel_size=3, pa... |
_bp.route('/<repopath:repository>/blobs/uploads/', methods=['POST'])
_for_account_recovery_mode
_repository_name()
_registry_jwt_auth(scopes=['pull', 'push'])
_repo_write(allow_for_superuser=True, disallow_for_restricted_users=True)
_protect
_readonly
def start_blob_upload(namespace_name, repo_name):
repository_ref... |
_attr(allow_interpreted_subclasses=True)
class FileSystemCache():
def __init__(self) -> None:
self.package_root: list[str] = []
self.flush()
def set_package_root(self, package_root: list[str]) -> None:
self.package_root = package_root
def flush(self) -> None:
self.stat_cache:... |
class DataCollatorForWav2Vec2Pretraining():
model: Wav2Vec2ForPreTraining
feature_extractor: Wav2Vec2FeatureExtractor
padding: Union[(bool, str)] = 'longest'
pad_to_multiple_of: Optional[int] = None
mask_time_prob: Optional[float] = 0.65
mask_time_length: Optional[int] = 10
def __call__(self... |
.parametrize('username,password', users)
def test_create_update(db, client, username, password, json_data):
client.login(username=username, password=password)
url = reverse(urlnames['list'])
response = client.post(url, json_data, content_type='application/json')
assert (response.status_code == status_ma... |
def MNIST(train=True, batch_size=None, augm_flag=True):
if (batch_size == None):
if train:
batch_size = train_batch_size
else:
batch_size = test_batch_size
transform_base = [transforms.ToTensor()]
transform_train = transforms.Compose(([transforms.RandomCrop(28, paddin... |
class DBusProperty():
IFACE = 'org.freedesktop.DBus.Properties'
ISPEC = '\n<method name="Get">\n <arg type="s" name="interface_name" direction="in"/>\n <arg type="s" name="property_name" direction="in"/>\n <arg type="v" name="value" direction="out"/>\n</method>\n<method name="GetAll">\n <arg type="s... |
class ImageNetTrainer():
def __init__(self, tfrecord_dir: str, training_inputs: List[str], data_inputs: List[str], validation_inputs: List[str], image_size: int=224, batch_size: int=128, num_epochs: int=1, format_bgr: bool=False, model_type: str='resnet'):
if (not data_inputs):
raise ValueError(... |
class LeadingOrderDifferential(BaseLeadingOrderSurfaceForm):
def __init__(self, param, domain, options=None):
super().__init__(param, domain, options)
def set_rhs(self, variables):
domain = self.domain
sum_a_j = variables[f'Sum of x-averaged {domain} electrode volumetric interfacial curr... |
(frozen=True)
class ExportedPickupDetails():
index: PickupIndex
name: str
description: str
collection_text: list[str]
conditional_resources: list[ConditionalResources]
conversion: list[ResourceConversion]
model: PickupModel
original_model: PickupModel
other_player: bool
original_... |
class PyrockoRingfaultDelegate(SourceDelegate):
__represents__ = 'PyrockoRingfaultSource'
display_backend = 'pyrocko'
display_name = 'Ringfault'
parameters = ['store_dir', 'easting', 'northing', 'depth', 'diameter', 'strike', 'dip', 'magnitude', 'npointsources']
ro_parameters = []
class Ringfaul... |
def test_multiple_services():
import threading as mt
import queue
q = queue.Queue()
def _test_ms(i):
cfg = config()
try:
helper_multiple_services(i)
q.put(True)
except rs.NotImplemented as ni:
assert cfg.notimpl_warn_only, ('%s ' % ni)
... |
def construct_prompt_token(params, tokenizer: GPT2TokenizerFast, train_datasets: list, only_train_last: bool=False, max_len: int=1000):
if only_train_last:
print('Only set the last in-context example for training.')
newline = tokenizer.encode('\n', add_special_tokens=False)
newlines = tokenizer.enco... |
def XGBoost(filename, x_predict, model_name, xgb_outputname, set_now, game_name, change_side):
data = pd.read_csv(filename)
data = data[needed]
data.dropna(inplace=True)
data.reset_index(drop=True, inplace=True)
data = data[(data.type != '')]
data = data[(data.type != '')]
data = data[(data.... |
def train(train_loader, model, criterion, optimizer, epoch, cfg, logger, writer):
model.eval()
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
num_iter = len(train_loader)
end = time.time()
time1 = time.time()
for (idx, (images, labels)) in enumerate(train_loade... |
class PutObjectAction(BaseAction):
valid_actions = {'PutObject', 'OpenObject', 'CloseObject'}
def get_reward(self, state, prev_state, expert_plan, goal_idx, low_idx=None):
if (low_idx is None):
subgoal = expert_plan[goal_idx]['planner_action']
else:
subgoal = expert_plan[... |
def return_canoncailised_smiles_str(molecule, remove_am=True, allHsExplicit=False, kekuleSmiles=True) -> str:
mol_copy = Chem.RWMol(molecule)
if remove_am:
for atom in mol_copy.GetAtoms():
atom.ClearProp('molAtomMapNumber')
smiles = Chem.MolToSmiles(mol_copy, allHsExplicit=allHsExplicit,... |
def usage():
print('Usage:', os.path.basename(sys.argv[0]), '[options] file')
print('Options:')
print(' -d, --dcalls Apply clause D calls')
print(' -e, --enum=<string> How many solutions to compute')
print(' Available values: [1 .. all] (defau... |
class TED_eval(Dataset):
def __init__(self, transform=None):
self.ds_path = './datasets/ted/test/'
self.videos = os.listdir(self.ds_path)
self.transform = transform
def __getitem__(self, idx):
vid_name = self.videos[idx]
video_path = os.path.join(self.ds_path, vid_name)
... |
_db
def test_query_events_image(rf, graphql_client, conference_factory, event_factory):
now = timezone.now()
request = rf.get('/')
conference = conference_factory(start=now, end=(now + timezone.timedelta(days=3)))
event = event_factory(conference=conference, latitude=1, longitude=1)
resp = graphql_c... |
class CnfWrapper():
def __init__(self, grammar):
super(CnfWrapper, self).__init__()
self.grammar = grammar
self.rules = grammar.rules
self.terminal_rules = defaultdict(list)
self.nonterminal_rules = defaultdict(list)
for r in self.rules:
assert isinstance(... |
def test_load_initial_conftest_last_ordering(_config_for_test):
pm = _config_for_test.pluginmanager
class My():
def pytest_load_initial_conftests(self):
pass
m = My()
pm.register(m)
hc = pm.hook.pytest_load_initial_conftests
hookimpls = [(hookimpl.function.__module__, ('wrapp... |
class UfsFileSystem(MountFileSystem):
type = 'ufs'
aliases = ['4.2bsd', 'ufs2', 'ufs 2']
_mount_opts = 'ufstype=ufs2'
def detect(cls, source, description):
res = super().detect(source, description)
if (('BSD' in description) and ('4.2BSD' not in description) and ('UFS' not in description... |
def optimize(instance, max_time=10000, time_limit=100, threads=1):
model = CpoModel('BlockingJobShop')
interval_vars = dict()
for task in instance.tasks:
interval_vars[task] = interval_var(start=(0, max_time), end=(0, max_time), size=(task.length, max_time), name=('interval' + str(task.name)))
f... |
class CbamModule(nn.Module):
def __init__(self, channels, rd_ratio=(1.0 / 16), rd_channels=None, rd_divisor=1, spatial_kernel_size=7, act_layer=nn.ReLU, gate_layer='sigmoid', mlp_bias=False):
super(CbamModule, self).__init__()
self.channel = ChannelAttn(channels, rd_ratio=rd_ratio, rd_channels=rd_ch... |
def bootstrap_stderr(f, xs, iters):
import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())
res = []
chunk_size = min(1000, iters)
from tqdm import tqdm
print('bootstrapping for stddev:', f.__name__)
for bootstrap in tqdm(pool.imap(_bootstrap_internal(f, chunk_size), [(i, xs) for i in ra... |
class InMemoryLoggerTest(unittest.TestCase):
def test_in_memory_log(self) -> None:
logger = InMemoryLogger()
logger.log(name='metric1', data=123.0, step=0)
logger.log(name='metric1', data=456.0, step=1)
logger.log(name='metric1', data=789.0, step=2)
with captured_output() as ... |
def get_cls_loss(pred, label, select):
if (not bool(select.numel())):
return 0
try:
pred = torch.index_select(pred, 0, select)
label = torch.index_select(label, 0, select)
out = F.nll_loss(pred, label)
except:
print('error:\n', pred, label, pred.size(), label.size())
... |
def test_compatible_with_numpy_configuration(tmp_path):
files = ['dir1/__init__.py', 'dir2/__init__.py', 'file.py']
_populate_project_dir(tmp_path, files, {})
dist = Distribution({})
dist.configuration = object()
dist.set_defaults()
assert (dist.py_modules is None)
assert (dist.packages is N... |
.memory
def test_being_calc_next_time():
_takes_time.clear_cache()
_being_calc_next_time(0.13, 0.02)
sleep(1.1)
res_queue = queue.Queue()
thread1 = threading.Thread(target=_calls_being_calc_next_time, kwargs={'res_queue': res_queue}, daemon=True)
thread2 = threading.Thread(target=_calls_being_ca... |
_fixtures(SqlAlchemyFixture)
def demo_setup(sql_alchemy_fixture):
sql_alchemy_fixture.commit = True
Address(email_address='', name='Friend1').save()
Address(email_address='', name='Friend2').save()
Address(email_address='', name='Friend3').save()
Address(email_address='', name='Friend4').save() |
def test_multi_hook():
r2p = r2pipe.open('test/tests/multibranch', flags=['-2'])
r2p.cmd('s sym.check; aei; aeim; aer rdi=22021')
esilsolver = ESILSolver(r2p, debug=False, trace=False)
state = esilsolver.init_state()
state.set_symbolic_register('rdi')
rdi = state.registers['rdi']
state.solve... |
class KernelNet(nn.Module):
def __init__(self, in_channels, init_n_kernels, out_channels, depth, n_nodes, channel_change):
super().__init__()
c0 = c1 = (n_nodes * init_n_kernels)
c_node = init_n_kernels
self.stem0 = ConvOps(in_channels, c0, kernel_size=1, ops_order='weight_norm')
... |
class ModelArguments():
model_name_or_path: Optional[str] = field(default=None, metadata={'help': "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."})
model_type: Optional[str] = field(default=None, metadata={'help': ('If training from scratch, pass a model ty... |
def collect_raw_osm_stats(rulename='download_osm_data', metric_crs='EPSG:3857'):
snakemake = _mock_snakemake('download_osm_data')
options_raw = dict(snakemake.output)
options_raw.pop('generators_csv')
df_raw_osm_stats = collect_osm_stats(rulename, only_basic=True, metric_crs=metric_crs, **options_raw)
... |
class RoIAlignRotated(nn.Module):
def __init__(self, out_size, spatial_scale, sample_num=0, aligned=True, clockwise=False):
super(RoIAlignRotated, self).__init__()
self.out_size = out_size
self.spatial_scale = float(spatial_scale)
self.sample_num = int(sample_num)
self.aligne... |
def show_results(experiment):
results = experiment['results']
labels = experiment['labels']
for (i, (dataset, d_value)) in enumerate(results.items()):
f = plt.figure(figsize=(16.0, 10.0))
plt.suptitle(dataset, fontsize=20, fontweight='bold')
girds = {6: (2, 3), 12: (3, 4)}[len(result... |
def inference(args):
audio_path = args.audio_path
output_midi_path = args.output_midi_path
device = ('cuda' if (args.cuda and torch.cuda.is_available()) else 'cpu')
(audio, _) = load_audio(audio_path, sr=sample_rate, mono=True)
transcriptor = PianoTranscription(device=device, checkpoint_path=None)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.