code stringlengths 281 23.7M |
|---|
def test_topics(gl, gitlab_version):
assert (not gl.topics.list())
create_dict = {'name': 'my-topic', 'description': 'My Topic'}
if (gitlab_version.major >= 15):
create_dict['title'] = 'my topic title'
topic = gl.topics.create(create_dict)
assert (topic.name == 'my-topic')
if (gitlab_ver... |
class SubtypeVisitor(RTypeVisitor[bool]):
def __init__(self, right: RType) -> None:
self.right = right
def visit_rinstance(self, left: RInstance) -> bool:
return (isinstance(self.right, RInstance) and (self.right.class_ir in left.class_ir.mro))
def visit_runion(self, left: RUnion) -> bool:
... |
class ValidateTest(TestCase):
def test_validate_does_not_mutate_schema_adding_nullable_key(self):
schema = {'type': 'object', 'properties': {'email': {'type': 'string'}, 'enabled': {'type': 'boolean'}}, 'example': {'enabled': False, 'email': ''}}
validate({'email': ''}, schema)
self.assertTr... |
def _generate_indices(left_index: np.ndarray, right_index: np.ndarray, conditions: list[tuple[(pd.Series, pd.Series, str)]]) -> tuple:
for condition in conditions:
(left, right, op) = condition
left = left._values[left_index]
right = right._values[right_index]
op = operator_map[op]
... |
class BaseModelOutputWithPoolingAndCrossAttentions(ModelOutput):
last_hidden_state: torch.FloatTensor = None
pooler_output: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
attentions: Optional[Tuple[t... |
class DiracConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
super(DiracConv, self).__init__()
self.activ = nn.ReLU(inplace=True)
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padd... |
(name='module', params=[DataclassModule(dataclass=attr.dataclass, fields=attr.fields, field=attr.ib), DataclassModule(dataclass=dataclasses.dataclass, fields=dataclasses.fields, field=dataclasses.field)], ids=['attrs', 'dataclasses'])
def dataclass_param(request: _pytest.fixtures.SubRequest) -> DataclassModule:
mod... |
class InstanceL2Norm(nn.Module):
def __init__(self, size_average=True, eps=1e-05, scale=1.0):
super().__init__()
self.size_average = size_average
self.eps = eps
self.scale = scale
def forward(self, input):
if self.size_average:
return (input * (self.scale * ((... |
class ReductionCell0(nn.Module):
def __init__(self, in_chs_left, out_chs_left, in_chs_right, out_chs_right, pad_type=''):
super(ReductionCell0, self).__init__()
self.conv_prev_1x1 = ActConvBn(in_chs_left, out_chs_left, 1, stride=1, padding=pad_type)
self.conv_1x1 = ActConvBn(in_chs_right, ou... |
class Unet(SegmentationModel):
def __init__(self, encoder_name: str='resnet34', encoder_depth: int=5, encoder_weights: Optional[str]='imagenet', decoder_use_batchnorm: bool=True, decoder_channels: List[int]=(256, 128, 64, 32, 16), decoder_attention_type: Optional[str]=None, in_channels: int=3, classes: int=1, activ... |
class DataloaderSkipNoneWrapper(DataloaderWrapper):
def __init__(self, dataloader: Iterable) -> None:
super().__init__(dataloader)
def __iter__(self) -> Iterator[Any]:
self._iter = iter(self.dataloader)
return self
def __next__(self) -> Any:
next_batch = None
while (n... |
_info
def Hawkeye_file(filename):
res = Manager().list([])
p = Pool(30)
q = Manager().Queue()
try:
f = open(filename, 'r')
urls = f.readlines()
f.close()
print('~:{}'.format(len(urls)))
if urls:
for i in urls:
p.apply_async(Get_tile_fil... |
class lazy_dict(Dict[(_K, _V)]):
def __init__(self, d, f_value):
dict.__init__(self, d)
self.f_value = f_value
def __missing__(self, key: _K) -> _V:
value = self.f_value(key)
self[key] = value
return value
def __repr__(self):
return '{}({}, f_value={!r})'.form... |
def test_mouse_release_event_when_rotate_action_zero(view, item):
view.scene.addItem(item)
event = MagicMock()
event.scenePos.return_value = QtCore.QPointF(15, 25)
item.rotate_active = True
item.rotate_orig_degrees = 0
item.rotate_start_angle = (- 45)
item.event_anchor = QtCore.QPointF(10, 2... |
class CGBlock(dict):
def __init__(self, fid=None, pointer=None):
if (fid is not None):
self.read_cg(fid, pointer)
def read_cg(self, fid, pointer):
fid.seek(pointer)
self['pointer'] = pointer
(self['id'], self['reserved'], self['length'], self['link_count'], self['cg_c... |
class Stem(nn.Sequential):
def __init__(self, in_chs, out_chs, kernel_size=3, stride=4, pool='maxpool', num_rep=3, num_act=None, chs_decay=0.5, layers: LayerFn=None):
super().__init__()
assert (stride in (2, 4))
layers = (layers or LayerFn())
if isinstance(out_chs, (list, tuple)):
... |
def is_boolean(value, arg_name, logger=None):
if (not isinstance(value, bool)):
if logger:
logger.error(f'''Invalid value for the argument '{arg_name}': {value}. Specify a boolean.
''')
else:
print(f'''ERROR: Invalid value for the argument '{arg_name}': {value}. Specify a boo... |
class PublisherFallbackAdsView(FallbackAdsMixin, PublisherAccessMixin, UserPassesTestMixin, DetailView):
model = Flight
template_name = 'adserver/publisher/fallback-ads-list.html'
def dispatch(self, request, *args, **kwargs):
self.publisher = get_object_or_404(Publisher, slug=self.kwargs['publisher_... |
class ISSampler(BatchSampler):
def __init__(self, algo, n_backtrack='all', n_is_pretrain=0, init_is=0, skip_is_itrs=False, hist_variance_penalty=0.0, max_is_ratio=0, ess_threshold=0):
self.n_backtrack = n_backtrack
self.n_is_pretrain = n_is_pretrain
self.skip_is_itrs = skip_is_itrs
s... |
def add_model_args(parser: ArgumentParser) -> None:
parser.add_argument('--model', choices=('rf', 'gp', 'nn', 'mpn'), default='rf', help='the model type to use')
parser.add_argument('--test-batch-size', type=int, help='the size of batch of predictions during model inference. NOTE: This has nothing to do with mo... |
def makeItemTree(stack, title):
topItem = QtWidgets.QTreeWidgetItem([title])
topItem.frame = None
font = topItem.font(0)
font.setWeight(font.Weight.Bold)
topItem.setFont(0, font)
items = [topItem]
for entry in stack:
if isinstance(entry, QtWidgets.QTreeWidgetItem):
item =... |
def update():
for episode in range(100):
observation = env.reset()
while True:
env.render()
action = RL.choose_action(str(observation))
(observation_, reward, done) = env.step(action)
RL.learn(str(observation), action, reward, str(observation_))
... |
class RecentFilesView(QtWidgets.QListView):
def __init__(self, parent, view, files=None):
super().__init__(parent)
self.view = view
self.files = (files or [])
self.clicked.connect(self.on_clicked)
self.setModel(RecentFilesModel(self.files))
self.setMouseTracking(True)... |
class Post(ContentManageable):
title = models.CharField(max_length=200, blank=True, null=True)
content = MarkupField(default_markup_type=DEFAULT_MARKUP_TYPE)
abstract = models.TextField(blank=True, null=True)
MEDIA_TEXT = 1
MEDIA_PHOTO = 2
MEDIA_VIDEO = 3
MEDIA_LINK = 4
MEDIA_CHOICES = (... |
class DrawMav():
def __init__(self, state, window):
(self.mav_points, self.mav_meshColors) = self.get_points()
mav_position = np.array([[state.north], [state.east], [(- state.altitude)]])
R = Euler2Rotation(state.phi, state.theta, state.psi)
rotated_points = self.rotate_points(self.m... |
(name='print')
('tab', value=cmdutils.Value.count_tab)
('pdf', flag='f', metavar='file')
def printpage(tab: Optional[apitypes.Tab], preview: bool=False, *, pdf: Optional[pathlib.Path]=None) -> None:
if (tab is None):
return
try:
if preview:
_print_preview(tab)
elif pdf:
... |
class ChannelStateWaiter():
raiden: 'RaidenService'
retry_timeout: float
token_network_registry_address: TokenNetworkRegistryAddress
token_address: TokenAddress
partner_address: Address
def _get_channel_state(self, chain_state: ChainState) -> Optional[NettingChannelState]:
return _get_ch... |
def test(env, pg_reinforce, n=50):
reward_list = []
dialogLen_list = []
success_list = []
for i_test in tqdm(range(n)):
assert (len(pg_reinforce.reward_buffer) == 0)
(cur_reward, cur_dialogLen, cur_success) = run_one_dialog(env, pg_reinforce)
assert (cur_success is not None)
... |
def _create_splits(features_paths: List[Path], labels_dir_dict: Dict[(Task, Path)], splits_path: Path) -> None:
labels_path_dicts = _create_labels_path_dicts(features_paths, labels_dir_dict)
labels_path_exists = [_any_labels_exist(labels_path_dict) for labels_path_dict in labels_path_dicts]
all_names = [nam... |
class ServerLoggingFormatter(logging.Formatter):
converter = time.gmtime
def format(self, record):
if flask.has_request_context():
who = flask.request.remote_addr
is_socketio = hasattr(flask.request, 'sid')
where = flask.request.url
if is_socketio:
... |
def upgrade(saveddata_engine):
try:
saveddata_engine.execute('SELECT defaultChar, chars FROM characters LIMIT 1')
except sqlalchemy.exc.DatabaseError:
saveddata_engine.execute('ALTER TABLE characters ADD COLUMN defaultChar INTEGER')
saveddata_engine.execute('ALTER TABLE characters ADD CO... |
def run_pip(venv_dir, *args, quiet=False, **kwargs):
args = list(args)
if quiet:
args.insert(1, '-q')
arg_str = ' '.join((str(arg) for arg in args))
utils.print_col('venv$ pip {}'.format(arg_str), 'blue')
venv_python = get_venv_python(venv_dir)
return subprocess.run(([venv_python, '-m', ... |
.timeout(60)
def test_upload_collection_generators(local_client, remote_client):
records = generate_fixtures(UPLOAD_NUM_VECTORS)
vectors = []
payload = []
for record in records:
vectors.append(record.vector)
payload.append(record.payload)
payload = itertools.cycle(payload)
local_... |
class ElectronicStructureResult(EigenstateResult):
def hartree_fock_energy(self) -> float:
return self.get('hartree_fock_energy')
_fock_energy.setter
def hartree_fock_energy(self, value: float) -> None:
self.data['hartree_fock_energy'] = value
def nuclear_repulsion_energy(self) -> Option... |
class TestMimicTPW2Reader(unittest.TestCase):
yaml_file = 'mimicTPW2_comp.yaml'
def setUp(self):
from satpy._config import config_search_paths
from satpy.readers.mimic_TPW2_nc import MimicTPW2FileHandler
self.reader_configs = config_search_paths(os.path.join('readers', self.yaml_file))
... |
class MultiHeadAttention(nn.Module):
def __init__(self, emb_size, num_heads, dropout):
super().__init__()
self.emb_size = emb_size
self.num_heads = num_heads
self.keys = nn.Linear(emb_size, emb_size)
self.queries = nn.Linear(emb_size, emb_size)
self.values = nn.Linear... |
class VolGroup_TestCase(unittest.TestCase):
def runTest(self):
data1 = FC3_VolGroupData()
data2 = FC3_VolGroupData()
self.assertEqual(data1.format, True)
self.assertEqual(data1.pesize, 32768)
self.assertEqual(data1.preexist, False)
self.assertEqual(F21_VolGroupData().... |
class State(ViewColumn):
name = 'State'
def __init__(self, fittingView, params):
ViewColumn.__init__(self, fittingView)
self.mainFrame = gui.mainFrame.MainFrame.getInstance()
self.resizable = False
self.size = 16
self.maxsize = self.size
self.mask = wx.LIST_MASK_I... |
def add_computed_time(t):
if (t[0] in 'now noon midnight'.split()):
t['computed_time'] = {'now': datetime.now().time().replace(microsecond=0), 'noon': time(hour=12), 'midnight': time()}[t[0]]
else:
t['HH'] = {'am': (int(t['HH']) % 12), 'pm': ((int(t['HH']) % 12) + 12)}[t.ampm]
t['compute... |
def test_init_false(converter: BaseConverter) -> None:
class A():
a: int
b: int = field(init=False)
_c: int = field(init=False)
d: int = field(init=False, default=4)
converter.register_unstructure_hook(A, make_dict_unstructure_fn(A, converter))
a = A(1)
a.b = 2
a._c =... |
def columnize(array, displaywidth=80, colsep=' ', arrange_vertical=True, ljust=True, lineprefix='', opts={}):
if (not isinstance(array, (list, tuple))):
raise TypeError('array needs to be an instance of a list or a tuple')
if (len(opts.keys()) > 0):
o = {key: get_option(key, opts) for key in de... |
def test_non_unittest_no_setupclass_support(pytester: Pytester) -> None:
testpath = pytester.makepyfile('\n class TestFoo(object):\n x = 0\n\n \n def setUpClass(cls):\n cls.x = 1\n\n def test_method1(self):\n assert self.x == 0\n\n ... |
def test_method_const_instance_attr_same_method() -> None:
node = builder.extract_node('\n class A:\n def __init__(self, x):\n if x:\n self.x = 1\n else:\n self.x = 2\n\n def set_x(self):\n self.x = 3\n\n def get_x(self):\n ... |
def test_adr_invalid_and_night(sam_data):
inverters = sam_data['adrinverter']
testinv = 'Zigor__Sunzet_3_TL_US_240V__CEC_2011_'
vdcs = np.array([39.873036, 0.0, np.nan, 420])
pdcs = np.array([188.09182, 0.0, 420, np.nan])
pacs = inverter.adr(vdcs, pdcs, inverters[testinv])
assert_allclose(pacs, ... |
class TestChangeKeyboardControl(EndianTest):
def setUp(self):
self.req_args_0 = {'attrs': {'led': 196, 'auto_repeat_mode': 0, 'bell_pitch': (- 2303), 'bell_percent': (- 5), 'key_click_percent': (- 59), 'key': 190, 'bell_duration': (- 4223), 'led_mode': 1}}
self.req_bin_0 = b'f\x00\x00\n\x00\x00\x00\... |
def concept_preparation(train_captions, dataset, source_lang=configs.main_lang, target_lang=None, topk=1000):
if (target_lang is None):
target_lang = source_lang
print(f'Parse English captions to get the most frequent {topk} concepts')
save_path = os.path.join(configs.concepts_root, dataset, target_... |
class TokenAddLayout(QGridLayout):
def __init__(self, dialog, callback):
QGridLayout.__init__(self)
self.setSpacing(8)
self.setColumnStretch(3, 1)
self.callback = callback
self.dialog = dialog
self.addresses = self.dialog.parent().wallet.get_addresses_sort_by_balance(... |
def is_special_target(right: ProperType) -> bool:
if (isinstance(right, FunctionLike) and right.is_type_obj()):
if (right.type_object().fullname == 'builtins.tuple'):
return True
if (right.type_object().fullname in ('mypy.types.Type', 'mypy.types.ProperType', 'mypy.types.TypeAliasType'))... |
def load_op_library(path):
if (os.name == 'nt'):
if (not os.path.exists(path)):
path = re.sub('\\.so$', '.dll', path)
if (not os.path.exists(path)):
return None
path = resource_loader.get_path_to_datafile(path)
ret = load_library.load_op_library(path)
assert ret, ... |
def test_pre_greedy_node_rewriter():
empty_fgraph = FunctionGraph([], [])
x = MyVariable('x')
y = MyVariable('y')
c1 = Constant(MyType(), 1, 'c1')
c2 = Constant(MyType(), 2, 'c2')
o1 = op2(c1, c2)
o3 = op1(c1, y)
o2 = op1(o1, c2, x, o3, o1)
assert (o2.owner.inputs[0].owner is not Non... |
def test_resolve_module_exports_from_file_log_on_unknown_file_location(caplog, tmp_path):
file = (tmp_path / 'some.js')
file.write_text("export * from './does-not-exist.js';")
resolve_module_exports_from_file(file, 2)
assert (len(caplog.records) == 1)
assert caplog.records[0].message.startswith('Did... |
_datapipe('zip_longest')
class ZipperLongestIterDataPipe(IterDataPipe):
datapipes: Tuple[IterDataPipe]
length: Optional[int]
fill_value: Any
def __init__(self, *datapipes: IterDataPipe, fill_value: Any=None):
if (not all((isinstance(dp, IterDataPipe) for dp in datapipes))):
raise Typ... |
class AttributeTestModel(Model):
class Meta():
host = '
table_name = 'test'
binary_attr = BinaryAttribute(hash_key=True, legacy_encoding=False)
binary_set_attr = BinarySetAttribute(legacy_encoding=False)
number_attr = NumberAttribute()
number_set_attr = NumberSetAttribute()
unico... |
def is_transaction_pending(chain_state: ChainState, transaction: ContractSendEvent, state_change: StateChange) -> bool:
return (not (is_transaction_effect_satisfied(chain_state, transaction, state_change) or is_transaction_invalidated(transaction, state_change) or is_transaction_expired(transaction, chain_state.blo... |
class PrimeCosmeticPatchesDialog(BaseCosmeticPatchesDialog, Ui_PrimeCosmeticPatchesDialog):
_cosmetic_patches: PrimeCosmeticPatches
def __init__(self, parent: (QtWidgets.QWidget | None), current: PrimeCosmeticPatches):
super().__init__(parent)
self.setupUi(self)
self._cosmetic_patches = ... |
class WorkQueue(object):
def __init__(self, queue_name, transaction_factory, canonical_name_match_list=None, has_namespace=False):
self._queue_name = queue_name
self._transaction_factory = transaction_factory
self._currently_processing = False
self._has_namespaced_items = has_namespa... |
class CalcCriteriaTestCase(unittest.TestCase):
def setUp(self):
self.Z = np.array([[0, 1, 1, 0], [1, 0, 1, 0], [0, 1, 1, 1], [0, 1, 0, 1], [0, 0, 0, 0]], dtype=np.int)
self.Y = np.array([[0, 1, 1, 0], [1, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 0, 0]], dtype=np.int)
def test_hamming_loss(se... |
class CacheClearCommand(Command):
name = 'cache clear'
description = 'Clears a Poetry cache by name.'
arguments = [argument('cache', description='The name of the cache to clear.')]
options = [option('all', description='Clear all entries in the cache.')]
def handle(self) -> int:
cache = self.... |
def ArrayDataStrategy(draw, id_, n_dim, subtype):
if (not n_dim):
if isinstance(subtype, rt.Port):
return draw(InPortDataStrategy(id_, subtype))
else:
return draw(InterfaceDataStrategy(id_, subtype))
else:
data = {}
for i in range(n_dim[0]):
da... |
class FreeTypeError(FontException):
def __init__(self, message, errcode):
self.message = message
self.errcode = errcode
def __str__(self):
return ('%s: %s (%s)' % (self.__class__.__name__, self.message, self._ft_errors.get(self.errcode, 'unknown error')))
def check_and_raise_on_error... |
class Processor():
def __init__(self, backend=ProcessorBackends.NUMPY, output_color: str='RGB'):
self.color_mode = output_color
self.backend = self._initialize_backend(backend)
def process(self, rect, width, height, region, rotation_angle):
return self.backend.process(rect, width, height... |
def batch_bounds_for_packing(lengths):
last_length = 0
count = len(lengths)
result = []
for (i, (length, group)) in enumerate(itertools.groupby(reversed(lengths))):
if ((i > 0) and (length <= last_length)):
raise ValueError('lengths must be decreasing and positive')
result.ex... |
def iter_12(cc_or_eom, k):
if isinstance(cc_or_eom, kccsd_rhf.RCCSD):
cc = cc_or_eom
else:
cc = cc_or_eom._cc
(o, v) = padding_k_idx(cc, kind='split')
kconserv = cc.khelper.kconserv
(yield (o[k],))
for ki in range(cc.nkpts):
for kj in range(cc.nkpts):
kb = kco... |
def test_wrapper_name():
assert (get_name(Wrapper(42)) == 'int')
assert (get_name(Wrapper('eat at joe.')) == 'str')
assert (get_name(Wrapper(str)) == 'str')
assert (get_name(Wrapper(object)) == 'object')
assert (get_name(Wrapper(foo)) == 'foo')
assert (get_name(Wrapper(foo())) == 'foo')
asse... |
def _set_tensor_dict(module_dict, hooks, module, name: str, tensor: torch.Tensor) -> None:
was_buffer = False
out = module_dict['_parameters'].pop(name, None)
if (out is None):
out = module_dict['_buffers'].pop(name, None)
was_buffer = (out is not None)
if (out is None):
out = mo... |
class OutputsCallback(Callback):
def __init__(self, save_dir: Path=Path('./outputs'), layers: List[int]=[(- 1)], output_embeddings: bool=True, output_attentions: bool=False, output_logits: bool=False) -> None:
self.rank_label = uuid.uuid4()
self.output_attentions = output_attentions
self.out... |
def _get_in_video_path(input_videos_dir: Path, video_relative_path: Path) -> Path:
in_video_dir = (input_videos_dir / video_relative_path.parent)
in_video_short_name = video_relative_path.name
in_video_paths = [p for p in in_video_dir.glob((in_video_short_name + '*')) if is_video_path(p)]
if (len(in_vid... |
def add_subcommand(subparsers, parents):
parser = subparsers.add_parser('migrate', parents=parents, help='Migrate a configuration file to the current API.')
parser.add_argument('-c', '--config', action='store', default=get_config_file(), help='Use the specified configuration file (migrates every .py file in thi... |
class ScratchPad(group._Group):
def __init__(self, name='scratchpad', dropdowns: (list[config.DropDown] | None)=None, label='', single=False):
group._Group.__init__(self, name, label=label)
self._dropdownconfig = ({dd.name: dd for dd in dropdowns} if (dropdowns is not None) else {})
self.dro... |
def load_inferred_feature(feature_path: str, banning_gifs: set=set()):
_gif_ds = pd.read_csv(feature_path)
_gif_ds['gif_feature'] = _gif_ds['gif_feature'].apply(ast.literal_eval).apply(np.array)
_gif_ds = _gif_ds[_gif_ds['gif_id'].apply((lambda x: (x not in banning_gifs)))]
gif_index_to_id = _gif_ds['gi... |
('PyQt6.QtWidgets.QGraphicsScene.mousePressEvent')
def test_mouse_press_event_when_left_click_over_diff_item_in_edit_mode(mouse_mock, view, item):
txtitem = BeeTextItem('foo bar')
txtitem.exit_edit_mode = MagicMock()
view.scene.addItem(txtitem)
view.scene.edit_item = txtitem
view.scene.itemAt = Magi... |
_db
def test_submit_talk_with_not_valid_conf_topic(graphql_client, user, conference_factory, topic_factory):
graphql_client.force_login(user)
conference = conference_factory(topics=('my-topic',), languages=('it',), submission_types=('talk',), active_cfp=True, durations=('50',), audience_levels=('Beginner',))
... |
def test_contextvar_support() -> None:
var: contextvars.ContextVar[str] = contextvars.ContextVar('test')
var.set('before')
assert (var.get() == 'before')
async def inner() -> None:
task = _core.current_task()
assert (task.context.get(var) == 'before')
assert (var.get() == 'before... |
def parse_args():
parser = argparse.ArgumentParser(description='Translate using existing NMT models', usage='translator.py [<args>] [-h | --help]')
parser.add_argument('--input', type=str, required=True, nargs=2, help='Path of input file')
parser.add_argument('--output', type=str, required=True, help='Path ... |
def handle_netif_receive_skb(event_info):
global of_count_rx_skb_list
(name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info
if (cpu in net_rx_dic.keys()):
rec_data = {'event_name': 'netif_receive_skb', 'event_t': time, 'skbaddr': skbaddr, 'len': skblen}
event_list = n... |
class MobileNet(nn.Module):
def __init__(self, width_multiplier=1, class_num=100):
super().__init__()
alpha = width_multiplier
self.stem = nn.Sequential(BasicConv2d(3, int((32 * alpha)), 3, padding=1, bias=False), DepthSeperabelConv2d(int((32 * alpha)), int((64 * alpha)), 3, padding=1, bias=... |
def sphinx_build(test_dir, confoverrides=None):
os.chdir('tests/{0}'.format(test_dir))
try:
app = Sphinx(srcdir='.', confdir='.', outdir='_build/text', doctreedir='_build/.doctrees', buildername='text', confoverrides=confoverrides)
app.build(force_all=True)
(yield)
finally:
i... |
class CosineLrUpdaterHook(LrUpdaterHook):
def __init__(self, target_lr=0, **kwargs):
self.target_lr = target_lr
super(CosineLrUpdaterHook, self).__init__(**kwargs)
def get_lr(self, runner, base_lr):
if self.by_epoch:
progress = runner.epoch
max_progress = runner.m... |
def filter_by_size(indices, dataset, max_positions, raise_exception=False):
if (isinstance(max_positions, float) or isinstance(max_positions, int)):
if (hasattr(dataset, 'sizes') and isinstance(dataset.sizes, np.ndarray)):
ignored = indices[(dataset.sizes[indices] > max_positions)].tolist()
... |
def build_dataloader(dataset, imgs_per_gpu, workers_per_gpu, num_gpus=1, dist=True, **kwargs):
shuffle = kwargs.get('shuffle', True)
if dist:
(rank, world_size) = get_dist_info()
if shuffle:
sampler = DistributedGroupSampler(dataset, imgs_per_gpu, world_size, rank)
else:
... |
def create_font(n, param):
ifont = ImageFont.truetype('font.ttf', param[1])
sizes = {}
for c in param[0]:
sizes[c] = create_character(n, c, ifont)
print(('const PROGMEM struct font_character font%d[] = {' % n))
for c in param[0]:
print(('{%d, %d, %d, %d, font%d_%02x},' % (ord(c), siz... |
()
('-c', '--checkpoint', required=True)
('-o', '--output_dir', required=True)
('-d', '--device', default='cuda:0')
def main(checkpoint, output_dir, device):
if os.path.exists(output_dir):
click.confirm(f'Output path {output_dir} already exists! Overwrite?', abort=True)
pathlib.Path(output_dir).mkdir(pa... |
def decrypt_object(d):
objects = dict()
if (d is None):
return objects
if (d.get('name') in ['Object', 'object']):
return objects
if (d.get('type') in utils.TYPE_CORRESPONDENCE):
return objects
if (d.get('name') not in objects):
objects.update({d.get('name'): d})
... |
class SegmentSequence():
def __init__(self, segments=None):
if isinstance(segments, bytes):
from .parser import FinTS3Parser
parser = FinTS3Parser()
data = parser.explode_segments(segments)
segments = [parser.parse_segment(segment) for segment in data]
... |
def get_synthesizability(molecule):
buyable = get_buyability(molecule)
if buyable:
return 1.0
else:
HOST = '
params = {'smiles': molecule, 'max_depth': 5, 'max_branching': 25, 'expansion_time': 60, 'max_ppg': 100, 'template_count': 1000, 'max_cum_prob': 0.999, 'chemical_property_logi... |
class PipInstall(metaclass=ABCMeta):
def __init__(self, wheel, creator, image_folder) -> None:
self._wheel = wheel
self._creator = creator
self._image_dir = image_folder
self._extracted = False
self.__dist_info = None
self._console_entry_points = None
def _sync(se... |
()
('bulk_file', type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True))
('-restart', '--restart', type=stages, help='The stage the workflow should be restarted from.')
_options
def run(bulk_file: str, skip_stages: Optional[List[str]]=None, end: Optional[str]=None, restart: Optional[str]=None, c... |
class CsvDataset(Dataset):
def __init__(self, input_filename, transforms, img_key, caption_key, sep='\t'):
logging.debug(f'Loading csv data from {input_filename}.')
df = pd.read_csv(input_filename, sep=sep)
self.images = df[img_key].tolist()
self.captions = df[caption_key].tolist()
... |
class SnapshotsServicer(object):
def Create(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def List(self, request, context):
context.set_code(grpc.StatusC... |
def check_version_info(conn, version_table, expected_version):
version_from_table = conn.execute(sa.select((version_table.c.version,))).scalar()
if (version_from_table is None):
version_from_table = 0
if (version_from_table != expected_version):
raise AssetDBVersionError(db_version=version_f... |
class LatexyzInsertPairCommand(sublime_plugin.TextCommand):
def run(self, edit, arg):
left = ('\\\\left' + arg[0].replace('\\', '\\\\'))
right = ('\\\\right' + arg[1].replace('\\', '\\\\'))
lz_settings = sublime.load_settings(lz_settings_file)
d = (1 if lz_settings.get('auto_create_f... |
.parametrize('username,password', users)
.parametrize('issue_id', issues)
.parametrize('project_id', projects)
def test_issue_send_post_email(db, client, username, password, project_id, issue_id):
client.login(username=username, password=password)
issue = Issue.objects.filter(project_id=project_id, id=issue_id)... |
_tf
class TFFunnelModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = ((TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification) if is_tf_available() else ())
pipeline_model_mapping = ({'feature-extraction': ... |
def _run_box(box, client, registry, ca_cert):
(vagrant, vagrant_scp) = _check_vagrant()
if (not vagrant):
print('vagrant command not found')
return
if (not vagrant_scp):
print('vagrant-scp plugin not installed')
return
namespace = 'devtable'
repo_name = ('testrepo%s' ... |
def canonicalize_version(version: Union[(Version, str)], *, strip_trailing_zero: bool=True) -> str:
if isinstance(version, str):
try:
parsed = Version(version)
except InvalidVersion:
return version
else:
parsed = version
parts = []
if (parsed.epoch != 0):
... |
(frozen=True)
class EventPickupNode(ResourceNode):
event_node: EventNode
pickup_node: PickupNode
def create_from(cls, index: int, event_node: EventNode, next_node: PickupNode) -> EventPickupNode:
return cls(event_node.identifier.renamed(f'EventPickup - {event_node.event.long_name} + {next_node.name}... |
class VideoDatasetMultiClips(VideoDataset):
def __loading(self, path, video_frame_indices):
clips = []
segments = []
for clip_frame_indices in video_frame_indices:
clip = self.loader(path, clip_frame_indices)
if (self.spatial_transform is not None):
se... |
def lock_screen(request):
crypt = CryptPwd()
if (request.method == 'GET'):
user = UserProfile.objects.get(username=request.user)
UserProfile.objects.filter(username=request.user).update(login_status=3)
request.session['lock'] = 'lock'
if ('lock_screen' not in request.META.get('HT... |
class Infraction(Enum):
BAN = auto()
KICK = auto()
TIMEOUT = auto()
VOICE_MUTE = auto()
SUPERSTAR = auto()
WARNING = auto()
WATCH = auto()
NOTE = auto()
NONE = auto()
def __str__(self) -> str:
return self.name
async def invoke(self, user: (Member | User), message: dis... |
def test_omitting_none(converter: BaseConverter):
class A():
a: int
b: int = field(init=False)
converter.register_unstructure_hook(A, make_dict_unstructure_fn(A, converter, a=override(), b=override()))
assert (converter.unstructure(A(1)) == {'a': 1})
converter.register_structure_hook(A, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.