code stringlengths 281 23.7M |
|---|
class DoPredictDuringTraining(TrainerCallback):
def __init__(self, test_dataset, processor):
super(DoPredictDuringTraining, self).__init__()
self.test_dataset = test_dataset.remove_columns('label')
self.processor = processor
self.best_score = None
def on_evaluate(self, args: Trai... |
def run(settings):
settings.description = 'Default train settings for DiMP with ResNet50 as backbone.'
settings.batch_size = 10
settings.num_workers = 8
settings.multi_gpu = False
settings.print_interval = 1
settings.normalize_mean = [0.485, 0.456, 0.406]
settings.normalize_std = [0.229, 0.2... |
def test_custom_ellipsoid():
ce = CustomEllipsoid(semi_major_axis=6378137, inverse_flattening=298.)
assert (ce.name == 'undefined')
assert (ce.semi_major_metre == 6378137)
assert (ce.semi_minor_metre == 6356752.)
assert_almost_equal(ce.inverse_flattening, 298.)
assert (sorted(ce.to_json_dict()) ... |
class DnCNN(nn.Module):
def __init__(self, channels, num_of_layers=17):
super(DnCNN, self).__init__()
self.num_of_layers = num_of_layers
kernel_size = 3
padding = 1
features = 64
self.layers = nn.ModuleList()
self.layers.append(nn.Conv2d(in_channels=channels, ... |
class NewLispLexer(RegexLexer):
name = 'NewLisp'
url = '
aliases = ['newlisp']
filenames = ['*.lsp', '*.nl', '*.kif']
mimetypes = ['text/x-newlisp', 'application/x-newlisp']
version_added = '1.5'
flags = (re.IGNORECASE | re.MULTILINE)
builtins = ('^', '--', '-', ':', '!', '!=', '?', '', ... |
class TestRealWorldLocate():
def setup_method(self) -> None:
self.dirpath = os.path.join(os.path.dirname(__file__), './data/')
network_distance = pandas.read_csv((self.dirpath + 'SF_network_distance_candidateStore_16_censusTract_205_new.csv'))
ntw_dist_piv = network_distance.pivot_table(valu... |
def cross_layer_equalization_manual():
model = models.resnet18(pretrained=True)
model = model.eval()
layer_list = [(model.conv1, model.bn1), (model.layer1[0].conv1, model.layer1[0].bn1)]
bn_dict = {}
for conv_bn in layer_list:
bn_dict[conv_bn[0]] = conv_bn[1]
batch_norm_fold.fold_given_b... |
def sql_log(db_config, db_login_user, db_sql_content, db_sql_res, db_sql_res_thead=''):
try:
log = DBLog.objects.create(db_config=db_config, db_login_user=db_login_user, db_sql_content=db_sql_content, db_sql_res=db_sql_res, db_sql_res_thead=db_sql_res_thead)
return log.id
except Exception as e:
... |
(frozen=True)
class FunctionInfo():
async_kind: AsyncFunctionKind
is_classmethod: bool
is_staticmethod: bool
is_decorated_coroutine: bool
is_overload: bool
is_override: bool
is_evaluated: bool
is_abstractmethod: bool
decorators: List[Tuple[(Value, Value, ast.AST)]]
node: Function... |
.parametrize('dims, args', [(2, {}), (3, {}), (2, {'how': 'pairs'}), (2, {'how': 'pairs_skewed'}), (2, {'how': 'before_after'}), (2, {'legend_iteration': 'all'}), (2, {'legend_iteration': 'grid_iteration'}), (2, {'legend_iteration': 1, 'how': 'before_after'}), (2, {'legend_iteration': 1, 'how': 'pairs'})])
def test_plo... |
class TestConfigVersioning(unittest.TestCase):
def test_upgrade_downgrade_consistency(self):
cfg = get_cfg()
cfg.USER_CUSTOM = 1
down = downgrade_config(cfg, to_version=0)
up = upgrade_config(down)
self.assertTrue((up == cfg))
def _merge_cfg_str(self, cfg, merge_str):
... |
class PageQuerySet(models.QuerySet):
def prefetch_elements(self):
return self.prefetch_related(*self.model.prefetch_lookups)
def filter_by_catalog(self, catalog):
ids = [descendant.id for descendant in catalog.descendants if isinstance(descendant, self.model)]
return self.filter(id__in=i... |
.parametrize(('test_type', 'test_status', 'expected'), [(TYPE_INFO, STATUS_DRAFT, ':abbr:`I (Informational, Draft)`'), (TYPE_INFO, STATUS_ACTIVE, ':abbr:`IA (Informational, Active)`'), (TYPE_INFO, STATUS_ACCEPTED, ':abbr:`IA (Informational, Accepted)`'), (TYPE_INFO, STATUS_DEFERRED, ':abbr:`ID (Informational, Deferred)... |
class IdentityResidualBlock(nn.Module):
def __init__(self, in_channels, channels, stride=1, dilation=1, groups=1, norm_act=ABN, dropout=None):
super(IdentityResidualBlock, self).__init__()
if ((len(channels) != 2) and (len(channels) != 3)):
raise ValueError('channels must contain either ... |
def make_json(clean_path, noisy_path, json_path):
clean_list = os.listdir(clean_path)
noisy_list = os.listdir(noisy_path)
clean_list.sort()
noisy_list.sort()
clean_list = get_info(clean_path, clean_list)
noisy_list = get_info(noisy_path, noisy_list)
if (not os.path.exists(json_path)):
... |
class VirtualFile():
_vfiles = {}
_counter = (- 1)
def readfromid(cls, id, length):
if (length is None):
return cls._vfiles[id].read()
else:
return cls._vfiles[id].read(length)
def writetoid(cls, id, buffer):
return cls._vfiles[id].write(buffer)
def cl... |
def call(command, args, payload=None, action='print', filter=None):
url = (args.url + command)
if payload:
if args.auth_key:
payload['auth_key'] = args.auth_key
else:
payload = {key: (getattr(args, key) if (key == 'email') else str(getattr(args, key))) for key in dir(args) if ((k... |
def extract_smis(library, smiles_col=0, title_line=True) -> List[str]:
if (Path(library).suffix == '.gz'):
open_ = partial(gzip.open, mode='rt')
else:
open_ = open
with open_(library) as fid:
reader = csv.reader(fid)
if title_line:
next(reader)
smis = []
... |
(suppress_health_check=[HealthCheck.function_scoped_fixture], deadline=None)
(args=arglists(st.integers()), kwargs=map_reduce_kwargs_iterators(), _parallel=(st.booleans() | st.none()))
.filterwarnings('ignore:.*:pytest.PytestUnraisableExceptionWarning')
def test_map_reduce(ray_context, func, args, kwargs, _parallel):
... |
class BuildUsageExamplesTests(unittest.TestCase):
def setUpClass(cls):
cls.das = DummyArtifacts()
cls.tempdir = cls.das.tempdir
cls.pm = PluginManager()
def tearDownClass(cls):
cls.das.free()
('qiime2.core.archive.provenance_lib.replay.build_action_usage')
('qiime2.core.a... |
class RandomCrop(object):
def __init__(self, size, *args, **kwargs):
self.size = size
def __call__(self, im_lb):
im = im_lb['im']
lb = im_lb['lb']
assert (im.size == lb.size)
(W, H) = self.size
(w, h) = im.size
if ((W, H) == (w, h)):
return dic... |
def fid_inception_v3():
inception = models.inception_v3(num_classes=1008, aux_logits=False, pretrained=False)
inception.Mixed_5b = FIDInceptionA(192, pool_features=32)
inception.Mixed_5c = FIDInceptionA(256, pool_features=64)
inception.Mixed_5d = FIDInceptionA(288, pool_features=64)
inception.Mixed_... |
def test_a_decorated_singleton_is_created_as_close_to_the_root_where_dependencies_fulfilled():
class NonInjectableD():
def __init__(self, required) -> None:
self.required = required
class SingletonC():
def __init__(self, d: NonInjectableD):
self.d = d
parent_injector ... |
class VolumeGANDiscriminator(nn.Module):
def __init__(self, resolution=(- 1), init_res=4, image_channels=3, architecture='resnet', use_wscale=True, wscale_gain=1.0, lr_mul=1.0, mbstd_groups=4, mbstd_channels=1, fmaps_base=(32 << 10), fmaps_max=512, filter_kernel=(1, 3, 3, 1), conv_clamp=None, eps=1e-08, label_dim=0... |
def var__global(self, clusters, n_chunk, segmentation_tg_op=None):
data_json_copy = []
labels_copy = []
for l in clusters:
for d in clusters[l]:
data_json_copy.append(d)
labels_copy.append(l)
tasks = []
while data_json_copy:
data_json_copy_part = data_json_cop... |
class FairseqOptimizer(object):
def __init__(self, args):
super().__init__()
self.args = args
def add_args(parser):
pass
def optimizer(self):
if (not hasattr(self, '_optimizer')):
raise NotImplementedError
if (not isinstance(self._optimizer, torch.optim.Op... |
class ActionCompareTest(unittest.TestCase):
def setUp(self):
self.base_dir = os.path.join(comtst.abs_test_dir, b'action_compare')
self.from1_struct = {'from1': {'contents': {'fileChanged': {'content': 'initial'}, 'fileOld': {}, 'fileUnchanged': {'content': 'unchanged'}}}}
self.from1_path = o... |
def sort_all_auto_mappings(overwrite: bool=False):
fnames = [os.path.join(PATH_TO_AUTO_MODULE, f) for f in os.listdir(PATH_TO_AUTO_MODULE) if f.endswith('.py')]
diffs = [sort_auto_mapping(fname, overwrite=overwrite) for fname in fnames]
if ((not overwrite) and any(diffs)):
failures = [f for (f, d) i... |
class DeliveryBase(DeliveryNamedTuple):
def mu(self):
return self.monitor_units
def combine(cls, *args):
first = cls(*args[0])
if (len(args) == 1):
return first
return first.merge(*args[1:])
def merge(self: DeliveryGeneric, *args: DeliveryGeneric) -> DeliveryGener... |
def test_parallel_xeb_fidelities() -> None:
sampler = cirq.Simulator()
qubit_locs = [(0, 0), (0, 1), (0, 2)]
qubits = [cirq.GridQubit(*idx) for idx in qubit_locs]
int_layers = [{(qubit_locs[0], qubit_locs[1])}, {(qubit_locs[1], qubit_locs[2])}]
xeb_configs = [[cirq.Moment([(cirq.ISWAP(qubits[0], qub... |
def merge_dict(to_update: dict, other_dict: dict) -> None:
for (key, value) in other_dict.items():
has_map = (isinstance(value, Mapping) and isinstance(to_update.get(key, None), Mapping))
if has_map:
merge_dict(to_update[key], value)
else:
to_update[key] = value |
class TLibraryValueCompletion(TestCase):
def setUp(self):
config.init()
def tearDown(self):
config.quit()
def test_ctr(self):
w = LibraryValueCompletion('artist', SongLibrary())
e = Gtk.Entry()
e.set_completion(w)
self.assertEqual(w.get_entry(), e)
sel... |
class TestMakeConfirmationTask(TestIncidents):
def test_make_confirmation_task_check(self):
with no_create_task():
self.cog_instance.make_confirmation_task(MockMessage(id=123))
self.cog_instance.bot.wait_for.assert_called_once()
created_check = self.cog_instance.bot.wait_for.call... |
class Migration(migrations.Migration):
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('hotels', '0006_remove_hotelroomreservation_user_id_and_more')]
operations = [migrations.AlterField(model_name='hotelroomreservation', name='user', field=models.ForeignKey(on_delete=django.db.model... |
def parse_args():
parser = argparse.ArgumentParser(description='Finetune (m)LUKE on a token classification task (such as NER) with the accelerate library')
parser.add_argument('--dataset_name', type=str, default=None, help='The name of the dataset to use (via the datasets library).')
parser.add_argument('--... |
class Integer(Value):
def __init__(self, value: int, rtype: RType=short_int_rprimitive, line: int=(- 1)) -> None:
if (is_short_int_rprimitive(rtype) or is_int_rprimitive(rtype)):
self.value = (value * 2)
else:
self.value = value
self.type = rtype
self.line = l... |
_model
def skresnext50_32x4d(pretrained=False, **kwargs):
sk_kwargs = dict(rd_ratio=(1 / 16), rd_divisor=32, split_input=False)
model_args = dict(block=SelectiveKernelBottleneck, layers=[3, 4, 6, 3], cardinality=32, base_width=4, block_args=dict(sk_kwargs=sk_kwargs), zero_init_last=False, **kwargs)
return _... |
class EncryptedPassportElement(TelegramObject):
__slots__ = ('selfie', 'files', 'type', 'translation', 'email', 'hash', 'phone_number', 'reverse_side', 'front_side', 'data')
def __init__(self, type: str, hash: str, data: Optional[Union[(PersonalDetails, IdDocumentData, ResidentialAddress)]]=None, phone_number: ... |
class StableSet(GraphOptimizationApplication):
def to_quadratic_program(self) -> QuadraticProgram:
mdl = Model(name='Stable set')
n = self._graph.number_of_nodes()
x = {i: mdl.binary_var(name=f'x_{i}') for i in range(n)}
for (w, v) in self._graph.edges:
self._graph.edges[... |
class RiverSplit(MultiSplitLink):
def __init__(self, model, *args, nsteps=1, **kwargs):
factors = kwargs.pop('factors')
extra_slots = (len(factors) - 1)
costs = kwargs.pop('costs', [0.0])
max_flows = kwargs.pop('max_flows', [None])
super(RiverSplit, self).__init__(model, nste... |
class decoder_old(nn.Module):
def __init__(self, in_dim=128, out_dim=(17 * 3), h_dim=128):
super(decoder, self).__init__()
self.in_dim = in_dim
self.h_dim = h_dim
self.out_dim = out_dim
self.fc1 = nn.Linear(in_dim, h_dim)
self.relu1 = nn.ReLU(inplace=True)
sel... |
def sortlist(n, m):
xx = xi
yy = y1[n]
resultX = []
x = []
y = []
resultY = list(reversed(np.sort(yy)))
le = len(xi)
for i in resultY:
pos = yy.index(i)
resultX.append(xx[pos])
for i in range(m):
x.append(resultX[i])
y.append(resultY[i])
return (x,... |
class QueryStepComparative(QueryStep):
def __init__(self, creator):
super().__init__(creator)
def parse_comparator_value(grounding_comparative, good_values=['>', '<', '>=', '<=', '=', '!=', 'like']):
assert grounding_comparative.iscomp(), f"Comparator should be grounded to a key of type 'compara... |
def hess(fcn: Callable[(..., torch.Tensor)], params: Sequence[Any], idxs: Union[(None, int, Sequence[int])]=None) -> Union[(LinearOperator, List)]:
idxs_list = _setup_idxs(idxs, params)
pfcn = get_pure_function(fcn)
res = []
def gen_pfcn2(idx):
_sibling(pfcn)
def pfcn2(*params):
... |
def suggestDType(x):
if (isinstance(x, list) or isinstance(x, tuple)):
if (len(x) == 0):
raise Exception('can not determine dtype for empty list')
x = x[0]
if hasattr(x, 'dtype'):
return x.dtype
elif isinstance(x, float):
return float
elif isinstance(x, int):
... |
class ClsAgnosticPredictHead(nn.Module):
def __init__(self, num_class, num_heading_bin, num_proposal, seed_feat_dim=256, objectness=True, heading=False, compute_sem_scores=True):
super().__init__()
self.num_class = num_class
self.num_heading_bin = num_heading_bin
self.num_proposal = ... |
def read_item_index_to_entity_id_file():
file = 'data/item_index2entity_id_rehashed.txt'
i = 0
for line in open(file, encoding='utf-8').readlines():
item_index = line.strip().split('\t')[0]
satori_id = line.strip().split('\t')[1]
item_index_old2new[item_index] = i
entity_id2i... |
(safer.closer)
class TestCloser(unittest.TestCase):
def test_callable_closer(self, safer_closer):
results = []
with safer_closer(results.append) as fp:
fp.write('one')
fp.write('two')
assert (results == [])
assert (results == ['onetwo'])
def test_calla... |
def get_cached_module_file(pretrained_model_name_or_path: Union[(str, os.PathLike)], module_file: str, cache_dir: Optional[Union[(str, os.PathLike)]]=None, force_download: bool=False, resume_download: bool=False, proxies: Optional[Dict[(str, str)]]=None, use_auth_token: Optional[Union[(bool, str)]]=None, revision: Opti... |
def generate_beacons(args):
default_cfg_path = '../data/configs/default.cfg'
wad_ids = util.get_sorted_wad_ids(args.wad_dir)
for (idx, wad_id) in enumerate(wad_ids):
start = time.time()
nodes = {}
edges = {}
for i in range(args.iters):
explore_map_random_policy(de... |
def special_keys_init():
for (key, val) in tuple(special_keys.items()):
special_keys[('a-' + key)] = (ALT_KEY, val)
for char in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!{}':
special_keys[('a-' + char)] = (ALT_KEY, ord(char))
for char in 'abcdefghijklmnopqrstuvwxyz_':
sp... |
def verify_post_install(pipx_exit_code: int, captured_outerr, caplog, package_name: str, test_error_fh: io.StringIO, using_clear_path: bool, deps: bool=False) -> Tuple[(bool, Optional[bool], Optional[Path])]:
pip_error_file = None
caplog_problem = False
install_success = (f'installed package {package_name}'... |
def sql_pred_parse(pred):
pred = (' * FROM' + pred)
if (pred == ' * FROM WHERE '):
return {}
pred_slot_values = []
parsed = sqlparse.parse(pred)
if (not parsed):
return {}
stmt = parsed[0]
sql_toks = pred.split()
operators = [' = ', ' LIKE ', ' < ', ' > ', ' >= ', ' <= '... |
def add_all_source_types(command_tester_factory: CommandTesterFactory, poetry_with_source: Poetry, source_primary: Source, source_default: Source, source_secondary: Source, source_supplemental: Source, source_explicit: Source) -> None:
add = command_tester_factory('source add', poetry=poetry_with_source)
for so... |
class OneLayerBRNN(nn.Module):
def __init__(self, input_size, hidden_size, prefix='stack_rnn', opt={}, dropout=None):
super(OneLayerBRNN, self).__init__()
self.opt = opt
self.prefix = prefix
self.cell_type = self.opt.get('{}_cell'.format(self.prefix), 'lstm')
self.emb_dim = s... |
class Visualizer():
def __init__(self, opt):
self.opt = opt
self.tf_log = opt.tf_log
self.use_html = (opt.isTrain and (not opt.no_html))
self.win_size = opt.display_winsize
self.name = opt.name
if self.tf_log:
import tensorflow as tf
self.tf = ... |
class ApplyKmeans(object):
def __init__(self, km_path):
self.km_model = joblib.load(km_path)
self.C_np = self.km_model.cluster_centers_.transpose()
self.Cnorm_np = (self.C_np ** 2).sum(0, keepdims=True)
self.C = torch.from_numpy(self.C_np)
self.Cnorm = torch.from_numpy(self.C... |
def plot(samples):
fig = plt.figure(figsize=(4, 4))
gs = gridspec.GridSpec(4, 4)
gs.update(wspace=0.05, hspace=0.05)
for (i, sample) in enumerate(samples):
ax = plt.subplot(gs[i])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')... |
def get_yt_ids(req: Requirement, highest_diff: int) -> Iterable[tuple[(str, int, int)]]:
if (not isinstance(req, RequirementArrayBase)):
return
if (((diff := get_difficulty(req)) is not None) and (diff > highest_diff)):
highest_diff = diff
if (req.comment is not None):
if ('youtu' in... |
def test_cancel_chunked_upload():
chunk_cleanup_queue = FakeQueue()
args = dict(base_args)
args['context'] = StorageContext('nyc', chunk_cleanup_queue, None, None)
swift = FakeSwiftStorage(**args)
(uuid, metadata) = swift.initiate_chunked_upload()
chunks = [b'this', b'is', b'some', b'chunked', b... |
class GPSRecord(object):
def __init__(self, al, pv, st, tm):
self._al = al
self._pv = pv
self._st = st
self._tm = tm
def time(self):
if (not (self._st.tracking_status_code == 0)):
raise NoGPSTime()
if (not self._tm.gps_utc_offset_flag):
rai... |
class LeftOuterJoin(operator):
def __init__(self, on, hints):
self.on = on
self.hints = hints
def used_vars(self):
from pythonql.Ast import get_all_vars, get_ast
return get_all_vars(self.on)
def execute(self, table, prior_locs, prior_globs, left_child, right_child):
f... |
def test_bloq_as_cirq_gate_multi_dimensional_signature():
bloq = SwapWithZero(2, 3, 4)
cirq_quregs = get_named_qubits(bloq.signature.lefts())
op = BloqAsCirqGate(bloq).on_registers(**cirq_quregs)
cirq.testing.assert_has_diagram(cirq.Circuit(op), '\nselection0: SwapWithZero\n \nselection... |
_equilibrium_solver('PDD', reason_to_exclude=reason_to_exclude)
def equilibrium_pdd(junction: Junction, T: float=298.0, output_equilibrium: int=1, meshpoints: int=(- 400), **options) -> None:
output = process_structure(junction=junction, T=T, meshpoints=meshpoints, **options)
dd.gen = 0
print('Solving equil... |
('pickle')
def test_frame_wise_iteration():
(X, Y) = _get_small_datasets(padded=False)
lengths = np.array([len(x) for x in X], dtype=int)
num_utterances = len(lengths)
X = MemoryCacheFramewiseDataset(X, lengths, cache_size=len(X))
Y = MemoryCacheFramewiseDataset(Y, lengths, cache_size=len(Y))
as... |
class TagListEditor(qltk.Window):
_WIDTH = 600
_HEIGHT = 300
def __init__(self, title, values=None):
super().__init__()
self.use_header_bar()
self.set_border_width(12)
self.set_title(title)
self.set_default_size(self._WIDTH, self._HEIGHT)
vbox = Gtk.VBox(spaci... |
def get_logger(file_path):
dir = os.path.dirname(file_path)
if (not os.path.exists(dir)):
os.makedirs(dir)
logger = logging.getLogger()
log_format = '%(asctime)s | %(message)s'
formatter = logging.Formatter(log_format, datefmt='%m/%d %H:%M:%S')
file_handler = logging.FileHandler(file_pat... |
class TestAssertEqual(TestCase):
def test_you(self):
self.assertRegexpMatches(abc, 'xxx')
def test_me(self):
self.assertRegexpMatches(123, (xxx + y))
def test_everybody(self):
self.assertRegexpMatches('abc', 'def')
def test_message(self):
self.assertRegexpMatches((123 + z... |
def check_plugin_project_files(app_folder: Path, plugin_name: str, plugin_description: str, html_file: str='index.html', config_file: str=config['project_config_filename'], python_file: str='main.py'):
html_file_path = (app_folder / html_file)
assert html_file_path.exists(), f'{html_file} not found! :('
ass... |
class KCrossAttnDownBlock2D(nn.Module):
def __init__(self, in_channels: int, out_channels: int, temb_channels: int, cross_attention_dim: int, dropout: float=0.0, num_layers: int=4, resnet_group_size: int=32, add_downsample=True, attention_head_dim: int=64, add_self_attention: bool=False, resnet_eps: float=1e-05, re... |
class RunningMeter(object):
def __init__(self, decay):
self.decay = decay
def reset(self):
self.val = 0
self.last = 0
def record(self, val, n=1):
self.last = val
decay = (1 - ((1 - self.decay) ** n))
self.val = (((1 - decay) * self.val) + (decay * val))
de... |
def test_handle_block_lower_block_number():
setup = make_target_state(block_number=10)
new_block = Block(block_number=(setup.block_number - 1), gas_limit=1, block_hash=factories.make_transaction_hash())
iteration = target.state_transition(target_state=setup.new_state, state_change=new_block, channel_state=s... |
def seperate_end_word_punctuations(data):
if verbose:
print(('#' * 10), 'Step - End word punctuations:')
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) and (not k[(len(k) - 1)].isalnum()))]
temp_dict = {}
for word ... |
def test_cylinder():
cylinder = Cylinder(10.0, 5.0, name='cylinder', color='blue', material='METAL')
assert (cylinder.name == 'cylinder')
assert (cylinder.__str__() == 'Cylinder cylinder color:blue material:METAL length:10.0 radius:5.0')
assert (cylinder.__repr__() == 'Cylinder')
assert (cylinder.le... |
(2, 'where', 'itemids')
def getVariations(itemids, groupIDs=None, where=None, eager=None):
for itemid in itemids:
if (not isinstance(itemid, int)):
raise TypeError('All passed item IDs must be integers')
if (len(itemids) == 0):
return []
itemfilter = or_(*((items_table.c.variatio... |
class WindowRecord(SimpleBuilderApp):
def __init__(self, equipment_service, data_path=None, listSport=None, parent=None, date=None, title=None, distance=None, time=None, upositive=None, unegative=None, bpm=None, calories=None, comment=None, windowTitle=None, equipment=[]):
logging.debug('>>')
self.p... |
def run_examples():
with caldav.DAVClient(url=caldav_url, username=username, password=password, headers=headers) as client:
my_principal = client.principal()
calendars = my_principal.calendars()
print_calendars_demo(calendars)
find_delete_calendar_demo(my_principal, 'Test calendar fr... |
((gdkpixbuf2 is None), 'GdkPixBuf not available')
class GdkPixBufTest(PygletTestCase):
def test_load_image(self):
filename = self.get_test_data_file('images', '8bpp.gif')
with open(filename, 'rb') as f:
loader = gdkpixbuf2.GdkPixBufLoader(filename, f)
pixbuf = loader.get_pixb... |
('/json/package', endpoint='package')
_required('LIST')
def package():
api = flask.current_app.config['PYLOAD_API']
try:
id = int(flask.request.args.get('id'))
data = api.get_package_data(id)
tmp = data['links']
tmp.sort(key=(lambda entry: entry['order']))
data['links'] =... |
def _make_stage(transformation_module, in_channels, bottleneck_channels, out_channels, block_count, num_groups, stride_in_1x1, first_stride, dilation=1):
blocks = []
stride = first_stride
for _ in range(block_count):
blocks.append(transformation_module(in_channels, bottleneck_channels, out_channels,... |
def _test():
import torch
pretrained = False
models = [drnc26, drnc42, drnc58, drnd22, drnd38, drnd54, drnd105]
for model in models:
net = model(pretrained=pretrained)
net.eval()
weight_count = _calc_width(net)
print('m={}, {}'.format(model.__name__, weight_count))
... |
def _generic_gaussian_circuit(qubits: Sequence[cirq.Qid], quadratic_hamiltonian: 'openfermion.QuadraticHamiltonian', occupied_orbitals: Optional[Sequence[int]], initial_state: Union[(int, Sequence[int])]) -> cirq.OP_TREE:
n_qubits = len(qubits)
(circuit_description, start_orbitals) = gaussian_state_preparation_... |
def install_legacy_fan(args):
path_fan = os.path.join(FAKE_DIRECTORY, 'class/hwmon', 'hwmon12')
print('Installing Fan sensor {path}'.format(path=path_fan))
if (not os.path.isdir(path_fan)):
print('The directory {path} is not present. Creating a new one..'.format(path=path_fan))
os.makedirs(p... |
class RHEL5_TestCase(CommandTest):
command = 'key'
def runTest(self):
self.assert_parse('key 012345abcd', 'key 012345abcd\n')
self.assert_parse('key --skip', 'key --skip\n')
self.assert_parse_error('key')
self.assert_parse_error('key --bogus-option')
self.assert_parse_err... |
def extract_macosx_min_system_version(path_to_lib):
with open(path_to_lib, 'rb') as lib_file:
(BaseClass, magic_number) = get_base_class_and_magic_number(lib_file, 0)
if (magic_number not in [FAT_MAGIC, FAT_MAGIC_64, MH_MAGIC, MH_MAGIC_64]):
return
if (magic_number in [FAT_MAGIC,... |
def _run_do_update(app_data, distribution, embed_filename, for_py_version, periodic, search_dirs):
from virtualenv.seed.wheels import acquire
wheel_filename = (None if (embed_filename is None) else Path(embed_filename))
embed_version = (None if (wheel_filename is None) else Wheel(wheel_filename).version_tup... |
class ErrorHandler(object):
def __init__(self, error_queue):
import signal
import threading
self.error_queue = error_queue
self.children_pids = []
self.error_thread = threading.Thread(target=self.error_listener, daemon=True)
self.error_thread.start()
signal.si... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str, default='/afs/crc.nd.edu/user/y/ypeng4/UACANet/configs/UACANet-L.yaml')
parser.add_argument('--resume', action='store_true', default=False)
parser.add_argument('--verbose', action='store_true', default=False)
... |
def create_confirmation_dialog(title, message, uid):
def _confirm():
nonlocal result
i = BrowserView.instances[uid]
ok = i.localization['global.ok']
cancel = i.localization['global.cancel']
result = BrowserView.display_confirmation_dialog(ok, cancel, message)
semaphor... |
def command_shighband(command, args):
def setup(parser):
add_source_options(parser)
add_sensor_options(parser)
add_filter_options(parser)
parser.set_defaults(rel_lowpass_frequency=0.125)
parser.set_defaults(rel_highpass_frequency=0.25)
(parser, opts, args) = cl_parse(comm... |
.parametrize(['ops', 'state', 'final_states', 'probabilities'], [pytest.param(PZ, basis(2, 0), [state0, None], [1, 0], id='PZ_ket'), pytest.param(PZ, basis(2, 0).proj(), [state0.proj(), None], [1, 0], id='PZ_dm'), pytest.param(PZ_ket, basis(2, 0), [state0, None], [1, 0], id='PZket_ket'), pytest.param(PZ_ket, basis(2, 0... |
class SegformerOverlapPatchEmbeddings(nn.Module):
def __init__(self, patch_size, stride, num_channels, hidden_size):
super().__init__()
self.proj = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=stride, padding=(patch_size // 2))
self.layer_norm = nn.LayerNorm(hidden_siz... |
class WrapLinker(Linker):
def __init__(self, linkers: Sequence[PerformLinker], wrapper: Callable) -> None:
self.fgraph: Optional[FunctionGraph] = None
self.linkers = linkers
self.wrapper = wrapper
def __copy__(self) -> 'WrapLinker':
other = self.__class__(linkers=[copy(x) for x i... |
def spatial_svd_example(config: argparse.Namespace):
data_pipeline = ImageNetDataPipeline(config)
model = models.resnet18(pretrained=True)
if config.use_cuda:
model.to(torch.device('cuda'))
model.eval()
accuracy = data_pipeline.evaluate(model, use_cuda=config.use_cuda)
logger.info('Origi... |
(debug=True)
('tab', value=cmdutils.Value.cur_tab)
('count', value=cmdutils.Value.count)
def debug_webaction(tab: apitypes.Tab, action: str, count: int=1) -> None:
for _ in range(count):
try:
tab.action.run_string(action)
except apitypes.WebTabError as e:
raise cmdutils.Comma... |
def get_args():
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent("\n To import bookmarks, you'll need the path to your profile or an\n exported HTML file from your browser's bookmark manager. Redirect\n the output from thi... |
class _Normalization(pystiche.Module):
def __init__(self, mean: Sequence[float], std: Sequence[float]) -> None:
super().__init__()
self.mean = mean
self.std = std
def _channel_stats_to_tensor(image: torch.Tensor, mean: Sequence[float], std: Sequence[float]) -> Tuple[(torch.Tensor, torch.... |
def get_default_log() -> Path:
data_directory = os.path.expandvars('$XDG_DATA_HOME')
if (data_directory == '$XDG_DATA_HOME'):
data_directory = os.path.expanduser('~/.local/share')
qtile_directory = (Path(data_directory) / 'qtile')
if (not qtile_directory.exists()):
qtile_directory.mkdir(... |
def report_energy(bodies=SYSTEM, pairs=PAIRS, e=0.0):
for (((x1, y1, z1), v1, m1), ((x2, y2, z2), v2, m2)) in pairs:
dx = (x1 - x2)
dy = (y1 - y2)
dz = (z1 - z2)
e -= ((m1 * m2) / ((((dx * dx) + (dy * dy)) + (dz * dz)) ** 0.5))
for (r, [vx, vy, vz], m) in bodies:
e += ((m... |
def computer_move(board):
pos = board.random_move()
if (pos == PASS):
return PASS
tree = UCTNode()
tree.unexplored = board.useful_moves()
nboard = Board()
for game in range(GAMES):
node = tree
nboard.reset()
nboard.replay(board.history)
node.play(nboard)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.