code stringlengths 281 23.7M |
|---|
class EditorWizardPage(BasePyzoWizardPage):
_title = translate('wizard', 'The editor is where you write your code')
_image_filename = 'pyzo_editor.png'
_descriptions = [translate('wizard', 'In the *editor*, each open file is represented as a tab. By\n right-clicking on a tab, files can be run, saved,... |
_against_invalid_ecpoint
def CKD_pub(parent_pubkey: bytes, parent_chaincode: bytes, child_index: int) -> Tuple[(bytes, bytes)]:
if (child_index < 0):
raise ValueError('the bip32 index needs to be non-negative')
if (child_index & BIP32_PRIME):
raise Exception('not possible to derive hardened chil... |
class FSNERModel(torch.nn.Module):
def __init__(self, pretrained_model_name_or_path='sayef/fsner-bert-base-uncased'):
super(FSNERModel, self).__init__()
self.bert = AutoModel.from_pretrained(pretrained_model_name_or_path, return_dict=True)
self.cos = torch.nn.CosineSimilarity(3, 1e-08)
... |
class StarDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
starRating = index.data()
if isinstance(starRating, StarRating):
if (option.state & QStyle.State_Selected):
painter.fillRect(option.rect, option.palette.highlight())
starRating.p... |
def unpool_with_argmax(pool, ind, name=None, ksize=[1, 2, 2, 1]):
with tf.variable_scope(name):
input_shape = pool.get_shape().as_list()
output_shape = (input_shape[0], (input_shape[1] * ksize[1]), (input_shape[2] * ksize[2]), input_shape[3])
flat_input_size = np.prod(input_shape)
fl... |
def DecodeAttr(datatype, value):
if (datatype == 'string'):
return DecodeString(value)
elif (datatype == 'octets'):
return DecodeOctets(value)
elif (datatype == 'integer'):
return DecodeInteger(value)
elif (datatype == 'ipaddr'):
return DecodeAddress(value)
elif (data... |
class CategoricalGRUPolicy(StochasticPolicy, LasagnePowered, Serializable):
def __init__(self, env_spec, hidden_dim=32, feature_network=None, state_include_action=True, hidden_nonlinearity=NL.tanh):
assert isinstance(env_spec.action_space, Discrete)
Serializable.quick_init(self, locals())
su... |
.parametrize('dtype', ['U', 'S', 'u1', 'u2', 'i8', 'int'])
def test_read_bgen__contig_dtype(shared_datadir, dtype):
path = (shared_datadir / 'example.bgen')
ds = read_bgen(path, contig_dtype=dtype)
dtype = np.dtype(dtype)
if (dtype.kind in {'U', 'S'}):
assert (ds['variant_contig'].dtype == np.in... |
class TestConvertor(unittest.TestCase):
def test_basic(self):
self.assertEquals(time.convert(60, 's', 's'), 60.0)
self.assertEquals(time.convert(60, 's', 'm'), 1.0)
self.assertEquals(time.convert(60000, 'ms', 'm'), 1.0)
self.assertEquals(time.convert(60000, 'MS', 'minutes'), 1.0)
... |
def _threshold_and_support(input, dim=0):
(input_srt, _) = torch.sort(input, descending=True, dim=dim)
input_cumsum = (input_srt.cumsum(dim) - 1)
rhos = _make_ix_like(input, dim)
support = ((rhos * input_srt) > input_cumsum)
support_size = support.sum(dim=dim).unsqueeze(dim)
tau = input_cumsum.g... |
class AbstractNotificationAdapter(QObject):
NAME: str
close_id = pyqtSignal(int)
click_id = pyqtSignal(int)
error = pyqtSignal(str)
clear_all = pyqtSignal()
def present(self, qt_notification: 'QWebEngineNotification', *, replaces_id: Optional[int]) -> int:
raise NotImplementedError
d... |
class StaticWrapper(hwndwrapper.HwndWrapper):
friendlyclassname = 'Static'
windowclasses = ['Static', 'WindowsForms\\d*\\.STATIC\\..*', 'TPanel', '.*StaticText']
can_be_label = True
def __init__(self, hwnd):
super(StaticWrapper, self).__init__(hwnd)
def _needs_image_prop(self):
if (s... |
class CrPVP(PVP):
VERBALIZER = {'0': ['silly'], '1': ['solid']}
def get_parts(self, example: InputExample) -> FilledPattern:
text_a = self.shortenable(example.text_a)
if (self.pattern_id == 1):
string_list_a = [text_a, 'I', 'think', 'it', 'is', self.mask, '!']
string_list... |
class ConvDropoutNormNonlin(nn.Module):
def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2d, norm_op_kwargs=None, dropout_op=nn.Dropout2d, dropout_op_kwargs=None, nonlin=nn.LeakyReLU, nonlin_kwargs=None):
super(ConvDropoutNormNonlin, self).__init__... |
class SGWinogradSchemaChallenge(Task):
VERSION = 0
DATASET_PATH = 'super_glue'
DATASET_NAME = 'wsc'
def has_training_docs(self):
return True
def has_validation_docs(self):
return True
def has_test_docs(self):
return False
def training_docs(self):
if self.has_t... |
def _group_keys_by_module(keys: List[str], original_names: Dict[(str, str)]):
def _submodule_name(key):
pos = key.rfind('.')
if (pos < 0):
return None
prefix = key[:(pos + 1)]
return prefix
all_submodules = [_submodule_name(k) for k in keys]
all_submodules = [x fo... |
class DevServer(SuperHTTPServer):
def __init__(self, base_url, *args, **kwargs):
self.base_url = base_url
super().__init__(*args, **kwargs)
def run(self):
try:
self.serve_forever()
except KeyboardInterrupt:
pass
finally:
self.server_clo... |
_fixtures(WebFixture)
def test_basic_fixed_attributes(web_fixture):
fixture = web_fixture
widget = HTMLElement(fixture.view, 'x')
tester = WidgetTester(widget)
widget.set_attribute('attr1', 'value1')
widget.add_to_attribute('listattr', ['one', 'two'])
widget.add_to_attribute('listattr', ['three'... |
class SendGrantInput(BaseGrantInput):
name: str
full_name: str
conference: strawberry.ID
age_group: AgeGroup
gender: str
occupation: Occupation
grant_type: GrantType
python_usage: str
been_to_other_events: str
community_contribution: str
interested_in_volunteering: Interested... |
def pretf_blocks():
bucket = (yield resource.aws_s3_bucket.test(bucket='pretf-example-aws-files', acl='private'))
total_files = 0
total_bytes = 0
for source in ('files', 'more-files'):
objects = (yield aws_s3_bucket_objects(bucket=bucket, source=source))
total_files += objects.total_file... |
class RelativeObjectPosition(_PositionType):
def __init__(self, entity, dx, dy, dz=None, orientation=Orientation()):
self.target = entity
self.dx = convert_float(dx)
self.dy = convert_float(dy)
self.dz = convert_float(dz)
if (not isinstance(orientation, Orientation)):
... |
class Bottleneck(MetaModule):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck, self).__init__()
self.conv1 = MetaConv2d(in_planes, planes, kernel_size=1, bias=False)
self.bn1 = MetaBatchNorm2d(planes)
self.conv2 = MetaConv2d(planes, planes, kernel_... |
def dump_infos_gdb(parsed):
with tempfile.TemporaryDirectory() as tempdir:
coredump = os.path.join(tempdir, 'dump')
subprocess.run(['coredumpctl', 'dump', '-o', coredump, str(parsed.pid)], check=True)
subprocess.run(['gdb', parsed.exe, coredump, '-ex', 'info threads', '-ex', 'thread apply al... |
_on_failure
.parametrize('number_of_nodes', [2])
.parametrize('deposit', [1000])
.parametrize('enable_rest_api', [True])
def test_api_channel_withdraw(api_server_test_instance: APIServer, raiden_network: List[RaidenService], token_addresses, pfs_mock):
(_, app1) = raiden_network
pfs_mock.add_apps(raiden_network... |
class Rename():
def __init__(self, project, resource, offset=None):
self.project = project
self.resource = resource
if (offset is not None):
self.old_name = worder.get_name_at(self.resource, offset)
this_pymodule = self.project.get_pymodule(self.resource)
... |
def setup_smoketest(*, eth_client: EthClient, print_step: StepPrinter, free_port_generator: Iterator[Port], debug: bool=False, stdout: IO=None, append_report: Callable=print) -> Iterator[RaidenTestSetup]:
make_requests_insecure()
datadir = mkdtemp()
testchain_manager = setup_testchain_for_smoketest(eth_clie... |
class RemoveButton(QtWidgets.QToolButton):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setText('Remove')
def enterEvent(self, e):
if (self.window().showhelp is True):
QtWidgets.QToolTip.showText(e.globalPos(), '<h3>Undo Annotations</h3>Successi... |
def is_pathname_valid(pathname: str) -> bool:
try:
if ((not isinstance(pathname, str)) or (not pathname)):
return False
(_, pathname) = os.path.splitdrive(pathname)
root_dirname = (os.environ.get('HOMEDRIVE', 'C:') if IS_WINDOWS else os.path.sep)
assert os.path.isdir(root... |
def test_proto3_schema():
mock_proto3_schema_str = '\n syntax = "proto3";\n\n message User {\n required string name = 1;\n required int32 age = 2;\n }\n '
client = FilesystemClient(scheme='file')
with patch.object(client, '_read_file', return_value=mock_proto3_schema_str):
... |
class TestEOH(QiskitAquaTestCase):
('initial_state', 'circuit')
def test_eoh(self, mode):
size = 2
aqua_globals.random_seed = 0
temp = aqua_globals.random.random(((2 ** size), (2 ** size)))
h_1 = (temp + temp.T)
qubit_op = MatrixOperator(matrix=h_1)
temp = aqua_gl... |
class MarkSheetTestCase(unittest.TestCase):
def setUp(self) -> None:
img_path = '../../image_data/DIP3E_CH11_Original_Images/Fig1111(a)(triangle).tif'
self.img = Image.open(img_path)
self.img = np.asarray(self.img)
self.img = self.img.astype(np.uint8)
def test_get_centroid(self):... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data_arg... |
.parametrize('blockysize', [1, 2, 3, 7, 61, 62])
def test_creation_untiled_blockysize(tmp_path, blockysize):
tmpfile = (tmp_path / 'test.tif')
with rasterio.open(tmpfile, 'w', count=1, height=61, width=37, dtype='uint8', blockysize=blockysize, tiled=False) as dataset:
pass
with rasterio.open(tmpfile... |
def uc_sepset(cg: CausalGraph, priority: int=3, background_knowledge: (BackgroundKnowledge | None)=None) -> CausalGraph:
assert (priority in [0, 1, 2, 3, 4])
cg_new = deepcopy(cg)
R0 = []
UC_dict = {}
UT = [(i, j, k) for (i, j, k) in cg_new.find_unshielded_triples() if (i < k)]
for (x, y, z) in ... |
def test_chat_photo():
user_photo_small = 'AQADAgADrKcxGylBBQAJIH3qihAAAwIAAylBBQAF7bDHYwABnc983KcAAh4E'
user_photo_small_unique = 'AQADIH3qihAAA9ynAAI'
user_photo_big = 'AQADAgADrKcxGylBBQAJIH3qihAAAwMAAylBBQAF7bDHYwABnc983qcAAh4E'
user_photo_big_unique = 'AQADIH3qihAAA96nAAI'
chat_photo_small = 'A... |
def simulation(method, m=400, n=3000, rvec=[10, 50, 25], rho=0.1, nrep=50, seed=1234, burnin=200, win_size=200, track_cp_burnin=100, n_check_cp=20, alpha=0.01, proportion=0.5, n_positive=3, min_test_size=100, tolerance_num=0, factor=1):
result = ([np.nan] * nrep)
run_times = ([np.nan] * nrep)
random_state =... |
class Person(models.Model):
name = models.CharField(max_length=255)
title = tagulous.models.SingleTagField(initial='Mr, Mrs', help_text='This is a SingleTagField - effectively a CharField with dynamic choices', on_delete=models.CASCADE)
skills = tagulous.models.TagField(Skill, help_text='This field does not... |
def create_3cloths(cloth1_start, cloth1_end, cloth1_length, cloth2_start, cloth2_end, cloth2_length, cloth3_start, cloth3_end, cloth3_length, r_id, junction=1, n_lanes=1, lane_offset=3, road_marks=std_roadmark_broken()):
warn('create_cloth_arc_cloth should not be used anymore, please use the create_road (see exampe... |
def generate_triplet_from_seeds(seeds: List[List[str]], max_triplets_per_set=None) -> List[Tuple[(str, str, str)]]:
triplets = []
all_words = {phrase for cluster in seeds for phrase in cluster}
for (i, seed_values) in enumerate(seeds):
other_words = list((all_words - set(seed_values)))
if (l... |
class ModelForModelSizeMeasure(nn.Module):
def __init__(self, C, num_classes, layers, criterion, alphas_normal, alphas_reduce, steps=4, multiplier=4, stem_multiplier=3):
super(ModelForModelSizeMeasure, self).__init__()
self._C = C
self._num_classes = num_classes
self._layers = layers... |
def test_nested_point_user_strategy():
limit_dict = {'p1': {'x': range(224, 240)}, 'p2': pst.bitstructs(Point2D, {'x': range(0, 2), 'y': range(2, 4)})}
print('')
(bs=pst.bitstructs(NestedPoint, limit_dict))
(max_examples=16)
def actual_test(bs):
assert isinstance(bs, NestedPoint)
ass... |
def test_handle_inittarget():
block_number = 1
pseudo_random_generator = random.Random()
channels = make_channel_set([channel_properties])
transfer_properties = LockedTransferSignedStateProperties(amount=channels[0].partner_state.contract_balance, expiration=((channels[0].reveal_timeout + block_number) ... |
def add_control_inputs(op, cops):
if (not isinstance(op, _tf_ops.Operation)):
raise TypeError('Expected a tf.Operation, got: {}', type(op))
cops = _util.make_list_of_op(cops, allow_graph=False)
for cop in cops:
if (cop in op.control_inputs):
raise ValueError('{} is already a cont... |
def object_issubclass(node: nodes.NodeNG, class_or_seq: list[InferenceResult], context: (InferenceContext | None)=None) -> (util.UninferableBase | bool):
if (not isinstance(node, nodes.ClassDef)):
raise TypeError(f'{node} needs to be a ClassDef node')
return _object_type_is_subclass(node, class_or_seq, ... |
class User(ModelReprMixin, models.Model):
id = models.BigIntegerField(primary_key=True, validators=(MinValueValidator(limit_value=0, message='User IDs cannot be negative.'),), verbose_name='ID', help_text='The ID of this user, taken from Discord.')
name = models.CharField(max_length=32, help_text='The username,... |
class UserDashboardViewTest(TestCase):
def setUpTestData(cls):
add_default_data()
def login(self, name):
self.client.login(username=name, password=name)
self.pu = PytitionUser.objects.get(user__username=name)
return self.pu
def logout(self):
self.client.logout()
d... |
('pypyr.config.config.init')
def test_trace_log_level_none(mock_config_init):
arg_list = ['blah', 'ctx string']
with patch('pypyr.pipelinerunner.run') as mock_pipeline_run:
with patch('traceback.print_exc') as mock_traceback:
mock_pipeline_run.side_effect = AssertionError('Test Error Mock')
... |
def raise_error_and_retry(max_try, time_gap, func, *args, **kargs):
import logging
logging.debug('Debugging, Enter raise_error_and_retry')
sth = None
for i in range(max_try):
success_flag = False
try:
sth = func(*args, **kargs)
success_flag = True
except E... |
class SmtLibSolver(object):
def set_logic(self, logic):
raise NotImplementedError
def declare_fun(self, symbol):
raise NotImplementedError
def declare_const(self, symbol):
raise NotImplementedError
def define_fun(self, name, args, rtype, expr):
raise NotImplementedError
... |
def auto_load_resume(model, path, status):
if (status == 'train'):
pth_files = os.listdir(path)
nums_epoch = [int(name.replace('epoch', '').replace('.pth', '')) for name in pth_files if ('.pth' in name)]
if (len(nums_epoch) == 0):
return (0, init_lr)
else:
max... |
def main():
def positive_float(value):
val = float(value)
if (val <= 0):
raise ArgumentError
return val
parser = ArgumentParser()
parser.add_argument('-V', '--version', action='version', version=__version__)
parser.add_argument('-u', '--unit', default='1e-6', type=pos... |
class BotCreatePullRequestTest(TestCase):
def test_plain(self):
bot = bot_factory(bot_token=None)
bot._bot_repo = 'BOT REPO'
bot._user_repo = 'USER REPO'
bot.create_pull_request('title', 'body', 'new_branch')
self.assertEqual(bot.provider.create_pull_request.called, True)
... |
class VariableNotConsistentError(VariableError):
def __init__(self, old_var: 'VariableValue', new_var: 'VariableValue') -> None:
self.old_var = old_var
self.new_var = new_var
def __str__(self) -> str:
return f'create: {self.new_var.source} cannot set var.{self.new_var.name}={repr(self.ne... |
def check_repetition(DB=bib_db):
bib_dict = {}
for entry in DB.entries:
title = entry['title']
title = str(title).strip()
title = title.replace('{', '').replace('}', '')
if (title in bib_dict.keys()):
bib_dict[title] = (bib_dict[title] + 1)
else:
b... |
class MultiResolutionSTFTLoss(torch.nn.Module):
def __init__(self, fft_sizes=[2048, 1024, 512], hop_sizes=[240, 120, 50], win_lengths=[1200, 600, 240], window='hann_window'):
super(MultiResolutionSTFTLoss, self).__init__()
assert (len(fft_sizes) == len(hop_sizes) == len(win_lengths))
self.st... |
def module_in_path(modname: str, path: (str | Iterable[str])) -> bool:
modname = modname.split('.')[0]
try:
filename = file_from_modpath([modname])
except ImportError:
return False
if (filename is None):
return False
filename = _normalize_path(filename)
if isinstance(path... |
.parametrize('parameters, expected', [pytest.param(['-p', 'C'], 1, id='Only C'), pytest.param(['-p', 'C', '-p', 'AB', '-p', 'N', '-p', 'O'], 5, id='CNO alpha beta'), pytest.param([], 7, id='All present'), pytest.param(['--no-targets'], 0, id='No targets')])
def test_combine_cli_all(run_cli, tmpdir, acetone, coumarin, o... |
class LifeCycleHook():
__slots__ = ('__weakref__', '_context_providers', '_current_state_index', '_effect_funcs', '_effect_stops', '_effect_tasks', '_render_access', '_rendered_atleast_once', '_schedule_render_callback', '_scheduled_render', '_state', 'component')
component: ComponentType
def __init__(self,... |
class DbRouter():
def db_for_read(self, model, **hints):
if ((model._meta.app_label == 'app') and (model._meta.model_name == 'seconditem')):
return 'second'
return None
def db_for_write(self, model, **hints):
if ((model._meta.app_label == 'app') and (model._meta.model_name ==... |
def generate_ode_function(*args, **kwargs):
generators = {'lambdify': LambdifyODEFunctionGenerator, 'cython': CythonODEFunctionGenerator, 'theano': TheanoODEFunctionGenerator}
generator = kwargs.pop('generator', 'lambdify')
try:
g = generator(*args, **kwargs)
except TypeError:
try:
... |
def bind_subscription_to_org(subscription_id, org_id, user_id):
try:
return OrganizationRhSkus.create(subscription_id=subscription_id, org_id=org_id, user_id=user_id)
except model.DataModelException as ex:
logger.error('Problem binding subscription to org %s: %s', org_id, ex)
except peewee.I... |
.skipif((os.getenv('GITHUB_ACTIONS', False) and (platform.system() in ['Windows', 'Darwin'])), reason='On Windows & MacOS precise timings are not accurate.')
class TestPTBJobstore():
def test_default_jobstore_instance(self, jobstore):
assert (type(jobstore) in (PTBMongoDBJobStore, PTBSQLAlchemyJobStore))
... |
class Address(Base):
__tablename__ = 'eventresult_address'
id = Column(Integer, primary_key=True)
email_address = Column(UnicodeText)
name = Column(UnicodeText)
reviewed = Column(Boolean)
fields = ExposedNames()
fields.name = (lambda i: Field(label='Name', required=True))
fields.email_ad... |
def clipboard_manager(request, minimal_conf_noscreen, manager_nospawn):
widget = libqtile.widget.Clipboard(**getattr(request, 'param', dict()))
config = minimal_conf_noscreen
config.screens = [Screen(top=Bar([widget], 10))]
manager_nospawn.start(config)
if (manager_nospawn.backend.name != 'x11'):
... |
def main(local_rank, args):
torch.backends.cudnn.benchmark = True
cfg = Config.fromfile(args.py_config)
dataset_config = cfg.dataset_params
ignore_label = dataset_config['ignore_label']
version = dataset_config['version']
train_dataloader_config = cfg.train_data_loader
val_dataloader_config ... |
def _reg_to_soq(binst: Union[(BloqInstance, DanglingT)], reg: Register, available: Union[(Set[Soquet], _IgnoreAvailable)]=_IgnoreAvailable()) -> SoquetT:
if reg.shape:
soqs = np.empty(reg.shape, dtype=object)
for ri in reg.all_idxs():
soq = Soquet(binst, reg, idx=ri)
soqs[ri]... |
def MI_Estimator(ft1, ft2, model):
scores = model(ft1, ft2)
def js_fgan_lower_bound_obj(scores):
scores_diag = scores.diag()
first_term = (- F.softplus((- scores_diag)).mean())
n = scores.size(0)
second_term = ((torch.sum(F.softplus(scores)) - torch.sum(F.softplus(scores_diag))) ... |
class Lines(object):
def __init__(self, lines):
self.lines = lines
self.line_count = len(lines)
self.current_line_number = 0
def current_line(self):
return self.lines[(self.current_line_number - 1)].strip()
def next_line(self):
self.current_line_number += 1
if... |
class OutdatedHwFirmwareException(UserFacingException):
def text_ignore_old_fw_and_continue(self) -> str:
suffix = ((_('The firmware of your hardware device is too old. If possible, you should upgrade it. You can ignore this error and try to continue, however things are likely to break.') + '\n\n') + _('Ign... |
def main() -> None:
trials = 3
print('Testing baseline')
baseline = trial(trials, Command((lambda : None), (lambda : execute(['python3', '-m', 'mypy', 'mypy']))))
report('Baseline', baseline)
print('Testing cold cache')
cold_cache = trial(trials, Command((lambda : delete_folder('.mypy_cache')), ... |
def test_create_left_lane_merge_first_lane():
lanedef = xodr.LaneDef(10, 20, 2, 1, 1)
lanes = xodr.create_lanes_merge_split(0, [lanedef], 30, xodr.std_roadmark_solid_solid(), 3, 3)
assert (len(lanes.lanesections) == 3)
assert (lanes.lanesections[0].s == 0)
assert (lanes.lanesections[1].s == 10)
... |
def test_batch():
with assert_raises(TypeError):
table.batch(timestamp='invalid')
b = table.batch()
b.put(b'row1', {b'cf1:col1': b'value1', b'cf1:col2': b'value2'})
b.put(b'row2', {b'cf1:col1': b'value1', b'cf1:col2': b'value2', b'cf1:col3': b'value3'})
b.delete(b'row1', [b'cf1:col4'])
b... |
(skip_s4_test(), reason='Only works if S4 installed')
def test_arbitrary_pol_rcwa():
import numpy as np
from solcore import material, si
from solcore.structure import Layer, Structure
from solcore.absorption_calculator.rigorous_coupled_wave import calculate_rat_rcwa, calculate_absorption_profile_rcwa
... |
class Effect5079(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'kineticDamage', ship.getModifiedItemAttr('shipBonusCF2'), skill='Caldari Frigate', **kwargs) |
def cmp(rpin, rpout):
_check_for_files(rpin, rpout)
if rpin.isreg():
if (not rpout.isreg()):
return None
(fp1, fp2) = (rpin.open('rb'), rpout.open('rb'))
result = _cmp_file_obj(fp1, fp2)
if (fp1.close() or fp2.close()):
raise RPathException('Error closing ... |
def load_operative_gin_configurations(checkpoint_dir):
gin_log_file = operative_config_path(checkpoint_dir)
with gin.unlock_config():
gin.parse_config_file(gin_log_file)
gin.finalize()
logging.info('Operative Gin configurations loaded from `checkpoint_dir`: %s', gin_log_file) |
def train():
train_set = {}
train_batch = {}
valid_set = {}
valid_loader = {}
batch_per_epo = defaultdict(int)
for task in pretrain_tasks:
train_set[task] = get_dataset(task, images, 'train')
valid_set[task] = get_dataset(task, images, 'val')
r = args.r[task]
trai... |
class QFIBase(DerivativeBase):
def __init__(self, qfi_method: Union[(str, CircuitQFI)]='lin_comb_full'):
if isinstance(qfi_method, CircuitQFI):
self._qfi_method = qfi_method
elif (qfi_method == 'lin_comb_full'):
from .circuit_qfis import LinCombFull
self._qfi_meth... |
class Zero(InitialState):
def __init__(self, num_qubits: int) -> None:
super().__init__()
validate_min('num_qubits', num_qubits, 1)
self._num_qubits = num_qubits
def _replacement():
return 'Zero(num_qubits) is the same as a empty QuantumCircuit(num_qubits).'
def construct_cir... |
def parse_args(argv):
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', dest='kscfg', required=True, help=_('Path to kickstart config file'))
parser.add_argument('-v', '--version', dest='version', default=DEVEL, help=_('Kickstart version to use for interpreting config'))
parser.ad... |
class CookieJarInterfaceTests(unittest.TestCase):
def test_add_cookie_header(self):
from mechanize import CookieJar
class MockRequest(object):
def __init__(self):
self.added_headers = []
self.called = set()
def log_called(self):
... |
class TestEncodeDecode(TestNameCheckVisitorBase):
_passes()
def test(self):
def capybara(s: str, b: bytes):
assert_is_value(s.encode('utf-8'), TypedValue(bytes))
assert_is_value(b.decode('utf-8'), TypedValue(str))
_passes()
def test_encode_wrong_type(self):
def ca... |
('pyinaturalist.client.get_access_token', return_value='token')
def test_client_auth(get_access_token):
client = iNatClient()
final_params_1 = client.request(request_function, auth=True)
final_params_2 = client.request(request_function)
assert (final_params_1['access_token'] == 'token')
assert ('acc... |
class Retry():
def __init__(self, fail_msg='retry failed!', ignore_exceptions=(), dt=sleep_time, tmax=max_sleep, return_on_fail=False):
self.fail_msg = fail_msg
self.ignore_exceptions = ignore_exceptions
self.dt = dt
self.tmax = tmax
self.return_on_fail = return_on_fail
d... |
.parametrize('text', ('SHOW', 'CREATE', 'ALTER', 'DROP', 'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'WHERE', 'GROUP', 'ORDER', 'BY', 'AS', 'DISTINCT', 'JOIN', 'WITH', 'RECURSIVE', 'PARTITION', 'NTILE', 'MASTER_PASSWORD', 'XA', 'REQUIRE_TABLE_PRIMARY_KEY_CHECK', 'STREAM'))
def test_keywords(lexer, text):
assert (list(l... |
class colors():
if sys.stdout.isatty():
BLUE = '\x1b[94m'
GREEN = '\x1b[92m'
YELLOW = '\x1b[93m'
RED = '\x1b[91m'
ENDC = '\x1b[0m'
BOLD = '\x1b[1m'
UNDERLINE = '\x1b[4m'
else:
HEADER = ''
BLUE = ''
GREEN = ''
YELLOW = ''
... |
.parametrize('base,one,two', [pytest.param(Version.parse('3.0.0'), Version.parse('3.0.0-1'), Version.parse('3.0.0-2'), id='post'), pytest.param(Version.parse('3.0.0'), Version.parse('3.0.0+local.1'), Version.parse('3.0.0+local.2'), id='local')])
def test_allows_post_releases_explicit_with_min(base: Version, one: Versio... |
class DictConfigSource(ConfigSource):
def __init__(self) -> None:
self._config: dict[(str, Any)] = {}
def config(self) -> dict[(str, Any)]:
return self._config
def add_property(self, key: str, value: Any) -> None:
keys = key.split('.')
config = self._config
for (i, ke... |
def create_sdf_abc(sdfcommand, marching_cube_command, LIB_command, num_sample, bandwidth, res, expand_rate, raw_dirs, iso_val, max_verts, ish5=True, normalize=True, g=0.0, reduce=4):
os.system(LIB_command)
start = 0
for split in ['train', 'test']:
model_dir = os.path.join(raw_dirs['mesh_dir'], split... |
def run(scenarios_list, config, wait_duration, failed_post_scenarios, kubeconfig_path, kubecli: KrknKubernetes, telemetry: KrknTelemetryKubernetes) -> (list[str], list[ScenarioTelemetry]):
scenario_telemetries: list[ScenarioTelemetry] = []
failed_scenarios = []
for scenario_config in scenarios_list:
... |
class DBusUser(object):
found_users = {}
def __init__(self, user, display):
self.user = user
self.display = display
which = (user, display)
try:
self.environ = self.found_users[which]
return
except KeyError:
pass
for proc in pro... |
def _process_mmcls_checkpoint(checkpoint):
state_dict = checkpoint['state_dict']
new_state_dict = OrderedDict()
for (k, v) in state_dict.items():
if k.startswith('backbone.'):
new_state_dict[k[9:]] = v
new_checkpoint = dict(state_dict=new_state_dict)
return new_checkpoint |
def tensorize_and_pad(batch, device, pad):
device = torch.device(device)
(input_dict, gt_dict, feat_dict) = (dict(), dict(), dict())
(traj_data, feat_list) = list(zip(*batch))
for key in feat_list[0].keys():
feat_dict[key] = [el[key] for el in feat_list]
assert (len(set([t['dataset_name'] fo... |
class Discriminator(nn.Module):
def __init__(self, input_nc):
super(Discriminator, self).__init__()
model = [nn.Conv2d(input_nc, 64, 4, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True)]
model += [nn.Conv2d(64, 128, 4, stride=2, padding=1), nn.InstanceNorm2d(128), nn.LeakyReLU(0.2, inpla... |
def main() -> None:
help_factory: Any = (lambda prog: RawDescriptionHelpFormatter(prog=prog, max_help_position=32))
parser = ArgumentParser(prog='incremental_checker', description=__doc__, formatter_class=help_factory)
parser.add_argument('range_type', metavar='START_TYPE', choices=['last', 'commit'], help=... |
def require_session_login(func):
(func)
def wrapper(*args, **kwargs):
result = validate_session_cookie()
if result.has_nonrobot_user:
result.apply_to_context()
authentication_count.labels(result.kind, True).inc()
return func(*args, **kwargs)
elif (not ... |
def unary_iteration(l_iter: int, r_iter: int, flanking_ops: List[cirq.Operation], controls: Sequence[cirq.Qid], selection: Sequence[cirq.Qid], qubit_manager: cirq.QubitManager, break_early: Callable[([int, int], bool)]=(lambda l, r: False)) -> Iterator[Tuple[(cirq.OP_TREE, cirq.Qid, int)]]:
assert ((2 ** len(select... |
class FunctionMask(MaskBase):
def __init__(self, function):
self._function = function
def _validate_wcs(self, new_data=None, new_wcs=None, **kwargs):
pass
def _include(self, data=None, wcs=None, view=()):
result = self._function(data, wcs, view)
if (result.shape != data[view]... |
def log_predictions(args: argparse.Namespace, eval_dataset: NERDataset, outputs: EvalPrediction, prefix: str='eval'):
if (not args.do_train):
wandb.init(reinit=False)
labels = get_ner_labels('')
label_map: Dict[(int, str)] = {i: label for (i, label) in enumerate(labels)}
data = []
out_file =... |
class CodeMixin():
email = ''
code = ''
verified = False
def verify(self):
self.verified = True
self.save()
def generate_code(cls):
return uuid.uuid4().hex
def make_code(cls, email):
code = cls()
code.email = email
code.code = cls.generate_code()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.