code stringlengths 281 23.7M |
|---|
class HydrogenIntegrationTest(unittest.TestCase):
def setUp(self):
geometry = [('H', (0.0, 0.0, 0.0)), ('H', (0.0, 0.0, 0.7414))]
basis = 'sto-3g'
multiplicity = 1
filename = os.path.join(DATA_DIRECTORY, 'H2_sto-3g_singlet_0.7414')
self.molecule = MolecularData(geometry, basi... |
def getElementRotation(obj, reverse=False):
axis = None
face = getElementShape(obj, Part.Face)
if (not face):
edge = getElementShape(obj, Part.Edge)
if edge:
return getEdgeRotation(edge, reverse)
return FreeCAD.Rotation()
else:
if (face.Orientation == 'Reverse... |
class StubOutForTestingTest(unittest.TestCase):
def setUp(self):
super(StubOutForTestingTest, self).setUp()
self.stubber = mox3_stubout.StubOutForTesting()
def test_stubout_method_with_set(self):
non_existing_path = 'non_existing_path'
self.assertFalse(mox3_stubout_example.check_... |
class DescribeRGBColor():
def it_is_natively_constructed_using_three_ints_0_to_255(self):
RGBColor(18, 52, 86)
with pytest.raises(ValueError, match='RGBColor\\(\\) takes three integer valu'):
RGBColor('12', '34', '56')
with pytest.raises(ValueError, match='\\(\\) takes three inte... |
class SimilarValueTool(BaseTool):
spark: Union[(SparkSession, ConnectSparkSession)] = Field(exclude=True)
name = 'similar_value'
description = '\n This tool takes a string keyword and searches for the most similar value from a vector store with all\n possible values from the desired column.\n Input... |
def _freeze_except_cascade_rpn_cls_reg(model):
for v in model.parameters():
v.requires_grad = False
for child in model.module.roi_heads.box_predictor.children():
for v in child.cls_score.parameters():
v.requires_grad = True
for v in child.bbox_pred.parameters():
v... |
class LogWheelDestroy(Event):
def from_dict(self):
super().from_dict()
self.attack_id = self._data.get('attackId')
self.attacker = objects.Character(self._data.get('attacker', {}))
self.vehicle = objects.Vehicle(self._data.get('vehicle', {}))
self.damage_type_category = self.... |
def normalize_text(s):
def remove_articles(text):
return re.sub('\\b(a|an|the)\\b', ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return ''.join((ch for ch in text if (ch not in exclude)))
def ... |
def get_real_arch(arch, stages=[2, 3, 3]):
arch = list(arch)
result = ''
for stage in stages:
id_num = 0
for idx in range(stage):
op = arch.pop(0)
if (idx == 0):
result += op
continue
if (op != '0'):
result +... |
class File(BaseType):
def __init__(self, *, required: bool=True, none_ok: bool=False, completions: _Completions=None) -> None:
super().__init__(none_ok=none_ok, completions=completions)
self.required = required
def to_py(self, value: _StrUnset) -> _StrUnsetNone:
self._basic_py_validation... |
class MnliProcessor(object):
def get_train_examples(self, data_dir, num_train_samples=(- 1)):
if (num_train_samples != (- 1)):
return self._create_examples(self._read_tsv(os.path.join(data_dir, 'mnli_train.tsv')), 'mnli_train')[:num_train_samples]
return self._create_examples(self._read_... |
def setup_args():
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument('dataset', type=str, help='dataset path')
parent_parser.add_argument('-a', '--architecture', type=str, choices=pretrained_models.keys(), help='model architecture', required=True)
parent_parser.add_argume... |
class AttrVI_ATTR_DEST_INCREMENT(RangeAttribute):
resources = [(constants.InterfaceType.pxi, 'INSTR'), (constants.InterfaceType.pxi, 'MEMACC'), (constants.InterfaceType.vxi, 'INSTR'), (constants.InterfaceType.vxi, 'MEMACC')]
py_name = 'destination_increment'
visa_name = 'VI_ATTR_DEST_INCREMENT'
visa_typ... |
class BasicDiscriminatorLoss(nn.Module):
def __init__(self, config=None):
super(BasicDiscriminatorLoss, self).__init__()
def forward(self, real_outputs, fake_outputs):
loss = 0
real_losses = []
fake_losses = []
for (dr, dg) in zip(real_outputs, fake_outputs):
... |
def drop_warning_stat(idata: arviz.InferenceData) -> arviz.InferenceData:
nidata = arviz.InferenceData(attrs=idata.attrs)
for (gname, group) in idata.items():
if ('sample_stat' in gname):
group = group.drop_vars(names=['warning', 'warning_dim_0'], errors='ignore')
nidata.add_groups({... |
class NCEAverage(nn.Module):
def __init__(self, inputSize, outputSize, K, T=0.07, momentum=0.5, Z=None):
super(NCEAverage, self).__init__()
self.nLem = outputSize
self.unigrams = torch.ones(self.nLem)
self.multinomial = AliasMethod(self.unigrams)
self.multinomial.cuda()
... |
('/v1/organization/<orgname>/prototypes')
_param('orgname', 'The name of the organization')
class PermissionPrototypeList(ApiResource):
schemas = {'NewPrototype': {'type': 'object', 'description': 'Description of a new prototype', 'required': ['role', 'delegate'], 'properties': {'role': {'type': 'string', 'descript... |
class WindowSpecificationTestCases(unittest.TestCase):
def setUp(self):
Timings.defaults()
self.app = Application(backend='win32').start(_notepad_exe())
self.dlgspec = self.app.UntitledNotepad
self.ctrlspec = self.app.UntitledNotepad.Edit
def tearDown(self):
self.app.kill... |
def test_nyquist_exceptions():
sys = ct.rss(2, 2, 2)
with pytest.raises(ct.exception.ControlMIMONotImplemented, match='only supports SISO'):
ct.nyquist_plot(sys)
sys = ct.rss(2, 1, 1)
with pytest.raises(AttributeError):
ct.nyquist_plot(sys, arrow_width=8, arrow_length=6)
with pytest.... |
class JSONTableWriter(FrameWriter):
_default_orient = 'records'
def __init__(self, obj, orient, date_format, double_precision, ensure_ascii, date_unit, default_handler=None):
super(JSONTableWriter, self).__init__(obj, orient, date_format, double_precision, ensure_ascii, date_unit, default_handler=defaul... |
class SilentTestSource(Silence):
def __init__(self, duration, frequency=440, sample_rate=44800, envelope=None):
super().__init__(duration, frequency, sample_rate, envelope)
self.bytes_read = 0
def get_audio_data(self, nbytes):
data = super().get_audio_data(nbytes)
if (data is not... |
def distortionParameter(types):
parameters = []
if (types == 'barrel'):
Lambda = ((np.random.random_sample() * (- 5e-05)) / 4)
x0 = 256
y0 = 256
parameters.append(Lambda)
parameters.append(x0)
parameters.append(y0)
return parameters
elif (types == 'pin... |
class ExcelImporter():
def __init__(self):
self.logger = qf_logger.getChild(self.__class__.__name__)
def import_cell(self, file_path: str, cell_address: str, sheet_name: str=None) -> Union[(int, float, str)]:
self.logger.info('Started importing data from {}'.format(file_path))
work_book ... |
def main():
exp_config = json.loads(_jsonnet.evaluate_file(args.exp_config_file))
model_config_file = exp_config['model_config']
if ('model_config_args' in exp_config):
model_config_args = exp_config['model_config_args']
if (args.model_config_args is not None):
model_config_args_... |
class RegisterObject():
__slots__ = ['_register_name', '_value', '_called_by_func', '_current_type', '_type_history']
def __init__(self, register_name, value, called_by_func=None, value_type=None):
self._register_name = register_name
self._value = value
self._current_type = value_type
... |
def bounds(geometry, north_up=True, transform=None):
geometry = (getattr(geometry, '__geo_interface__', None) or geometry)
if ('bbox' in geometry):
return tuple(geometry['bbox'])
geom = (geometry.get('geometry') or geometry)
if (not (('coordinates' in geom) or ('geometries' in geom) or ('feature... |
(repr=False, slots=True, hash=True)
class _SubclassOfValidator():
type = attrib()
def __call__(self, inst, attr, value):
if (not issubclass(value, self.type)):
msg = f"'{attr.name}' must be a subclass of {self.type!r} (got {value!r})."
raise TypeError(msg, attr, self.type, value)... |
.mongo
def test_mongo_being_calculated():
(mongetter=_test_mongetter)
def _takes_time(arg_1, arg_2):
sleep(3)
return ((random() + arg_1) + arg_2)
_takes_time.clear_cache()
res_queue = queue.Queue()
thread1 = threading.Thread(target=_calls_takes_time, kwargs={'res_queue': res_queue}, ... |
def preprocess_request_body(body: Optional[RequestParams]) -> Optional[RequestParams]:
if (not body):
return None
for resource in ['project', 'observation']:
if (resource in body):
body[resource] = preprocess_request_params(body[resource], convert_lists=False)
else:
body ... |
.slow
.parametrize('kwargs,op', [({}, 'sum'), ({}, 'mean'), pytest.param({}, 'min', marks=pytest.mark.slow), ({}, 'median'), pytest.param({}, 'max', marks=pytest.mark.slow), pytest.param({}, 'var', marks=pytest.mark.slow), pytest.param({}, 'count', marks=pytest.mark.slow), ({'ddof': 0}, 'std'), pytest.param({'quantile'... |
class StructureBranch(nn.Module):
def __init__(self, in_channels=4, use_sigmoid=True, use_spectral_norm=True, init_weights=True):
super(StructureBranch, self).__init__()
self.use_sigmoid = use_sigmoid
self.conv1 = self.features = nn.Sequential(spectral_norm(nn.Conv2d(in_channels=in_channels,... |
class Vex2Esil():
def __init__(self, arch, bits=64):
self.arch = arch
self.bits = bits
self.aarch = self.arch
if ((bits in arch_dict) and (arch in arch_dict[bits])):
self.aarch = arch_dict[bits][arch]
self.arch_class = archinfo_dict[self.aarch]()
self.vex_... |
def _fetch_build_eggs(dist):
try:
dist.fetch_build_eggs(dist.setup_requires)
except Exception as ex:
msg = "\n It is possible a package already installed in your system\n contains an version that is invalid according to PEP 440.\n You can try `pip install --use-pep517` as a ... |
def pretix_categories():
return {'count': 3, 'next': None, 'previous': None, 'results': [{'id': 1, 'name': {'en': 'Tickets', 'it': 'Biglietti'}, 'internal_name': 'tickets', 'description': {'en': ''}, 'position': 0, 'is_addon': False}, {'id': 2, 'name': {'en': 'Gadget', 'it': 'Premi'}, 'internal_name': None, 'descri... |
class SimulatorMaster(threading.Thread):
class ClientState(object):
def __init__(self):
self.memory = [[] for _ in range(3)]
self.ident = None
def __init__(self, pipe_c2s, pipe_s2c):
super(SimulatorMaster, self).__init__()
assert (os.name != 'nt'), "Doesn't suppor... |
def cos_similarity(ref_counts, gen_counts):
if ((len(ref_counts) == 0) or (len(gen_counts) == 0)):
return np.nan
keys = np.unique((list(ref_counts.keys()) + list(gen_counts.keys())))
ref_vec = np.array([ref_counts.get(k, 0) for k in keys])
gen_vec = np.array([gen_counts.get(k, 0) for k in keys])... |
class Screens(object):
bars = Bars()
def init_mono_screen_single_bar(self):
return [Screen(top=self.bars.init_top_single_bar())]
def init_mono_screen_double_bar(self):
return [Screen(top=self.bars.init_top_double_bar(), bottom=self.bars.init_bottom_double_bar())]
def init_dual_screen_sin... |
class SELinuxRoleTest(ProvyTestCase):
def setUp(self):
super(SELinuxRoleTest, self).setUp()
self.role = SELinuxRole(prov=None, context={'cleanup': []})
def provisions_correctly(self):
with self.mock_role_methods('install_packages', 'activate'):
self.role.provision()
... |
def _get_cosine_with_hard_restarts_schedule_with_warmup_lr_lambda(current_step: int, *, num_warmup_steps: int, num_training_steps: int, num_cycles: int):
if (current_step < num_warmup_steps):
return (float(current_step) / float(max(1, num_warmup_steps)))
progress = (float((current_step - num_warmup_step... |
def _generate_optimizer_class_with_gradient_clipping(optimizer: Type[torch.optim.Optimizer], *, per_param_clipper: Optional[_GradientClipper]=None, global_clipper: Optional[_GradientClipper]=None) -> Type[torch.optim.Optimizer]:
assert ((per_param_clipper is None) or (global_clipper is None)), 'Not allowed to use b... |
def gimme_save_string(opt):
varx = vars(opt)
base_str = ''
for key in varx:
base_str += str(key)
if isinstance(varx[key], dict):
for (sub_key, sub_item) in varx[key].items():
base_str += ((('\n\t' + str(sub_key)) + ': ') + str(sub_item))
else:
... |
def test_postloop_hooks(capsys):
testargs = ['prog', 'say hello', 'quit']
with mock.patch.object(sys, 'argv', testargs):
app = PluggedApp()
app.register_postloop_hook(app.prepost_hook_one)
app.register_postloop_hook(app.prepost_hook_two)
app.cmdloop()
(out, err) = capsys.readouterr()
... |
def gen_candidate(level):
global compnum
size = len(freArr[(level - 1)])
start = 0
for i in range(size):
Q = ''
R = ''
R = freArr[(level - 1)][i].name[1:level]
Q = freArr[(level - 1)][start].name[0:(level - 1)]
if (Q != R):
start = binary_search(level,... |
def add_QdrantServicer_to_server(servicer, server):
rpc_method_handlers = {'HealthCheck': grpc.unary_unary_rpc_method_handler(servicer.HealthCheck, request_deserializer=qdrant__pb2.HealthCheckRequest.FromString, response_serializer=qdrant__pb2.HealthCheckReply.SerializeToString)}
generic_handler = grpc.method_h... |
.parametrize('levels_setting, excludes_setting, level, source, msg, expected_ret, expected_level', [({}, {}, usertypes.JsLogLevel.error, 'qute:test', 'msg', False, None), ({'qute:*': ['error']}, {}, usertypes.JsLogLevel.error, 'qute:bla', 'msg', True, usertypes.MessageLevel.error), ({'qute:*': ['error']}, {'qute:*': ['... |
class ReducedFocalLoss(nn.Module):
def __init__(self, alpha=1, gamma=2, reduce=True, reduce_th=0.5, **kwargs):
super(ReducedFocalLoss, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.reduce = reduce
self.reduce_th = reduce_th
def forward(self, inputs, targets)... |
class WRNConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, activate):
super(WRNConv, self).__init__()
self.activate = activate
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=... |
def _should_use_custom_op(input):
assert isinstance(input, torch.Tensor)
if ((not enabled) or (not torch.backends.cudnn.enabled)):
return False
if (input.device.type != 'cuda'):
return False
if (LooseVersion(torch.__version__) >= LooseVersion('1.7.0')):
return True
warnings.w... |
class Router(object):
default_pattern = '[^/]+'
default_filter = 're'
_MAX_GROUPS_PER_PATTERN = 99
def __init__(self, strict=False):
self.rules = []
self._groups = {}
self.builder = {}
self.static = {}
self.dyna_routes = {}
self.dyna_regexes = {}
s... |
class TestGraphPartition(QiskitOptimizationTestCase):
def setUp(self):
super().setUp()
aqua_globals.random_seed = 100
self.num_nodes = 4
self.w = random_graph(self.num_nodes, edge_prob=0.8, weight_range=10)
(self.qubit_op, self.offset) = graph_partition.get_operator(self.w)
... |
def make_commitment_output_to_local_address(revocation_pubkey: bytes, to_self_delay: int, delayed_pubkey: bytes) -> str:
local_script = make_commitment_output_to_local_witness_script(revocation_pubkey, to_self_delay, delayed_pubkey)
return bitcoin.redeem_script_to_address('p2wsh', bh2u(local_script)) |
def pixel_group(score, mask, embedding, kernel_label, kernel_contour, kernel_region_num, distance_threshold):
assert isinstance(score, (torch.Tensor, np.ndarray))
assert isinstance(mask, (torch.Tensor, np.ndarray))
assert isinstance(embedding, (torch.Tensor, np.ndarray))
assert isinstance(kernel_label, ... |
('python_ta.config.toml.load', side_effect=FileNotFoundError)
def test_load_messages_config_logging(_, caplog):
try:
load_messages_config('non_existent_file.toml', 'default_file.toml', True)
except FileNotFoundError:
assert ('Could not find messages config file at' in caplog.text)
assert... |
def filter_ss_table(store_sales_df, filtered_item_df):
filtered_ss_df = store_sales_df[store_sales_df['ss_customer_sk'].notnull()].reset_index(drop=True)
filtered_ss_df = filtered_ss_df.loc[((filtered_ss_df['ss_sold_date_sk'] >= q12_store_sale_sk_start_date) & (filtered_ss_df['ss_sold_date_sk'] <= (q12_store_sa... |
.parametrize('option', ['-o', '--output-image'])
def test_output_image(mock_image_optimization, mock_write_image, set_argv, option):
expected_file = '/path/to/output/image'
expected_image = object()
mock_image_optimization(return_value=expected_image)
mock = mock_write_image()
set_argv(f'{option}={e... |
def load_zip_file(file, fileNameRegExp='', allEntries=False):
try:
archive = zipfile.ZipFile(file, mode='r', allowZip64=True)
except:
raise Exception('Error loading the ZIP archive')
pairs = []
for name in archive.namelist():
addFile = True
keyName = name
if (file... |
class Logger(object):
def __init__(self, name, exp_dir, opt, commend='', HTML_doc=False, log_dir='log', checkpoint_dir='checkpoint', sample='samples', web='web', test_dir='test'):
self.name = name
self.exp_dir = os.path.join(os.path.abspath('experiments'), exp_dir)
self.log_dir = os.path.joi... |
class Terminal():
_terminals = {}
_detached_terminals = []
def __init__(self, view=None):
self.view = view
self._cached_cursor = [0, 0]
self._size = sublime.load_settings('Terminus.sublime-settings').get('size', (None, None))
self._cached_cursor_is_hidden = [True]
sel... |
def aggregate(prob, keep_bg=False):
k = prob.shape
new_prob = torch.cat([torch.prod((1 - prob), dim=0, keepdim=True), prob], 0).clamp(1e-07, (1 - 1e-07))
logits = torch.log((new_prob / (1 - new_prob)))
if keep_bg:
return F.softmax(logits, dim=0)
else:
return F.softmax(logits, dim=0)[... |
class NumexprGroup(Numexpr):
def __init__(self, expr: Numexpr):
self.__expr = expr
def evaluate(self, data, time, use_date):
return self.__expr.evaluate(data, time, use_date)
def __repr__(self):
return ('<NumexprGroup expr=%r>' % self.__expr)
def use_date(self):
return se... |
class Fp32GroupNorm(nn.GroupNorm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def forward(self, input):
output = F.group_norm(input.float(), self.num_groups, (self.weight.float() if (self.weight is not None) else None), (self.bias.float() if (self.bias is not None) el... |
def get_index_class(index: (type[BaseIndex] | str)) -> type[BaseIndex]:
if (isinstance(index, type) and issubclass(index, BaseIndex)):
return index
if (index == 'l2'):
return L2Index
elif (index == 'annoy'):
return AnnoyIndex
elif (index == 'kd_tree'):
return KDTreeIndex
... |
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, max_norm: float=0, args=None, writer=None):
model.train()
criterion.train()
metric_logger = utils.MetricLogger(delimiter=' ')
metric_logger.... |
class MultiphaseBuilder(ThermalBuilder):
def __init__(self, casePath, solverSettings=getDefaultMultiphaseSolverSettings(), templatePath='tutorials/heatTransfer/buoyantBoussinesqSimpleFoam/hotRoom/', fluidProperties={'name': 'air', 'compressible': False, 'kinematicViscosity': 100000.0}, turbulenceProperties={'name':... |
def load_lvis_json(json_file, image_root, dataset_name=None, extra_annotation_keys=None):
from lvis import LVIS
json_file = PathManager.get_local_path(json_file)
timer = Timer()
lvis_api = LVIS(json_file)
if (timer.seconds() > 1):
logger.info('Loading {} takes {:.2f} seconds.'.format(json_fi... |
class TestFormatSize():
TESTS = [((- 1024), '-1.00k'), ((- 1), '-1.00'), (0, '0.00'), (1023, '1023.00'), (1024, '1.00k'), (1034.24, '1.01k'), (((1024 * 1024) * 2), '2.00M'), ((1024 ** 10), '1024.00Y'), (None, '?.??')]
KILO_TESTS = [(999, '999.00'), (1000, '1.00k'), (1010, '1.01k')]
.parametrize('size, out',... |
_state_transitions.register
def _handle_channel_settled(action: ContractReceiveChannelSettled, channel_state: NettingChannelState, **kwargs: Optional[Dict[(Any, Any)]]) -> TransitionResult[Optional[NettingChannelState]]:
events: List[Event] = []
if (action.channel_identifier == channel_state.identifier):
... |
def get_preresnet_cifar(num_classes, blocks, bottleneck, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
assert (num_classes in [10, 100])
if bottleneck:
assert (((blocks - 2) % 9) == 0)
layers = ([((blocks - 2) // 9)] * 3)
else:
assert (((bl... |
class Period():
def __init__(self, months: int=0, days: int=0) -> None:
self._months = months
self._days = days
def make(cls, data: Any) -> Period:
if isinstance(data, cls):
return data
elif isinstance(data, str):
return cls().add_tenure(data)
else... |
class NetworkImageNet(nn.Module):
def __init__(self, C, num_classes, layers, auxiliary, genotype):
super(NetworkImageNet, self).__init__()
self._layers = layers
self._auxiliary = auxiliary
self.drop_path_prob = 0.0
self.stem0 = nn.Sequential(nn.Conv2d(3, (C // 2), kernel_size... |
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
layout = QHBoxLayout()
self.ax = pg.PlotWidget()
self.ax.showGrid(True, True)
self.line = pg.InfiniteLine(pos=(- 20), pen=pg.mkPen('k', width=3), movable=Fals... |
def mock_clone(url: str, *_: Any, source_root: (Path | None)=None, **__: Any) -> MockDulwichRepo:
parsed = ParsedUrl.parse(url)
assert (parsed.pathname is not None)
path = re.sub('(.git)?$', '', parsed.pathname.lstrip('/'))
assert (parsed.resource is not None)
folder = (((FIXTURE_PATH / 'git') / par... |
def doc2js(doc):
cls2ner = ['PER', 'LOC', 'ORG', 'MISC', 'FP-PER', 'FP-LOC', 'FP-ORG', 'FP-MISC', 'FN-PER', 'FN-LOC', 'FN-ORG', 'FN-MISC']
(text, entities, offset, n_entities) = ('', [], 0, 0)
for (sent, boe, eoe, coe) in doc:
acc_len = [offset]
for w in sent:
acc_len.append(((ac... |
class TransformValuesRewrite(GraphRewriter):
transform_rewrite = in2out(transform_values, ignore_newtrees=True)
scan_transform_rewrite = in2out(transform_scan_values, ignore_newtrees=True)
def __init__(self, values_to_transforms: Dict[(TensorVariable, Union[(Transform, None)])]):
self.values_to_tran... |
class HTML():
def __init__(self, web_dir, title, refresh=0):
self.title = title
self.web_dir = web_dir
self.img_dir = os.path.join(self.web_dir, 'images')
if (not os.path.exists(self.web_dir)):
os.makedirs(self.web_dir)
if (not os.path.exists(self.img_dir)):
... |
def _deque_mock():
base_deque_class = '\n class deque(object):\n maxlen = 0\n def __init__(self, iterable=None, maxlen=None):\n self.iterable = iterable or []\n def append(self, x): pass\n def appendleft(self, x): pass\n def clear(self): pass\n def count(self,... |
class Lighting(QGraphicsView):
def __init__(self, parent=None):
super(Lighting, self).__init__(parent)
self.angle = 0.0
self.m_scene = QGraphicsScene()
self.m_lightSource = None
self.m_items = []
self.setScene(self.m_scene)
self.setupScene()
timer = QT... |
class FocalLoss(nn.Module):
def __init__(self, loss_weight=1.0, pos_weight=1.0, gamma=1.5, alpha=0.25, reduction='mean'):
super(FocalLoss, self).__init__()
self.loss_weight = loss_weight
self.pos_weight = pos_weight
self.loss_fcn = nn.BCEWithLogitsLoss(pos_weight=self.pos_weight, red... |
.parametrize('username,password', users)
.parametrize('project_id', projects)
.parametrize('condition_id', conditions)
def test_resolve(db, client, username, password, project_id, condition_id):
client.login(username=username, password=password)
url = (reverse(urlnames['resolve'], args=[project_id]) + f'?condit... |
def test_raises(pytester: Pytester) -> None:
pytester.makepyfile('\n from nose.tools import raises\n\n (RuntimeError)\n def test_raises_runtimeerror():\n raise RuntimeError\n\n (Exception)\n def test_raises_baseexception_not_caught():\n raise BaseException\n\... |
class Effect6558(BaseEffect):
type = 'overheat'
def handler(fit, module, context, projectionRange, **kwargs):
overloadBonus = module.getModifiedItemAttr('overloadTrackingModuleStrengthBonus')
module.boostItemAttr('maxRangeBonus', overloadBonus, **kwargs)
module.boostItemAttr('falloffBonu... |
class ArmorRRColumn(GraphColumn):
name = 'ArmorRR'
stickPrefixToValue = True
def __init__(self, fittingView, params):
super().__init__(fittingView, 80, (3, 0, 3))
def _getValue(self, fit):
defaultSpoolValue = eos.config.settings['globalDefaultSpoolupPercentage']
return (fit.getRe... |
class IteratorProducer(Producer):
_e_factors = ('iterator',)
protocol = PROTOCOL_CHUNKS
def __init__(self, iterator):
self.iterator = iter(iterator)
self.__next__ = self.iterator.__next__
super().__init__()
def realign(self):
pass
def __next__(self, next=next):
... |
def test_relative_in_modules(fixture_path):
result = fixture_path.runpytest('-v')
result.assert_outcomes(passed=9, failed=0)
result.stdout.fnmatch_lines(['mod2_test.py::TestB::test_a PASSED', 'mod1_test.py::TestA::test_c PASSED', 'mod2_test.py::TestB::test_b PASSED', 'mod1_test.py::TestA::test_a PASSED', 's... |
def maybe_add_to_os_environ_pathlist(var, newpath):
import os
if os.path.isabs(newpath):
try:
oldpaths = os.environ[var].split(os.pathsep)
if (newpath not in oldpaths):
newpaths = os.pathsep.join(([newpath] + oldpaths))
os.environ[var] = newpaths
... |
class Card(QGraphicsPixmapItem):
def __init__(self, value, suit, *args, **kwargs):
super(Card, self).__init__(*args, **kwargs)
self.signals = Signals()
self.stack = None
self.child = None
self.value = value
self.suit = suit
self.side = None
self.vector... |
class QSVR(SVR, SerializableModelMixin):
def __init__(self, *, quantum_kernel: Optional[BaseKernel]=None, **kwargs):
if ('kernel' in kwargs):
msg = "'kernel' argument is not supported and will be discarded, please use 'quantum_kernel' instead."
warnings.warn(msg, QiskitMachineLearnin... |
class Key(object):
def __init__(self, network, compressed=False):
self.network = network
self.compressed = compressed
def __eq__(self, other):
return (other and (self.network == other.network) and (type(self) == type(other)))
def __ne__(self, other):
return (not (self == othe... |
def train(args):
multi_gpus = False
if (len(args.gpus.split(',')) > 1):
multi_gpus = True
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpus
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
save_dir = os.path.join(args.save_dir, (((args.model_pre + args.backbone.upper()) +... |
.parametrize('node_type', [TeleporterNetworkNode])
def test_unchanged_create_new_node_corruption(skip_qtbot, corruption_game_description, node_type):
node = next((node for node in corruption_game_description.region_list.iterate_nodes() if isinstance(node, node_type)))
dialog = NodeDetailsPopup(corruption_game_d... |
def smoke_test(executable: pathlib.Path, debug: bool, qt5: bool) -> None:
stdout_whitelist = []
stderr_whitelist = ['\\[.*\\] PyInstaller Bootloader .*', '\\[.*\\] LOADER: .*']
if IS_MACOS:
stderr_whitelist.extend(['objc\\[.*\\]: .* One of the two will be used\\. Which one is undefined\\.', 'QCoreAp... |
def test_ds_non_existent(pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'DOES_NOT_EXIST')
pytester.makepyfile('def test_ds(): pass')
result = pytester.runpytest_subprocess()
result.stderr.fnmatch_lines(['*ImportError:*DOES_NOT_EXIST*'])
... |
def test_extract_variable_with_similar(config, workspace, code_action_context):
document = create_document(workspace, 'simple.py')
line = 6
start_col = document.lines[line].index('a + b')
end_col = document.lines[line].index(')\n')
selection = Range((line, start_col), (line, end_col))
response =... |
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [migrations.CreateModel(name='Manufacturer', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=120)), ('location', models.CharFie... |
class GraphAttentionLayer(nn.Module):
def __init__(self, input_dim, output_dim, num_gat_iters=1, num_heads=4, dropout=0.5, alpha=0.2):
super(GraphAttentionLayer, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.num_gat_iters = num_gat_iters
self.n... |
def generate_dealloc_for_class(cl: ClassIR, dealloc_func_name: str, clear_func_name: str, emitter: Emitter) -> None:
emitter.emit_line('static void')
emitter.emit_line(f'{dealloc_func_name}({cl.struct_name(emitter.names)} *self)')
emitter.emit_line('{')
emitter.emit_line('PyObject_GC_UnTrack(self);')
... |
def test_base_case_call() -> None:
with RecursionTable('fact') as table:
def fact(n):
if (n == 0):
return 1
else:
return (n * fact((n - 1)))
fact(0)
recursive_dict = table.get_recursive_dict()
assert (len(list(recursive_dict.keys())) ==... |
class Window(_Window, base.Window):
_window_mask = (((EventMask.StructureNotify | EventMask.PropertyChange) | EventMask.EnterWindow) | EventMask.FocusChange)
def __init__(self, window, qtile):
_Window.__init__(self, window, qtile)
self._wm_class: (list[str] | None) = None
self.update_wm_... |
def make_solver(iter_idx, output_dir):
solver_content = 'net: "{0}/model/train_nyu_pose_ren_s{1}.prototxt"\ntest_iter: 64\ntest_interval: 1000\nbase_lr: 0.001\nlr_policy: "step"\ngamma: 0.1\nstepsize: 40000\ndisplay: 100\nmax_iter: 160000\nmomentum: 0.9\nweight_decay: 0.0005\nsnapshot: 40000\nsnapshot_prefix: "{0}/... |
def reorder_items(items: Sequence[nodes.Item]) -> List[nodes.Item]:
argkeys_cache: Dict[(Scope, Dict[(nodes.Item, Dict[(FixtureArgKey, None)])])] = {}
items_by_argkey: Dict[(Scope, Dict[(FixtureArgKey, Deque[nodes.Item])])] = {}
for scope in HIGH_SCOPES:
scoped_argkeys_cache = argkeys_cache[scope] =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.