code stringlengths 281 23.7M |
|---|
def apply_adaround_example():
AimetLogger.set_level_for_all_areas(logging.DEBUG)
tf.keras.backend.clear_session()
model = keras_model()
dataset_size = 32
batch_size = 16
possible_batches = (dataset_size // batch_size)
input_data = np.random.rand(dataset_size, 16, 16, 3)
dataset = tf.data... |
class Logging():
__instance = None
__logger_level_dic = {'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'WARN': logging.WARN, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG}
def __init__(self):
self.__logger = logging.getLogger()
self.__filename = 'train.log'
__log_info = log_info... |
class TestEnvVarHandling(BaseTestCase):
def test_reading_wrap_handler(self):
with Popen([sys.executable], stdin=PIPE, stdout=PIPE) as p:
(stdout, _) = p.communicate(b'from pyvisa import ctwrapper;print(ctwrapper.WRAP_HANDLER);exit()')
assert (b'True' == stdout.rstrip())
env = os.... |
class StateSwitcher(QState):
def __init__(self, machine):
super(StateSwitcher, self).__init__(machine)
self.m_stateCount = 0
self.m_lastIndex = 0
def onEntry(self, event):
n = ((qrand() % self.m_stateCount) + 1)
while (n == self.m_lastIndex):
n = ((qrand() % s... |
()
('--input', '-i', 'image_path', help='Path to an image')
('--lsb-count', '-n', default=2, show_default=2, type=int, help='How many LSBs to display')
_context
def stegdetect(ctx: click.Context, image_path: str, lsb_count: int) -> None:
if image_path:
StegDetect.show_lsb(image_path, lsb_count)
else:
... |
def test_format_descriptors():
with pytest.raises(RuntimeError) as excinfo:
m.get_format_unbound()
assert re.match('^NumPy type info missing for .*UnboundStruct.*$', str(excinfo.value))
ld = np.dtype('longdouble')
ldbl_fmt = (('4x' if (ld.alignment > 4) else '') + ld.char)
ss_fmt = (('^T{?:b... |
def _parse_assignments(lvalue: Expression, stmt: AssignmentStmt) -> tuple[(list[NameExpr], list[Expression])]:
lvalues: list[NameExpr] = []
rvalues: list[Expression] = []
if isinstance(lvalue, (TupleExpr, ListExpr)):
if all((isinstance(item, NameExpr) for item in lvalue.items)):
lvalues ... |
def graphite_electrolyte_exchange_current_density_Ecker2015(c_e, c_s_surf, c_s_max, T):
k_ref = (1.11 * 1e-10)
m_ref = (pybamm.constants.F * k_ref)
E_r = 53400
arrhenius = (pybamm.exp(((- E_r) / (pybamm.constants.R * T))) * pybamm.exp((E_r / (pybamm.constants.R * 296.15))))
return ((((m_ref * arrhen... |
.network
def test_installer_with_pypi_repository(package: ProjectPackage, locker: Locker, installed: CustomInstalledRepository, config: Config, env: NullEnv) -> None:
pool = RepositoryPool()
pool.add_repository(MockRepository())
installer = Installer(NullIO(), env, package, locker, pool, config, installed=i... |
class AgentRLConfig():
def __init__(self):
self.use_gpu = False
self.input_dim = ((((189 + 11) + 189) + 4) + 9)
self.hidden1_dim = 100
self.hidden2_dim = 6
self.dp = 0.2
self.DPN_model_path = (root_path + '/agents/agent_rl_model/')
self.DPN_model_name = 'TwoLa... |
.skipif((sys.version_info[:2] <= (3, 7)), reason="regex doesn't work well in py36 (for some edge cases)")
def test_split():
assert (deps.split('\n pyscaffold>=42.1.0,<43.0\n platformdirs==1\n cookiecutter<8\n mypkg~=9.0') == ['pyscaffold>=42.1.0,<43.0', 'platformdirs==1', 'cookiecutter<8', 'mypkg~=9.0']... |
.skip(reason="Rewrite disabled as it don't support unsorted indices")
.skipif((not pytensor.config.cxx), reason='G++ not available, so we need to skip this test.')
def test_local_csm_grad_c():
data = vector()
(indices, indptr, shape) = (ivector(), ivector(), ivector())
mode = get_default_mode()
if (pyte... |
def flatten_dictionary(input, sep='.', prefix=None):
for (name, value) in sorted(input.items()):
fullname = sep.join(filter(None, [prefix, name]))
if isinstance(value, dict):
for result in flatten_dictionary(value, sep, fullname):
(yield result)
else:
... |
.parametrize('constraint_parts,expected', [(['3.8'], Version.from_parts(3, 8)), (['=', '3.8'], Version.from_parts(3, 8)), (['==', '3.8'], Version.from_parts(3, 8)), (['>', '3.8'], VersionRange(min=Version.from_parts(3, 8))), (['>=', '3.8'], VersionRange(min=Version.from_parts(3, 8), include_min=True)), (['<', '3.8'], V... |
('/')
class TodoList(Resource):
_list_with(listed_todo)
def get(self):
return [{'id': id, 'todo': todo} for (id, todo) in TODOS.items()]
(parser=parser)
_with(todo, code=201)
def post(self):
args = parser.parse_args()
todo_id = ('todo%d' % (len(TODOS) + 1))
TODOS[todo... |
def load_and_merge_dbfs(database_directory: pathlib.Path, refresh_cache: bool) -> 'pd.DataFrame':
patimg = load_iview_dbf(database_directory, refresh_cache, 'patimg')
dates = pd.to_datetime(patimg['IMG_DATE'], format='%Y%m%d').dt.date
date_options = dates.sort_values(ascending=False).unique()
selected_d... |
class torrentproject(object):
url = '
name = 'TorrentProject'
supported_categories = {'all': '0'}
class MyHTMLParser(HTMLParser):
def __init__(self, url):
HTMLParser.__init__(self)
self.url = url
self.insideResults = False
self.insideDataDiv = Fals... |
def xserver_start(display, executable='Xvfb', authfile=None):
pid = os.fork()
if (pid != 0):
return pid
if (authfile is None):
authfile = os.devnull
signal.signal(signal.SIGUSR1, signal.SIG_IGN)
cmd = [executable, '-auth', authfile, '-noreset', display]
print('starting xserver: `... |
class Effect6039(BaseEffect):
type = 'passive'
def handler(fit, module, context, projectionRange, **kwargs):
fit.modules.filteredItemMultiply((lambda mod: mod.item.requiresSkill('Small Projectile Turret')), 'trackingSpeed', (1 / module.getModifiedItemAttr('modeTrackingPostDiv')), stackingPenalties=True,... |
class BenchmarkSpec(namedtuple('BenchmarkSpec', 'name version origin')):
__slots__ = ()
def from_raw(cls, raw):
if isinstance(raw, BenchmarkSpec):
return (raw, None)
elif isinstance(raw, str):
return parse_benchmark(raw)
else:
raise ValueError(f'unsupp... |
def load(name):
f = pd.read_csv(f'datasets/{name}_LLMs.csv')
a_human = f['human'].tolist()
mgt_text_list = []
for detectLLM in ['ChatGLM', 'Dolly', 'ChatGPT-turbo', 'GPT4All', 'StableLM', 'Claude']:
mgt_text_list.append(f[f'{detectLLM}'].fillna('').tolist())
res = []
for i in range(len(a... |
class s3fd(nn.Module):
def __init__(self):
super(s3fd, self).__init__()
self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)
self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
... |
class PublisherGroup(TimeStampedModel):
name = models.CharField(_('Name'), max_length=200, help_text=_('Visible to advertisers'))
slug = models.SlugField(_('Publisher group slug'), max_length=200, unique=True)
publishers = models.ManyToManyField(Publisher, related_name='publisher_groups', blank=True, help_t... |
class EditDistance(object):
def __init__(self, time_mediated):
self.time_mediated_ = time_mediated
self.scores_ = np.nan
self.backtraces_ = np.nan
self.confusion_pairs_ = {}
def cost(self, ref, hyp, code):
if self.time_mediated_:
if (code == Code.match):
... |
def parse_threshold(threshold):
tmp = threshold.split(',')
parsed_thresholds = []
results = {}
results['thresholds'] = parsed_thresholds
for i in tmp:
if (i.find('=') < 1):
raise InvalidThreshold(("Invalid input: '%s' is not of the format key=value" % i))
(key, value) = i... |
class LxMounts(gdb.Command):
def __init__(self):
super(LxMounts, self).__init__('lx-mounts', gdb.COMMAND_DATA)
def invoke(self, arg, from_tty):
argv = gdb.string_to_argv(arg)
if (len(argv) >= 1):
try:
pid = int(argv[0])
except gdb.error:
... |
class TestConstantsWithoutRequest():
def test__all__(self):
expected = {key for (key, member) in constants.__dict__.items() if ((not key.startswith('_')) and (getattr(member, '__module__', 'telegram.constants') == 'telegram.constants') and (key != 'sys'))}
actual = set(constants.__all__)
ass... |
class S3ObjectStore(IObjectStore):
def __init__(self, bucket_prefix: str) -> None:
self.bucket = bucket_prefix
super().__init__()
def put_many(self, objects: List[object], *args, **kwargs) -> List[Any]:
result = []
for obj in objects:
serialized = cloudpickle.dumps(ob... |
class TwoLayerBidirectionalGRUModel(nn.Module):
def __init__(self):
super(TwoLayerBidirectionalGRUModel, self).__init__()
self.recurrent = torch.nn.GRU(input_size=3, hidden_size=5, num_layers=2, bidirectional=True)
def forward(self, x, hx=None):
return self.recurrent(x, hx) |
class YahooOAuth(BaseOAuth1):
name = 'yahoo-oauth'
ID_KEY = 'guid'
AUTHORIZATION_URL = '
REQUEST_TOKEN_URL = '
ACCESS_TOKEN_URL = '
EXTRA_DATA = [('guid', 'id'), ('access_token', 'access_token'), ('expires', 'expires')]
def get_user_details(self, response):
(fullname, first_name, las... |
def update_rule_buffer(rule_buffer_list, rule_path_list):
for rule_path in rule_path_list:
with open(rule_path, 'r') as json_file:
json_data = json.loads(json_file.read())
if isinstance(json_data, list):
for rule_data in json_data:
rule_buffer_list.append(Rule... |
def entropy_loss(output, pooling, softmax, logsoftmax):
(pooling_hf, pooling_lf) = pooling
(softmax_hf, softmax_lf) = softmax
(logsoftmax_hf, logsoftmax_lf) = logsoftmax
(output_hf, output_lf) = output
pool_hf = pooling_hf(output_hf)
le_hf = (- torch.mean(torch.mul(softmax_hf(pool_hf), logsoftma... |
class FusionOptimizer(GraphRewriter):
def add_requirements(self, fgraph):
fgraph.attach_feature(ReplaceValidate())
def elemwise_to_scalar(inputs, outputs):
replace_inputs = [(inp, inp.clone()) for inp in inputs]
outputs = clone_replace(outputs, replace=replace_inputs)
inputs = [i... |
()
('--color', default='auto', help='use colored output (no|auto|always)')
('--log-level', default='WARN', help='log level (debug|info|warn|error)')
('-I', '--include', multiple=True, help='include a path in the Specstrom module search paths')
_context
def root(ctx, color, log_level, include):
if (color.lower() == ... |
def pytest_configure(config: Config) -> None:
import faulthandler
stderr_fileno = get_stderr_fileno()
if faulthandler.is_enabled():
config.stash[fault_handler_original_stderr_fd_key] = stderr_fileno
config.stash[fault_handler_stderr_fd_key] = os.dup(stderr_fileno)
faulthandler.enable(file=co... |
class TestCaseHandshakeLoss(TestCase):
_num_runs = 50
def name():
return 'handshakeloss'
def testname(p: Perspective):
return 'multiconnect'
def abbreviation():
return 'L1'
def desc():
return 'Handshake completes under extreme packet loss.'
def timeout() -> int:
... |
def get_effective_match_source(s: str, start: int, end: int) -> Match:
_start = (- 1)
for i in range(start, (start - 2), (- 1)):
if (i < 0):
_start = (i + 1)
break
if is_span_separator(s[i]):
_start = i
break
if (_start < 0):
return Non... |
class LoraInjectedConv2d(nn.Module):
def __init__(self, in_channels: int, out_channels: int, kernel_size, stride=1, padding=0, dilation=1, groups: int=1, bias: bool=True, r: int=4, dropout_p: float=0.1, scale: float=1.0):
super().__init__()
if (r > min(in_channels, out_channels)):
raise ... |
class TestLeavesScope(TestNameCheckVisitorBase):
_passes()
def test_leaves_scope(self):
def capybara(cond):
if cond:
return
else:
x = 3
print(x)
_passes()
def test_try_always_leaves_scope(self):
def capybara(cond):
... |
class SolidfilesCom(SimpleDownloader):
__name__ = 'SolidfilesCom'
__type__ = 'downloader'
__version__ = '0.09'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fal... |
class GraphicsLayout(GraphicsWidget):
def __init__(self, parent=None, border=None):
GraphicsWidget.__init__(self, parent)
if (border is True):
border = (100, 100, 100)
elif (border is False):
border = None
self.border = border
self.layout = QtWidgets.Q... |
class NativeTorchQuantWrapper(nn.Module):
def __init__(self, post_training_module: Union[(StaticGridQuantWrapper, LearnedGridQuantWrapper)], module_name: str, device: torch.device):
super(NativeTorchQuantWrapper, self).__init__()
self._module_to_wrap = getattr(post_training_module, module_name)
... |
class TFMobileViTSelfOutput(tf.keras.layers.Layer):
def __init__(self, config: MobileViTConfig, hidden_size: int, **kwargs) -> None:
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(hidden_size, name='dense')
self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)
... |
class Migration(migrations.Migration):
dependencies = [('blog', '0002_auto__2128')]
operations = [migrations.AlterField(model_name='post', name='content', field=i18n.fields.I18nTextField(blank=True, verbose_name='content')), migrations.AlterField(model_name='post', name='excerpt', field=i18n.fields.I18nTextFiel... |
def optimize_one_inter_rep(inter_rep, layer_name, target, probe, lr=0.001, max_epoch=256, loss_func=nn.HuberLoss(), smoothness_loss_func=None, image=None, verbose=False):
with autocast('cuda', enabled=False):
target_clone = torch.Tensor(target).to(torch.float).to(torch_device).unsqueeze(0).unsqueeze(0)
... |
def get_coeffs_for_poly3(length, lane_offset, zero_start, lane_width_end=None):
start_heading = 0
end_heading = 0
s0 = 0
s1 = length
A = np.array([[0, 1, (2 * s0), (3 * (s0 ** 2))], [0, 1, (2 * s1), (3 * (s1 ** 2))], [1, s0, (s0 ** 2), (s0 ** 3)], [1, s1, (s1 ** 2), (s1 ** 3)]])
if zero_start:
... |
class SwishLayerNorm(nn.Module):
def __init__(self, input_dims: Union[(int, List[int], torch.Size)], device: Optional[torch.device]=None) -> None:
super().__init__()
self.norm: torch.nn.modules.Sequential = nn.Sequential(nn.LayerNorm(input_dims, device=device), nn.Sigmoid())
def forward(self, in... |
def test_create_questionset_page(db):
questionset = QuestionSet.objects.exclude(pages=None).first()
page = questionset.pages.first()
page.locked = True
page.save()
with pytest.raises(ValidationError):
QuestionSetLockedValidator()({'parents': [questionset], 'locked': False}) |
def _build(isolation: bool, srcdir: PathType, outdir: PathType, distribution: str, config_settings: (ConfigSettingsType | None), skip_dependency_check: bool) -> str:
if isolation:
return _build_in_isolated_env(srcdir, outdir, distribution, config_settings)
else:
return _build_in_current_env(srcd... |
def _build_call_graph(bloq: Bloq, generalizer: GeneralizerT, ssa: SympySymbolAllocator, keep: Callable[([Bloq], bool)], max_depth: Optional[int], g: nx.DiGraph, depth: int) -> None:
if (bloq in g):
return
g.add_node(bloq)
if keep(bloq):
return
if ((max_depth is not None) and (depth >= ma... |
def example_dconv_offset():
print('using extra offsets')
input = torch.randn(B, inC, inT, inH, inW).cuda()
offset = torch.randn(B, (((kT * kH) * kW) * 3), inT, inH, inW).cuda()
dcn = DeformConv(inC, outC, kernel_size=[kT, kH, kW], stride=[sT, sH, sW], padding=[pT, pH, pW], dilation=[dT, dH, dW]).cuda()
... |
class _RunAlgoError(click.ClickException, ValueError):
exit_code = 1
def __init__(self, pyfunc_msg, cmdline_msg=None):
if (cmdline_msg is None):
cmdline_msg = pyfunc_msg
super(_RunAlgoError, self).__init__(cmdline_msg)
self.pyfunc_msg = pyfunc_msg
def __str__(self):
... |
def assert_args_presence(args, doc, member, name):
args_not_in_doc = [(arg not in doc) for arg in args]
if any(args_not_in_doc):
raise ValueError('{} {} arguments are not present in documentation '.format(name, list(compress(args, args_not_in_doc))), member.__module__)
words = doc.replace('*', '').s... |
def main():
dataset = morefusion.datasets.YCBVideoDataset(split='train')
class_names = morefusion.datasets.ycb_video.class_names
example = dataset[1000]
rgb = example['color']
depth = example['depth']
K = example['meta']['intrinsic_matrix']
pcd = morefusion.geometry.pointcloud_from_depth(dep... |
class DoubleBarrier(object):
def __init__(self, client, path, num_clients, identifier=None):
self.client = client
self.path = path
self.num_clients = num_clients
self._identifier = (identifier or ('%s-%s' % (socket.getfqdn(), os.getpid())))
self.participating = False
... |
class Walker(object, metaclass=MetaNodeTypeHandler):
def __init__(self, env=None):
if (env is None):
import pysmt.environment
env = pysmt.environment.get_env()
self.env = env
self.functions = {}
for o in op.all_types():
try:
self.fu... |
class Progbar(object):
def __init__(self, target, width=30, verbose=1, interval=0.05):
self.width = width
if (target is None):
target = (- 1)
self.target = target
self.sum_values = {}
self.unique_values = []
self.start = time.time()
self.last_updat... |
class BotogramStyle(style.Style):
background_color = '#fff'
highlight_color = '#f3f3f3'
default_style = ''
styles = {token.Whitespace: 'underline #f8f8f8', token.Error: '#a40000 border:#ef2929', token.Other: NAMES, token.Comment: COMMENTS, token.Keyword: KEYWORD, token.Operator: OPERATORS, token.Operato... |
.parametrize('node', ['Path(__file__).parent', 'PathNode(path=Path(__file__).parent)', 'PickleNode(path=Path(__file__).parent)'])
def test_error_when_path_dependency_is_directory(runner, tmp_path, node):
source = f'''
from pathlib import Path
from pytask import PickleNode, PathNode
def task_example(path... |
class QuadraticProgramElement():
def __init__(self, quadratic_program: 'problems.QuadraticProgram') -> None:
from .quadratic_program import QuadraticProgram
if (not isinstance(quadratic_program, QuadraticProgram)):
raise TypeError('QuadraticProgram instance expected')
self._quadr... |
def postprocess_text(preds, responses, metric_name):
preds = [pred.strip() for pred in preds]
responses = [response.strip() for response in responses]
if (metric_name == 'rouge'):
preds = ['\n'.join(nltk.sent_tokenize(pred)) for pred in preds]
responses = ['\n'.join(nltk.sent_tokenize(respon... |
class ThrottleTest(EvenniaTest):
def test_throttle(self):
ips = ('94.100.176.153', '45.56.148.77', '5.196.1.129')
kwargs = {'limit': 5, 'timeout': (15 * 60)}
throttle = Throttle(**kwargs)
for ip in ips:
self.assertFalse(throttle.check(ip))
for x in range(50):
... |
def get_your_qr_page(request, qr_secret):
ri = get_ri_from_secret(qr_secret)
if (ri is not None):
return render(request, 'qr_app/your-qr-page.html', context={'qr_image': reverse('get_qr_from_secret', args=[qr_secret]), 'qr_image_svg': reverse('get_qr_from_secret_svg', args=[qr_secret]), 'qr_image_eps': ... |
class TimeBuildModelLossActiveMaterial():
param_names = ['model', 'model option']
params = ([pybamm.lithium_ion.SPM, pybamm.lithium_ion.DFN], ['none', 'stress-driven', 'reaction-driven', 'stress and reaction-driven'])
def setup(self, _model, _params):
set_random_seed()
def time_setup_model(self,... |
class wz_input_before_epoch(unittest.TestCase):
def test(self):
run_test(self, ['-w 1023 604799'], ' Month/Day/Year H:M:S 01/16/1980 11:59:58 GPS\n Modified Julian Date 44254. GPS\n GPSweek DayOfWeek SecOfWeek 1 3 302398.500000\n FullGPSweek Zcount ... |
class KeyedOptimizer(optim.Optimizer):
def __init__(self, params: Mapping[(str, Union[(torch.Tensor, ShardedTensor)])], state: Mapping[(Any, Any)], param_groups: Collection[Mapping[(str, Any)]]) -> None:
torch._C._log_api_usage_once(f'torchrec.optim.{self.__class__.__name__}')
self._optimizer_step_p... |
.parametrize(('test_input', 'expected'), [('pep-0008.rst', {'authors': 'Guido van Rossum, Barry Warsaw, Alyssa Coghlan', 'number': 8, 'shorthand': ':abbr:`PA (Process, Active)`', 'title': 'Style Guide for Python Code', 'python_version': ''}), ('pep-0719.rst', {'authors': 'Thomas Wouters', 'number': 719, 'shorthand': ':... |
def affine(inp, units, bias=True, W_initializer=None, b_initializer=None, W_name=WEIGHT_DEFAULT_NAME, bias_name=BIAS_DEFAULT_NAME):
input_size = inp.get_shape()[(- 1)].value
W = _weight_variable([input_size, units], initializer=W_initializer, name=W_name)
output = tf.matmul(inp, W)
if bias:
b = ... |
class EpisodeDescrSamplerTest(tf.test.TestCase):
dataset_spec = test_utils.DATASET_SPEC
split = Split.VALID
def setUp(self):
super(EpisodeDescrSamplerTest, self).setUp()
self.sampler = self.make_sampler()
def make_sampler(self):
return sampling.EpisodeDescriptionSampler(self.data... |
def resp_create_commit():
content = {'id': 'ed899a2f4b50b4370feeeab42383c746', 'short_id': 'ed899a2f', 'title': 'Commit message'}
with responses.RequestsMock() as rsps:
rsps.add(method=responses.POST, url=' json=content, content_type='application/json', status=200)
(yield rsps) |
class Module(object):
in_namespace_package = False
namespace_package_name = None
def __init__(self, name, directory=Path()):
self.name = name
name_as_path = name.replace('.', os.sep)
pkg_dir = (directory / name_as_path)
py_file = (directory / (name_as_path + '.py'))
s... |
def create_video_folders(dataset, output_dir, tmp_dir):
if (not os.path.exists(output_dir)):
os.makedirs(output_dir)
if (not os.path.exists(tmp_dir)):
os.makedirs(tmp_dir)
label_to_dir = {}
for label_name in dataset['label-name'].unique():
this_dir = os.path.join(output_dir, labe... |
def _read_yaml_area_file_content(area_file_name):
from pyresample.utils import recursive_dict_update
if isinstance(area_file_name, (str, pathlib.Path, io.IOBase)):
area_file_name = [area_file_name]
area_dict = {}
for area_file_obj in area_file_name:
if isinstance(area_file_obj, io.IOBase... |
class AutoapiPropertyDocumenter(AutoapiDocumenter, autodoc.PropertyDocumenter):
objtype = 'apiproperty'
directivetype = 'property'
priority = ((autodoc.PropertyDocumenter.priority * 100) + 100)
def can_document_member(cls, member, membername, isattr, parent):
return isinstance(member, PythonProp... |
class Plugin(TrezorPlugin, QtPlugin):
icon_unpaired = 'trezor_unpaired.png'
icon_paired = 'trezor.png'
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
def pin_matrix_widget_class(self):
from trezorlib.qt.pinmatrix import PinMatrixWi... |
.pydicom
def test_sum_doses_in_datasets():
scale1 = 0.01
data1 = (np.array([[[0.9, 0.8, 0.7], [0.6, 0.5, 0.4]], [[0.91, 0.81, 0.71], [0.61, 0.51, 0.41]], [[0.92, 0.82, 0.72], [0.62, 0.52, 0.42]], [[0.93, 0.83, 0.73], [0.63, 0.53, 0.43]]]) / scale1).astype(np.uint32)
scale2 = 5e-09
data2 = (np.array([[[0... |
def grant_superuser_rights(proj: Project) -> Project:
superuser = proj.export_users()[0]
superuser['record_delete'] = 1
superuser['record_rename'] = 1
superuser['lock_records_all_forms'] = 1
superuser['lock_records'] = 1
res = proj.import_users([superuser])
assert (res == 1)
return proj |
def delete_oldest_logs(file_list: List[Path], keep_number: int) -> None:
file_list = sorted(file_list)
if (len(file_list) > keep_number):
for existing_file in file_list[:(- keep_number)]:
try:
existing_file.unlink()
except FileNotFoundError:
pass |
def apply_optimizer_in_backward(optimizer_class: Type[torch.optim.Optimizer], params: Iterable[torch.nn.Parameter], optimizer_kwargs: Dict[(str, Any)]) -> None:
from torch.distributed.optim import _apply_optimizer_in_backward
warn("This API is deprecated. Please use Pytorch Distributed's _apply_optimizer_in_bac... |
class TestStats(BaseTestCase):
simple_benchmark = pd.Series((np.array([0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]) / 100), index=pd.date_range('2000-1-30', periods=9, freq='D'))
positive_returns = pd.Series((np.array([1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) / 100), index=pd.date_range('2000-1-30', perio... |
class Fragment(Molecule):
type: Literal['Fragment'] = 'Fragment'
bond_indices: List[Tuple[(int, int)]] = Field(default_factory=list, description='The map indices of the atoms in the parent molecule that are involved in the bond. The fragment was built around these atoms. Note that one fragment might have more t... |
def copy_parameters(from_model: nn.Module, our_model: nn.Module) -> nn.Module:
from_state_dict = from_model.state_dict()
our_state_dict = our_model.state_dict()
config = our_model.config
all_keys = []
for stage_idx in range(len(config.hidden_sizes)):
for block_id in range(config.depths[stage... |
class GptEncoder(nn.Module):
def __init__(self, args):
super(GptEncoder, self).__init__()
self.layers_num = args.layers_num
self.transformer = nn.ModuleList([TransformerLayer(args) for _ in range(self.layers_num)])
def forward(self, emb, seg):
(batch_size, seq_length, _) = emb.si... |
def test_majorana_operator_commutes_with():
a = MajoranaOperator((0, 1, 5))
b = MajoranaOperator((1, 2, 7))
c = MajoranaOperator((2, 3, 4))
d = MajoranaOperator((0, 3, 6))
assert a.commutes_with(b)
assert (not a.commutes_with(c))
assert a.commutes_with(d)
assert b.commutes_with(c)
as... |
def scrape():
credentials = load_credentials()
if (credentials is None):
(username, password) = prompt_credentials()
else:
(username, password) = credentials
user_input = int(input('[Required] - How many followers do you want to scrape (100-2000 recommended): '))
usernames = input('E... |
def main():
sid = data['wps_checkin']
for item in sid:
sio.write('---{}---\n\n'.format(item['name']))
b1 = docer_webpage_clockin(item['sid'])
if (b1 == 1):
checinRecord_url = '
r = s.get(checinRecord_url, headers={'sid': item['sid']})
resp = json.loads... |
class GosuTemplateLexer(Lexer):
name = 'Gosu Template'
aliases = ['gst']
filenames = ['*.gst']
mimetypes = ['text/x-gosu-template']
url = '
version_added = '1.5'
def get_tokens_unprocessed(self, text):
lexer = GosuLexer()
stack = ['templateText']
(yield from lexer.get... |
def matplotlib_plt(scatters, title, ylabel, output_file, limits=None, show=False, figsize=None):
linestyle = '-'
hybrid_matches = ['HM', 'VTM', 'JPEG', 'JPEG2000', 'WebP', 'BPG', 'AV1']
if (figsize is None):
figsize = (9, 6)
(fig, ax) = plt.subplots(figsize=figsize)
for sc in scatters:
... |
def test_dataid():
from satpy.dataset.dataid import DataID, ModifierTuple, ValueList, WavelengthRange
did = make_dataid()
assert issubclass(did._id_keys['calibration']['type'], ValueList)
assert ('enum' not in did._id_keys['calibration'])
did = make_dataid(name='cheese_shops', resolution=None)
a... |
def _validate_header(header: str, line_num: int, content: str) -> MessageIterator:
if (header == 'Title'):
(yield from _validate_title(line_num, content))
elif (header == 'Author'):
(yield from _validate_author(line_num, content))
elif (header == 'Sponsor'):
(yield from _validate_spo... |
.parametrize('readme, content_type', [('README.rst', 'text/x-rst'), ('README.md', 'text/markdown'), ('README', 'text/plain'), (Path('README.rst'), 'text/x-rst'), (Path('README.md'), 'text/markdown'), (Path('README'), 'text/plain')])
def test_utils_helpers_readme_content_type(readme: (str | Path), content_type: str) -> ... |
def run_fio(testfile, duration, iotype, iodepth, blocksize, jobs):
global args
eta = ('never' if args.quiet else 'always')
outfile = tempfile.NamedTemporaryFile()
cmd = f'fio --direct=1 --ioengine=libaio --name=coef --filename={testfile} --runtime={round(duration)} --readwrite={iotype} --iodepth={iodept... |
def test_port_single(do_test):
class A(Component):
def construct(s):
s.in_ = InPort(Bits32)
a = A()
a._ref_ports = [(['clk'], 'clk', rt.Port('input', rdt.Vector(1)), 0), (['in_'], 'in_', rt.Port('input', rdt.Vector(32)), 0), (['reset'], 'reset', rt.Port('input', rdt.Vector(1)), 0)]
a... |
class Effect4416(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Torpedoes')), 'explosionDelay', ship.getModifiedItemAttr('shipBonusCF'), skill='Caldari Frigate', **kwargs) |
class Trainer():
def __init__(self, args, logger, attack):
self.args = args
self.logger = logger
self.attack = attack
def standard_train(self, model, tr_loader, va_loader=None):
self.train(model, tr_loader, va_loader, False)
def adversarial_train(self, model, tr_loader, va_lo... |
class ChineseNumberUnit(ChineseChar):
def __init__(self, power, simplified, traditional, big_s, big_t):
super(ChineseNumberUnit, self).__init__(simplified, traditional)
self.power = power
self.big_s = big_s
self.big_t = big_t
def __str__(self):
return '10^{}'.format(self.... |
def get_gdbserver_type():
def exit_handler(event):
global gdbserver_type
gdbserver_type = None
gdb.events.exited.disconnect(exit_handler)
def probe_qemu():
try:
return (gdb.execute('monitor info version', to_string=True) != '')
except gdb.error:
re... |
def is_recursive_pair(s: Type, t: Type) -> bool:
if (isinstance(s, TypeAliasType) and s.is_recursive):
return (isinstance(get_proper_type(t), (Instance, UnionType)) or (isinstance(t, TypeAliasType) and t.is_recursive) or isinstance(get_proper_type(s), TupleType))
if (isinstance(t, TypeAliasType) and t.i... |
class Test_DATETIME(TestCaseDATETIME2):
table_name = 'test_datetime'
ddl_create = f'CREATE TABLE {table_name} (test DATETIME)'
min_date = datetime.datetime(1753, 1, 1, 0, 0, 0, 0)
max_date = datetime.datetime(9999, 12, 31, 23, 59, 59, 997000)
def test_min_select(self):
self.conn.execute_quer... |
def create_earley_parser(lexer_conf: LexerConf, parser_conf: ParserConf, options) -> earley.Parser:
resolve_ambiguity = (options.ambiguity == 'resolve')
debug = (options.debug if options else False)
tree_class = ((options.tree_class or Tree) if (options.ambiguity != 'forest') else None)
extra = {}
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.