code stringlengths 281 23.7M |
|---|
def create_page_xml(imageFilename, height, width):
now = datetime.now()
pcgts = PcGtsType(Metadata=MetadataType(Creator='SBB_QURATOR', Created=now, LastChange=now), Page=PageType(imageWidth=str(width), imageHeight=str(height), imageFilename=imageFilename, readingDirection='left-to-right', textLineOrder='top-to-... |
class IdleInTransactions(QueryStats):
path = '%(datname)s.idle_in_tranactions.%(metric)s'
multi_db = True
base_query = "\n SELECT 'idle_in_transactions',\n max(COALESCE(ROUND(EXTRACT(epoch FROM now()-query_start)),0))\n AS idle_in_transaction\n FROM pg_stat_acti... |
class SplitContainer(Container, QtWidgets.QSplitter):
sigStretchChanged = QtCore.Signal()
def __init__(self, area, orientation):
QtWidgets.QSplitter.__init__(self)
self.setOrientation(orientation)
Container.__init__(self, area)
def _insertItem(self, item, index):
self.insertW... |
class CmdFinish(CmdTradeBase):
key = 'end trade'
aliases = 'finish trade'
locks = 'cmd:all()'
help_category = 'Trading'
def func(self):
caller = self.caller
self.tradehandler.finish(force=True)
caller.msg((self.str_caller % 'You |raborted|n trade. No deal was made.'))
... |
class AlbumId(NamedTuple):
id_value: str
title: str
artist: str
discs: int
tracks: int
last_directory_parts: str
def of_song(cls, s: SongWrapper):
parts = s('~dirname').rsplit(os.path.sep, maxsplit=2)[(- 2):]
return AlbumId(s.album_key[0], (s('albumsort', '') or s('album')), ... |
def main(args=None):
if (args is None):
args = sys.argv[1:]
epilog = 'Talpa is part of the kite InSAR framework.\nMore at DFG Project, University of Kiel\n\n Marius Isken (marius.-potsdam.de)\n Henriette Sudhaus'
desc = 'Crust deformation modeling'
parser = ap.ArgumentParser(prog='talpa', epil... |
.slow
.parametrize('orient', ['v', 'h'])
_figures_equal()
def test_DecisionMatrixPlotter_box(decision_matrix, orient, fig_test, fig_ref):
dm = decision_matrix(seed=42, min_alternatives=3, max_alternatives=3, min_criteria=3, max_criteria=3)
plotter = plot.DecisionMatrixPlotter(dm=dm)
test_ax = fig_test.subpl... |
def filter_empty_instances(instances, by_box=True, by_mask=True, box_threshold=1e-05):
assert (by_box or by_mask)
r = []
if by_box:
r.append(instances.gt_boxes.nonempty(threshold=box_threshold))
if (instances.has('gt_masks') and by_mask):
r.append(instances.gt_masks.nonempty())
if (n... |
class AerospikeCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(AerospikeCollector, self).get_default_config_help()
config_help.update({'req_host': 'Hostname', 'req_port': 'Port', 'statistics': 'Collect statistics', 'latency': 'Collect latency metrics', ... |
def get_groups_for_user(user, local=True, maxage=timedelta(seconds=0), targetID=None, use_volatile=True):
groups_cmd = ops.cmd.getDszCommand('groups', local=local, network=(not local), user=user)
local_string = ('local' if local else 'network')
tag = ('%s_%s_%s' % (USERGROUPS_TAG_BASE, local_string.upper(),... |
class Dog(Creature):
def __init__(self, rand):
super().__init__(rand)
self.attack = [1, 4]
self.love = 2
self.hp_max = 10
self.hp = self.hp_max
self.name = 'Dog'
self.images = ['dog_normal']
def give_hug(self):
super().give_hug()
self.image... |
def merge(seqs: list[list[TypeInfo]]) -> list[TypeInfo]:
seqs = [s.copy() for s in seqs]
result: list[TypeInfo] = []
while True:
seqs = [s for s in seqs if s]
if (not seqs):
return result
for seq in seqs:
head = seq[0]
if (not [s for s in seqs if (... |
class GEN():
def __init__(self, itemNum, userNum, emb_dim, lamda, param=None, initdelta=0.05, learning_rate=0.05):
self.itemNum = itemNum
self.userNum = userNum
self.emb_dim = emb_dim
self.lamda = lamda
self.param = param
self.initdelta = initdelta
self.learni... |
class TransformedDataset(Dataset):
def __init__(self, source, transform, img_index=0):
self.source = source
self.transform = transform
self.img_index = img_index
def __len__(self):
return len(self.source)
def __getitem__(self, index):
out = self.source[index]
... |
class Ball(pyglet.sprite.Sprite):
ball_image = pyglet.resource.image(BALL_IMAGE)
width = ball_image.width
height = ball_image.height
def __init__(self):
x = (random.random() * (window.width - self.width))
y = (random.random() * (window.height - self.height))
super(Ball, self).__i... |
class _FunctionCorrelation(torch.autograd.Function):
def forward(self, first, second):
rbot0 = first.new_zeros([first.size(0), (first.size(2) + 8), (first.size(3) + 8), first.size(1)])
rbot1 = first.new_zeros([first.size(0), (first.size(2) + 8), (first.size(3) + 8), first.size(1)])
self.save... |
def update_config(config_file):
exp_config = None
with open(config_file) as f:
exp_config = edict(yaml.load(f, Loader=yaml.FullLoader))
for (k, v) in exp_config.items():
if (k in config):
if isinstance(v, dict):
_update_dict(config, k, v)
... |
def test_store_blob(initialized_db):
location = database.ImageStorageLocation.select().get()
digest = 'somecooldigest'
blob_storage = model.blob.store_blob_record_and_temp_link(ADMIN_ACCESS_USER, REPO, digest, location, 1024, 0, 5000)
assert (blob_storage.content_checksum == digest)
assert (blob_sto... |
def setup_multi_processes(cfg):
if (platform.system() != 'Windows'):
mp_start_method = cfg.get('mp_start_method', 'fork')
current_method = mp.get_start_method(allow_none=True)
if ((current_method is not None) and (current_method != mp_start_method)):
warnings.warn(f'Multi-process... |
class Migration(migrations.Migration):
dependencies = [('adserver', '0028_ad_network_defaults')]
operations = [migrations.CreateModel(name='PublisherPayout', fields=[('created', django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, verbose_name='created')), ('modified', django_extensions.db.field... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if (args.options is not None):
cfg.merge_from_dict(args.options)
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
if (args.work_dir is not None):
cfg.work_dir = args.work_dir
eli... |
class BayesianTrainer(BaseTrainer):
def __init__(self, model, loss_function, train_data, valid_data, dicts, opt, setup_optimizer=True):
super().__init__(model, loss_function, train_data, valid_data, dicts, opt)
if self.cuda:
torch.cuda.set_device(self.opt.gpus[0])
if (self.op... |
class Portfolio():
def __init__(self, data_handler: DataHandler, initial_cash: float, timer: Timer):
self.initial_cash = initial_cash
self.data_handler = data_handler
self.timer = timer
self.net_liquidation = initial_cash
self.gross_exposure_of_positions = 0
self.curr... |
class TestAutoQuant():
def test_auto_quant_run_inference(self, sess, unlabeled_dataset):
bn_folded_acc = 0.5
with patch_ptq_techniques(bn_folded_acc, None, None) as mocks:
with create_tmp_directory() as results_dir:
auto_quant = AutoQuant(sess, starting_ops, ending_ops, u... |
def test_init_without_routes():
block_number = BlockNumber(1)
routes = []
pseudo_random_generator = random.Random()
init_state_change = ActionInitInitiator(factories.UNIT_TRANSFER_DESCRIPTION, routes)
channel_map = {}
iteration = initiator_manager.state_transition(payment_state=None, state_chang... |
def get_t_mask(img, hsv_ranges=None):
if (hsv_ranges is None):
hsv_ranges = [[0, 255], [130, 216], [150, 230]]
hsv_img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
mask = np.ones(img.shape[:2], dtype=bool)
for c in range(len(hsv_ranges)):
(l, h) = hsv_ranges[c]
mask &= (l <= hsv_img[(.... |
def visualize_changes_after_optimization(old_model: torch.nn.Module, new_model: torch.nn.Module, results_dir: str, selected_layers: List=None) -> List[plotting.Figure]:
file_path = os.path.join(results_dir, 'visualize_changes_after_optimization.html')
plotting.output_file(file_path)
subplots = []
if sel... |
class _SynchronizedBatchNorm(_BatchNorm):
def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True):
super(_SynchronizedBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine)
self._sync_master = SyncMaster(self._data_parallel_master)
self._is_parallel... |
class ReduceScatter_Wait(Function):
def forward(ctx, pg: dist.ProcessGroup, myreq: Request[Tensor], *dummy_tensor: Tensor) -> Tensor:
assert (myreq.req is not None)
myreq.req.wait()
myreq.req = None
output = myreq.tensor
myreq.tensor = None
ctx.myreq = myreq
c... |
class CreateShardingInfoTest(unittest.TestCase):
def setUp(self) -> None:
self.tables = [EmbeddingBagConfig(name='table_0', feature_names=['feature_0'], embedding_dim=4, num_embeddings=4), EmbeddingBagConfig(name='table_1', feature_names=['feature_1'], embedding_dim=4, num_embeddings=4)]
self.constr... |
def test_history_expanded_with_regex_argument(base_app):
run_cmd(base_app, 'alias create sc shortcuts')
run_cmd(base_app, 'help')
run_cmd(base_app, 'help history')
run_cmd(base_app, 'sc')
(out, err) = run_cmd(base_app, 'history -v /sh.*cuts/')
expected = normalize('\n 1 alias create sc short... |
_func('float, int, int: object')
def ml_get_zoo_tree(train_size=0.75, max_depth=5, random_state=245245):
dataset = pd.read_csv(os.path.join(os.path.dirname(__file__), 'data', 'zoo.csv'))
dataset = dataset.drop('animal_name', axis=1)
features = dataset.drop('class', axis=1)
targets = dataset['class']
... |
def compute_mfcc(filename, sr=22000):
try:
(audio, sr) = librosa.load(filename, sr=sr, res_type='kaiser_fast')
except:
(audio, o_sr) = sf.read(filename)
audio = librosa.core.resample(audio, o_sr, sr)
mfcc = librosa.feature.mfcc(y=audio, sr=sr)
mfcc_delta = librosa.feature.delta(m... |
('make-impersonator-property', [values.W_Symbol], simple=False)
def make_imp_prop(sym, env, cont):
from pycket.interpreter import return_multi_vals
name = sym.utf8value
prop = imp.W_ImpPropertyDescriptor(name)
pred = imp.W_ImpPropertyPredicate(prop)
accs = imp.W_ImpPropertyAccessor(prop)
return ... |
.unit()
def test_import_optional():
match = "pytask requires .*notapackage.* pip .* conda .* 'notapackage'"
with pytest.raises(ImportError, match=match) as exc_info:
import_optional_dependency('notapackage')
assert isinstance(exc_info.value.__context__, ImportError)
result = import_optional_depe... |
class ParallelSentencesDataset(Dataset):
def __init__(self, student_model: SentenceTransformer, teacher_model: SentenceTransformer, batch_size: int=8, use_embedding_cache: bool=True):
self.student_model = student_model
self.teacher_model = teacher_model
self.datasets = []
self.datase... |
class CoordStage(object):
def __init__(self, n_embed, down_factor):
self.n_embed = n_embed
self.down_factor = down_factor
def eval(self):
return self
def encode(self, c):
assert ((0.0 <= c.min()) and (c.max() <= 1.0))
(b, ch, h, w) = c.shape
assert (ch == 1)
... |
def _expected_no_editor_error():
expected_exception = 'OSError'
if hasattr(sys, 'pypy_translation_info'):
expected_exception = 'EnvironmentError'
expected_text = normalize("\nEXCEPTION of type '{}' occurred with message: Please use 'set editor' to specify your text editing program of choice.\nTo ena... |
def main():
parser = argparse.ArgumentParser(description='testing neural Datalog through time (NDTT)')
parser.add_argument('-d', '--Domain', required=True, type=str, help='which domain to work on?')
parser.add_argument('-fn', '--FolderName', required=True, type=str, help='base name of the folder to store th... |
class Receiver(threading.Thread):
def run(self):
M = []
L = []
while True:
L.append(len(q))
m = q.pop(True)
if (m == 'stop'):
break
else:
M.append(m)
self.M = M
self.avSize = (float(sum(L)) / len(... |
def wrap_builder(old_builder):
app = make_app('docs_dev_app')
thread_started = threading.Event()
def run_in_thread():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
server_started = asyncio.Event()
async def set_thread_event_when_started():
(await se... |
def _munge_variant_of(variant_of):
if (variant_of is None):
variant_of = ()
elif isinstance(variant_of, VariantField):
variant_of = (variant_of,)
else:
variant_of = tuple(variant_of)
for variant in variant_of:
if (not isinstance(variant, VariantField)):
... |
class Arcsinh(SpecificFunction):
def __init__(self, child):
super().__init__(np.arcsinh, child)
def _from_json(cls, snippet: dict):
instance = super()._from_json(np.arcsinh, snippet)
return instance
def _function_diff(self, children, idx):
return (1 / sqrt(((children[0] ** 2)... |
class ZookeeperCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(ZookeeperCollector, self).get_default_config_help()
config_help.update({'publish': (("Which rows of 'status' you would like to publish." + " Telnet host port' and type stats and hit enter to... |
def get_word_pair_sim_bw_models(year1, year2, model_path, selected_ngrams, all_model_vectors, top_k_acc):
(word_pairs, em1, em2) = get_acceleration_bw_models(year1, year2, model_path, selected_ngrams, all_model_vectors, top_k_acc)
word_pair_sim_df = pd.DataFrame(list(word_pairs.items()), columns=['Word Pair', '... |
class Portal(object):
def __init__(self, application):
sys.path.append('.')
self.services = service.MultiService()
self.services.setServiceParent(application)
self.amp_protocol = None
self.sessions = PORTAL_SESSIONS
self.sessions.portal = self
self.process_id ... |
class MyOp(Op):
def __init__(self, name, dmap=None, x=None):
if (dmap is None):
dmap = {}
self.name = name
self.destroy_map = dmap
self.x = x
def make_node(self, *inputs):
inputs = list(map(is_variable, inputs))
for input in inputs:
if (not... |
class PriceBasedSlippage(Slippage):
def __init__(self, slippage_rate: float, data_provider: DataProvider, max_volume_share_limit: Optional[float]=None):
super().__init__(data_provider, max_volume_share_limit)
self.slippage_rate = slippage_rate
def _get_fill_prices(self, date: datetime, orders: S... |
def split_batchnorm_params(model: nn.Module):
batchnorm_params = []
other_params = []
for module in model.modules():
if (list(module.children()) != []):
for params in module.parameters(recurse=False):
if params.requires_grad:
other_params.append(params... |
def qdb_print(msgtype: QDB_MSG, msg: str) -> None:
def print_error(msg):
return f'{color.RED}[!] {msg}{color.END}'
def print_info(msg):
return f'{color.CYAN}[+] {msg}{color.END}'
color_coated = {QDB_MSG.ERROR: print_error, QDB_MSG.INFO: print_info}.get(msgtype)(msg)
print(color_coated) |
def _simplify_polys(polys, minarea=0.01, tolerance=0.01, filterremote=False):
if isinstance(polys, MultiPolygon):
polys = sorted(polys.geoms, key=attrgetter('area'), reverse=True)
mainpoly = polys[0]
mainlength = np.sqrt((mainpoly.area / (2.0 * np.pi)))
if (mainpoly.area > minarea):
... |
def bfs(initial: Iterable, expand: Callable) -> Iterator:
open_q = deque(list(initial))
visited = set(open_q)
while open_q:
node = open_q.popleft()
(yield node)
for next_node in expand(node):
if (next_node not in visited):
visited.add(next_node)
... |
class Parser(html.parser.HTMLParser):
def __init__(self):
super().__init__()
self._stream = []
def handle_starttag(self, tag, attrs):
attrs = sorted(attrs, key=(lambda x: x[0]))
attrs = '|'.join([((k[0] + ':') + k[1]) for k in attrs])
self._stream.append(('<', tag, attrs)... |
def main(args, init_distributed=False):
utils.import_user_module(args)
assert ((args.max_tokens is not None) or (args.max_sentences is not None)), 'Must specify batch size either with --max-tokens or --max-sentences'
if (torch.cuda.is_available() and (not args.cpu)):
torch.cuda.set_device(args.devic... |
class Output():
def json_encoder(obj, ignore_error=False):
if isinstance(obj, Output):
return obj.embed_data()
elif isinstance(obj, OutputList):
return obj.data
if (not ignore_error):
raise TypeError(('Object of type %s is not JSON serializable' % obj.__c... |
def batcher(params, batch):
batch = [(sent if (sent != []) else ['.']) for sent in batch]
embeddings = []
for sent in batch:
sentvec = []
for word in sent:
if (word in params.word_vec):
sentvec.append(params.word_vec[word])
if (not sentvec):
ve... |
def test_mult_factor_out_qm() -> None:
assert (str(parse('a|b*|').reduce()) == 'a|b*')
assert (str(parse('(a|b*|)').reduce()) == 'a|b*')
assert (str(parse('(a|b*|)c').reduce()) == '(a|b*)c')
assert (str(parse('()').reduce()) == '')
assert (str(parse('([$%\\^]|){1}').reduce()) == '[$%\\^]?') |
class PlayEntityRotation(Packet):
id = 41
to = 1
def __init__(self, entity_id: int, yaw: float, pitch: float, on_ground: bool) -> None:
super().__init__()
self.entity_id = entity_id
self.yaw = yaw
self.pitch = pitch
self.on_ground = on_ground
def encode(self) -> b... |
class FC3_NFS(KickstartCommand):
removedKeywords = KickstartCommand.removedKeywords
removedAttrs = KickstartCommand.removedAttrs
def __init__(self, writePriority=0, *args, **kwargs):
KickstartCommand.__init__(self, writePriority, *args, **kwargs)
self.server = kwargs.get('server', None)
... |
def get_image_paths(image_id_to_image, image_ids):
paths = []
for image_id in image_ids:
image = image_id_to_image[image_id]
(base, filename) = os.path.split(image['url'])
path = os.path.join(os.path.basename(base), filename)
paths.append(path)
return paths |
class NodeGroupManager():
def __init__(self, path: str, gname: str):
self.NODE_GROUP_PREFIX = gname
self.cluster_config = self._read_yaml(path)
self.init_groups = self._cluster_node_groups(self.cluster_config)
self.init_group_res = self._parse_node_resources()
def _cluster_node_g... |
.parametrize('index', [None, 0])
def test_memmap_new(index):
t = torch.tensor([1])
m = MemoryMappedTensor.from_tensor(t)
if (index is not None):
m1 = m[index]
else:
m1 = m
m2 = MemoryMappedTensor.from_tensor(m1)
assert isinstance(m2, MemoryMappedTensor)
assert (m2._filename =... |
class HIDManager(EventDispatcher):
def __init__(self):
self.manager_ref = c_void_p(iokit.IOHIDManagerCreate(None, kIOHIDOptionsTypeNone))
self.schedule_with_run_loop()
self.devices = self._get_devices()
self.matching_callback = self._register_matching_callback()
self.removal_... |
def transforms_imagenet_eval(img_size=224, crop_pct=None, interpolation='bilinear', use_prefetcher=False, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD):
crop_pct = (crop_pct or DEFAULT_CROP_PCT)
if isinstance(img_size, (tuple, list)):
assert (len(img_size) == 2)
if (img_size[(- 1)] == im... |
class JSONPlugin(object):
name = 'json'
api = 2
def __init__(self, json_dumps=json_dumps):
self.json_dumps = json_dumps
def apply(self, callback, route):
dumps = self.json_dumps
if (not dumps):
return callback
def wrapper(*a, **ka):
try:
... |
class Session():
def __init__(self, verbosity, app_data, interpreter, creator, seeder, activators) -> None:
self._verbosity = verbosity
self._app_data = app_data
self._interpreter = interpreter
self._creator = creator
self._seeder = seeder
self._activators = activator... |
class BuildActionUsageTests(CustomAssertions):
def setUpClass(cls):
cls.das = DummyArtifacts()
cls.tempdir = cls.das.tempdir
cls.pm = PluginManager()
def tearDownClass(cls):
cls.das.free()
def test_build_action_usage_python(self):
plugin = 'dummy_plugin'
actio... |
def get_label_length_seq(content):
label_seq = []
length_seq = []
start = 0
for i in range(len(content)):
if (content[i] != content[start]):
label_seq.append(content[start])
length_seq.append((i - start))
start = i
label_seq.append(content[start])
leng... |
def test2():
model = load_model((str(exp_url) + 'models/theultimate.h5'))
test_datagen = ImageDataGenerator(rescale=(1.0 / 255))
test_generator = test_datagen.flow_from_directory(test_data_dir, target_size=(img_height, img_width), batch_size=batch_size, class_mode='binary')
print(model.metrics_names)
... |
def _recall_update_input_check(input: torch.Tensor, target: torch.Tensor, num_classes: Optional[int]) -> None:
if (input.size(0) != target.size(0)):
raise ValueError(f'The `input` and `target` should have the same first dimension, got shapes {input.shape} and {target.shape}.')
if (target.ndim != 1):
... |
class TestSendMediaGroupWithoutRequest():
async def test_send_media_group_throws_error_with_group_caption_and_individual_captions(self, bot, chat_id, media_group, media_group_no_caption_only_caption_entities, media_group_no_caption_only_parse_mode):
for group in (media_group, media_group_no_caption_only_cap... |
class RenameRefactoringTest(unittest.TestCase):
def setUp(self):
super().setUp()
self.project = testutils.sample_project()
def tearDown(self):
testutils.remove_project(self.project)
super().tearDown()
def _local_rename(self, source_code, offset, new_name):
testmod = t... |
def test_update_legacy_tasks(db, settings):
xml_file = ((((Path(settings.BASE_DIR) / 'xml') / 'elements') / 'legacy') / 'views.xml')
root = read_xml_file(xml_file)
version = root.attrib.get('version')
elements = flat_xml_to_elements(root)
elements = convert_elements(elements, version)
elements =... |
def build_transforms(cfg, is_train=True):
res = []
if is_train:
size_train = cfg.INPUT.SIZE_TRAIN
do_augmix = cfg.INPUT.DO_AUGMIX
augmix_prob = cfg.INPUT.AUGMIX_PROB
do_autoaug = cfg.INPUT.DO_AUTOAUG
autoaug_prob = cfg.INPUT.AUTOAUG_PROB
do_flip = cfg.INPUT.DO_FLI... |
.parametrize('x, axis, exc', [(set_test_value(pt.vector(), rng.random(size=(2,)).astype(config.floatX)), None, None), (set_test_value(pt.matrix(), rng.random(size=(2, 3)).astype(config.floatX)), 0, None), (set_test_value(pt.matrix(), rng.random(size=(2, 3)).astype(config.floatX)), 1, None)])
def test_LogSoftmax(x, axis... |
class Migration(migrations.Migration):
dependencies = [('voting', '0012_vote_propagated')]
operations = [migrations.RemoveField(model_name='vote', name='propagated'), migrations.AlterField(model_name='rankrequest', name='conference', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='co... |
def make_env(name, episode_length, action_repeat, seed, observation_type):
(suite, name) = name.split('_', 1)
rendered = (observation_type in ['rgb_image', 'binary_image'])
if any(((env in name) for env in IMAGE_CROP_ENVS)):
size = (240, 320)
crop = (12, 25, 12, 25)
else:
size = ... |
class GraphConv(nn.Module):
def __init__(self, in_feats, out_feats, weight=False, activation=None):
super(GraphConv, self).__init__()
self._in_feats = in_feats
self._out_feats = out_feats
self._norm = 'both'
if weight:
self.weight = nn.Parameter(th.Tensor(in_feats... |
def render_pep440(pieces: Dict[(str, Any)]) -> str:
if pieces['closest-tag']:
rendered = pieces['closest-tag']
if (pieces['distance'] or pieces['dirty']):
rendered += plus_or_dot(pieces)
rendered += ('%d.g%s' % (pieces['distance'], pieces['short']))
if pieces['dir... |
def test_regularization():
X = rnd.randn(10, 2)
y = np.hstack(((- np.ones((5,))), np.ones((5,))))
Z = (rnd.randn(10, 2) + 1)
clf = ImportanceWeightedClassifier(loss_function='lr', l2_regularization=None)
assert isinstance(clf.clf, LogisticRegressionCV)
clf = ImportanceWeightedClassifier(loss_fun... |
def eval_anomaly_detection_coldstart(model, all_train_data, all_train_labels, all_train_timestamps, all_test_data, all_test_labels, all_test_timestamps, delay):
t = time.time()
all_data = {}
all_repr = {}
all_repr_wom = {}
for k in all_train_data:
all_data[k] = np.concatenate([all_train_data... |
class FinallyNonlocalControl(CleanupNonlocalControl):
def __init__(self, outer: NonlocalControl, saved: Value) -> None:
super().__init__(outer)
self.saved = saved
def gen_cleanup(self, builder: IRBuilder, line: int) -> None:
(target, cleanup) = (BasicBlock(), BasicBlock())
builde... |
class Action():
format_string: str = ''
def __init__(self, *values: '_Operand') -> None:
self.values = values
def __eq__(self, other: Any) -> bool:
return ((type(self) is type(other)) and (len(self.values) == len(other.values)) and all((((type(v1) is type(v2)) and v1._equals_to(v2)) for (v1,... |
class DylanConsoleLexer(Lexer):
name = 'Dylan session'
aliases = ['dylan-console', 'dylan-repl']
filenames = ['*.dylan-console']
mimetypes = ['text/x-dylan-console']
url = '
version_added = '1.6'
_example = 'dylan-console/console'
_prompt_re = re.compile('\\?| ')
def get_tokens_unpro... |
class ExportMutatedModule(ContextMenuSingle):
def __init__(self):
self.mainFrame = gui.mainFrame.MainFrame.getInstance()
def display(self, callingWindow, srcContext, mainItem):
if (srcContext != 'fittingModule'):
return False
if (self.mainFrame.getActiveFit() is None):
... |
_against_invalid_ecpoint
def CKD_priv(parent_privkey: bytes, parent_chaincode: bytes, child_index: int) -> Tuple[(bytes, bytes)]:
if (child_index < 0):
raise ValueError('the bip32 index needs to be non-negative')
is_hardened_child = bool((child_index & BIP32_PRIME))
return _CKD_priv(parent_privkey=p... |
class EditorPidWatcher(QObject):
appeared = pyqtSignal()
def __init__(self, directory, parent=None):
super().__init__(parent)
self._pidfile = (directory / 'editor_pid')
self._watcher = QFileSystemWatcher(self)
self._watcher.addPath(str(directory))
self._watcher.directoryC... |
def get_measured_qubits(transpiled_circuits):
qubit_index = None
qubit_mappings = {}
for (idx, qc) in enumerate(transpiled_circuits):
measured_qubits = []
for (inst, qargs, _) in qc.data:
if (inst.name != 'measure'):
continue
measured_qubits.append(qar... |
class Effect4558(BaseEffect):
type = 'passive'
def handler(fit, skill, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('XL Cruise Missiles')), 'thermalDamage', (skill.getModifiedItemAttr('damageMultiplierBonus') * skill.level), **kwargs) |
def getQDarkStyleDarkQPalette():
BG_DARK = QtGui.QColor('#19232D')
BG_NORMAL = QtGui.QColor('#37414F')
BG_LIGHT = QtGui.QColor('#455364')
FG_DARK = QtGui.QColor('#9DA9B5')
FG_NORMAL = QtGui.QColor('#E0E1E3')
FG_LIGHT = QtGui.QColor('#F0F0F0')
SEL_DARK = QtGui.QColor('#1A72BB')
SEL_NORMAL... |
def test_mount_blob_into_repository(registry_model):
repository_ref = registry_model.lookup_repository('devtable', 'simple')
latest_tag = registry_model.get_repo_tag(repository_ref, 'latest')
manifest = registry_model.get_manifest_for_tag(latest_tag)
target_repository_ref = registry_model.lookup_reposit... |
class TestTfModuleReducer(unittest.TestCase):
.tf1
def test_reducing_tf_slim_model(self):
tf.compat.v1.reset_default_graph()
sess = tf.compat.v1.Session()
module_zero_channels_list = []
x = tf.compat.v1.placeholder(tf.float32, [1, 32, 32, 3])
_ = tf_slim_basic_model(x)
... |
def process_examples(examples):
progress = tqdm(range(len(examples['id'])), desc='Processing Samples')
idxs = []
image_paths = []
for index in progress:
image_path = examples['image_path'][index]
idxs.append(examples['id'][index])
image_paths.append(image_path)
return (idxs, ... |
.parametrize('username,password', users)
.parametrize('export_format', export_formats)
def test_export(db, client, username, password, export_format):
client.login(username=username, password=password)
url = ((reverse(urlnames['export']) + export_format) + '/')
response = client.get(url)
assert (respons... |
def parameters():
params = TrackerParams()
params.debug = 0
params.visualization = False
params.use_gpu = True
params.image_sample_size = (18 * 16)
params.search_area_scale = 5
params.sample_memory_size = 50
params.learning_rate = 0.01
params.init_samples_minimum_weight = 0.25
pa... |
class TestAHIHSDFileHandler():
def test_bad_calibration(self):
with pytest.raises(ValueError, match='Invalid calibration mode: BAD_MODE. Choose one of (.*)'):
with _fake_hsd_handler(fh_kwargs={'calib_mode': 'BAD_MODE'}):
pass
.parametrize(('round_actual_position', 'expected_r... |
def scalar_to_float(scalar: Scalar) -> float:
if isinstance(scalar, Tensor):
scalar = scalar.squeeze()
numel = scalar.numel()
if (numel != 1):
raise ValueError(f'Scalar tensor must contain a single item, {numel} given.')
return float(scalar.cpu().detach().numpy().item())
... |
def get_scheduler(optimizer, opt):
if (opt.lr_policy == 'linear'):
def lambda_rule(epoch):
lr_l = (1.0 - (max(0, ((epoch + opt.epoch_count) - opt.n_epochs)) / float((opt.n_epochs_decay + 1))))
return lr_l
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)
... |
class Onset(entity):
def __init__(self, phonemes, lang):
self.feats = {}
self._p_changed = True
self.featpaths = {}
self.lang = lang
if phonemes:
self.children = phonemes
else:
self.children = []
def isBranching(self):
return (len(s... |
class SurvivalGFormula():
def __init__(self, df, idvar, exposure, outcome, time, weights=None):
self.exposure = exposure
self.outcome = outcome
self.t = time
self.id = idvar
self._missing_indicator = '__missing_indicator__'
(self.gf, self._miss_flag, self._continuous_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.