code stringlengths 281 23.7M |
|---|
class RequestController():
def __init__(self) -> None:
self.dispatcher = Dispatcher()
def dispatch_request(self, request: Any) -> None:
if isinstance(request, Request):
self.dispatcher.dispatch(request)
else:
print('request must be a Request object') |
def main():
mc.send_angles([(- 90), 0, 0, 0, 0, 0, 40], 60)
time.sleep(2.5)
for i in range(4):
mc.send_angle(4, 45, 95)
time.sleep(1.5)
mc.send_angle(4, (- 45), 95)
time.sleep(1.5)
for i in range(4):
mc.send_angle(4, 45, 20)
time.sleep(2.5)
mc.send... |
def test_dtcwt2(size, J, no_grad=False, dev='cuda'):
x = torch.randn(*size, requires_grad=(not no_grad)).to(dev)
(h0a, h0b, _, _, h1a, h1b, _, _) = level1('farras')
(cols, rows) = lowlevel2.prep_filt_quad_afb2d(h0a, h1a, h0b, h1b, device=dev)
yh = []
for j in range(3):
(x, y) = lowlevel2.qua... |
class Solution():
def calculate(self, s: str) -> int:
nums = [[]]
ops = []
for c in s:
if (c == ' '):
continue
if ((c in set('+-*/')) and nums[0]):
ops.append(c)
nums[(- 1)] = int(''.join(nums[(- 1)]))
nu... |
_member_required
(last_modified_func=last_modified_document)
def view_document(request, uuid):
uuid = UUID(uuid)
try:
doc = Document.objects.all().get(uuid=uuid)
except Document.DoesNotExist:
raise Http404('Document with this uuid does not exist.')
backrefs = None
try:
with c... |
class FromReader(UtilsFromReader):
def __init__(self, ffrom, bw, bl, ldr, ldr_w, data_pointers, code_pointers, bw_blocks, bl_blocks, ldr_blocks, ldr_w_blocks, data_pointers_blocks, code_pointers_blocks):
super().__init__(ffrom)
self._write_zeros_to_from(bw_blocks, bw)
self._write_zeros_to_fr... |
def test_raw_pool_custom_cleanup_ok():
cleanup_mock = tests.mock.Mock()
pool = db_pool.RawConnectionPool(DummyDBModule(), cleanup=cleanup_mock)
conn = pool.get()
pool.put(conn)
assert (cleanup_mock.call_count == 1)
with pool.item() as conn:
pass
assert (cleanup_mock.call_count == 2) |
class TestLogger():
def test_format_should_be_valid_json(self, capsys: pytest.CaptureFixture[str]):
logger.log(foo='bar')
raw_log_output = capsys.readouterr().out
try:
json.loads(raw_log_output)
except json.JSONDecodeError:
pytest.fail('Log output was not vali... |
.requires_roxar
def test_rox_surfaces_clipboard_general2d_data(roxar_project, roxinstance):
rox = xtgeo.RoxUtils(roxar_project)
project = rox.project
surf = xtgeo.surface_from_roxar(project, 'TopReek', SURFCAT1)
surf.to_roxar(project, 'mycase', 'myfolder', stype='clipboard')
surf2 = xtgeo.surface_fr... |
class FedLARSSyncAggregator(SyncAggregatorWithOptimizer):
def __init__(self, *, global_model: IFLModel, channel: Optional[IdentityChannel]=None, **kwargs) -> None:
init_self_cfg(self, component_class=__class__, config_class=FedLARSSyncAggregatorConfig, **kwargs)
super().__init__(global_model=global_... |
class FsspecFile(RepositoryFile):
def __init__(self, fs: AbstractFileSystem, path: str, fsspec_args: Optional[FsspecArgs]=None):
super().__init__()
self._fs = fs
self._path = path
self._fsspec_args = (FsspecArgs() if (fsspec_args is None) else fsspec_args)
def open(self, mode: st... |
class Shrink():
def __init__(self, ilo, shrink_node='DETERMINISTIC', node_filters=None, number_of_shards=1, number_of_replicas=1, shrink_prefix='', shrink_suffix='-shrink', copy_aliases=False, delete_after=True, post_allocation=None, wait_for_active_shards=1, wait_for_rebalance=True, extra_settings=None, wait_for_c... |
.skip(reason='Need to update to ethpm v3')
def test_ethpm_already_installed():
path = _get_data_folder().joinpath('packages/zeppelin.snakecharmers.eth')
path.mkdir()
path.joinpath('.0.0').mkdir()
with pytest.raises(FileExistsError):
install_package('ethpm://zeppelin.snakecharmers.eth:1/.0.0') |
.parametrize('value', (((ADDRESS_A, 'balance', 1), (ADDRESS_A, 'balance', 2)), ((ADDRESS_A, 'storage', 1, 12345), (ADDRESS_A, 'storage', 1, 54321))))
def test_normalize_state_detects_duplicates(value):
with pytest.raises(ValidationError, match='Some state item is defined multiple times'):
normalize_state(va... |
class FakeInfoWatcherWithTimer(core.InfoWatcher):
def __init__(self, delay_s: int=60, time_change: float=0.02):
super().__init__(delay_s)
self.start_timer = time.time()
self.time_change = time_change
def get_state(self, job_id: str, mode: str='standard') -> str:
duration = (time.... |
class OptionSeriesParetoSonificationDefaultinstrumentoptionsMappingTremoloDepth(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text... |
class GrpcNotifierFactory(object):
def __init__(self, config):
self.config = config
def create_and_register_service(self, server):
service = GrpcNotifier(notifier_api=notifier, service_config=self.config)
notifier_pb2_grpc.add_NotifierServicer_to_server(service, server)
LOGGER.in... |
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [migrations.CreateModel(name='Blog', fields=[('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('date_added', models.DateTimeFi... |
def test_commands_can_return_md(dummy_execute_and_send):
(dummy, m) = dummy_execute_and_send
dummy._execute_and_send(cmd='return_args_as_md', args=['foo', 'bar'], match=None, msg=m, template_name=dummy.return_args_as_md._err_command_template)
response = dummy.pop_message()
assert ('foobar' == response.b... |
class InvalidForm(BadRequest):
def __init__(self, form):
super().__init__()
self.form = form
self.message = self._message()
def _message(self):
result = []
for (key, value) in self.form.errors.items():
for message in value:
result.append('{0}: ... |
def deploy_modal():
modal_deploy_cmd = ['modal', 'deploy', 'app']
try:
console.print(f" [bold cyan]Running: {' '.join(modal_deploy_cmd)}[/bold cyan]")
subprocess.run(modal_deploy_cmd, check=True)
console.print(" [bold green]'modal deploy' executed successfully.[/bold green]")
except ... |
class TransactionCoverage(db.Model):
__tablename__ = 'ofec_agg_coverage_date_mv'
idx = db.Column(db.Integer, primary_key=True)
committee_id = db.Column('committee_id', db.String, doc=docs.COMMITTEE_ID)
fec_election_year = db.Column('fec_election_yr', db.Integer)
transaction_coverage_date = db.Column... |
def _is_declaration(Line: str) -> bool:
comment = False
for i in range(0, len(Line)):
if (Line[i] == '#'):
comment = True
if ((Line[i] == '=') and (not comment)):
if (('[' in Line[i]) and (']' in Line[i])):
l_bracket = Line[i].find('[')
new... |
class BaseModifyPacketTest(base_tests.SimpleDataPlane):
def verify_modify(self, actions, pkt, exp_pkt):
(in_port, out_port) = openflow_ports(2)
actions = (actions + [ofp.action.output(out_port)])
logging.info('Running actions test for %s', pp(actions))
delete_all_flows(self.controlle... |
_metaclass(abc.ABCMeta)
class tlv(stringify.StringifyMixin):
_TYPE_LEN = 1
_LENGTH_LEN = 2
_TYPE = {'ascii': ['egress_id_mac', 'last_egress_id_mac', 'next_egress_id_mac', 'mac_address']}
def __init__(self, length):
self.length = length
def parser(cls, buf):
pass
def serialize(sel... |
class UAVEnv(object):
height = ground_length = ground_width = 100
sum_task_size = (60 * 1048576)
loc_uav = [50, 50]
bandwidth_nums = 1
B = (bandwidth_nums * (10 ** 6))
p_noisy_los = (10 ** (- 13))
p_noisy_nlos = (10 ** (- 11))
flight_speed = 50.0
f_ue = .0
f_uav = .0
r = (10 ... |
def poker_game(ws: WebSocket, connection_channel: str):
client_channel = ChannelWebSocket(ws)
if ('player-id' not in session):
client_channel.send_message({'message_type': 'error', 'error': 'Unrecognized user'})
client_channel.close()
return
session_id = str(uuid.uuid4())
player_... |
.parametrize('analysis_config', [AnalysisConfig(), AnalysisConfig.from_dict({})])
def test_analysis_config_iter_config_default_initialisation(analysis_config):
assert (analysis_config.num_iterations == 4)
assert (analysis_config.num_retries_per_iter == 4)
analysis_config.set_num_iterations(42)
assert (a... |
class OptionPlotoptionsXrangeSonificationDefaultspeechoptionsMappingPlaydelay(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: ... |
class Schur_Qp(SchurPrecon):
def __init__(self, L, prefix=None, bdyNullSpace=False):
SchurPrecon.__init__(self, L, prefix, bdyNullSpace)
self.operator_constructor = SchurOperatorConstructor(self)
self.Q = self.operator_constructor.initializeQ()
def setUp(self, global_ksp, newton_its=None... |
class _SCUtil():
PROG_NAMESERVER = re.compile('.*nameserver\\[\\d+\\] : ({}).*'.format(RE_IPV4_ADDRESS))
def _parse_resolver(lines, istart):
ips = []
iline = istart
for iline in range(istart, len(lines)):
matches = _SCUtil.PROG_NAMESERVER.match(lines[iline])
if ma... |
class JSONChecker(Checker):
CHECKER_DATA_TYPE = 'json'
CHECKER_DATA_SCHEMA = {'type': 'object', 'properties': {'url': {'type': 'string', 'format': 'uri'}, 'tag-query': {'type': 'string'}, 'tag-data-url': {'type': 'string'}, 'commit-query': {'type': 'string'}, 'commit-data-url': {'type': 'string'}, 'version-quer... |
def run_migrations_online():
configuration = config.get_section(config.config_ini_section)
configuration['sqlalchemy.url'] = get_url()
connectable = engine_from_config(configuration, prefix='sqlalchemy.', poolclass=pool.NullPool)
with connectable.connect() as connection:
context.configure(connec... |
def test_deepcopy_args():
provider = providers.List()
dependent_provider1 = providers.Factory(list)
dependent_provider2 = providers.Factory(dict)
provider.add_args(dependent_provider1, dependent_provider2)
provider_copy = providers.deepcopy(provider)
dependent_provider_copy1 = provider_copy.args... |
def main(timeout=0):
global mainloop
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
adapter = find_adapter(bus)
if (not adapter):
print('LEAdvertisingManager1 interface not found')
return
adapter_props = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NA... |
class TestMacsXLSForMacs2010_(unittest.TestCase):
def test_load_macs2_xls_file(self):
macsxls = MacsXLS(fp=io.StringIO(MACS2010__data))
self.assertEqual(macsxls.macs_version, '2.0.10.')
self.assertEqual(macsxls.name, 'Gli1_ChIP_vs_input_36bp_bowtie_mm10_BASE_mfold5,50_Pe-5_Q0.05_bw250_MACS2'... |
class Labish():
("Please use 'names' instead.")
def labish_names(self) -> tuple[(str, ...)]:
return self.names()
("Please use 'indexes' instead.")
def labish_indexes(self) -> list[int]:
return self.indexes()
def names(self) -> tuple[(str, ...)]:
return self.channels[:(- 1)]
... |
class OptionPlotoptionsFunnel3dSonificationTracksMappingTremoloSpeed(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class TestFocalLoss(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
np.random.seed(42)
def test_focal_loss_equals_ce_loss(self) -> None:
inputs = logit(torch.tensor([[[0.95], [0.9], [0.98], [0.99]]], dtype=torch.float32))
targets = torch.tensor([[[1], [1], [1], [1]]]... |
class LocalFileAdminTests(Base.FileAdminTests):
def fileadmin_class(self):
return fileadmin.FileAdmin
def fileadmin_args(self):
return ((self._test_files_root, '/files'), {})
def test_fileadmin_sort_bogus_url_param(self):
fileadmin_class = self.fileadmin_class()
(fileadmin_ar... |
class TestPluginsNorthCommon(object):
.parametrize('value, expected', [('xxx', 'xxx'), ('1xx', '1xx'), ('x1x', 'x1x'), ('xx1', 'xx1'), ('26/04/2018 11:14', '26/04/2018 11:14'), ((- 180.2), (- 180.2)), (0.0, 0.0), (180.0, 180.0), (180.2, 180.2), ('-180.2', (- 180.2)), ('180.2', 180.2), ('180.0', 180.0), ('180.', 180... |
class CustomSystemRoleSchema(Schema):
class Meta():
type_ = 'custom-system-role'
self_view = 'v1.custom_system_role_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
id = fields.Str(dump_only=True)
name = fields.Str(required=True)
panel_permissions = Relations... |
('cuda.bmm_rcr_n1.func_decl')
def gen_function_decl(func_attrs):
func_name = func_attrs['name']
backend_spec = CUDASpec()
elem_input_type = backend_spec.dtype_to_lib_type(func_attrs['inputs'][0]._attrs['dtype'])
elem_output_type = backend_spec.dtype_to_lib_type(func_attrs['outputs'][0]._attrs['dtype'])
... |
def flatten_diff(diff):
valid_instructions = ('KEEP', 'REMOVE', 'ADD', 'UPDATE')
def _get_all_nested_diff_instructions(diffpart):
out = []
typ = type(diffpart)
if ((typ == tuple) and (len(diffpart) == 3) and (diffpart[2] in valid_instructions)):
out = [diffpart[2]]
el... |
class table_desc_stats_request(stats_request):
version = 6
type = 18
stats_type = 14
def __init__(self, xid=None, flags=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:
... |
class CategoricalDirichletModel():
def __init__(self, alpha: Tensor) -> None:
self.alpha_ = alpha
_variable
def dirichlet(self) -> dist.Distribution:
return dist.Dirichlet(self.alpha_)
_variable
def categorical(self) -> dist.Distribution:
return dist.Categorical(self.dirichle... |
def window_function(name, window_type, length, fft_mode, linewrap):
import scipy.signal
window = scipy.signal.get_window(window_type, length, fftbins=fft_mode)
arrays = [cgen.array_declare(name, length, values=window), cgen.constant_declare((name + '_length'), val=length)]
gen = '\n'.join(arrays)
w ... |
((detect_target().name() == 'rocm'), 'Not supported by ROCM.')
class VarTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(VarTestCase, self).__init__(*args, **kwargs)
self.test_count = 0
def _run_var(self, *, dim, unbiased, input_shape, keepdim=False, input_type='float16', ... |
class TornadoTest(unittest.TestCase, BaseTest):
expected_data = {'language': 'python', 'engine': 'tornado', 'evaluate': 'python', 'execute': True, 'read': True, 'write': True, 'prefix': '', 'suffix': '', 'trailer': '{{%(trailer)s}}', 'header': '{{%(header)s}}', 'render': '{{%(code)s}}', 'bind_shell': True, 'reverse... |
def test_inactivate_thin_cells(tmpdir):
grd = xtgeo.grid_from_file(EMEGFILE)
reg = xtgeo.gridproperty_from_file(EMERFILE, name='REGION')
nhdiv = 40
grd.convert_to_hybrid(nhdiv=nhdiv, toplevel=1650, bottomlevel=1690, region=reg, region_number=1)
grd.inactivate_by_dz(0.001)
grd.to_file(join(tmpdir... |
class GreetingWorkflowImpl(GreetingWorkflow):
def __init__(self):
retry_parameters = RetryParameters(maximum_attempts=1)
self.greeting_activities: GreetingActivities = Workflow.new_activity_stub(GreetingActivities, retry_parameters=retry_parameters)
async def get_greeting(self):
try:
... |
def f_parse_saves(threads=None, save_path=None, game_name_prefix='') -> None:
if (threads is not None):
config.CONFIG.threads = threads
if (save_path is None):
save_path = config.CONFIG.save_file_path
save_reader = save_parser.BatchSavePathMonitor(save_path, game_name_prefix=game_name_prefix... |
class FaucetUntaggedIPv4ControlPlaneFuzzTest(FaucetUntaggedTest):
CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "untagged"\n faucet_vips: ["10.0.0.254/24"]\n'
CONFIG = ('\n max_resolve_backoff_time: 1\n' + CONFIG_BOILER_UNTAGGED)
def test_ping_fragment_controller(self):
fir... |
class bBitMinHash(object):
__slots__ = ('seed', 'b', 'r', 'hashvalues')
_serial_fmt_params = '<qBdi'
_serial_fmt_block = 'Q'
def __init__(self, minhash, b=1, r=0.0):
b = int(b)
r = float(r)
if ((b > 32) or (b < 0)):
raise ValueError('b must be an integer in [0, 32]')
... |
('new')
def cancel_sell(uid, entry_id):
s = current_session()
entry = s.query(Exchange).filter((Exchange.id == entry_id), (Exchange.seller_id == uid)).first()
if (not entry):
raise exceptions.ItemNotFound
helpers.require_free_backpack_slot(s, uid)
item = entry.item
item.owner_id = uid
... |
def test_read_json_file():
file_contents = '{\n "hello": "world"\n}'
with make_tempdir({'tmp.json': file_contents}) as temp_dir:
file_path = (temp_dir / 'tmp.json')
assert file_path.exists()
data = read_json(file_path)
assert (len(data) == 1)
assert (data['hello'] == 'world') |
def test_vector_bilinear_exterior_facet_integral():
mesh = IntervalMesh(5, 5)
V = VectorFunctionSpace(mesh, 'CG', 1, dim=2)
u = TrialFunction(V)
v = TestFunction(V)
a = (inner(u, v) * ds)
A = assemble(a)
values = A.M.values
nonzeros = [[0, 0], [1, 1], [(- 2), (- 2)], [(- 1), (- 1)]]
... |
class ColorSet(object):
def __init__(self, h_range, s_range, v_range, overflow='cutoff', dep_wtp=1):
self.synchronization = 0
self.dep_wtp = dep_wtp
self.set_hsv_ranges(h_range, s_range, v_range)
assert (0.0 <= self._h_range[0] <= 360.0)
assert (0.0 <= self._h_range[1] <= 360... |
class OptionPlotoptionsAreasplinerangeStatesSelectMarker(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def enabledThreshold(self):
return self._config_get(2)
def enabledThreshold(self, num: float):
... |
def make_local_storage(path, env=None):
path = str(path)
try:
if (not os.path.exists(path)):
action = 'create'
os.makedirs(path, exist_ok=True)
else:
action = 'write to'
with tempfile.NamedTemporaryFile(dir=path):
pass
except Pe... |
def print_type(gtype, nonnull=True, except_types=()):
if isinstance(gtype, except_types):
raise ValidationError(f'{gtype} is not a valid type')
literal = None
if is_union(gtype):
if is_optional(gtype):
return f'{print_type(gtype.__args__[0], nonnull=False, except_types=except_typ... |
.integrationtest
.skipif((pymongo.version_tuple < (3, 0)), reason='New in 3.0')
def test_collection_insert_one(instrument, elasticapm_client, mongo_database):
blogpost = {'author': 'Tom', 'text': 'Foo', 'date': datetime.datetime.utcnow()}
elasticapm_client.begin_transaction('transaction.test')
r = mongo_dat... |
class TestStackMin(unittest.TestCase):
def test_stack_min(self):
print('Test: Push on empty stack, non-empty stack')
stack = StackMin()
stack.push(5)
self.assertEqual(stack.peek(), 5)
self.assertEqual(stack.minimum(), 5)
stack.push(1)
self.assertEqual(stack.pe... |
def aggregate(conf, fedavg_models, client_models, criterion, metrics, flatten_local_models, fa_val_perf, distillation_sampler, distillation_data_loader, val_data_loader, test_data_loader):
fl_aggregate = conf.fl_aggregate
(_, local_models) = agg_utils.recover_models(conf, client_models, flatten_local_models, us... |
class Heapdump(TelemetryDevice):
internal = False
command = 'heapdump'
human_name = 'Heap Dump'
help = 'Captures a heap dump.'
def __init__(self, log_root):
super().__init__()
self.log_root = log_root
def detach_from_node(self, node, running):
if running:
io.e... |
def test_hover_parameter_double_sf():
string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)})
file_path = ((test_dir / 'hover') / 'parameters.f90')
string += hover_req(file_path, 7, 55)
(errcode, results) = run_request(string, fortls_args=['--sort_keywords'])
assert (errcode == 0)
... |
class ClassBSpartlines(GrpCls.ClassHtml):
def css(self) -> AttrClsChart.AttrSkarkline:
if (self._css_struct is None):
self._css_struct = AttrClsChart.AttrSkarkline(self.component)
return self._css_struct
def css_class(self) -> Classes.CatalogDiv.CatalogDiv:
if (self._css_clas... |
class Use(models.Model):
PENDING = 'pending'
APPROVED = 'approved'
CONFIRMED = 'confirmed'
HOUSE_DECLINED = 'house declined'
USER_DECLINED = 'user declined'
CANCELED = 'canceled'
USE_STATUSES = ((PENDING, 'Pending'), (APPROVED, 'Approved'), (CONFIRMED, 'Confirmed'), (HOUSE_DECLINED, 'House D... |
class OptionPlotoptionsSeriesMarkerStatesSelect(Options):
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def fillColor(self):
return self._config_get('#cccccc')
def fillColor(self, text: str):
self._config... |
def in_range(accessing_obj, accessed_obj, *args, **kwargs):
range = (args[0] if args else 'MELEE')
if hasattr(accessing_obj, 'nattributes'):
if (not (combat := accessing_obj.ndb.combat)):
return False
return combat.any_in_range(accessing_obj, range)
else:
return false |
class UCS(Space):
BASE = 'xyz-d65'
NAME = 'ucs'
SERIALIZE = ('--ucs',)
CHANNELS = (Channel('u', 0.0, 1.0), Channel('v', 0.0, 1.0), Channel('w', 0.0, 1.0))
WHITE = WHITES['2deg']['D65']
def to_base(self, coords: Vector) -> Vector:
return ucs_to_xyz(coords)
def from_base(self, coords: ... |
class FalServerlessHost(Host):
_SUPPORTED_KEYS = frozenset({'machine_type', 'keep_alive', 'max_concurrency', 'max_multiplexing', 'setup_function', 'metadata', '_base_image', '_scheduler', '_scheduler_options'})
url: str = FAL_SERVERLESS_DEFAULT_URL
credentials: Credentials = field(default_factory=get_defaul... |
def main():
parser = argparse.ArgumentParser()
add_debug(parser)
add_app(parser)
add_properties(parser)
add_provider(parser)
parser.add_argument('--email', help='Email address to associate with application', default='PS-')
parser.add_argument('--project', help='Git project to associate with ... |
class TestPaymentACK(unittest.TestCase):
def test_dict_optional_fields_unused(self):
payment = paymentrequest.Payment('merchant_data', 'transaction_hex')
payment_ack = paymentrequest.PaymentACK(payment)
data = payment_ack.to_dict()
self.assertTrue(('payment' in data))
self.as... |
def cut_silences(audio_file, output_file, silence_time=400, threshold=(- 65)) -> Path:
audio = AudioSegment.from_file(audio_file)
silences = silence.split_on_silence(audio, min_silence_len=silence_time, silence_thresh=threshold)
combined = AudioSegment.empty()
for chunk in silences:
combined += ... |
def serialize_classification_report(cr):
tmp = list()
for row in cr.split('\n'):
parsed_row = [x.strip() for x in row.split(' ') if (len(x.strip()) > 0)]
if (len(parsed_row) > 0):
tmp.append(parsed_row)
measures = tmp[0]
out = defaultdict(dict)
for row in tmp[1:]:
... |
def flatten_site_pins(tile, site, site_pins, site_pin_node_to_wires):
def inner():
for site_pin in site_pins:
wires = tuple(site_pin_node_to_wires(tile, site_pin['node']))
if (len(wires) == 0):
(yield (check_and_strip_prefix(site_pin['site_pin'], (site + '/')), None))... |
def main(page: ft.Page):
page.add(ft.DataTable(width=700, bgcolor='yellow', border=ft.border.all(2, 'red'), border_radius=10, vertical_lines=ft.border.BorderSide(3, 'blue'), horizontal_lines=ft.border.BorderSide(1, 'green'), sort_column_index=0, sort_ascending=True, heading_row_color=ft.colors.BLACK12, heading_row_... |
def test_client_register_task_definition_without_optional_values(client):
containers = [{u'name': u'foo'}]
volumes = [{u'foo': u'bar'}]
role_arn = 'arn:test:role'
execution_role_arn = 'arn:test:role'
runtime_platform = {u'cpuArchitecture': u'X86_64', u'operatingSystemFamily': u'LINUX'}
task_defi... |
def test_envvar_expansion():
os.environ['TEST_SERVICE'] = 'foo'
aconf = Config()
fetcher = ResourceFetcher(logger, aconf)
fetcher.parse_yaml(yaml)
aconf.load_all(fetcher.sorted())
mappings = aconf.config['mappings']
test_mapping = mappings['test_mapping']
assert (test_mapping.service == ... |
def _shape(a: (ArrayLike | float), s: Shape) -> Shape:
if (not isinstance(a, Sequence)):
return s
size = len(a)
if (not size):
return (size,)
first = _shape(a[0], s)
for r in range(1, size):
if (_shape(a[r], s) != first):
raise ValueError('Ragged lists are not sup... |
def train(model, train_loader, val_loader, optimizer, init_lr=0.002, checkpoint_dir=None, checkpoint_interval=None, nepochs=None, clip_thresh=1.0):
model.train()
if use_cuda:
model = model.cuda()
linear_dim = model.linear_dim
criterion = nn.CrossEntropyLoss()
validate(val_loader)
global ... |
class TestGetActiveTasks(unittest.TestCase):
def test_get_active_tasks(self):
task_active = Mock(spec=asyncio.Task)
task_active.done = (lambda : False)
task_active.cancelled = (lambda : False)
task_done = Mock(spec=asyncio.Task)
task_done.done = (lambda : True)
task_d... |
def check_telemetry():
settings = sublime.load_settings('Emmet.sublime-settings')
updated = False
if (not settings.get('uid')):
uid = str(uuid.uuid4())
settings.set('uid', uid)
send_tracking_action('Init', 'install')
updated = True
if (settings.get('telemetry', None) is N... |
class TestListFieldLengthLimit(FieldValues):
valid_inputs = ()
invalid_inputs = [((0, 1), ['Ensure this field has at least 3 elements.']), ((0, 1, 2, 3, 4, 5), ['Ensure this field has no more than 4 elements.'])]
outputs = ()
field = serializers.ListField(child=serializers.IntegerField(), min_length=3, ... |
class PlotLimits():
value_minimum = limit_property('value_minimum', (float, int))
value_maximum = limit_property('value_maximum', (float, int))
value_limits = limits_property('value_minimum', 'value_maximum')
index_minimum = limit_property('index_minimum', int, minimum=0)
index_maximum = limit_prope... |
class ERC20TransferBenchmark(BaseERC20Benchmark):
def __init__(self) -> None:
super().__init__()
self._next_nonce = None
def name(self) -> str:
return 'ERC20 Transfer'
def _setup_benchmark(self, chain: MiningChain) -> None:
self._next_nonce = None
(txn, callback) = se... |
def extractNishao10Com(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagmap... |
class udf_data(bsn_tlv):
type = 207
def __init__(self, value=None):
if (value != None):
self.value = value
else:
self.value = 0
return
def pack(self):
packed = []
packed.append(struct.pack('!H', self.type))
packed.append(struct.pack('!H... |
()
('--path', help='Root directory of source to be checked', required=True, type=str)
('--fixit', default=False, help='Fix missing header', required=False, type=bool)
def check_header(path, fixit):
ret = dfs(path)
if (len(ret) == 0):
sys.exit(0)
print('Need to add Meta header to the following files.... |
def add_UnityToExternalProtoServicer_to_server(servicer, server):
rpc_method_handlers = {'Exchange': grpc.unary_unary_rpc_method_handler(servicer.Exchange, request_deserializer=pyrcareworld_dot_communicator__objects_dot_unity__message__pb2.UnityMessageProto.FromString, response_serializer=pyrcareworld_dot_communica... |
def create_cfg_from_cli(config_file: str, overwrites: Optional[List[str]], runner_class: Union[(None, str, Type[BaseRunner], Type[DefaultTask])]) -> CfgNode:
config_file = reroute_config_path(config_file)
with PathManager.open(config_file, 'r') as f:
print('Loaded config file {}:\n{}'.format(config_file... |
class RegisterViewTests(TestCase):
urlpatterns = [path('', include('{{ cookiecutter.project_slug }}.auth.urls'))]
def test_endpoint(self):
url = reverse('{{ cookiecutter.project_slug }}-auth:register')
self.assertEqual(url, '/register/')
def test_get_response_status_code(self):
url =... |
def init():
gitrootdir = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).decode('utf-8').strip()
sys.path.insert(0, os.path.join(gitrootdir, 'common'))
sys.path.insert(0, os.path.join(gitrootdir, 'python'))
gitsubdir = subprocess.check_output(['git', 'rev-parse', '--show-prefix']).decod... |
def analyze_call_sites(ghidra_analysis, func, index, prev):
result = []
references_to = ghidra_analysis.current_program.getReferenceManager().getReferencesTo(func.getEntryPoint())
for reference in references_to:
from_address = reference.getFromAddress()
calling_func = ghidra_analysis.flat_ap... |
def annotation_to_gff(annotation):
attrs = []
(query_name, best_hit_name, best_hit_evalue, best_hit_score, annotations, (og_name, og_cat, og_desc), max_annot_lvl, match_nog_names, all_orthologies, annot_orthologs) = annotation
match_nog_names = ','.join(match_nog_names)
attrs.append(f'em_OGs={match_nog_... |
.parametrize('oper, expected', [('add', [10, 10, 10, 12]), ('sub', [10, 10, 10, 8]), ('div', [10, 10, 10, 5]), ('mul', [10, 10, 10, 20]), ('set', [10, 10, 10, 2])])
def test_oper_points_inside_overlapping_polygon_v2(oper, expected):
pol = Polygons((SMALL_POLY_INNER + SMALL_POLY_OVERLAP_INNER))
poi = Points([(3.... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'name'
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path':... |
def wrap_stub(elf_file):
print(('Wrapping ELF file %s...' % elf_file))
e = esptool.bin_image.ELFFile(elf_file)
text_section = e.get_section('.text')
stub = {'entry': e.entrypoint, 'text': text_section.data, 'text_start': text_section.addr}
try:
data_section = e.get_section('.data')
s... |
def oklab_to_okhsl(lab: Vector, lms_to_rgb: Matrix, ok_coeff: list[Matrix]) -> Vector:
L = lab[0]
s = 0.0
l = toe(L)
c = math.sqrt(((lab[1] ** 2) + (lab[2] ** 2)))
h = (0.5 + (math.atan2((- lab[2]), (- lab[1])) / math.tau))
if ((l != 0.0) and (l != 1.0) and (c != 0)):
a_ = (lab[1] / c)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.