code stringlengths 281 23.7M |
|---|
def test_volume_sample_world_v_linear_values(volume: wp.uint64, points: wp.array(dtype=wp.vec3), values: wp.array(dtype=wp.float32)):
tid = wp.tid()
q = points[tid]
p = wp.volume_world_to_index(volume, q)
ones = wp.vec3(1.0, 1.0, 1.0)
values[tid] = wp.dot(wp.volume_sample_v(volume, p, wp.Volume.LINE... |
class TestClusterUtilizationOverTimeRange(unittest.TestCase):
('deltacat.utils.resources.ray')
def test_sanity(self, ray_mock):
from deltacat.utils.resources import ClusterUtilizationOverTimeRange
ray_mock.cluster_resources.side_effect = [{'CPU': 32} for _ in range(5)]
ray_mock.available... |
class AdaLayerNorm(nn.Module):
def __init__(self, embedding_dim, num_embeddings):
super().__init__()
self.emb = nn.Embedding(num_embeddings, embedding_dim)
self.silu = nn.SiLU()
self.linear = nn.Linear(embedding_dim, (embedding_dim * 2))
self.norm = nn.LayerNorm(embedding_dim... |
def test_generate_graphql_schema():
out = io.StringIO()
m_open = mock_open()
class TestSchema():
a: int
with patch('api.management.commands.graphql_schema.json.dump') as mock_j, patch('api.management.commands.graphql_schema.graphql_sync') as p, patch('api.management.commands.graphql_schema.open'... |
class MLMPreprocessor(Preprocessor):
def get_input_features(self, example: InputExample, labelled: bool, priming: bool=False, **kwargs) -> InputFeatures:
(input_ids, token_type_ids, block_flag) = self.pvp.encode(example)
attention_mask = ([1] * len(input_ids))
padding_length = (self.wrapper.... |
class testCommandsToCommandFile(unittest.TestCase):
def setUp(self):
self.command_file = '/tmp/cmdfile'
self.timestamp =
self.testhost = 'hosttest.example.com'
self.testauthor = ''
self.test_svc_desc = 'Test Service'
self.test_svc_group = 'TestSVCGroup'
self.... |
class Model(OriginalModel):
def __init__(self, *args, **kwargs):
logger.debug('Initializing %s: (args: %s, kwargs: %s', self.__class__.__name__, args, kwargs)
self.configfile = kwargs.get('configfile', None)
self.lowmem = self.config.get('lowmem', False)
kwargs['input_shape'] = (self... |
class Trainer(TrainerBase):
def __init__(self, args, train_loader=None, val_loader=None, test_loader=None, train=True):
super().__init__(args, train_loader=train_loader, val_loader=val_loader, test_loader=test_loader, train=train)
from cococaption_model import FewVLMCOCOCaption
model_kwargs ... |
def test_kuccsd_openshell():
cell = gto.M(unit='B', a=[[0.0, 6., 6.], [6., 0.0, 6.], [6., 6., 0.0]], mesh=([13] * 3), atom='H 0 0 0\n H 1. 1. 1.\n H 3. 3. 3.', basis=[[0, (1.0, 1.0)], [0, (0.5, 1.0)]], verbose=1, charge=0, spin=1)
nmp = [3, 1, 1]
cell.spin = (cell.spin * 3)... |
def wps_miniprogram_clockin(sid: str):
sio.write('\n\n ---wps---\n\n')
if (len(sid) == 0):
sio.write(': sid, \n\n')
return 0
elif (('*' in sid) or (sid[0] != 'V')):
sio.write(': sid, \n\n')
return 0
clockin_url = '
r = s.get(clockin_url, headers={'sid': sid})... |
class DistillKL(nn.Module):
def __init__(self, T):
super(DistillKL, self).__init__()
self.T = T
def forward(self, y_s, y_t):
p_s = F.log_softmax((y_s / self.T), dim=1)
p_t = F.softmax((y_t / self.T), dim=1)
loss = (F.kl_div(p_s, p_t, reduction='batchmean') * (self.T ** 2)... |
class GameObject(SavesProjectID):
def __init__(self, name='GameObject', parent=None):
self.name = name
self.components = []
self.transform = self.AddComponent(Transform)
if (parent is not None):
self.transform.ReparentTo(parent.transform)
self.tag = Tag(0)
... |
class DataPrep(object):
def __init__(self, raw_df: pd.DataFrame, categorical: list, log: list, mixed: dict, general: list, non_categorical: list, integer: list, type: dict, test_ratio: float):
self.categorical_columns = categorical
self.log_columns = log
self.mixed_columns = mixed
se... |
class Requirement(packaging.requirements.Requirement):
def __init__(self, requirement_string):
super(Requirement, self).__init__(requirement_string)
self.unsafe_name = self.name
project_name = safe_name(self.name)
(self.project_name, self.key) = (project_name, project_name.lower())
... |
class Display(object):
extension_major_opcodes = {}
error_classes = error.xerror_class.copy()
event_classes = event.event_class.copy()
def __init__(self, display=None):
(name, protocol, host, displayno, screenno) = connect.get_display(display)
self.display_name = name
self.defaul... |
def build_token(aud, token_type, build_id, job_id, expiration, instance_keys):
token_data = {'token_type': token_type, 'build_id': build_id, 'job_id': job_id, 'expiration': expiration}
token = generate_bearer_token(aud, ANONYMOUS_SUB, token_data, {}, expiration, instance_keys)
return token |
def do_test(cfg, model):
results = OrderedDict()
for dataset_name in cfg.DATASETS.TEST:
data_loader = build_detection_test_loader(cfg, dataset_name)
evaluator = get_evaluator(cfg, dataset_name, os.path.join(cfg.OUTPUT_DIR, 'inference', dataset_name))
results_i = inference_on_dataset(mode... |
def main():
if (not ('debug' in args.save)):
from nasbench_analysis import eval_darts_one_shot_model_in_nasbench as naseval
if (args.search_space == '1'):
search_space = SearchSpace1()
elif (args.search_space == '2'):
search_space = SearchSpace2()
elif (args.search_space == '3'):... |
def plot_hyperparam(hyperparam_to_plot, fig=None, ax_arr=None, big_ax=None, legend=False, dpi=300, figsize=(3, 5.5)):
if ((fig is None) and (ax_arr is None)):
(fig, ax_arr) = plt.subplots(2, 1, dpi=dpi, figsize=figsize)
for ax_ in ax_arr.flatten():
ax_.tick_params(pad=0.1)
if (big_ax is None... |
class RegistrationPendingWidget(TitledWidget):
def __init__(self, view, account_management_interface, verify_bookmark):
super().__init__(view)
config = ExecutionContext.get_context().config
self.add_child(P(view, text=(_('There is a registration pending for email address "%s".') % account_ma... |
class Registration():
def addMetadataFilterFactory(sparkSession, filterFactory):
sparkSession._jvm.io.xskipper.Registration.addMetadataFilterFactory(filterFactory)
def addIndexFactory(sparkSession, indexFactory):
sparkSession._jvm.io.xskipper.Registration.addIndexFactory(indexFactory)
def ad... |
def test_top_down_PoseTrack18_dataset_compatibility():
dataset = 'TopDownPoseTrack18Dataset'
dataset_class = DATASETS.get(dataset)
dataset_class.load_annotations = MagicMock()
dataset_class.coco = MagicMock()
channel_cfg = dict(num_output_channels=17, dataset_joints=17, dataset_channel=[[0, 1, 2, 3,... |
def _parse_freqplot_args(*args):
(syslist, plotstyle, omega, other) = ([], [], None, {})
i = 0
while (i < len(args)):
if isinstance(args[i], LTI):
syslist.append(args[i])
i += 1
if ((i < len(args)) and isinstance(args[i], str)):
plotstyle.append(ar... |
def rgb(x: ColorType) -> tuple[(float, float, float, float)]:
if isinstance(x, (tuple, list)):
if (len(x) == 4):
alpha = x[(- 1)]
else:
alpha = 1.0
return ((x[0] / 255.0), (x[1] / 255.0), (x[2] / 255.0), alpha)
elif isinstance(x, str):
if x.startswith('#')... |
class TLatin1TextListSpec(TestCase):
def test_read(self):
spec = Latin1TextListSpec('name')
self.assertEqual(spec.read(None, None, b'\x00xxx'), ([], b'xxx'))
self.assertEqual(spec.read(None, None, b'\x01foo\x00'), ([u'foo'], b''))
self.assertEqual(spec.read(None, None, b'\x01\x00'), ... |
class Log(Gtk.TextView):
__gtype_name__ = 'Log'
def __init__(self):
super().__init__()
self.text_buffer = self.get_buffer()
self.props.editable = False
self.props.monospace = True
self.props.wrap_mode = Gtk.WrapMode.WORD_CHAR
self.props.hexpand = True
self... |
def _execute(args):
pth = path.abspath(args.function_dir)
cfg = config.Config(pth, args.config, role=args.role, variables=args.variables)
if args.s3_bucket:
cfg.set_s3(args.s3_bucket, args.s3_key)
if args.no_virtualenv:
venv = False
elif args.virtualenv:
venv = args.virtualen... |
def _generate_positive_items(user_pos_dict):
if (not isinstance(user_pos_dict, dict)):
raise TypeError("'user_pos_dict' must be a dict.")
if (not user_pos_dict):
raise ValueError("'user_pos_dict' cannot be empty.")
(users_list, pos_items_list) = ([], [])
user_pos_len = []
for (user, ... |
class _Typedef(object):
base = 0
both = None
item = 0
kind = None
leng = None
refs = None
type = None
vari = None
xtyp = None
def __init__(self, **kwds):
self.reset(**kwds)
def __lt__(self, unused):
return True
def __repr__(self):
return repr(self.... |
class DDPG():
def __init__(self, state_space, action_dim):
self.name = 'DDPG'
self.sess = tf.Session()
self.state_space = state_space
self.action_dim = action_dim
self.ac_network = ActorCriticNetwork(self.sess, self.state_space, self.action_dim)
self.replay_buffer = R... |
def log_Phi(x):
if isinstance(x, np.ndarray):
result = []
for value in x:
if (value > 5):
result.append((- sps.norm.sf(value)))
else:
result.append(sps.norm.logcdf(value))
result = np.array(result)
elif (x > 5):
result = (- ... |
class BinaryPayloadBuilder():
def __init__(self, payload=None, byteorder=Endian.LITTLE, wordorder=Endian.BIG, repack=False):
self._payload = (payload or [])
self._byteorder = byteorder
self._wordorder = wordorder
self._repack = repack
def _pack_words(self, fstring, value):
... |
def polymer_species(subunit, site1, site2, size, closed=False):
_verify_sites(subunit, site1, site2)
if (size <= 0):
raise ValueError('size must be an integer greater than 0')
if (size == 1):
polymer = subunit({site1: None, site2: None})
elif (size == 2):
polymer = (subunit({site... |
class NumberParsingTestCase(unittest.TestCase):
def test_can_parse_decimals(self):
assert (decimal.Decimal('1099.98') == numbers.parse_decimal('1,099.98', locale='en_US'))
assert (decimal.Decimal('1099.98') == numbers.parse_decimal('1.099,98', locale='de'))
assert (decimal.Decimal('1099.98')... |
def save_checkpoint(filepath, obj, num_ckpt_keep=5):
name = re.match('(do|g)_\\d+', pathlib.Path(filepath).name).group(1)
ckpts = sorted(pathlib.Path(filepath).parent.glob(f'{name}_*'))
if (len(ckpts) > num_ckpt_keep):
[os.remove(c) for c in ckpts[:(- num_ckpt_keep)]]
print('Saving checkpoint to... |
def _deprecate(fn: Callable) -> Callable:
name = fn.__name__
msg = build_deprecation_message(f'The function ops.functional.{name}', '1.0', info=f'It was moved to loss.functional.{name}. See for details')
(fn)
def wrapper(*args, **kwargs):
warnings.warn(msg)
return fn(*args, **kwargs)
... |
class TestHashable(TestNameCheckVisitorBase):
_passes()
def test_type(self):
from typing import Hashable, Type
from typing_extensions import Protocol
class MyHashable(Protocol):
def __hash__(self) -> int:
raise NotImplementedError
def want_hash(h: Hash... |
def get_quantsim_artifacts(base_model):
base_model = prepare_model(base_model)
dummy_input = np.random.rand(1, 16, 16, 3)
sim = QuantizationSimModel(model=base_model, quant_scheme='tf_enhanced', rounding_mode='nearest', default_output_bw=8, default_param_bw=8, in_place=False, config_file=None)
sim.train... |
class ManniStyle(Style):
name = 'manni'
background_color = '#f0f3f3'
styles = {Whitespace: '#bbbbbb', Comment: 'italic #0099FF', Comment.Preproc: 'noitalic #009999', Comment.Special: 'bold', Keyword: 'bold #006699', Keyword.Pseudo: 'nobold', Keyword.Type: '#007788', Operator: '#555555', Operator.Word: 'bold... |
def registry_services():
return {'blobuploadcleanupworker': {'autostart': 'true'}, 'buildlogsarchiver': {'autostart': 'true'}, 'builder': {'autostart': 'true'}, 'chunkcleanupworker': {'autostart': 'true'}, 'expiredappspecifictokenworker': {'autostart': 'true'}, 'exportactionlogsworker': {'autostart': 'true'}, 'gcwo... |
class TrainDataset(Dataset):
def __init__(self, args, raw_datasets, cache_root):
self.raw_datasets = raw_datasets
cache_path = os.path.join(cache_root, 'russ_train.cache')
if (os.path.exists(cache_path) and args.dataset.use_cache):
self.extended_data = torch.load(cache_path)
... |
def _prep_metadata(md_sect, path):
if (not set(md_sect).issuperset(metadata_required_fields)):
missing = (metadata_required_fields - set(md_sect))
raise ConfigError(('Required fields missing: ' + '\n'.join(missing)))
res = LoadedConfig()
res.module = md_sect.get('module')
if (not all([m.... |
class DeformRoIPoolPack(DeformRoIPool):
def __init__(self, output_size, output_channels, deform_fc_channels=1024, spatial_scale=1.0, sampling_ratio=0, gamma=0.1):
super(DeformRoIPoolPack, self).__init__(output_size, spatial_scale, sampling_ratio, gamma)
self.output_channels = output_channels
... |
class TestPrunetraceback():
def test_custom_repr_failure(self, pytester: Pytester) -> None:
p = pytester.makepyfile('\n import not_exists\n ')
pytester.makeconftest('\n import pytest\n def pytest_collect_file(file_path, parent):\n return MyFile.... |
def test_channel_cleared_after_two_unlocks():
(our_model, _) = create_model(balance=700, num_pending_locks=1)
(partner_model, partner_key1) = create_model(balance=700, num_pending_locks=1)
channel_state = create_channel_from_models(our_model, partner_model, partner_key1)
block_number = 1
block_hash ... |
def make_url(ext: str, *, file_checksum: (str | None)=None, metadata_checksum: (str | None)=None, hashes: (dict[(str, str)] | None)=None, metadata: ((dict[(str, str)] | str) | None)=None) -> Link:
url = f'
if (not hashes):
file_checksum = (file_checksum or make_checksum())
url += f'#sha256={file... |
class GitEventHandler(BaseEventHandler):
def __init__(self, gitdir, source, modified_by, auto_init=False, ignore_errors=False):
BaseEventHandler.__init__(self)
self.gitdir = gitdir
self.modified_by = modified_by
self.source = source
self.messages = []
self.ignore_erro... |
class C1():
x = attr.ib(validator=attr.validators.instance_of(int))
y = attr.ib()
def method(self):
return self.x
def classmethod(cls):
return 'clsmethod'
def staticmethod():
return 'staticmethod'
def my_class(self):
return __class__
def my_super(self):
... |
class LastConv(Transition):
def __init__(self, in_channels, out_channels, num_inputs, kernel_size=3, **kwargs):
super().__init__(in_channels, out_channels)
self.num_inputs = num_inputs
self.conv_out = ConvModule(in_channels, out_channels, kernel_size, padding=((kernel_size - 1) // 2), **kwar... |
.parametrize('ngood, nbad, nsample, size', [(np.array(10, dtype=np.int64), np.array(20, dtype=np.int64), np.array(5, dtype=np.int64), None), (np.array(10, dtype=np.int64), np.array(20, dtype=np.int64), np.array(5, dtype=np.int64), []), (np.full((1, 2), 10, dtype=np.int64), np.array(20, dtype=np.int64), np.array(5, dtyp... |
def test_catalog_loader(tmpdir):
tmpcatalog = os.path.join(tmpdir, 'my_catalog.xosc')
cf = xosc.CatalogFile()
cf.create_catalog(tmpcatalog, 'TrajectoryCatalog', 'My first miscobject catalog', 'Mandolin')
orig = xosc.Controller('my_controller', xosc.Properties())
cf.add_to_catalog(orig)
cf.dump()... |
def atomic_write(filepath, binary=False, fsync=False):
tmppath = (filepath + '~')
while os.path.isfile(tmppath):
tmppath += '~'
try:
with open(tmppath, ('wb' if binary else 'w')) as file:
(yield file)
if fsync:
file.flush()
os.fsync(fil... |
(frozen=False)
class CollaborationState():
optimizer_step: int
samples_accumulated: int
target_batch_size: int
num_peers: int
eta_next_step: float
next_fetch_time: float
def should_perform_step(self):
return ((self.samples_accumulated >= self.target_batch_size) or (hivemind.get_dht_t... |
def _gen_rhf_response(mf, mo_coeff=None, mo_occ=None, singlet=None, hermi=0, max_memory=None):
assert (isinstance(mf, hf.RHF) and (not isinstance(mf, (uhf.UHF, rohf.ROHF))))
if (mo_coeff is None):
mo_coeff = mf.mo_coeff
if (mo_occ is None):
mo_occ = mf.mo_occ
mol = mf.mol
if isinstan... |
class DiscordMocksTests(unittest.TestCase):
def test_mock_role_default_initialization(self):
role = helpers.MockRole()
self.assertIsInstance(role, discord.Role)
self.assertEqual(role.name, 'role')
self.assertEqual(role.position, 1)
self.assertEqual(role.mention, '&role')
... |
def evaluation_plot(csv_file, criteria, label, save_name, val=True):
df = pd.read_csv(csv_file)
dict_criteria = {}
dict_criteria['ET'] = [x for x in df[(criteria + '_ET')] if (not np.isnan(x))][:(- 5)]
dict_criteria['TC'] = [x for x in df[(criteria + '_TC')] if (not np.isnan(x))][:(- 5)]
dict_criter... |
def _get_build_num(args):
search = reversed(run_conda_search('pypdfium2_raw', 'pypdfium2-team'))
if args.is_literal_latest:
assert (args.pdfium_ver > max([int(d['version']) for d in search])), 'Literal latest must resolve to a new version. This is done to avoid rebuilds without new version in scheduled ... |
class ChannelGate(nn.Module):
def __init__(self, in_channels, num_gates=None, return_gates=False, gate_activation='sigmoid', reduction=16, layer_norm=False):
super(ChannelGate, self).__init__()
if (num_gates is None):
num_gates = in_channels
self.return_gates = return_gates
... |
def test_connection():
con = pyodrx.Connection(1, 2, pyodrx.ContactPoint.start, 5)
con.add_lanelink(1, (- 1))
con.add_lanelink(2, (- 2))
prettyprint(con.get_element(pyodrx.JunctionType.direct))
con2 = pyodrx.Connection(1, 2, pyodrx.ContactPoint.start, 5)
con2.add_lanelink(1, (- 1))
con2.add_... |
class HighResolutionModule(nn.Module):
def __init__(self, num_branches, blocks, num_blocks, num_inchannels, num_channels, fuse_method, multi_scale_output=True):
super(HighResolutionModule, self).__init__()
self._check_branches(num_branches, blocks, num_blocks, num_inchannels, num_channels)
s... |
class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
def find_user_password(self, realm, authuri):
(user, password) = HTTPPasswordMgr.find_user_password(self, realm, authuri)
if (user is not None):
return (user, password)
return HTTPPasswordMgr.find_user_password(self, None, a... |
class TwoStageCNNGeometric(CNNGeometric):
def __init__(self, fr_feature_size=15, fr_kernel_sizes=[7, 5], fr_channels=[128, 64], feature_extraction_cnn='vgg', feature_extraction_last_layer='', return_correlation=False, normalize_features=True, normalize_matches=True, batch_normalization=True, train_fe=False, use_cud... |
_required
def plugin_create(request):
if (request.method == 'POST'):
form = PluginForm(request.POST, request.FILES)
form.fields['owners'].queryset = User.objects.exclude(pk=request.user.pk).order_by('username')
if form.is_valid():
plugin = form.save(commit=False)
plug... |
def convert2panoptic(cityscapesPath=None, outputFolder=None, useTrainId=False, setNames=['val', 'train', 'test']):
if (cityscapesPath is None):
if ('CITYSCAPES_DATASET' in os.environ):
cityscapesPath = os.environ['CITYSCAPES_DATASET']
else:
cityscapesPath = os.path.join(os.pa... |
class check_transitive_modifications(log_queries):
def __init__(self):
filters = ['^DELETE.+IN \\(SELECT.+$', '^UPDATE.+IN \\(SELECT.+$']
super(check_transitive_modifications, self).__init__(query_filters=filters)
def __exit__(self, exc_type, exc_val, exc_tb):
super(check_transitive_modi... |
def test_shell_commmand_complete_in_path(cmd2_app, request):
test_dir = os.path.dirname(request.module.__file__)
text = os.path.join(test_dir, 's')
line = 'shell {}'.format(text)
endidx = len(line)
begidx = (endidx - len(text))
expected = os.path.join(test_dir, ('scripts' + os.path.sep))
fir... |
class INT(IntEnum):
IRC40KSTBIF = (1 << 0)
LXTALSTBIF = (1 << 1)
IRC8MSTBIF = (1 << 2)
HXTALSTBIF = (1 << 3)
PLLSTBIF = (1 << 4)
PLL1STBIF = (1 << 5)
PLL2STBIF = (1 << 6)
CKMIF = (1 << 7)
IRC40KSTBIE = (1 << 8)
LXTALSTBIE = (1 << 9)
IRC8MSTBIE = (1 << 10)
HXTALSTBIE = (1 ... |
def generate_instrument_list(inst_loc, user_info=None):
instrument_names = inst_loc.__all__
instrument_download = []
instrument_optional_load = []
instrument_no_download = []
for inst_module in instrument_names:
try:
module = importlib.import_module(''.join(('.', inst_module)), p... |
def plot_repertoires(subsystem, sia, **kwargs):
if (config.REPERTOIRE_DISTANCE != 'GENERALIZED_INTRINSIC_DIFFERENCE'):
raise NotImplementedError('Only REPERTOIRE_DISTANCE = GENERALIZED_INTRINSIC_DIFFERENCE is supported')
cut_subsystem = subsystem.apply_cut(sia.partition)
labels = ['unpartitioned', '... |
class StemDecorator(ChartDecorator, SimpleLegendItem):
def __init__(self, series: QFSeries, key: str=None, marker_props: Mapping[(str, Any)]=None, stemline_props: Mapping[(str, Any)]=None, baseline_props: Mapping[(str, Any)]=None):
ChartDecorator.__init__(self, key)
SimpleLegendItem.__init__(self)
... |
class Gauge(gui.Svg):
def __init__(self, width, height, _min, _max):
super(Gauge, self).__init__(width=width, height=height)
self.width = width
self.height = height
self.min = _min
self.max = _max
self.scale_angle_range = ((math.pi * 2) - 1.0)
self.scale_value... |
def subfinder(mylist, pattern):
matches = []
indices = []
for (idx, i) in enumerate(range(len(mylist))):
if ((mylist[i] == pattern[0]) and (mylist[i:(i + len(pattern))] == pattern)):
matches.append(pattern)
indices.append(idx)
if matches:
return (matches[0], indic... |
class DeferredGeneratorList():
def __init__(self, generator):
self.gen = generator
self._elements = []
def __eq__(self, other):
return (list(self) == other)
def __getitem__(self, key) -> Any:
if (not isinstance(key, (int, slice))):
raise TypeError('Key must be eit... |
class Mssql():
ERROR_ACCOUNT_IS_DISABLED = 'Reason: The account is disabled'
ERROR_ACCOUNT_INVALID = 'Login failed for user '
ERROR_UNTRUSTED_DOMAIN = 'The login is from an untrusted domain and cannot be used with Windows authentication.'
ERROR_UNABLE_TO_CONNECT = 'Unable to connect:'
MS2019_BANNER ... |
def simple_run(learner, n):
def get_goal(learner):
if hasattr(learner, 'nsamples'):
return (lambda lrn: (lrn.nsamples > n))
else:
return (lambda lrn: (lrn.npoints > n))
def goal():
if isinstance(learner, BalancingLearner):
return get_goal(learner.learn... |
def preprocess_Youtube2Text(base_path):
os.makedirs(base_path, exist_ok=True)
url = '
refs_pickle = os.path.join(base_path, 'refs.pkl')
if (not os.path.exists(refs_pickle)):
wget.download(url, out=refs_pickle)
url = '
mapping_txt = os.path.join(base_path, 'youtube_mapping.txt')
if (n... |
class BatchSampler(BaseSampler):
def start_worker(self):
if (singleton_pool.n_parallel > 1):
singleton_pool.run_each(worker_init_tf)
parallel_sampler.populate_task(self.algo.env, self.algo.policy)
if (singleton_pool.n_parallel > 1):
singleton_pool.run_each(worker_init... |
def attach_as_old(c, filename):
c.execute('ATTACH DATABASE ? AS old', (filename,))
c.execute('BEGIN TRANSACTION')
try:
try:
(yield)
except:
try:
c.execute('ROLLBACK')
except sqlite3.OperationalError:
pass
raise
... |
(short_help='Update Python distributions')
('names', required=True, nargs=(- 1))
('--dir', '-d', 'directory', help='The directory in which distributions reside')
_context
def update(ctx: click.Context, *, names: tuple[(str, ...)], directory: (str | None)):
app: Application = ctx.obj
manager = app.get_python_man... |
def test_session_env_lazy(monkeypatch, gdalenv):
monkeypatch.setenv('AWS_ACCESS_KEY_ID', 'id')
monkeypatch.setenv('AWS_SECRET_ACCESS_KEY', 'key')
monkeypatch.setenv('AWS_SESSION_TOKEN', 'token')
expected = {'AWS_ACCESS_KEY_ID': 'id', 'AWS_SECRET_ACCESS_KEY': 'key', 'AWS_SESSION_TOKEN': 'token'}
with... |
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, framework: Optional[str]=None, revision: Optional[st... |
def mesh_query_point_loss(mesh: wp.uint64, query_points: wp.array(dtype=wp.vec3), projected_points: wp.array(dtype=wp.vec3), loss: wp.array(dtype=float)):
tid = wp.tid()
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
max_dist = 10012.0
p = query_points[tid]
... |
class Effect6307(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'thermalDamage', src.getModifiedItemAttr('shipBonusMD1'), skill='Minmatar Destroyer', **kwargs) |
class RwPooledEmbeddingSharding(BaseRwEmbeddingSharding[(EmbeddingShardingContext, KeyedJaggedTensor, torch.Tensor, torch.Tensor)]):
def create_input_dist(self, device: Optional[torch.device]=None) -> BaseSparseFeaturesDist[KeyedJaggedTensor]:
num_features = self._get_num_features()
feature_hash_siz... |
def evaluate_webnlg_challenge_2017(references_s, preds):
tmp_file_name = 'webnlg_challenge_2017_tmp4eval.txt'
with open(tmp_file_name, 'w') as tmp_file:
for pred in preds:
print(pred, file=tmp_file)
os.system('bash utils/process/general/dart_lib/run_eval_on_webnlg.sh {}'.format(tmp_file_... |
class PublicKey(Key):
def __init__(self, verifying_key, network=BitcoinMainNet, *args, **kwargs):
super(PublicKey, self).__init__(*args, network=network, **kwargs)
self._verifying_key = verifying_key
self.x = verifying_key.pubkey.point.x()
self.y = verifying_key.pubkey.point.y()
... |
(frozen=True)
class Preset(BitPackValue):
name: str
uuid: uuid_module.UUID
description: str
game: RandovaniaGame
configuration: BaseConfiguration
def as_json(self) -> dict:
return {'name': self.name, 'uuid': str(self.uuid), 'description': self.description, 'game': self.game.value, 'confi... |
def test_vec2_transform(test, device, n):
dest = wp.zeros(n=n, dtype=wp.vec2, device=device)
c = np.array((1.0, 2.0))
m = np.array(((3.0, (- 1.0)), (2.5, 4.0)))
wp.launch(transform_vec2, dim=n, inputs=[dest, m, c], device=device)
test.assertTrue(np.array_equal(dest.numpy(), np.tile((m c), (n, 1)))) |
class ImagePyramid(ComplexObject):
def __init__(self, edge_sizes: Sequence[int], num_steps: Union[(Sequence[int], int)], edge: Union[(Sequence[str], str)]='short', interpolation_mode: str='bilinear', resize_targets: Collection[loss.Loss]=()):
self._levels = self.build_levels(edge_sizes, num_steps, edge)
... |
def _validate_geometry_input(geoms, ids=None, valid_geometry_types=None):
if isinstance(geoms, (geopandas.GeoSeries | geopandas.GeoDataFrame)):
geoms = geoms.geometry
if (ids is None):
ids = geoms.index
ids = np.asarray(ids)
geom_types = set(geoms.geom_type)
if (v... |
def start_end_collate(batch):
batch_meta = [e['meta'] for e in batch]
model_inputs_keys = batch[0]['model_inputs'].keys()
batched_data = dict()
for k in model_inputs_keys:
if (k == 'span_labels'):
batched_data[k] = [dict(spans=e['model_inputs']['span_labels']) for e in batch]
... |
def test_metadata_dictionary_keys():
package = package_file.PackageFile.from_filename(helpers.SDIST_FIXTURE, None)
assert (set(package.metadata_dictionary()) == {'name', 'version', 'filetype', 'pyversion', 'metadata_version', 'summary', 'home_page', 'author', 'author_email', 'maintainer', 'maintainer_email', 'l... |
def _get_unsharded_module_names_helper(model: torch.nn.Module, path: str, unsharded_module_names: Set[str]) -> bool:
sharded_children = set()
for (name, child) in model.named_children():
curr_path = (path + name)
if isinstance(child, ShardedModule):
sharded_children.add(name)
... |
def make_sequence(feats, feats_aux):
inputs = [tf.train.Feature(float_list=tf.train.FloatList(value=feat)) for feat in feats]
inputs_aux = [tf.train.Feature(float_list=tf.train.FloatList(value=feat_aux)) for feat_aux in feats_aux]
feature_list = {'inputs': tf.train.FeatureList(feature=inputs), 'inputs_aux':... |
class DCUN_TFC_FiLM_LaSAFT(DenseCUNet_FiLM):
def __init__(self, n_fft, input_channels, internal_channels, n_blocks, n_internal_layers, first_conv_activation, last_activation, t_down_layers, f_down_layers, kernel_size_t, kernel_size_f, bn_factor, min_bn_units, tfc_tdf_bias, tfc_tdf_activation, num_tdfs, dk, control_... |
class RagRayDistributedRetriever(RagRetriever):
def __init__(self, config, question_encoder_tokenizer, generator_tokenizer, retrieval_workers, index=None):
if ((index is not None) and index.is_initialized() and (len(retrieval_workers) > 0)):
raise ValueError("When using Ray for distributed fine-... |
def plot_losses(losses: Union[(nn.Module, List[nn.Module])], visdom_server: Optional['visdom.Visdom']=None, env: Optional[str]=None, win: Optional[str]=None, title: str='') -> Any:
if ((visdom_server is None) and visdom_connected()):
visdom_server = vis[(- 1)]
if ((not visdom_server) or (not visdom_serv... |
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
cand_indexes = []
for (i, token) in enumerate(tokens):
if ((token == '[CLS]') or (token == '[SEP]')):
continue
cand_indexes.append(i)
rng.shuffle(cand_indexes)
output_tokens =... |
def with_progress(iterable, desc=None, total=None, leave=True):
try:
from tqdm import tqdm
def _it(iterable, desc, total, leave):
if (total is None):
try:
total = len(iterable)
except Exception:
total = 0
... |
class UserReal():
def __init__(self, config):
with open(config.restaurants_info_dict_path, 'r') as f:
self.restaurants_info_dict = json.load(f)
self.business_info_dict = None
self.user_name = None
def init_episode(self, user_name, business_name):
self.business_info_di... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.