code stringlengths 281 23.7M |
|---|
class Effect6734(BaseEffect):
type = ('active', 'gang')
def handler(fit, module, context, projectionRange, **kwargs):
for x in range(1, 5):
if module.getModifiedChargeAttr('warfareBuff{}ID'.format(x)):
value = module.getModifiedItemAttr('warfareBuff{}Value'.format(x))
... |
def test_annotate_output_dir(testdir):
script = testdir.makepyfile(SCRIPT)
result = testdir.runpytest('-v', f'--cov={script.dirpath()}', ('--cov-report=annotate:' + DEST_DIR), script)
result.stdout.fnmatch_lines(['*- coverage: platform *, python * -*', ('Coverage annotated source written to dir ' + DEST_DIR... |
class QlOsUefi(QlOs):
type = QL_OS.UEFI
def __init__(self, ql: Qiling):
super().__init__(ql)
self.entry_point = 0
self.running_module: str
self.smm: SmmEnv
self.heap: QlMemoryHeap
self.on_module_enter: MutableSequence[Callable[([str], bool)]] = []
self.on_... |
class ValueTrigger(_TriggerType):
def __init__(self, name, delay, conditionedge, valuecondition, triggeringpoint='start'):
self.name = name
if (triggeringpoint not in ['start', 'stop']):
raise ValueError('not a valid triggering point, valid start or stop')
if (triggeringpoint == ... |
def init():
if (QWebEngineUrlScheme is not None):
assert (not QWebEngineUrlScheme.schemeByName(_QUTE).name())
scheme = QWebEngineUrlScheme(_QUTE)
scheme.setFlags((QWebEngineUrlScheme.Flag.LocalScheme | QWebEngineUrlScheme.Flag.LocalAccessAllowed))
QWebEngineUrlScheme.registerScheme(s... |
class Conv2dBlock_my(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, stride, padding=0, norm='none', activation='relu', pad_type='zero'):
super(Conv2dBlock_my, self).__init__()
self.use_bias = True
if (pad_type == 'reflect'):
self.pad = nn.ReflectionPad2d(paddi... |
class PetitionCreationStep1(forms.Form):
title = forms.CharField(max_length=200)
def clean_title(self):
title = self.cleaned_data.get('title')
filters = {'title': title}
if self.owned_by_org:
org = Organization.objects.get(slugname=self.orgslugname)
filters.update... |
class LazyProxy():
__slots__ = ['_func', '_args', '_kwargs', '_value', '_is_cache_enabled', '_attribute_error']
if TYPE_CHECKING:
_func: Callable[(..., Any)]
_args: tuple[(Any, ...)]
_kwargs: dict[(str, Any)]
_is_cache_enabled: bool
_value: Any
_attribute_error: (... |
class FP16Optimizer(_FP16OptimizerMixin, optim.FairseqOptimizer):
def __init__(self, args, params, fp32_optimizer, fp32_params):
super().__init__(args)
self.fp16_params = params
self.fp32_optimizer = fp32_optimizer
self.fp32_params = fp32_params
if (getattr(args, 'fp16_scale_... |
def average_state_dicts(state_dicts: List[Dict[(str, torch.Tensor)]]):
new_sd = {}
for k in state_dicts[0].keys():
tensors = [sd[k] for sd in state_dicts]
new_t = (sum(tensors) / len(tensors))
assert isinstance(new_t, torch.Tensor)
new_sd[k] = new_t
return new_sd |
def lih_hamiltonian():
geometry = [('Li', (0.0, 0.0, 0.0)), ('H', (0.0, 0.0, 1.45))]
active_space_start = 1
active_space_stop = 3
molecule = MolecularData(geometry, 'sto-3g', 1, description='1.45')
molecule.load()
molecular_hamiltonian = molecule.get_molecular_hamiltonian(occupied_indices=range(... |
class NonNegativeParametrizer(nn.Module):
def __init__(self, minimum: float=0.0, eps: float=Consts.Eps):
super().__init__()
minimum = float(minimum)
eps = float(eps)
self.register_buffer('eps', torch.Tensor([(eps ** 2)]))
bound = ((minimum + (eps ** 2)) ** 0.5)
self.l... |
class BatchManager(object):
def __init__(self, data, batch_size):
self.batch_data = self.sort_and_pad(data, batch_size)
self.len_data = len(self.batch_data)
def sort_and_pad(self, data, batch_size):
num_batch = int(math.ceil((len(data) / batch_size)))
sorted_data = sorted(data, k... |
class RecallSessionMetricComputation(RecMetricComputation):
def __init__(self, *args: Any, session_metric_def: SessionMetricDef, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._add_state(NUM_TRUE_POS, torch.zeros(self._n_tasks, dtype=torch.double), add_window_state=True, dist_reduce_... |
def main(args):
coverage_path = os.path.abspath(args[0])
coverage_dir = ((coverage_path + '.') + str(random.getrandbits(64)))
mkdir_p(coverage_dir)
env = os.environ.copy()
env['GCOV_PREFIX'] = coverage_dir
subprocess.check_call(args[1:], env=env)
arch_path = (coverage_dir + '.archive')
w... |
def build_cli_parser(description='Red Canary example script'):
parser = argparse.ArgumentParser(description=description)
parser.add_argument('--profile', type=str, action='store', help='The credentials.response profile to use.')
parser.add_argument('--prefix', type=str, action='store', help='Output filename... |
class DictionaryConfig(AppConfig):
name = 'dictionary'
verbose_name = _('Dictionary')
def ready(self):
import dictionary.signals
DOMAIN = 'xyzsozluk.com'
PROTOCOL = '
FROM_EMAIL = ''
TOPICS_PER_PAGE_DEFAULT = 50
ENTRIES_PER_PAGE_DEFAULT = 10
ENTRIES_PER_PAGE_PROFILE = 15
... |
class TestPauliBasis(unittest.TestCase):
X = numpy.array([[0, 1], [1, 0]])
Y = numpy.array([[0, (- 1j)], [1j, 0]])
Z = numpy.array([[1, 0], [0, (- 1)]])
def assertMatricesAlmostEqual(self, lhs, rhs, places=None):
self.assertEqual(lhs.shape, rhs.shape, 'Marix shapes differ: {} vs {}'.format(lhs, ... |
class TransitionExperience(object):
def __init__(self, prob_state, all_state, action, reward, **kwargs):
self.prob_state = prob_state
self.all_state = all_state
self.action = action
self.reward = reward
for (k, v) in six.iteritems(kwargs):
setattr(self, k, v) |
class MegaCrypto():
def base64_decode(data):
data = to_bytes(data, 'ascii')
data += (b'=' * ((- len(data)) % 4))
return base64.b64decode(data, b'-_')
def base64_encode(data):
return base64.b64encode(data, b'-_')
def a32_to_bytes(a):
return struct.pack('>{}I'.format(le... |
class VanillaDQN(BaseAgent):
def __init__(self, cfg):
super().__init__(cfg)
self.cfg = cfg
self.env_name = cfg['env']['name']
self.agent_name = cfg['agent']['name']
self.env = {'Train': make_env(cfg['env']['name'], max_episode_steps=int(cfg['env']['max_episode_steps'])), 'Tes... |
def unannotate_value(origin: Value, extension: Type[ExtensionT]) -> Tuple[(Value, Sequence[ExtensionT])]:
if (not isinstance(origin, AnnotatedValue)):
return (origin, [])
matches = [metadata for metadata in origin.metadata if isinstance(metadata, extension)]
if (matches and all_of_type(matches, Exte... |
class NeighboringStreetOrientationDeviation():
def __init__(self, gdf):
self.gdf = gdf
self.orientation = gdf.geometry.apply(self._orient)
(inp, res) = gdf.sindex.query_bulk(gdf.geometry, predicate='intersects')
itself = (inp == res)
inp = inp[(~ itself)]
res = res[(~... |
class AMSGrad(OptimizationAlgorithm):
def __init__(self, **kwargs):
default_parameters = {'learning_rate': 0.001, 'beta1': 0.9, 'beta2': 0.999, 'eps': 1e-07}
restart_variables = {'V': 0.0, 'S': 0.0, 'S_hat': 0.0}
super(self.__class__, self).__init__(alg_default_parameters=default_parameters,... |
class GPT2OnnxConfig(OnnxConfigWithPast):
def __init__(self, config: PretrainedConfig, task: str='default', patching_specs: List[PatchingSpec]=None, use_past: bool=False):
super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
if (not getattr(self._config, 'pad_token_i... |
def test_specific_location(hatch, helpers, temp_dir_data, path_append, dist_name, mocker):
install = mocker.patch('hatch.python.core.PythonManager.install')
install_dir = (((temp_dir_data / 'foo') / 'bar') / 'baz')
helpers.write_distribution(install_dir, dist_name)
dist_dir = (install_dir / dist_name)
... |
class MultipleDatasets(Dataset):
def __init__(self, dbs, make_same_len=True):
print(('=' * 20), 'MultipleDatasets', ('=' * 20))
self.dbs = dbs
self.db_num = len(self.dbs)
self.max_db_data_num = max([len(db) for db in dbs])
self.db_len_cumsum = np.cumsum([len(db) for db in dbs... |
class Xception(nn.Module):
def __init__(self, output_stride=16, in_channels=3, pretrained=True):
super(Xception, self).__init__()
if (output_stride == 16):
(b3_s, mf_d, ef_d) = (2, 1, (1, 2))
if (output_stride == 8):
(b3_s, mf_d, ef_d) = (1, 2, (2, 4))
self.co... |
def test_trajectory_position():
traj = OSC.Trajectory('my traj', False)
traj.add_shape(OSC.Clothoid(0.001, 0.001, 100, OSC.WorldPosition()))
pos = OSC.TrajectoryPosition(traj, 0)
prettyprint(pos)
pos2 = OSC.TrajectoryPosition(traj, 0)
pos3 = OSC.TrajectoryPosition(traj, 0, 3)
assert (pos2 ==... |
class _ViewProviderCfdAnalysis():
def __init__(self, vobj):
vobj.Proxy = self
def getIcon(self):
return ':/icons/fem-cfd-analysis.svg'
def attach(self, vobj):
self.ViewObject = vobj
self.Object = vobj.Object
self.bubbles = None
def updateData(self, obj, prop):
... |
class FitTest(unittest.TestCase):
def test_fit_evaluate_every_n_epochs(self) -> None:
input_dim = 2
train_dataset_len = 8
eval_dataset_len = 4
batch_size = 2
max_epochs = 3
evaluate_every_n_epochs = 1
expected_train_steps_per_epoch = (train_dataset_len / batch... |
def parse_args():
parser = argparse.ArgumentParser('D2 model converter')
parser.add_argument('--source_model', default='', type=str, help='Path or url to the model to convert')
parser.add_argument('--output_model', default='', type=str, help='Path where to save the converted model')
return parser.parse... |
class TestUtils(TestCase):
def test_print_table(self):
(df2, df3) = (df.copy(), df.copy())
df2['F'] = 0
print_table(df2)
df3['A'] = 0
print_table(df3, tablefmt='html', floatfmt='.3f')
def test__postprocess_dataframe(self):
df2 = df.copy()
df2.Values = [1.5... |
def test_git_archive_export_ignore(wd: WorkDir, monkeypatch: pytest.MonkeyPatch) -> None:
wd.write('test1.txt', 'test')
wd.write('test2.txt', 'test')
wd.write('.git/info/attributes', '/test1.txt -export-ignore\n/test2.txt export-ignore')
wd('git add test1.txt test2.txt')
wd.commit()
monkeypatch.... |
def test_weird_key_names_dict_params():
res = substitute_params('SELECT * FROM cust WHERE salesrep = %(n %s ##ame)s', {'n %s ##ame': b'John Doe'})
eq_(res, b"SELECT * FROM cust WHERE salesrep = 'John Doe'")
res = substitute_params('SELECT * FROM cust WHERE salesrep = %(n %s ##ame)s', {'n %s ##ame': 'John Do... |
def test_available_languages(dict_tmp_path, monkeypatch):
for f in ['pl-PL-2-0.bdic', english().remote_filename]:
(dict_tmp_path / f).touch()
monkeypatch.setattr(dictcli, 'language_list_from_api', (lambda : [(lang.code, lang.remote_filename) for lang in langs()]))
languages = sorted(dictcli.availabl... |
_fixtures(WebFixture, DisclosedInputFixture)
def test_validation_of_undisclosed_yet_required_input(web_fixture, disclosed_input_fixture):
fixture = disclosed_input_fixture
wsgi_app = web_fixture.new_wsgi_app(enable_js=True, child_factory=fixture.MyForm.factory())
web_fixture.reahl_server.set_app(wsgi_app)
... |
class ValidateResult(object):
def __init__(self, kind, missing=False, user=None, token=None, oauthtoken=None, robot=None, appspecifictoken=None, signed_data=None, error_message=None, sso_token=None):
self.kind = kind
self.missing = missing
self.error_message = error_message
self.cont... |
def ql_syscall_sysinfo(ql: Qiling, info: int):
fields = ((4660, ql.pack), (8192, ql.pack), (8192, ql.pack), (8192, ql.pack), (, ql.pack), (, ql.pack), (, ql.pack), (0, ql.pack), (0, ql.pack), (0, ql.pack), (1, ql.pack16), (0, ql.pack), (0, ql.pack), (0, ql.pack32))
data = b''.join((pmethod(val) for (val, pmetho... |
def localize_to_utc(time, location):
if isinstance(time, dt.datetime):
if (time.tzinfo is None):
time = pytz.timezone(location.tz).localize(time)
time_utc = time.astimezone(pytz.utc)
else:
try:
time_utc = time.tz_convert('UTC')
except TypeError:
... |
class SuperResTransforms(TransformsConfig):
def __init__(self, opts):
super(SuperResTransforms, self).__init__(opts)
def get_transforms(self):
if (self.opts.resize_factors is None):
self.opts.resize_factors = '1,2,4,8,16,32'
factors = [int(f) for f in self.opts.resize_factors... |
def query_info():
def _got_status(status):
(_, _, _, _, pinfo, sinfo) = _parse_status(status)
_print_info(pinfo, sinfo)
_reactor_stop()
def _portal_running(response):
query_status(_got_status)
def _portal_not_running(fail):
print('Evennia is not running.')
send_in... |
class UNetDecoder(nn.Module):
def __init__(self, encoder: Union[(PlainConvEncoder, ResidualEncoder)], num_classes: int, n_conv_per_stage: Union[(int, Tuple[(int, ...)], List[int])], deep_supervision, nonlin_first: bool=False):
super().__init__()
self.deep_supervision = deep_supervision
self.... |
class ESIM(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_size, embeddings=None, padding_idx=0, dropout=0.5, num_classes=2, device='cpu', isSTS=False):
super(ESIM, self).__init__()
self.vocab_size = vocab_size
self.embedding_dim = embedding_dim
self.hidden_size = hi... |
_env
def fillnodata(image, mask=None, max_search_distance=100.0, smoothing_iterations=0):
if ((mask is None) and isinstance(image, MaskedArray)):
mask = (~ image.mask)
if (not dtypes.is_ndarray(mask)):
raise ValueError('An mask array is required')
if isinstance(image, MaskedArray):
i... |
class SpinOutputter(Thread):
def __init__(self, initial_message):
super(SpinOutputter, self).__init__()
self.previous_line = ''
self.next_line = initial_message
self.running = True
self.daemon = True
def spinning_cursor():
while 1:
for cursor in '|/-\\... |
.unit()
class TestFDCapture():
def test_simple(self, tmpfile):
fd = tmpfile.fileno()
cap = capture.FDCapture(fd)
data = b'hello'
os.write(fd, data)
pytest.raises(AssertionError, cap.snap)
cap.done()
cap = capture.FDCapture(fd)
cap.start()
os.wr... |
class Model(object):
def __init__(self, config):
self.config = config
self.lr = config['lr']
self.char_dim = config['char_dim']
self.lstm_dim = config['lstm_dim']
self.num_tags = 2
self.num_chars = config['num_char']
self.global_step = tf.Variable(0, trainable... |
def parse_question_answers(response):
vqa_data = re.findall('\\{.*?\\}', response)
for json_string in vqa_data:
json_string = json_string.replace('\t', ' ').replace('\n', ' ')
json_string = json_string.replace(',}', '}')
json_string = json_string.replace('`', '"').replace('\', "', '", "'... |
def make_py_pkg_info(context: Context, pkg_dir: Path) -> PackageInfo:
with context.cd(pkg_dir):
proj_metadata = json.loads(ensure_result(context, 'hatch project metadata').stdout)
return PackageInfo(name=proj_metadata['name'], path=pkg_dir, language='py', version=proj_metadata['version']) |
class LaSOTVideo(Video):
def __init__(self, name, root, video_dir, init_rect, img_names, gt_rect, attr, absent, load_img=False):
super(LaSOTVideo, self).__init__(name, root, video_dir, init_rect, img_names, gt_rect, attr, load_img)
self.absent = np.array(absent, np.int8)
def load_tracker(self, p... |
.parametrize('case', [CaseConnectInToWireComp, CaseConnectBitsConstToOutComp, CaseConnectConstToOutComp, CaseConnectBitSelToOutComp, CaseConnectSliceToOutComp, CaseBitSelOverBitSelComp, CaseBitSelOverPartSelComp, CasePartSelOverBitSelComp, CasePartSelOverPartSelComp])
def test_verilog_structural_L1(case):
run_test(... |
class HyperParameters():
def parse(self, unknown_arg_ok=False):
parser = ArgumentParser()
parser.add_argument('--benchmark', action='store_true')
parser.add_argument('--no_amp', action='store_true')
parser.add_argument('--static_root', help='Static training data root', default='data/... |
def cascade_randomization(arch, num_layers_from_last=None):
model = models.__dict__[arch](pretrained=True)
num = ((- 1) * num_layers_from_last)
conv2d_keys = []
for key in model.features._modules.keys():
if isinstance(model.features._modules[key], nn.Conv2d):
conv2d_keys.append(key)
... |
_fixtures(WebFixture, DataTableFixture)
def test_sorting(web_fixture, data_table_fixture):
web_fixture.reahl_server.set_app(data_table_fixture.wsgi_app)
web_fixture.quit_browser()
browser = web_fixture.driver_browser
browser.open('/')
assert (not data_table_fixture.is_column_sorted(1, 'ascending'))
... |
def play_many(pathserv, timeout=120):
conf = fs.get_session_configuration(pathserv)
if conf['dev_debug']:
pass
elif conf['protect_raw_data']:
raise mpexceptions.ExceptionAttemptToBreakRawDataProtection()
playlist_gen = pathserv.session_playlist_generator()
core_play_many(pathserv, pl... |
def create_quant_info(encoding, tensor_quantizer, opMode, useSymmetricEncoding=False, enabled=True, bitwidth=8):
quant_info = libquant_info.QcQuantizeInfo()
encoding.bw = bitwidth
quant_info.encoding = [encoding]
quant_info.opMode = opMode
quant_info.useSymmetricEncoding = useSymmetricEncoding
q... |
class AutomaticFailoverWrapper(object):
def __init__(self, primary_db, fallback_db=None):
self._primary_db = primary_db
self._fallback_db = fallback_db
def __getattr__(self, attribute):
if ((attribute != 'execute_sql') and hasattr(self._primary_db, attribute)):
return getattr... |
(frozen=True, slots=True)
class NodeResourceInfo():
resource_index: int
node_identifier: NodeIdentifier
long_name: str = dataclasses.field(hash=False, repr=False)
short_name: str = dataclasses.field(hash=False, repr=False)
resource_type: ResourceType = dataclasses.field(init=False, hash=False, repr=... |
def get_ingress_cmd(interface_list: typing.List[str], network_parameters: typing.Dict[(str, str)], duration: int=300):
tc_set = tc_unset = tc_ls = ''
param_map = {'latency': 'delay', 'loss': 'loss', 'bandwidth': 'rate'}
interface_pattern = re.compile('^[a-z0-9\\-\\\\_]+$')
ifb_pattern = re.compile('^ifb... |
class Effect1009(BaseEffect):
type = 'passive'
def handler(fit, skill, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Medium Pulse Laser Specialization')), 'damageMultiplier', (skill.getModifiedItemAttr('damageMultiplierBonus') * skill.level), **k... |
class Ui_Settings(object):
def setupUi(self, Settings):
Settings.setObjectName('Settings')
Settings.resize(1082, 659)
Settings.setMinimumSize(QtCore.QSize(0, 0))
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(Settings)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
... |
class fsdp_config():
mixed_precision: bool = True
use_fp16: bool = False
seed: int = 42
fsdp_activation_checkpointing: bool = True
limit_all_gathers: bool = True
sharding_strategy: ShardingStrategy = ShardingStrategy.FULL_SHARD
checkpoint_type: StateDictType = StateDictType.FULL_STATE_DICT
... |
def test_validate_raises(kernel_types=kernel_types, contiguity_types=contiguity_types, triang_types=triang_types):
with pytest.raises(ValueError):
_validate_geometry_input(rivers, valid_geometry_types=kernel_types)
with pytest.raises(ValueError):
_validate_geometry_input(columbus, valid_geometry... |
class NominationEntry(ModelReprMixin, models.Model):
nomination = models.ForeignKey(Nomination, on_delete=models.CASCADE, help_text='The nomination this entry belongs to.', related_name='entries')
actor = models.ForeignKey(User, on_delete=models.CASCADE, help_text='The staff member that nominated this user.', r... |
def test_cached_per_instance():
get_x_cache = CachingClass.get_x.__cached_per_instance_cache__
with_kwargs_cache = CachingClass.with_kwargs.__cached_per_instance_cache__
assert_eq(0, len(get_x_cache), extra=repr(get_x_cache))
assert_eq(0, len(with_kwargs_cache), extra=repr(with_kwargs_cache))
object... |
class proposed_method_involve_AD(BaseNet):
def __init__(self, conf):
super(proposed_method_involve_AD, self).__init__(conf)
self.discriminator = None
self.generator = None
self.gan = None
def build(self):
discr = critic_2D_with_AD(self.conf.discr_params)
discr.bui... |
_start_docstrings('\n VAN Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ', VAN_START_DOCSTRING)
class VanForImageClassification(VanPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.van = VanMod... |
class AttrVI_ATTR_RET_COUNT(RangeAttribute):
resources = [constants.EventType.io_completion]
py_name = 'return_count'
visa_name = 'VI_ATTR_RET_COUNT'
visa_type = 'ViUInt32'
default = NotAvailable
(read, write, local) = (True, False, True)
(min_value, max_value, values) = (0, , None) |
def precision(k=10):
def top_k(y_true, y_pred, rel_threshold=0.0):
if (k <= 0):
return 0.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,... |
def main(args: argparse.Namespace):
model_path = args.model
input_dir = args.input_dir
output_dir = args.output_dir
with_image = (True if output_dir else False)
with_gpu = (True if torch.cuda.is_available() else False)
model = load_model(model_path, with_gpu)
for image_fn in os.listdir(input... |
def create_quantsim_model_and_compute_encodings(model, dummy_input, quantsim_config=None):
from pathlib import Path
Path('/tmp/test_batch_norm_fold_to_scale').mkdir(parents=True, exist_ok=True)
config_file_path = '/tmp/test_batch_norm_fold_to_scale/quantsim_config.json'
quantsim_config = (quantsim_confi... |
def verify_help_text(cmd2_app: cmd2.Cmd, help_output: Union[(str, List[str])], verbose_strings: Optional[List[str]]=None) -> None:
if isinstance(help_output, str):
help_text = help_output
else:
help_text = ''.join(help_output)
commands = cmd2_app.get_visible_commands()
for command in com... |
def is_cython_or_generator(fn):
if hasattr(fn, '__func__'):
fn = fn.__func__
if inspect.isgeneratorfunction(fn):
return True
name = type(fn).__name__
return ((name == 'generator') or (name == 'method_descriptor') or (name == 'cython_function_or_method') or (name == 'builtin_function_or_m... |
class SynchronizedLyrics(EventPlugin, PluginConfigMixin):
PLUGIN_ID = 'SynchronizedLyrics'
PLUGIN_NAME = _('Synchronized Lyrics')
PLUGIN_DESC = _('Shows synchronized lyrics from an .lrc file with same name as the track (or similar).')
PLUGIN_ICON = Icons.FORMAT_JUSTIFY_FILL
SYNC_PERIOD = 10000
D... |
def find_length(data):
if (len(data.shape) > 1):
return 0
data = data[:min(20000, len(data))]
base = 3
auto_corr = acf(data, nlags=400, fft=True)[base:]
local_max = argrelextrema(auto_corr, np.greater)[0]
try:
max_local_max = np.argmax([auto_corr[lcm] for lcm in local_max])
... |
(Publisher)
class PublisherAdmin(RemoveDeleteMixin, SimpleHistoryAdmin):
list_display = ('name', 'slug', 'report', 'revenue_share_percentage', 'payout_method', 'unauthed_ad_decisions', 'allow_paid_campaigns', 'allow_affiliate_campaigns', 'allow_community_campaigns', 'allow_house_campaigns', 'record_views')
list... |
def push_to_hf_hub(model, repo_id: str, commit_message: str='Add model', token: Optional[str]=None, revision: Optional[str]=None, private: bool=False, create_pr: bool=False, model_config: Optional[dict]=None):
repo_url = create_repo(repo_id, token=token, private=private, exist_ok=True)
(_, repo_owner, repo_name... |
def test_request_reset_password_fails_with_not_active_user(graphql_client, sent_emails):
user = UserFactory(email='', is_active=False)
body = graphql_client.query('mutation($email: String!) {\n requestResetPassword(email: $email) {\n __typename\n ... on OperationSuccess ... |
class F29_Bootloader(F21_Bootloader):
removedKeywords = F21_Bootloader.removedKeywords
removedAttrs = F21_Bootloader.removedAttrs
def _getParser(self):
op = F21_Bootloader._getParser(self)
op.add_argument('--upgrade', action='store_true', default=False, deprecated=F29, help='upgrade the boot... |
_for('torch', '2.0', None)
def set_tensor_dict(module_dict, module, name: str, tensor: torch.Tensor) -> None:
if (name in module_dict['_parameters']):
del module_dict['_parameters'][name]
was_buffer = (name in module_dict['_buffers'])
if was_buffer:
del module_dict['_buffers'][name]
if i... |
def area_def2basemap(area_def, **kwargs):
import warnings
warnings.warn("Basemap is no longer maintained. Please switch to cartopy by using 'area_def.to_cartopy_crs()'. See the pyresample documentation for more details.", DeprecationWarning, stacklevel=2)
from mpl_toolkits.basemap import Basemap
basemap... |
def make_baseline_net(output_dir):
with open('{}/model/test_nyu_baseline_testset.prototxt'.format(output_dir), 'w') as f:
f.write(hand_baseline('test-test', output_dir))
with open('{}/model/test_nyu_baseline_trainset.prototxt'.format(output_dir), 'w') as f:
f.write(hand_baseline('test-train', ou... |
def test_resolve_lang_codes_m2m100():
sources = [dlt.lang.m2m100.FRENCH, 'fr', 'French']
targets = [dlt.lang.m2m100.ENGLISH, 'en', 'English']
for (source, target) in zip(sources, targets):
s = _resolve_lang_codes(source, 'source', 'm2m100')
t = _resolve_lang_codes(target, 'target', 'm2m100')... |
def test_messages(caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.INFO)
logger.info('boo %s', 'arg')
logger.info('bar %s\nbaz %s', 'arg1', 'arg2')
assert ('boo arg' == caplog.messages[0])
assert ('bar arg1\nbaz arg2' == caplog.messages[1])
assert (caplog.text.count('\n') > le... |
class BasicTokenizer(object):
def __init__(self, do_lower_case=True, never_split=('[UNK]', '[SEP]', '[PAD]', '[CLS]', '[MASK]')):
self.do_lower_case = do_lower_case
self.never_split = never_split
def tokenize(self, text):
text = self._clean_text(text)
text = self._tokenize_chines... |
class STAT0(IntEnum):
SMBALT = (1 << 15)
SMBTO = (1 << 14)
PECERR = (1 << 12)
OUERR = (1 << 11)
AERR = (1 << 10)
LOSTARB = (1 << 9)
BERR = (1 << 8)
TBE = (1 << 7)
RBNE = (1 << 6)
STPDET = (1 << 4)
ADD10SEND = (1 << 3)
BTC = (1 << 2)
ADDSEND = (1 << 1)
SBSEND = (1 ... |
class ContextManagerTests(unittest.TestCase):
.patch('sys.stdout', new_callable=io.StringIO)
def test_no_context(self, mock_stdout):
with ContextManagers([]):
print('Transformers are awesome!')
self.assertEqual(mock_stdout.getvalue(), 'Transformers are awesome!\n')
.patch('sys.st... |
class Wheel(distribution.Distribution):
def __init__(self, filename: str, metadata_version: Optional[str]=None) -> None:
self.filename = filename
self.basefilename = os.path.basename(self.filename)
self.metadata_version = metadata_version
self.extractMetadata()
def py_version(sel... |
class TestQcQuantizeRecurrentOp(unittest.TestCase):
testcases = [TestCase(test_name='rnn_single_layer_no_bias', model=torch.nn.RNN(input_size=4, hidden_size=5, num_layers=1, bias=False), input_shape=(5, 3, 4)), TestCase(test_name='rnn_single_layer', model=torch.nn.RNN(input_size=4, hidden_size=5, num_layers=1), inp... |
class MultiHeadedAttention(torch.nn.Module):
def __init__(self, h, query_size, value_size, dropout=0.1):
super().__init__()
assert ((query_size % h) == 0)
assert ((value_size % h) == 0)
self.d_k = (value_size // h)
self.h = h
self.linears = torch.nn.ModuleList([torch.... |
def _recon_lcs(x, y):
(i, j) = (len(x), len(y))
table = _lcs(x, y)
if (table[(i, j)] == 0):
return []
lcs = []
while 1:
if ((i == 0) or (j == 0)):
break
elif (x[(i - 1)] == y[(j - 1)]):
lcs = ([(x[(i - 1)], (i - 1))] + lcs)
i = (i - 1)
... |
def _read_spotting_detections_and_labels(results_dir: Path, video_data: List[VideoDatum]):
detections = []
labels = []
for video_datum in video_data:
base_path = (results_dir / video_datum.relative_path)
labels_path = _labels_path(base_path, Task.SPOTTING)
if labels_path.exists():
... |
def notify_closing(handle: ((Handle | int) | _HasFileNo)) -> None:
locals()[LOCALS_KEY_KI_PROTECTION_ENABLED] = True
try:
return GLOBAL_RUN_CONTEXT.runner.io_manager.notify_closing(handle)
except AttributeError:
raise RuntimeError('must be called from async context') from None |
class TAKInfo(StreamInfo):
channels = 0
length = 0
sample_rate = 0
bitrate = 0
encoder_info = ''
_error(IOError, TAKHeaderError)
_error(BitReaderError, TAKHeaderError)
def __init__(self, fileobj):
stream_id = fileobj.read(4)
if ((len(stream_id) != 4) or (not (stream_id ==... |
('--user', '-u', default='reanahub', help='DockerHub user name [reanahub]')
('--tag', '-t', default='latest', help="Image tag to push. Default 'latest'. Use 'auto' to push git-tag-based value such as '0.7.0-alpha.3'")
('--component', '-c', multiple=True, default=['CLUSTER'], help='Which components? [name|CLUSTER]')
('-... |
class CIFAR_Net(nn.Module):
def __init__(self, args):
super(CIFAR_Net, self).__init__()
self.conv1 = (torch.nn.Sequential(nn.Conv2d(3, 10, kernel_size=5), nn.ReLU(), nn.BatchNorm2d(10), nn.Dropout(p=args.dp_rate), nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2), dilation=(1, 1))) if args.BatchNorm el... |
def setup_args():
description = 'Collect codec metrics and performances.'
parser = argparse.ArgumentParser(description=description)
subparsers = parser.add_subparsers(dest='codec', help='Select codec')
subparsers.required = True
parser.add_argument('image', type=str, help='image filepath')
parse... |
class ParameterAssignment(VersionBase):
def __init__(self, parameterref, value):
self.parameterref = parameterref
self.value = value
def __eq__(self, other):
if isinstance(other, ParameterAssignment):
if (self.get_attributes() == other.get_attributes()):
retur... |
def sort_along_x(x, y):
out_x = []
out_y = []
for (i, j) in zip(x, y):
i = np.array(i)
j = np.array(j)
ind = np.argsort(i, axis=0)
out_x.append(np.take_along_axis(i, ind[::(- 1)], axis=0).tolist())
out_y.append(np.take_along_axis(j, ind[::(- 1)], axis=0).tolist())
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.