code stringlengths 281 23.7M |
|---|
class FileOutput(Output):
def __init__(self, file=None, pts=None, split=None):
super().__init__(pts=pts)
self.dead = False
self.fileoutput = file
self._firstframe = True
self._before = None
self._connectiondead = None
self._splitsize = split
def fileoutput... |
def test_tag_name(converter: BaseConverter) -> None:
union = Union[(A, B)]
tag_name = 't'
configure_tagged_union(union, converter, tag_name=tag_name)
assert (converter.unstructure(A(1), union) == {tag_name: 'A', 'a': 1})
assert (converter.unstructure(B('1'), union) == {tag_name: 'B', 'a': '1'})
... |
class LineMaterial(Material):
uniform_type = dict(Material.uniform_type, color='4xf4', thickness='f4')
def __init__(self, color=(1, 1, 1, 1), thickness=2.0, color_mode='auto', map=None, map_interpolation='linear', aa=True, **kwargs):
super().__init__(**kwargs)
self.color = color
self.aa ... |
def get_config():
config = get_default_configs()
training = config.training
training.sde = 'vpsde'
training.continuous = False
training.reduce_mean = True
sampling = config.sampling
sampling.method = 'pc'
sampling.predictor = 'ancestral_sampling'
sampling.corrector = 'none'
data ... |
class WashExecutor(ActionExecutor):
def execute(self, script: Script, state: EnvironmentState, info: ExecutionInfo, char_index, modify=True, in_place=False):
current_line = script[0]
info.set_current_line(current_line)
node = state.get_state_node(current_line.object())
if (node is No... |
def load_ref(path):
with open(path) as f:
lines = f.readlines()
(src, tgt, refs) = ([], [], [])
i = 0
while (i < len(lines)):
if lines[i].startswith('S-'):
src.append(lines[i].split('\t')[1].rstrip())
i += 1
elif lines[i].startswith('T-'):
tgt.... |
def _etree_to_vdom(node: etree._Element, transforms: Iterable[_ModelTransform]) -> VdomDict:
if (not isinstance(node, etree._Element)):
msg = f'Expected node to be a etree._Element, not {type(node).__name__}'
raise TypeError(msg)
children = _generate_vdom_children(node, transforms)
el = vdom... |
def load_tinynas_net(backbone_cfg):
import ast
struct_str = ''.join([x.strip() for x in backbone_cfg.net_structure_str])
struct_info = ast.literal_eval(struct_str)
for layer in struct_info:
if ('nbitsA' in layer):
del layer['nbitsA']
if ('nbitsW' in layer):
del la... |
.parametrize('protocol', ['ucx', 'ucxx'])
def test_initialize_ucx_all(protocol):
if (protocol == 'ucx'):
pytest.importorskip('ucp')
elif (protocol == 'ucxx'):
pytest.importorskip('ucxx')
p = mp.Process(target=_test_initialize_ucx_all, args=(protocol,))
p.start()
p.join()
assert (... |
class CalendarWrapper(hwndwrapper.HwndWrapper):
friendlyclassname = 'Calendar'
windowclasses = ['SysMonthCal32']
has_title = False
place_in_calendar = {'background': win32defines.MCSC_BACKGROUND, 'month_background': win32defines.MCSC_MONTHBK, 'text': win32defines.MCSC_TEXT, 'title_background': win32defi... |
def test_line_dict_parser():
data_ret = [json.dumps({'filename': 'sample1.jpg', 'text': 'hello'}), json.dumps({'filename': 'sample2.jpg', 'text': 'world'})]
keys = ['filename', 'text']
with pytest.raises(AssertionError):
parser = LineJsonParser('filename')
with pytest.raises(AssertionError):
... |
def plot_results(model, p, facs, clis=None):
(fig, ax) = plt.subplots(figsize=(6, 6))
(markersize, markersize_factor) = (4, 4)
ax.set_title(model.name, fontsize=15)
cli_points = {}
fac_sites = {}
for (i, dv) in enumerate(model.fac_vars):
if dv.varValue:
dv = facs.loc[(i, 'dv'... |
class ProjectIssueNoteAwardEmojiManager(NoUpdateMixin, RESTManager):
_path = '/projects/{project_id}/issues/{issue_iid}/notes/{note_id}/award_emoji'
_obj_cls = ProjectIssueNoteAwardEmoji
_from_parent_attrs = {'project_id': 'project_id', 'issue_iid': 'issue_iid', 'note_id': 'id'}
_create_attrs = Required... |
def bind(key, *, info):
model = completionmodel.CompletionModel(column_widths=(20, 60, 20))
data = _bind_current_default(key, info)
if data:
model.add_category(listcategory.ListCategory('Current/Default', data))
cmdlist = util.get_cmd_completions(info, include_hidden=True, include_aliases=True)
... |
def admin_required(func):
(func)
def wrapper(*args, **kwargs):
print(current_user)
if (not current_user.is_authenticated):
return abort(401)
if (not current_user.is_administrator):
return abort(403)
return func(*args, **kwargs)
return wrapper |
def match_pattern(string: str, i: int) -> MatchResult[Pattern]:
concs = []
(c, i) = match_conc(string, i)
concs.append(c)
while True:
try:
i = static(string, i, '|')
(c, i) = match_conc(string, i)
concs.append(c)
except NoMatch:
return (Pat... |
class RBDBContentHandler(ContentHandler):
def __init__(self, library):
ContentHandler.__init__(self)
self._library = library
self._current = None
self._tag = None
self._changed_songs = []
def characters(self, content):
if ((self._current is not None) and (self._ta... |
def parse_gltf_file(file, filename, batch):
if (file is None):
file = pyglet.resource.file(filename, 'r')
elif (file.mode != 'r'):
file.close()
file = pyglet.resource.file(filename, 'r')
try:
data = json.load(file)
except json.JSONDecodeError:
raise ModelDecodeExc... |
def pipeline(task: str=None, model: Optional=None, config: Optional[Union[(str, PretrainedConfig)]]=None, tokenizer: Optional[Union[(str, PreTrainedTokenizer, PreTrainedTokenizerFast)]]=None, feature_extractor: Optional[Union[(str, PreTrainedFeatureExtractor)]]=None, image_processor: Optional[Union[(str, BaseImageProce... |
class Config(object):
NAME = None
GPU_COUNT = 1
IMAGES_PER_GPU = 2
STEPS_PER_EPOCH = 1000
VALIDATION_STEPS = 50
BACKBONE = 'resnet101'
COMPUTE_BACKBONE_SHAPE = None
BACKBONE_STRIDES = [4, 8, 16, 32, 64]
FPN_CLASSIF_FC_LAYERS_SIZE = 1024
TOP_DOWN_PYRAMID_SIZE = 256
NUM_CLASSES... |
def getdirinfo(pathtocheck):
cmd = ops.cmd.getDszCommand('dir', path=('"%s"' % os.path.dirname(pathtocheck)), mask=('"%s"' % os.path.basename(pathtocheck)))
obj = cmd.execute()
if cmd.success:
try:
return (obj.diritem[0].fileitem[0].filetimes.accessed.time, obj.diritem[0].fileitem[0].fil... |
class AbstractNlg(object):
def __init__(self, domain, complexity):
self.domain = domain
self.complexity = complexity
def generate_sent(self, actions, **kwargs):
raise NotImplementedError('Generate sent is required for NLG')
def sample(self, examples):
return np.random.choice(... |
class Bounds():
south_west: Point
north_east: Point
def contains_point(self, point: Point) -> bool:
in_lon = (self.south_west.lon <= point.lon <= self.north_east.lon)
in_lat = (self.south_west.lat <= point.lat <= self.north_east.lat)
return (in_lon and in_lat)
def from_dict(cls, ... |
class Effect8243(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Mining')), 'duration', ship.getModifiedItemAttr('exhumersBonusOreMiningDuration'), skill='Exhumers', **kwargs) |
class PreActBottleneck(nn.Module):
def __init__(self, cin, cout=None, cmid=None, stride=1):
super().__init__()
cout = (cout or cin)
cmid = (cmid or (cout // 4))
self.gn1 = nn.GroupNorm(32, cin)
self.conv1 = conv1x1(cin, cmid)
self.gn2 = nn.GroupNorm(32, cmid)
... |
def args_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=50, help='rounds of training')
parser.add_argument('--frac', type=float, default=1.0, help='the fraction of clients: C')
parser.add_argument('--local_ep', type=int, default=5, help='the number of loca... |
_fixtures(WebFixture, SqlAlchemyFixture, ValidationScenarios.with_javascript)
def test_input_validation_cues_javascript_interaction(web_fixture, sql_alchemy_fixture, javascript_validation_scenario):
fixture = javascript_validation_scenario
web_fixture.reahl_server.set_app(web_fixture.new_wsgi_app(child_factory=... |
class Config():
(TRAIN, DEV, TEST) = range(3)
def __init__(self, dataset_size, shuffle_before_select, dataset_file, simplified, horizon, reward_function_type, use_localhost, stop_action_reward, screen_size):
self.dataset_size = dataset_size
self.shuffle_before_select = shuffle_before_select
... |
class MetricResult(object):
def __init__(self, result: float, meta: Dict[(str, Any)]={}):
self._result = result
self._meta = meta
def result(self):
return self._result
def meta(self):
return self._meta
def __repr__(self):
if self._meta:
meta_str = ','.... |
def handle_format(self, data, rectype=XL_FORMAT):
DEBUG = 0
bv = self.biff_version
if (rectype == XL_FORMAT2):
bv = min(bv, 30)
if (not self.encoding):
self.derive_encoding()
strpos = 2
if (bv >= 50):
fmtkey = unpack('<H', data[0:2])[0]
else:
fmtkey = self.act... |
def __print_size_warning(ow, oh, w, h):
if (not hasattr(__print_size_warning, 'has_printed')):
print(('The image size needs to be a multiple of 4. The loaded image size was (%d, %d), so it was adjusted to (%d, %d). This adjustment will be done to all images whose sizes are not multiples of 4' % (ow, oh, w, ... |
class VoxelResBackBone8x(nn.Module):
def __init__(self, model_cfg, input_channels, grid_size, **kwargs):
super().__init__()
self.model_cfg = model_cfg
norm_fn = partial(nn.BatchNorm1d, eps=0.001, momentum=0.01)
self.sparse_shape = (grid_size[::(- 1)] + [1, 0, 0])
self.conv_in... |
def fractional(value: NumberOrString) -> str:
try:
number = float(value)
if (not math.isfinite(number)):
return _format_not_finite(number)
except (TypeError, ValueError):
return str(value)
whole_number = int(number)
frac = Fraction((number - whole_number)).limit_denom... |
def default_profile(monkeypatch):
profile = QtWebEngineCore.QWebEngineProfile()
profile.setter = webenginesettings.ProfileSetter(profile)
monkeypatch.setattr(profile, 'isOffTheRecord', (lambda : False))
monkeypatch.setattr(webenginesettings, 'default_profile', profile)
return profile |
.parametrize('namespace_name, repo_name, tag_names, expected', [('devtable', 'simple', ['latest'], 'latest'), ('devtable', 'simple', ['unknown', 'latest'], 'latest'), ('devtable', 'simple', ['unknown'], None)])
def test_find_matching_tag(namespace_name, repo_name, tag_names, expected, initialized_db):
repo = get_re... |
class F9_Firewall(FC3_Firewall):
removedKeywords = FC3_Firewall.removedKeywords
removedAttrs = FC3_Firewall.removedAttrs
def _getParser(self):
op = FC3_Firewall._getParser(self)
op.remove_argument('--high', version=F9)
op.remove_argument('--medium', version=F9)
return op |
class MeanIoU():
def __init__(self, class_indices, ignore_label: int, label_str, name):
self.class_indices = class_indices
self.num_classes = len(class_indices)
self.ignore_label = ignore_label
self.label_str = label_str
self.name = name
def reset(self) -> None:
s... |
class KnownValues(unittest.TestCase):
def test_vxc_col(self):
ni = numint2c.NumInt2C()
ni.collinear = 'c'
dm = mf.get_init_guess(mol, 'minao')
(n, e, v) = ni.nr_vxc(mol, mf.grids, 'B88,', dm)
self.assertAlmostEqual(n, 9., 5)
self.assertAlmostEqual(e, (- 8.), 6)
... |
class WaterBigBoxPBE0(unittest.TestCase):
def setUpClass(cls):
cell = gto.Cell()
cell.verbose = 4
cell.output = '/dev/null'
cell.atom = '\n O 0.00000 0.00000 0.11779\n H 0.00000 0.75545 -0.47116\n H 0.00000 ... |
def send_mime_email(mime_msg: MIMEMultipart, mail_from: str, mail_to: str, smtp_host: str, smtp_port: int, smtp_user: str, smtp_password: str, use_ssl: bool=True, use_tls: bool=False):
if use_tls:
server = smtplib.SMTP(smtp_host, smtp_port)
server.starttls()
elif use_ssl:
server = smtpli... |
def get_initial_pos(nparticles, scale, dtype):
nrows = int((nparticles ** 0.5))
ncols = int(np.ceil((nparticles / nrows)))
x0 = torch.linspace(0, scale, ncols, dtype=dtype)
y0 = torch.linspace(0, scale, nrows, dtype=dtype)
(y, x) = torch.meshgrid(y0, x0)
y = y.reshape((- 1))[:nparticles]
x =... |
class LatentEncoder(nn.Module):
def __init__(self, num_hidden, num_latent, input_dim, num_self_attention_l):
super(LatentEncoder, self).__init__()
self.input_projection = Linear(input_dim, num_hidden)
self.self_attentions = nn.ModuleList([Attention(num_hidden) for _ in range(num_self_attenti... |
def zaleplon_with_other_formula() -> GoalDirectedBenchmark:
zaleplon = TanimotoScoringFunction('O=C(C)N(CC)C1=CC=CC(C2=CC=NC3=C(C=NN23)C#N)=C1', fp_type='ECFP4')
formula = IsomerScoringFunction('C19H17N3O2')
specification = uniform_specification(1, 10, 100)
return GoalDirectedBenchmark(name='Zaleplon MP... |
def test_select_components():
from reana.reana_dev.utils import select_components
from reana.config import REPO_LIST_ALL, REPO_LIST_CLIENT, REPO_LIST_CLUSTER
for (input_value, output_expected) in ((['reana-job-controller'], ['reana-job-controller']), (['reana-job-controller', 'reana'], ['reana-job-controlle... |
def _parse_static_node_value(node):
import ast
from collections import OrderedDict
if isinstance(node, ast.Num):
value = node.n
elif isinstance(node, ast.Str):
value = node.s
elif isinstance(node, ast.List):
value = list(map(_parse_static_node_value, node.elts))
elif isin... |
def test_render_registry_fails():
r = gfx.renderers._base.RenderFunctionRegistry()
r.register(Object1, Material1, foo1)
with raises(TypeError):
r.register(4, Material1, foo1)
with raises(TypeError):
r.register(str, Material1, foo1)
with raises(TypeError):
r.register(Object1, ... |
_REGISTRY.register()
class CIFARSTL(DatasetBase):
dataset_dir = 'cifar_stl'
domains = ['cifar', 'stl']
def __init__(self, cfg):
root = osp.abspath(osp.expanduser(cfg.DATASET.ROOT))
self.dataset_dir = osp.join(root, self.dataset_dir)
self.check_input_domains(cfg.DATASET.SOURCE_DOMAINS... |
def _partition_key(number_of_shards=None):
key = None
if (number_of_shards is not None):
shard_number = random.randrange(0, number_of_shards)
key = hashlib.sha1((KINESIS_PARTITION_KEY_PREFIX + str(shard_number)).encode('utf-8')).hexdigest()
else:
key = hashlib.sha1((KINESIS_PARTITION... |
def init_sensors():
global SENSORS
SENSORS = {}
LOGGER.debug('Reading sensors configuration...')
if os.path.isfile(os.path.join(CONFIG_PATH, SENSORS_CONFIG_FILE)):
SENSORS = read_yaml_file(os.path.join(CONFIG_PATH, SENSORS_CONFIG_FILE))
sensors_config_file_found = True
else:
... |
class Z3Visitor():
def __init__(self):
visitor = TransformVisitor()
visitor.register_transform(nodes.FunctionDef, self.set_function_def_z3_constraints)
self.visitor = visitor
def set_function_def_z3_constraints(self, node: nodes.FunctionDef):
types = {}
annotations = node... |
class TestGetKeyboardMapping(EndianTest):
def setUp(self):
self.req_args_0 = {'count': 207, 'first_keycode': 169}
self.req_bin_0 = b'e\x00\x00\x02\xa9\xcf\x00\x00'
self.reply_args_0 = {'keysyms': [[, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ], [, , ],... |
def _load_pre_prompt_dataset(data_path, augment_times):
with open(data_path, 'rb') as f:
data = pickle.load(f)
data = data['observations']
data_dict: Dict[(str, List[Any])] = {'input': [], 'output': [], 'route_descriptors': [], 'vehicle_descriptors': [], 'pedestrian_descriptors': [], 'ego_vehicle_de... |
def _init_placeholder(env):
Da = env.action_space.flat_dim
Do = env.observation_space.flat_dim
num_actors = env.num_envs
iteration_ph = get_placeholder(name='iteration', dtype=tf.int64, shape=None)
observations_ph = get_placeholder(name='observations', dtype=tf.float32, shape=(None, Do))
next_ob... |
def _dfs(graph, room_corners, current, end, path, path_len, all_paths, all_lens, trial_num):
if (current == end):
all_paths.append(path)
all_lens.append(float(path_len))
return
if (path_len > (6 + (trial_num * 5))):
return
elif check_corner_on_path(current, path, room_corners... |
class QlArchX86(QlArchIntel):
type = QL_ARCH.X86
bits = 32
_property
def uc(self) -> Uc:
return Uc(UC_ARCH_X86, UC_MODE_32)
_property
def regs(self) -> QlRegisterManager:
regs_map = dict(**x86_const.reg_map_8, **x86_const.reg_map_16, **x86_const.reg_map_32, **x86_const.reg_map_cr... |
def save_checkpoint(ckpt, is_best, save_dir, model_name=''):
if (not osp.exists(save_dir)):
os.makedirs(save_dir)
filename = osp.join(save_dir, (model_name + '.pt'))
torch.save(ckpt, filename)
if is_best:
best_filename = osp.join(save_dir, 'best_ckpt.pt')
shutil.copyfile(filename... |
def test_repr_pyobjectsdef_pyfunction_without_associated_resource(project):
code = 'def func(arg): pass'
mod = libutils.get_string_module(project, code)
obj = mod.get_attribute('func').pyobject
assert isinstance(obj, pyobjectsdef.PyFunction)
assert repr(obj).startswith('<rope.base.pyobjectsdef.PyFun... |
def test_multiple_column_references_from_previous_defined_cte():
sql = 'WITH\ncte1 AS (SELECT a, b FROM tab1),\ncte2 AS (SELECT a, max(b) AS b_max, count(b) AS b_cnt FROM cte1 GROUP BY a)\nINSERT INTO tab2\nSELECT cte1.a, cte2.b_max, cte2.b_cnt FROM cte1 JOIN cte2\nWHERE cte1.a = cte2.a'
assert_column_lineage_e... |
def _download_url(url):
req = urllib.request.Request(url, headers={'User-Agent': 'Quay (External Library Downloader)'})
for index in range(0, MAX_RETRY_COUNT):
try:
response = urllib.request.urlopen(req)
return response.read()
except urllib.error.URLError:
log... |
class AnsiStatusFormatter(object):
def __init__(self):
self._colourMap = ansi.ColourMap()
def __call__(self, status, options):
colour = self._colourMap.colourFor(status['user']['screen_name'])
return ('%s%s% 16s%s %s ' % (get_time_string(status, options), ansiFormatter.cmdColour(colour),... |
class AlexNetV1(_AlexNet):
output_stride = 8
def __init__(self):
super(AlexNetV1, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(3, 96, 11, 2), _BatchNorm2d(96), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2))
self.conv2 = nn.Sequential(nn.Conv2d(96, 256, 5, 1, groups=2), _BatchNorm2d(... |
class FrontierState(BaseState):
computation_class: Type[ComputationAPI] = FrontierComputation
transaction_context_class: Type[TransactionContextAPI] = FrontierTransactionContext
account_db_class: Type[AccountDatabaseAPI] = AccountDB
transaction_executor_class: Type[TransactionExecutorAPI] = FrontierTran... |
class memoized(object):
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args, **kwargs):
key = cPickle.dumps((args, kwargs))
try:
return self.cache[key]
except KeyError:
value = self.func(*args, **kwargs)
... |
def main(args):
pdf = get_input(args)
toc = pdf.get_toc(max_depth=args.max_depth)
for item in toc:
state = ('*' if (item.n_kids == 0) else ('-' if item.is_closed else '+'))
target = ('?' if (item.page_index is None) else (item.page_index + 1))
print(((' ' * item.level) + ('[%s] %s... |
def test_pycodestyle(workspace):
doc = Document(DOC_URI, workspace, DOC)
diags = pycodestyle_lint.pylsp_lint(workspace, doc)
assert all(((d['source'] == 'pycodestyle') for d in diags))
msg = 'W191 indentation contains tabs'
mod_import = [d for d in diags if (d['message'] == msg)][0]
assert (mod_... |
def infer_type_arguments(type_vars: Sequence[TypeVarLikeType], template: Type, actual: Type, is_supertype: bool=False, skip_unsatisfied: bool=False) -> list[(Type | None)]:
constraints = infer_constraints(template, actual, (SUPERTYPE_OF if is_supertype else SUBTYPE_OF))
return solve_constraints(type_vars, const... |
.parametrize('blocking_enabled, method', [(True, 'auto'), (True, 'adblock'), (False, 'auto'), (False, 'adblock'), (False, 'both'), (False, 'hosts')])
def test_disabled_blocking_update(config_stub, tmp_path, caplog, host_blocker_factory, blocking_enabled, method):
if (blocking_enabled and (method == 'auto')):
... |
def load_optimizer_state(optimizer: torch.optim.Optimizer, flat_metadata: Dict, flat_tensors: Sequence[torch.Tensor]):
flat_optimizer_state = []
for elem in flat_metadata:
if ((elem.get('type') == 'tensor') and isinstance(elem.get('index'), int)):
flat_optimizer_state.append(flat_tensors[ele... |
def simxGetCollectionHandle(clientID, collectionName, operationMode):
handle = ct.c_int()
if ((sys.version_info[0] == 3) and (type(collectionName) is str)):
collectionName = collectionName.encode('utf-8')
return (c_GetCollectionHandle(clientID, collectionName, ct.byref(handle), operationMode), handl... |
_module()
class MobileNetV2(nn.Module):
arch_settings = [[1, 16, 1], [6, 24, 2], [6, 32, 3], [6, 64, 4], [6, 96, 3], [6, 160, 3], [6, 320, 1]]
def __init__(self, widen_factor=1.0, strides=(1, 2, 2, 2, 1, 2, 1), dilations=(1, 1, 1, 1, 1, 1, 1), out_indices=(1, 2, 4, 6), frozen_stages=(- 1), conv_cfg=None, norm_c... |
class nnUNetTrainer_5epochs(nnUNetTrainer):
def __init__(self, plans: dict, configuration: str, fold: int, dataset_json: dict, unpack_dataset: bool=True, device: torch.device=torch.device('cuda')):
super().__init__(plans, configuration, fold, dataset_json, unpack_dataset, device)
self.num_epochs = 5 |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if (args.cfg_options is not None):
cfg.merge_from_dict(args.cfg_options)
setup_multi_processes(cfg)
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
if (args.work_dir is not None):
... |
class Planner(object):
def __init__(self, city_name):
self._city_track = city_track.CityTrack(city_name)
self._commands = []
def get_next_command(self, source, source_ori, target, target_ori):
track_source = self._city_track.project_node(source)
track_target = self._city_track.pr... |
def test_simple_for_with_surrounding_blocks() -> None:
src = '\n n = 10\n for i in range(n):\n print(i - 1)\n else:\n print(i + 1)\n print(i)\n '
cfg = build_cfg(src)
expected_blocks = [['n = 10', 'range(n)'], ['i'], ['print(i - 1)'], ['print(i + 1)'], ['print(i)'], []]
asse... |
class cvae_model_parser(fvae_model_parser):
def __init__(self, model_config_path):
super(cvae_model_parser, self).__init__(model_config_path)
self.config['conv_enc'] = parse_raw_conv_str(self.parser.get('model', 'conv_enc', ''))
def write_config(config, f):
super(cvae_model_parser, cvae_... |
def items(validator: Validator, items: Mapping[(Hashable, Any)], instance: Any, schema: Mapping[(Hashable, Any)]) -> Iterator[ValidationError]:
if (not validator.is_type(instance, 'array')):
return
for (index, item) in enumerate(instance):
(yield from validator.descend(item, items, path=index)) |
def CounterList():
(counters, set_counters) = use_state([0, 0, 0])
def make_increment_click_handler(index):
def handle_click(event):
new_value = (counters[index] + 1)
set_counters(((counters[:index] + [new_value]) + counters[(index + 1):]))
return handle_click
return ... |
def test_get_wavenumber_range(*args, **kwargs):
assert (get_wavenumber_range((1 * u.um), (10 * u.um), medium='vacuum', return_input_wunit=True) == (1000, 10000, 'nm_vac'))
assert (get_wavenumber_range(wavenum_min=10, wavenum_max=20, wunit=Default('cm-1'), return_input_wunit=True) == (10, 20, 'cm-1'))
assert... |
class _VIIRSCoefficients(_Coefficients):
LUTS = [np.array([0., 0.0015933, 0, 1.78644e-05, 0., 0., 0., 0., 0., 0., 0, 0, 0, 0, 0, 0]), np.array([0.812659, 0.832931, 1.0, 0.867785, 0.806816, 0.944958, 0.78812, 0.791204, 0.900564, 0.942907, 0, 0, 0, 0, 0, 0]), np.array([0.0433461, 0.0, 0.0178299, 0.0853012, 0, 0, 0, 0... |
class InfoCriteria(Scorer):
def __init__(self, crit='ebic', gamma='default', zero_tol=1e-06):
pass
def name(self):
return self.crit
def __call__(self, estimator, X, y, sample_weight=None, offsets=None):
if (sample_weight is not None):
raise NotImplementedError('TODO: add'... |
def pytest_addoption(parser):
parser.addoption('--non-interactive', action='store_true', help='[Interactive tests only] Do not use interactive prompts. Skip tests that cannot validate or run without.')
parser.addoption('--sanity', action='store_true', help='[Interactive tests only] Do not use interactive prompt... |
def test_iterative_find_nets():
class Top(ComponentLevel3):
def construct(s):
s.w = Wire(SomeMsg)
s.x = Wire(SomeMsg)
s.y = Wire(SomeMsg)
s.z = Wire(SomeMsg)
connect(s.w, s.x)
connect(s.x.a, s.y.a)
connect(s.y, s.z)
... |
def simplify_ops(ops):
ret = ops
if (ret.get('Modify') and ret.get('Insert')):
ins = ret['Insert']
mod = ret['Modify']
for i in range(len(mod)):
idx = (mod[i]['pos'] + len(mod[i]['label']))
for j in range((len(ins) - 1), (- 1), (- 1)):
if ((ins[j][... |
def get_expired_tag(repository_id, tag_name):
try:
return Tag.select().where((Tag.name == tag_name), (Tag.repository == repository_id)).where((~ (Tag.lifetime_end_ms >> None))).where((Tag.lifetime_end_ms <= get_epoch_timestamp_ms())).get()
except Tag.DoesNotExist:
return None |
def task_lists():
task_ptr_type = task_type.get_type().pointer()
init_task = gdb.parse_and_eval('init_task').address
t = g = init_task
while True:
while True:
(yield t)
t = utils.container_of(t['thread_group']['next'], task_ptr_type, 'thread_group')
if (t == g... |
def build_source(components, howcall):
components = [c.strip() for c in components]
components = [make_autocall(c, howcall) for c in components]
indent = ' '
lines = ''.join([f'''{indent}{SYMBOL} = {c}
''' for c in components])
howsig = howcall_to_howsig[howcall]
source = textwrap.dedent(... |
def check_valid(pos):
hex = pos.hex
tiles = pos.tiles
tot = 0
for i in range(8):
if (tiles[i] > 0):
tot += tiles[i]
else:
tiles[i] = 0
if (tot != hex.count):
raise Exception(('Invalid input. Expected %d tiles, got %d.' % (hex.count, tot))) |
class SupervisedGraphSage(nn.Module):
def __init__(self, num_classes, enc):
super(SupervisedGraphSage, self).__init__()
self.enc = enc
self.xent = nn.CrossEntropyLoss()
self.weight = nn.Parameter(torch.FloatTensor(num_classes, enc.embed_dim))
init.xavier_uniform(self.weight)
... |
class CT_LatentStyles(BaseOxmlElement):
lsdException = ZeroOrMore('w:lsdException', successors=())
count = OptionalAttribute('w:count', ST_DecimalNumber)
defLockedState = OptionalAttribute('w:defLockedState', ST_OnOff)
defQFormat = OptionalAttribute('w:defQFormat', ST_OnOff)
defSemiHidden = Optional... |
def main(args: argparse.Namespace):
text_renderer = PyGameTextRenderer.from_pretrained(args.renderer_name_or_path, use_auth_token=args.auth_token)
data = {'pixel_values': [], 'num_patches': []}
dataset_stats = {'total_uploaded_size': 0, 'total_dataset_nbytes': 0, 'total_num_shards': 0, 'total_num_examples':... |
class WarnTypoAccess(dict):
def __getitem__(self, key):
if (key == 'specialty'):
raise RuntimeError("You may be using the wrong spelling for 'speciality'; The correct key name is 'speciality', not 'specialty'.")
return super().__getitem__(key)
def get(self, key, default=None):
... |
def hook_cmp(se: SymbolicExecutor, pstate: ProcessState, addr: int):
zf = pstate.cpu.zf
sym_zf = pstate.read_symbolic_register(pstate.registers.zf)
(status, model) = pstate.solve((sym_zf.getAst() != zf))
if (status == SolverStatus.SAT):
new_seed = se.mk_new_seed_from_model(model)
se.enqu... |
.end_to_end()
.parametrize('file_or_folder', ['folder_a', 'folder_a/task_a.py', 'folder_b', 'folder_b/task_b.py'])
def test_passing_paths_via_configuration_file(tmp_path, file_or_folder):
config = f'''
[tool.pytask.ini_options]
paths = "{file_or_folder}"
'''
tmp_path.joinpath('pyproject.toml').write... |
class ArrayPredicate(SingleInputMixin, Filter):
params = ('op', 'opargs')
window_length = 0
_types(term=Term, opargs=tuple)
def __new__(cls, term, op, opargs):
hash(opargs)
return super(ArrayPredicate, cls).__new__(ArrayPredicate, op=op, opargs=opargs, inputs=(term,), mask=term.mask)
... |
(help='Send alerts based on the results of a Safety scan.')
('--check-report', help='JSON output of Safety Check to work with.', type=click.File('r'), default=sys.stdin)
('--policy-file', type=SafetyPolicyFile(), default='.safety-policy.yml', help='Define the policy file to be used')
('--key', envvar='SAFETY_API_KEY', ... |
class HighResolutionNet(nn.Module):
def __init__(self, cfg, in_chans=3, num_classes=1000, global_pool='avg', drop_rate=0.0, head='classification'):
super(HighResolutionNet, self).__init__()
self.num_classes = num_classes
self.drop_rate = drop_rate
stem_width = cfg['STEM_WIDTH']
... |
class RawTCPClient(Client):
def __init__(self, host, prog, vers, port, open_timeout=5000):
Client.__init__(self, host, prog, vers, port)
open_timeout = (open_timeout if (open_timeout is not None) else 5000)
self.connect((0.001 * open_timeout))
self.timeout = 4.0
def make_call(sel... |
def check_lockstring(accessing_obj, lockstring, no_superuser_bypass=False, default=False, access_type=None):
global _LOCK_HANDLER
if (not _LOCK_HANDLER):
_LOCK_HANDLER = LockHandler(_ObjDummy())
return _LOCK_HANDLER.check_lockstring(accessing_obj, lockstring, no_superuser_bypass=no_superuser_bypass,... |
.unit()
def test_captureresult() -> None:
cr = CaptureResult('out', 'err')
assert (len(cr) == 2)
assert (cr.out == 'out')
assert (cr.err == 'err')
(out, err) = cr
assert (out == 'out')
assert (err == 'err')
assert (cr[0] == 'out')
assert (cr[1] == 'err')
assert (cr == cr)
ass... |
class DataCollatorCTCWithPadding():
processor: AutoProcessor
padding: Union[(bool, str)] = 'longest'
max_length: Optional[int] = None
pad_to_multiple_of: Optional[int] = None
pad_to_multiple_of_labels: Optional[int] = None
def __call__(self, features: List[Dict[(str, Union[(List[int], torch.Tens... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.