code stringlengths 281 23.7M |
|---|
def load():
vgg = VGG16(weights=None, input_shape=(224, 224, 3))
x = vgg.layers[(- 2)].output
predictions_class = Dense(4, activation='softmax', name='predictions_class')(x)
prediction = [predictions_class]
model = Model(inputs=vgg.input, outputs=prediction)
sgd = SGD(lr=1e-05, momentum=0.9)
... |
def run(dataset_dir):
if (not tf.gfile.Exists(dataset_dir)):
tf.gfile.MakeDirs(dataset_dir)
training_filename = _get_output_filename(dataset_dir, 'train')
testing_filename = _get_output_filename(dataset_dir, 'test')
if (tf.gfile.Exists(training_filename) and tf.gfile.Exists(testing_filename)):
... |
class FakeSubscriptionApi(object):
def __init__(self):
self.subscription_extended = False
self.subscription_created = False
def lookup_subscription(self, customer_id, sku_id):
return None
def create_entitlement(self, customer_id, sku_id):
self.subscription_created = True
... |
class Migration(migrations.Migration):
dependencies = [('projects', '0042_allow_site_null')]
operations = [migrations.AlterField(model_name='project', name='catalog', field=models.ForeignKey(help_text='The catalog which will be used for this project.', null=True, on_delete=django.db.models.deletion.SET_NULL, re... |
(st.builds(Download, timestamp=st.shared(st.dates(), key='extract-item-data').map((lambda i: arrow.Arrow.fromdate(i)))), st.shared(st.dates(), key='extract-item-data').map((lambda i: f'{i.year:04}{i.month:02}{i.day:02}')))
def test_extract_item_data(download, expected):
assert (extract_item_date(download) == expect... |
class CornerPool(nn.Module):
pool_functions = {'bottom': BottomPoolFunction, 'left': LeftPoolFunction, 'right': RightPoolFunction, 'top': TopPoolFunction}
cummax_dim_flip = {'bottom': (2, False), 'left': (3, True), 'right': (3, False), 'top': (2, True)}
def __init__(self, mode):
super(CornerPool, se... |
class EigenQuaternionPrinter():
def __init__(self, val):
type = val.type
if (type.code == gdb.TYPE_CODE_REF):
type = type.target()
self.type = type.unqualified().strip_typedefs()
self.innerType = self.type.template_argument(0)
self.val = val
self.data = se... |
def test_one_hot():
y = np.hstack(((np.ones((10,)) * 0), (np.ones((10,)) * 1), (np.ones((10,)) * 2)))
(Y, labels) = one_hot(y)
assert (len(np.setdiff1d(np.unique(Y), [0, 1])) == 0)
assert np.all((labels == np.unique(y)))
assert (Y.shape[0] == y.shape[0])
assert (Y.shape[1] == len(labels)) |
def init_lmhead_dense_buffer():
args = get_args()
batch_pp = (args.batch_size // args.summa_dim)
seq_length = args.seq_length
hidden_pp = (args.hidden_size // args.summa_dim)
global _LMHEAD_DENSE_BUFFER
assert (_LMHEAD_DENSE_BUFFER is None), '_LMHEAD_DENSE_BUFFER is already initialized'
spac... |
class FxDialog(Factory.Popup):
def __init__(self, app, plugins, config, callback):
self.app = app
self.config = config
self.callback = callback
self.fx = self.app.fx
if (self.fx.get_history_config(allow_none=True) is None):
self.fx.set_history_config(True)
... |
class Adafactor(Optimizer):
def __init__(self, params, lr=None, eps=(1e-30, 0.001), clip_threshold=1.0, decay_rate=(- 0.8), beta1=None, weight_decay=0.0, scale_parameter=True, relative_step=True, warmup_init=False):
require_version('torch>=1.5.0')
if ((lr is not None) and relative_step):
... |
def remove_spectral_norm(module):
name = 'weight'
for (k, hook) in module._forward_pre_hooks.items():
if (isinstance(hook, SpectralNorm) and (hook.name == name)):
hook.remove(module)
del module._forward_pre_hooks[k]
return module
raise ValueError("spectral_norm of... |
class QuantizableBasicConv2d(inception_module.BasicConv2d):
def __init__(self, *args, **kwargs):
super(QuantizableBasicConv2d, self).__init__(*args, **kwargs)
self.relu = nn.ReLU()
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.relu(x)
return x
... |
class InlineInputLocation():
def __init__(self, latitude, longitude, live_period=None):
self.latitude = latitude
self.longitude = longitude
self.live_period = live_period
def _serialize(self):
args = {'latitude': self.latitude, 'longitude': self.longitude}
if (self.live_p... |
def write_color_old(text, attr=None):
res = []
chunks = terminal_escape.split(text)
n = 0
if (attr is None):
attr = 15
for chunk in chunks:
m = escape_parts.match(chunk)
if m:
for part in m.group(1).split(u';'):
if (part == u'0'):
... |
class MBConv(nn.Module):
def __init__(self, cnf: MBConvConfig, norm_layer: Callable[(..., nn.Module)], se_layer: Callable[(..., nn.Module)]=SqueezeExcitation) -> None:
super().__init__()
if (not (1 <= cnf.stride <= 2)):
raise ValueError('illegal stride value')
self.use_res_connec... |
class Properties():
DEFAULTS: ClassVar['Properties'] = None
TARGET_TYPE: ClassVar[Type] = None
def kwargs(self):
return {key: value for (key, value) in self.__dict__.items() if (value is not EMPTY)}
def extract(self, subset_type: Type) -> 'Properties':
field_names = [field.name for field... |
class Aggregate(Function):
def forward(ctx, A, X, C):
ctx.save_for_backward(A, X, C)
return (X.unsqueeze(2).expand(X.size(0), X.size(1), C.size(0), C.size(1)) - C.unsqueeze(0).unsqueeze(0)).mul_(A.unsqueeze(3)).sum(1)
def backward(ctx, GE):
(A, X, C) = ctx.saved_variables
gradA =... |
_rewriter([Blockwise])
def local_useless_unbatched_blockwise(fgraph, node):
op = node.op
inputs = node.inputs
batch_ndims = node.op.batch_ndim(node)
if all((all(inp.type.broadcastable[:batch_ndims]) for inp in inputs)):
if batch_ndims:
axis = tuple(range(batch_ndims))
inp... |
def intersectionAndUnion(output, target, K, ignore_index=255):
assert (output.ndim in [1, 2, 3])
assert (output.shape == target.shape)
output = output.reshape(output.size).copy()
target = target.reshape(target.size)
output[np.where((target == ignore_index))[0]] = ignore_index
intersection = outp... |
def fit_transform(x_text, words_dict, max_sen_len, max_doc_len):
(x, sen_len, doc_len) = ([], [], [])
for (index, doc) in enumerate(x_text):
t_sen_len = ([0] * max_doc_len)
t_x = np.zeros((max_doc_len, max_sen_len), dtype=int)
sentences = doc.split('<sssss>')
i = 0
for se... |
class TwoRoundDeterministicRewardEnv(gym.Env):
def __init__(self):
self.action_space = spaces.Discrete(2)
self.observation_space = spaces.Discrete(3)
self._reset()
def _step(self, action):
rewards = [[0, 3], [1, 2]]
assert self.action_space.contains(action)
if (se... |
class MultiRC(Task):
VERSION = 1
DATASET_PATH = 'super_glue'
DATASET_NAME = 'multirc'
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._training_docs is ... |
class Layer():
def __init__(self, module, name, weight_shape, output_shape):
self.module = module
self.name = str(name)
self.weight_shape = weight_shape
self.output_shape = output_shape
self.picked_for_compression = False
self.type_specific_params = None
self.... |
def _gen_hardcorenas(pretrained, variant, arch_def, **kwargs):
num_features = 1280
se_layer = partial(SqueezeExcite, gate_layer='hard_sigmoid', force_act_layer=nn.ReLU, rd_round_fn=round_channels)
model_kwargs = dict(block_args=decode_arch_def(arch_def), num_features=num_features, stem_size=32, norm_layer=p... |
class JointTestOptions(BoxToMaskOptions):
def initialize(self):
BoxToMaskOptions.initialize(self)
self.parser.add_argument('--ntest', type=int, default=float('inf'))
self.parser.add_arugment('--results_dir', type=str, default='results/')
self.parser.add_argument('--aspect_ratio', typ... |
class NonchalantHttpxRequest(HTTPXRequest):
async def _request_wrapper(self, method: str, url: str, request_data: Optional[RequestData]=None, read_timeout: ODVInput[float]=DEFAULT_NONE, connect_timeout: ODVInput[float]=DEFAULT_NONE, write_timeout: ODVInput[float]=DEFAULT_NONE, pool_timeout: ODVInput[float]=DEFAULT_... |
def to_string(decorated_class):
def __str__(self):
attributes = [attr for attr in dir(self) if ((not attr.startswith('_')) and (not (hasattr(self.__dict__[attr], '__call__') if (attr in self.__dict__) else hasattr(decorated_class.__dict__[attr], '__call__'))))]
output_format = [(f'{attr}={self.__dic... |
def test_postcmd(capsys):
app = PluggedApp()
app.onecmd_plus_hooks('say hello')
(out, err) = capsys.readouterr()
assert (out == 'hello\n')
assert (not err)
assert (app.called_postcmd == 1)
app.reset_counters()
app.register_postcmd_hook(app.postcmd_hook)
app.onecmd_plus_hooks('say hel... |
def define_D(input_nc, ndf, which_model_netD, n_layers_D=3, norm='batch', use_sigmoid=False, init_type='normal', gpu_ids=[]):
netD = None
use_gpu = (len(gpu_ids) > 0)
norm_layer = get_norm_layer(norm_type=norm)
if use_gpu:
assert torch.cuda.is_available()
if (which_model_netD == 'basic'):
... |
def _create_pr_per_tolerance_graph(pr_data_frame: DataFrame, methods: List[str]) -> Figure:
tolerances = _extract_tolerances(pr_data_frame, methods)
active_tolerance = tolerances[0]
active_pr_data_frame = pr_data_frame[(pr_data_frame[SpottingEvaluation.TOLERANCE] == active_tolerance)]
fig = px.line(acti... |
def _get_heuristic_col_headers(adjusted_table, row_index, col_index):
adjusted_cell = adjusted_table[row_index][col_index]
adjusted_col_start = adjusted_cell['adjusted_col_start']
adjusted_col_end = adjusted_cell['adjusted_col_end']
col_headers = []
for r in range(0, row_index):
row = adjust... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-k', '--keyword', help='VM search parameter')
parser.add_argument('-p1', '--powerOn', help='power on', action='store_true')
parser.add_argument('-p0', '--powerOff', help='power off', action='store_true')
parser.add_argument('hypervi... |
def measure_time(net, input, n_times):
net.eval()
warm_up = 20
sum_time = 0
for i in range((warm_up + n_times)):
torch.cuda.synchronize()
t0 = time.perf_counter()
out = net(input)
torch.cuda.synchronize()
t1 = time.perf_counter()
if (i >= warm_up):
... |
def test_gitlab_attribute_get():
o = types.GitlabAttribute('whatever')
assert (o.get() == 'whatever')
o.set_from_cli('whatever2')
assert (o.get() == 'whatever2')
assert (o.get_for_api(key='spam') == ('spam', 'whatever2'))
o = types.GitlabAttribute()
assert (o._value is None) |
def test_yield_logs_for_export(first_model, second_model, combined_model, initialized_db):
now = datetime.now()
with freeze_time(now):
first_model.log_action('push_repo', namespace_name='devtable', repository_name='simple', ip='1.2.3.4')
first_model.log_action('push_repo', namespace_name='devtab... |
class LazyI18nString():
def __init__(self, data: Optional[Union[(str, Dict[(str, str)])]]):
self.data = data
if (isinstance(self.data, str) and (self.data is not None)):
try:
j = json.loads(self.data)
except ValueError:
pass
else:
... |
class MyInnerGraphOp(Op, HasInnerGraph):
__props__ = ()
def __init__(self, inner_inputs, inner_outputs):
input_replacements = [(v, NominalVariable(n, v.type)) for (n, v) in enumerate(inner_inputs) if (not isinstance(v, Constant))]
outputs = clone_replace(inner_outputs, replace=input_replacements... |
class HvcsBase():
DEFAULT_ENV_TOKEN_NAME = 'HVCS_TOKEN'
def __init__(self, remote_url: str, hvcs_domain: (str | None)=None, hvcs_api_domain: (str | None)=None, token: (str | None)=None) -> None:
self.hvcs_domain = hvcs_domain
self.hvcs_api_domain = hvcs_api_domain
self.token = token
... |
def save_json_yaml(encoding_file_path: str, encodings_dict: dict):
encoding_file_path_json = encoding_file_path
encoding_file_path_yaml = (encoding_file_path + '.yaml')
with open(encoding_file_path_json, 'w') as encoding_fp_json:
json.dump(encodings_dict, encoding_fp_json, sort_keys=True, indent=4)
... |
def test_list_project_deploy_tokens(gitlab_cli, deploy_token):
cmd = ['-v', 'project-deploy-token', 'list', '--project-id', deploy_token.project_id]
ret = gitlab_cli(cmd)
assert ret.success
assert (deploy_token.name in ret.stdout)
assert (str(deploy_token.id) in ret.stdout)
assert (deploy_token.... |
class _PrivateActionFactory():
def parse_privateaction(element):
if element.findall('LongitudinalAction/SpeedAction/SpeedActionTarget/AbsoluteTargetSpeed'):
return AbsoluteSpeedAction.parse(element)
elif element.findall('LongitudinalAction/SpeedAction/SpeedActionTarget/RelativeTargetSpee... |
class DataPrep(object):
def __init__(self, raw_df: pd.DataFrame, categorical: list, log: list, mixed: dict, integer: list, type: dict, test_ratio: float):
self.categorical_columns = categorical
self.log_columns = log
self.mixed_columns = mixed
self.integer_columns = integer
s... |
class Block(Action, Mutation):
def mutate(_root, info, sender, subject):
if sender.blocked.filter(pk=subject.pk).exists():
sender.blocked.remove(subject)
return Block(feedback=_('removed blockages'))
sender.following.remove(subject)
subject.following.remove(sender)
... |
def _expand_manifest_paths(paths: List[str], filesystem: Optional[Union[(S3FileSystem, s3fs.S3FileSystem)]], content_type_provider: Callable[([str], ContentType)]) -> Tuple[(Dict[(ContentType, List[str])], CachedFileMetadataProvider)]:
assert (len(paths) == 1), f'Expected 1 manifest path, found {len(paths)}.'
p... |
def GaussianNoising(tensor, sigma, mean=0.0, noise_size=None, min=(- 1.0), max=1.0):
if (noise_size is None):
size = tensor.size()
else:
size = noise_size
noise = torch.FloatTensor(np.random.normal(loc=mean, scale=sigma, size=size))
return torch.clamp((noise + tensor), min=min, max=max) |
def test_add_constraint_with_optional(app: PoetryTestApplication, repo: TestRepository, tester: CommandTester) -> None:
repo.add_package(get_package('cachy', '0.2.0'))
tester.execute('cachy=0.2.0 --optional')
expected = '\nUpdating dependencies\nResolving dependencies...\n\nNo dependencies to install or upd... |
def attr_hook(ctx: FunctionContext) -> Type:
default = get_proper_type(ctx.default_return_type)
assert isinstance(default, Instance)
if (default.type.fullname == 'mod.Attr'):
attr_base = default
else:
attr_base = None
for base in default.type.bases:
if (base.type.fullname == ... |
def pblock_061(content):
stage_number = int(get1(content, b'03'))
fir = sxml.FIR(name=get1(content, b'04', optional=True), input_units=sxml.Units(name=punit(get1(content, b'06'))), output_units=sxml.Units(name=punit(get1(content, b'07'))), symmetry=psymmetry(get1(content, b'05')), numerator_coefficient_list=lis... |
def listen(ip, data_dir):
date_pattern = re.compile(b'\\d\\d\\d\\d-\\d\\d-\\d\\d\\d\\d:\\d\\d:\\d\\d')
data_dir = pathlib.Path(data_dir)
live_dir = data_dir.joinpath('live')
patients_dir = data_dir.joinpath('patients')
patient_icom_data = patients.PatientIcomData(patients_dir)
def archive_by_pat... |
def test_yamlrepresenter_dumps(temp_file_creator):
payload = {'key1': 'value1', 'key2': 'value2', 'key3': [0, 1, 2]}
representer = filesystem.YamlRepresenter()
file_path = temp_file_creator()
with open(file_path, representer.write_mode) as file:
representer.dump(file, payload)
assert (file_p... |
def test_validate_well_structured_too_many():
(q0, q1) = cirq.LineQubit.range(2)
circuit = cirq.Circuit([cirq.Moment([cirq.PhasedXPowGate(phase_exponent=0).on(q0)]), cirq.Moment([cirq.PhasedXPowGate(phase_exponent=0.5).on(q0)]), cirq.Moment([cg.SYC(q0, q1)]), cirq.measure(q0, q1, key='z')])
with pytest.rais... |
class TestRFC4514():
def test_invalid(self, subtests):
for value in ['C=US,CN=Joe , Smith,DC=example', ',C=US,CN=Joe , Smith,DC=example', 'C=US,UNKNOWN=Joe , Smith,DC=example', 'C=US,CN,DC=example', 'C=US,FOOBAR=example']:
with subtests.test():
with pytest.raises(ValueError):
... |
class SesquialteralHourglass(nn.Module):
def __init__(self, down1_seq, skip1_seq, up_seq, skip2_seq, down2_seq, merge_type='cat'):
super(SesquialteralHourglass, self).__init__()
assert (len(down1_seq) == len(up_seq))
assert (len(down1_seq) == len(down2_seq))
assert (len(skip1_seq) ==... |
def readPFM(file):
file = open(file, 'rb')
color = None
width = None
height = None
scale = None
endian = None
header = file.readline().rstrip()
if (header == 'PF'):
color = True
elif (header == 'Pf'):
color = False
else:
raise Exception('Not a PFM file.')
... |
def _non_fully_commuting_terms(hamiltonian: QubitOperator) -> List[QubitOperator]:
terms = list([QubitOperator(key) for key in hamiltonian.terms.keys()])
T = []
for i in range(len(terms)):
if any(((not _commutes(terms[i], terms[j])) for j in range(len(terms)))):
T.append(terms[i])
re... |
class Export(Plugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.project = None
self.snapshot = None
def render(self):
raise NotImplementedError
def submit(self):
raise NotImplementedError
def get_set(self, path, set_prefix=''):
... |
def compare(start, end):
start = tuple((int(n) for n in start))
end = tuple((int(n) for n in end))
if (start == end):
return True
now = time.localtime()[3:5]
if ((start < now < end) or (start < now > end < start)):
return True
elif ((start > end) and ((now > start) or (now < end)... |
.parametrize('rollback_enabled, expected_delete_calls, expected_retarget_tag_calls', [(True, ['deleted', 'zzerror', 'updated', 'created'], ['updated']), (False, ['deleted', 'zzerror'], [])])
_existing_mirrors
('util.repomirror.skopeomirror.SkopeoMirror.run_skopeo')
('workers.repomirrorworker.retarget_tag')
('workers.re... |
def add_new_game_command(sub_parsers):
parser: ArgumentParser = sub_parsers.add_parser('add-new-game', help='Loads the preset files and saves then again with the latest version')
parser.add_argument('--enum-name', help='The name of the RandovaniaGame enum, used in code.', required=True)
parser.add_argument(... |
_subclass('low_rank_gaussian')
class LRGaussian(Inference):
def __init__(self, base, base_args, base_kwargs, var_clamp=1e-06):
super(LRGaussian, self).__init__()
self.var_clamp = var_clamp
self.dist = None
def fit(self, mean, variance, cov_factor):
variance = torch.clamp(variance... |
def test_incorrect_reshape_motion_model():
with open(CONFIG_FILE, 'r') as config_file:
config = json.load(config_file)['TrackerConfig']
m = config['MotionModel']['measurements']
s = config['MotionModel']['states']
with pytest.raises(ValueError):
config['MotionModel']['measurements'] = (m... |
class ResNet18(chainer.Chain):
def __init__(self):
super(ResNet18, self).__init__(conv1_relu=ConvolutionBlock(3, 32), res2a_relu=ResidualBlock(32, 32), res2b_relu=ResidualBlock(32, 32), res3a_relu=ResidualBlockB(32, 64), res3b_relu=ResidualBlock(64, 64), res4a_relu=ResidualBlockB(64, 128), res4b_relu=Residu... |
class HaskellLexer(RegexLexer):
name = 'Haskell'
url = '
aliases = ['haskell', 'hs']
filenames = ['*.hs']
mimetypes = ['text/x-haskell']
version_added = '0.8'
reserved = ('case', 'class', 'data', 'default', 'deriving', 'do', 'else', 'family', 'if', 'in', 'infix[lr]?', 'instance', 'let', 'new... |
def agestring(delta):
retval = ''
if (delta.days > 0):
retval += ('%d days, ' % delta.days)
total_seconds = ((delta.microseconds + ((delta.seconds + ((delta.days * 24) * 3600)) * (10 ** 6))) / (10 ** 6))
if (total_seconds > 3600):
retval += ('%02d:' % (delta.seconds / 3600))
if (tota... |
class SegmentDataset(object):
def __init__(self, seq_d, seg_len=20, seg_shift=8, rand_seg=False):
self.seq_d = seq_d
self.seg_len = seg_len
self.seg_shift = seg_shift
self.rand_seg = rand_seg
self.seqlist = self.seq_d.seqlist
self.feats = self.seq_d.feats
self... |
class CategoricalRV(RandomVariable):
name = 'categorical'
ndim_supp = 0
ndims_params = [1]
dtype = 'int64'
_print_name = ('Categorical', '\\operatorname{Categorical}')
def __call__(self, p, size=None, **kwargs):
return super().__call__(p, size=size, **kwargs)
def rng_fn(cls, rng, p, ... |
class ChildWindowSpecificationFromWrapperTests(unittest.TestCase):
def setUp(self):
Timings.defaults()
self.app = Application(backend='win32').start(_notepad_exe())
self.ctrlspec = self.app.window(found_index=0).find().by(class_name='Edit')
def tearDown(self):
self.app.kill()
... |
def get_pad_articulation_state(art, max_dof):
(base_pos, base_quat, base_vel, base_ang_vel, qpos, qvel) = get_articulation_state(art)
k = len(qpos)
pad_obj_internal_state = np.zeros((2 * max_dof))
pad_obj_internal_state[:k] = qpos
pad_obj_internal_state[max_dof:(max_dof + k)] = qvel
return np.co... |
class BiEncoder(nn.Module):
def __init__(self, bi_layer, num_layers):
super().__init__()
self.layers = _get_clones(bi_layer, num_layers)
self.num_layers = num_layers
def forward(self, vis_feats, pos_feats, padding_mask, text_feats, text_padding_mask, end_points={}, detected_feats=None, d... |
class MultiDirectionBaseEnv(Serializable):
def __init__(self, velocity_reward_weight=1.0, survive_reward=0, ctrl_cost_coeff=0, contact_cost_coeff=0, velocity_deviation_cost_coeff=0, *args, **kwargs):
self._velocity_reward_weight = velocity_reward_weight
self._survive_reward = survive_reward
... |
class TestRequestMixin(object):
def mock_request(self, GET=None, POST=None):
r = HttpRequest()
r.path = MOCK_PATH
r.method = ('POST' if (POST is not None) else 'GET')
r.GET = (GET or QueryDict(''))
r.POST = (POST or QueryDict(''))
r._messages = CookieStorage(r)
... |
def test_photo():
photo_small = 'AgACAgIAAx0CAAGgr9AAAgmZX7b7IPLRl8NcV3EJkzHwI1gwT-oAAq2nMRuBpLlJPJY-URZfhTkgfeqKEAADAQADAgADbQADAZ8BAAEeBA'
photo_small_unique = 'AQADIH3qihAAAwGfAQAB'
photo_medium = 'AgACAgIAAx0CAAGgr9AAAgmZX7b7IPLRl8NcV3EJkzHwI1gwT-oAAq2nMRuBpLlJPJY-URZfhTkgfeqKEAADAQADAgADeAADAp8BAAEeBA'... |
def DescriptorChecksum(desc: str) -> str:
c = 1
cls = 0
clscount = 0
for ch in desc:
try:
pos = _INPUT_CHARSET_INV[ch]
except KeyError:
return ''
c = PolyMod(c, (pos & 31))
cls = ((cls * 3) + (pos >> 5))
clscount += 1
if (clscount =... |
def main():
project_root = Path(__file__).resolve().parent.parent
coverage_summary = (project_root / 'coverage-summary.json')
coverage_data = json.loads(coverage_summary.read_text(encoding='utf-8'))
total_data = coverage_data.pop('total')
lines = ['\n', 'Package | Statements\n', '--- | ---\n']
f... |
class TestErrorsWarnings():
def setup_method(self) -> None:
pol1 = Polygon([(0, 0), (1, 0), (1, 1)])
pol2 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
pol3 = Polygon([(2, 0), (3, 0), (3, 1), (2, 1)])
polygon_dict = {'geometry': [pol1, pol2, pol3]}
point = Point(10, 10)
... |
class Trainer(object):
def __init__(self, params=Params(), out_dir='', verbose=False):
if verbose:
print('Trainer inited with:\n{}'.format(str(params.__dict__)))
self.p = params
self.log_dir = os.path.join(out_dir, 'logs')
os.makedirs(self.log_dir, exist_ok=True)
... |
def rm_handler(args):
try:
log.info('Queuing rm of {} on {}', args.target_path, ('all hosts' if (not args.host) else ', '.join(sorted(args.host))))
patch_hosts(args.target_path, patch_mode=0, hosts=(args.host if args.host else None))
except Exception as e:
sys.exit(('Error: ' + str(e))) |
class ObjectBlock():
name = None
FBs = None
inputs = None
outputs = None
def __init__(self, name):
self.name = name
self.FBs = {}
self.inputs = {}
self.outputs = {}
def add_io(self, io):
if issubclass(type(io), Input):
self.inputs[io.name] = io... |
def parse_args():
parser = argparse.ArgumentParser(description='Train keypoints network')
parser.add_argument('--cfg', help='experiment configure file name', required=True, type=str)
parser.add_argument('opts', help='Modify config options using the command-line', default=None, nargs=argparse.REMAINDER)
... |
class VCSDependency(Dependency):
def __init__(self, name: str, vcs: str, source: str, branch: (str | None)=None, tag: (str | None)=None, rev: (str | None)=None, resolved_rev: (str | None)=None, directory: (str | None)=None, groups: (Iterable[str] | None)=None, optional: bool=False, develop: bool=False, extras: (Ite... |
def create_tree_items_for_requirement(tree: QtWidgets.QTreeWidget, root: (QtWidgets.QTreeWidget | QtWidgets.QTreeWidgetItem), requirement: Requirement) -> QtWidgets.QTreeWidgetItem:
parents: list[(QtWidgets.QTreeWidget | QtWidgets.QTreeWidgetItem)] = [root]
result = None
for (depth, text) in pretty_print.pr... |
class CrocLexer(RegexLexer):
name = 'Croc'
url = '
filenames = ['*.croc']
aliases = ['croc']
mimetypes = ['text/x-crocsrc']
version_added = ''
tokens = {'root': [('\\n', Whitespace), ('\\s+', Whitespace), ('(//.*?)(\\n)', bygroups(Comment.Single, Whitespace)), ('/\\*', Comment.Multiline, 'ne... |
def convert_ecp_to_nwchem(symb, ecp):
symb = _std_symbol(symb)
res = [('%-2s nelec %d' % (symb, ecp[0]))]
for ecp_block in ecp[1]:
l = ecp_block[0]
if (l == (- 1)):
res.append(('%-2s ul' % symb))
else:
res.append(('%-2s %s' % (symb, SPDF[l].lower())))
... |
def _generate_supported_model_classes(model_name: Type[PretrainedConfig], supported_tasks: Optional[Union[(str, List[str])]]=None) -> List[Type[PreTrainedModel]]:
model_config_class = CONFIG_MAPPING[model_name]
task_mapping = {'default': MODEL_MAPPING, 'pretraining': MODEL_FOR_PRETRAINING_MAPPING, 'next-sentenc... |
def pin_memory_fn(data, device=None):
if hasattr(data, 'pin_memory'):
return data.pin_memory(device)
elif isinstance(data, (str, bytes)):
return data
elif isinstance(data, collections.abc.Mapping):
pinned_data = {k: pin_memory_fn(sample, device) for (k, sample) in data.items()}
... |
def parse_genia() -> None:
output_dir_path = 'data/genia/'
os.makedirs(output_dir_path, mode=493, exist_ok=True)
output_file_list = ['genia.train', 'genia.dev', 'genia.test']
dataset_size_list = [15022, 1669, 1855]
do_lower_case = ('-cased' not in config.bert_model)
with open(CORPUS_FILE_PATH, '... |
class TimingSuite(TestSuite):
def save_test_time(self, test_name, duration):
file_prefix = getattr(settings, 'TESTS_REPORT_TMP_FILES_PREFIX', '_tests_report_')
file_name = '{}{}.txt'.format(file_prefix, os.getpid())
with open(file_name, 'a+') as f:
f.write('{name},{duration:.6f}\... |
class RCElement(pybamm.BaseSubModel):
def __init__(self, param, element_number, options=None):
super().__init__(param)
self.element_number = element_number
self.model_options = options
def get_fundamental_variables(self):
vrc = pybamm.Variable(f'Element-{self.element_number} over... |
class MockRole(CustomMockMixin, unittest.mock.Mock, ColourMixin, HashableMixin):
spec_set = role_instance
def __init__(self, **kwargs) -> None:
default_kwargs = {'id': next(self.discord_id), 'name': 'role', 'position': 1, 'colour': discord.Colour(), 'permissions': discord.Permissions()}
super().... |
.parametrize('blacklist, expected', [(['ab*'], expected_text(('a', 'yellow', 'a', 'message-info cmd-aa'))), (['*'], '')])
def test_blacklist(keyhint, config_stub, blacklist, expected):
config_stub.val.keyhint.blacklist = blacklist
bindings = {'normal': {'aa': 'message-info cmd-aa', 'ab': 'message-info cmd-ab', ... |
class LatentGridCRF(GridCRF, LatentGraphCRF):
def __init__(self, n_labels=None, n_features=None, n_states_per_label=2, inference_method=None, neighborhood=4):
LatentGraphCRF.__init__(self, n_labels, n_features, n_states_per_label, inference_method=inference_method)
GridCRF.__init__(self, n_states=se... |
.slow
.parametrize('alg', algos_disc)
def test_discrete_identity(alg):
kwargs = learn_kwargs[alg]
kwargs.update(common_kwargs)
learn_fn = (lambda e: get_learn_function(alg)(env=e, **kwargs))
env_fn = (lambda : DiscreteIdentityEnv(10, episode_len=100))
simple_test(env_fn, learn_fn, 0.9) |
def test_serializer_create_text(db, settings):
class MockedProject():
file_size = 1
class MockedView():
action = 'create'
project = MockedProject()
settings.PROJECT_FILE_QUOTA = '0'
validator = ValueQuotaValidator()
serializer = ValueSerializer()
serializer.context['view'... |
def visible(widget, width=None, height=None):
own_window = False
toplevel = widget.get_toplevel()
if (not isinstance(toplevel, Gtk.Window)):
window = Gtk.Window(type=Gtk.WindowType.POPUP)
window.add(widget)
own_window = True
else:
window = toplevel
if ((width is not N... |
def map(y_true, y_pred, rel_threshold=0):
s = 0.0
y_true = _to_list(np.squeeze(y_true).tolist())
y_pred = _to_list(np.squeeze(y_pred).tolist())
c = zip(y_true, y_pred)
random.shuffle(c)
c = sorted(c, key=(lambda x: x[1]), reverse=True)
ipos = 0
for (j, (g, p)) in enumerate(c):
if... |
def test_extract_link_hrefs(app, client):
crawler = Crawler(client=client, initial_paths=['/'], rules=(PERMISSIVE_HYPERLINKS_ONLY_RULE_SET + REQUEST_EXTERNAL_RESOURCE_LINKS_RULE_SET))
crawler.crawl()
link_nodes = crawler.graph.get_nodes_by_source('link')
assert (len(link_nodes) == 1)
assert (link_no... |
class TestFermionicTransformation(QiskitChemistryTestCase):
def setUp(self):
super().setUp()
try:
driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g')
except QiskitChemistryError:
self.skipTest('PYSCF driver ... |
('beeref.view.BeeGraphicsView.fitInView')
('beeref.view.BeeGraphicsView.centerOn')
def test_fit_rect_toggle_when_previous(center_mock, fit_mock, view):
item = MagicMock()
view.previous_transform = {'toggle_item': item, 'transform': QtGui.QTransform.fromScale(2, 2), 'center': QtCore.QPointF(30, 40)}
view.set... |
('pypyr.config.config.default_encoding', new='utf-16')
def test_json_pass_with_encoding(fs):
in_path = './tests/testfiles/test.json'
fs.create_file(in_path, contents='{\n "key1": "value1",\n "key2": "value2",\n "key3": "value3"\n}\n', encoding='utf-16')
context = pypyr.parser.jsonfile.get_parsed_co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.