code stringlengths 281 23.7M |
|---|
class TestTimeSeriesOOFModel():
def test_fit_predict(self):
(X, y) = gen_ts_data(10000)
model = TimeSeriesOOFModel(TsTestModel(), time_column='date', fold_cnt=20)
model.fit(X, y['y'])
pred = model.predict(X)
info = X.copy()
info['pred'] = pred
assert info['pre... |
class FullSyncStrategy(BaseSyncStrategy):
def get_sync_mode(cls) -> str:
return SYNC_FULL
async def sync(self, args: Namespace, logger: logging.Logger, chain: AsyncChainAPI, base_db: AtomicDatabaseAPI, peer_pool: BasePeerPool, event_bus: EndpointAPI, metrics_service: MetricsServiceAPI) -> None:
... |
def valve_flowreorder(input_ofmsgs, use_barriers=True):
output_ofmsgs = []
by_kind = _partition_ofmsgs(input_ofmsgs)
delete_global_ofmsgs = by_kind.get('deleteglobal', [])
if delete_global_ofmsgs:
global_types = {type(ofmsg) for ofmsg in delete_global_ofmsgs}
new_delete = [ofmsg for ofms... |
def test_constraints_expression():
and_expression = And([Constraint('number', ConstraintType(ConstraintTypes.LESS_THAN, 15)), Constraint('number', ConstraintType(ConstraintTypes.GREATER_THAN, 10))])
and_expression.check_validity()
assert and_expression.check(Description({'number': 12}))
assert and_expre... |
class ExpGen(object):
def __init__(self):
pass
def max(a, b):
exp = '({a}>{b}?{a}:{b})'.format(a=a, b=b)
return exp
def min(a, b):
exp = '({a}<{b}?{a}:{b})'.format(a=a, b=b)
return exp
def parse(expr):
s = SvalEE()
return s.eval(expr) |
class TestReadCommands(EfuseTestCase):
def test_help(self):
self.espefuse_not_virt_py('--help', check_msg='usage: __main__.py [-h]')
self.espefuse_not_virt_py(f'--chip {arg_chip} --help')
def test_help2(self):
self.espefuse_not_virt_py('', check_msg='usage: __main__.py [-h]', ret_code=1)... |
class HelpDetailTest(EvenniaWebTest):
url_name = 'help-entry-detail'
def setUp(self):
super().setUp()
create_help_entry('unit test db entry', 'unit test db entry text', category='General')
def get_kwargs(self):
return {'category': slugify('general'), 'topic': slugify('unit test db en... |
def getchangeserver():
return '0'
dialog = xbmcgui.Dialog()
changeserver = ''
servers = [['cdntel.115.com', 'vipcdntel.115.com', 'mzvipcdntel.115.com', 'fscdntel.115.com', 'mzcdntel.115.com'], ['cdnuni.115.com', 'vipcdnuni.115.com', 'mzvipcdnuni.115.com', 'fscdnuni.115.com', 'mzcdnuni.115.com'], ['cdngw... |
class TlsBulkCertificateResponseAttributesAllOf(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
return {'not_a... |
class SafeDict(dict):
def __setitem__(self, key, value):
if (key in self):
if (value is self[key]):
return
raise KeyError(("Attempted to override key '%s' in a SafeDict" % key))
return dict.__setitem__(self, key, value)
def update(self, *other_dicts):
... |
def _build_node_section(tree):
for (cluster_name, cluster_conf) in tree['cluster'].items():
node_kind_config = dict(((key, value) for (key, value) in cluster_conf.items() if key.endswith('_nodes')))
if ('nodes' not in cluster_conf):
cluster_conf['nodes'] = {}
for key in node_kind... |
def update_kpis(date, days=7):
df_summary = pd.read_sql(sql=app.session.query(stravaSummary).filter((stravaSummary.start_date_utc <= date)).statement, con=engine, index_col='start_date_local')
athlete_info = app.session.query(athlete).filter((athlete.athlete_id == 1)).first()
use_power = (True if (athlete_i... |
def _get_new_brunswick_flows(requests_obj):
url = '
response = requests_obj.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table', attrs={'bordercolor': '#191970'})
rows = table.find_all('tr')
headers = rows[1].find_all('td')
values = rows[2].find_all('td')
... |
def evals(n, degree=1, mesh=None):
if (mesh is None):
mesh = IntervalMesh(n, 0, pi)
V = FunctionSpace(mesh, 'CG', degree)
u = TrialFunction(V)
v = TestFunction(V)
a = (inner(grad(u), grad(v)) * dx)
bc = DirichletBC(V, 0.0, 'on_boundary')
eigenprob = LinearEigenproblem(a, bcs=bc, bc_s... |
class OptionPlotoptionsTreegraphLevelsColorvariation(Options):
def key(self):
return self._config_get(None)
def key(self, value: Any):
self._config(value, js_type=False)
def to(self):
return self._config_get(None)
def to(self, num: float):
self._config(num, js_type=False) |
class OptionSeriesWindbarbDragdropGuideboxDefault(Options):
def className(self):
return self._config_get('highcharts-drag-box-default')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('rgba(0, 0, 0, 0.1)')
def color(self,... |
.parametrize('calcs, ref_energy, ref_force_norm', [pytest.param({'real': {'type': 'g16', 'route': 'hf sto-3g'}, 'high': {'type': 'g16', 'route': 'b3lyp d95v'}}, (- 153.), 0., marks=using('gaussian16')), pytest.param({'real': {'type': 'g16', 'route': 'hf sto-3g'}, 'high': {'type': 'g16', 'route': 'b3lyp 3-21g'}}, (- 152... |
def parse_arguments() -> argparse.Namespace():
parser = argparse.ArgumentParser()
parser.add_argument('-g', '--ghidra_path', nargs='?', default='/opt/ghidra', help='path to Ghidra')
parser.add_argument('file_path', help='path to binary/firmware')
parser.add_argument('result_path', nargs='?', default='',... |
def print_comparatives(omorfi, word, upos, comp, outfile):
if (comp == 'POS'):
print('#### Nominal cases', file=outfile)
tags = '[CMP=POS]'
elif (comp == 'CMP'):
print('#### Comparative cases', file=outfile)
tags = '[DRV=MPI][CMP=CMP]'
elif (comp == 'SUP'):
print('###... |
class StridedConvolutionDenseBlock(PerceptionBlock):
def __init__(self, in_keys: Union[(str, List[str])], out_keys: Union[(str, List[str])], in_shapes: Union[(Sequence[int], List[Sequence[int]])], hidden_channels: List[int], hidden_kernels: List[Union[(int, Tuple[(int, ...)])]], convolution_dimension: int, hidden_s... |
def register_operators(op_dict: Dict[(str, Type[OperatorInterface])]):
global op_map
for (name, operator_class) in op_dict.items():
logger.debug(f'register op: {name}')
if (name not in op_map):
op_map[name] = operator_class
else:
raise ValueError(f'Duplicate opera... |
class Char_Array_Literal(Literal):
def __init__(self, t_string):
super().__init__()
assert isinstance(t_string, MATLAB_Token)
assert (t_string.kind in ('CARRAY', 'BANG'))
self.t_string = t_string
self.t_string.set_ast(self)
def __str__(self):
return (("'" + self.t... |
def drawcirc(r, w, du, dv, N):
w = np.maximum(w, 1)
x = (np.ones([N, 1]) * (((np.arange(0, N, 1, dtype='float') - ((N + 1) / 2)) - dv) / r))
y = ((((np.arange(0, N, 1, dtype='float') - ((N + 1) / 2)) - du) / r) * np.ones([1, N])).T
p = (0.5 + (0.5 * np.sin(np.minimum(np.maximum(((np.exp((np.array([(- 0.... |
def upgrade():
bind: Connection = op.get_bind()
bind.execute(text('\n UPDATE privacydeclaration \n SET flexible_legal_basis_for_processing = false \n WHERE flexible_legal_basis_for_processing IS NULL;\n '))
op.alter_column('privacydeclaration', 'flexible_legal_bas... |
class _Model():
__db_manager__: ClassVar[DatabaseManager]
query_class = BaseQuery
def __repr__(self):
identity = inspect(self).identity
if (identity is None):
pk = '(transient {0})'.format(id(self))
else:
pk = ', '.join((_to_str(value) for value in identity))
... |
def test_sync_checkpoint_save_file(tmpdir):
td_path = Path(tmpdir)
cp = SyncCheckpoint(checkpoint_dest=tmpdir)
dst_path = td_path.joinpath(SyncCheckpoint.TMP_DST_PATH)
assert (not dst_path.exists())
inp = td_path.joinpath('test')
with inp.open('wb') as f:
f.write(b'blah')
with inp.op... |
def test_read_arrow_optional_polars(requests_mock: Mocker):
response_data = b'A\xff\xff\xff\xff\xb0\x01\x00\x00\x10\x00\x00\x00\x00\x00\n\x00\x0e\x00\x06\x00\r\x00\x08\x00\n\x00\x00\x00\x00\x00\x04\x00\x10\x00\x00\x00\x00\x01\n\x00\x0c\x00\x00\x00\x08\x00\x04\x00\n\x00\x00\x00\x08\x00\x00\x00,\x01\x00\x00\x01\x00\x... |
def evaluate(data: List[List[Tuple[(str, str)]]], *args):
(total, correct) = (0, 0)
for sentence in data:
(tokens, gold) = tuple(zip(*sentence))
pred = [t[0] for t in predict(tokens, args)]
total += len(tokens)
correct += len([1 for (g, p) in zip(gold, pred) if (g == p)])
acc... |
def start_command():
parser = argparse.ArgumentParser(description='EmbedChain WhatsAppBot command line interface')
parser.add_argument('--host', default='0.0.0.0', help='Host IP to bind')
parser.add_argument('--port', default=5000, type=int, help='Port to bind')
args = parser.parse_args()
whatsapp_b... |
class ANTLRCommand(Command):
description = 'Run ANTLR'
user_options: List[str] = []
def run(self) -> None:
root_dir = abspath(dirname(__file__))
project_root = abspath(dirname(basename(__file__)))
for grammar in ['hydra/grammar/OverrideLexer.g4', 'hydra/grammar/OverrideParser.g4']:
... |
def fetch_production_capacity_for_all_zones(target_datetime: datetime, session: Session) -> (dict[(str, Any)] | None):
all_capacity = get_capacity_data_for_all_zones(target_datetime, session)
all_capacity = {k: v for (k, v) in all_capacity.items() if (k in IRENA_ZONES)}
logger.info(f'Fetched capacity data f... |
class IntegrationRuleDetailMDX():
def __init__(self, rule_id: str, rule: dict, changelog: Dict[(str, dict)], package_str: str):
self.rule_id = rule_id
self.rule = rule
self.changelog = changelog
self.package = package_str
self.rule_title = f"prebuilt-rule-{self.package}-{name... |
.parametrize('cmd_args', [['generate', '--output-path', 'generated/'], ['generate', '--output-path', 'generated/', '--progress'], ['generate', '--output-path', 'generated/', '--export-matches', 'generated/matches.yml'], ['generate', '--output-path', 'generated/', '-m', 'examples/mapping.yml']])
.usefixtures('_mock_dag'... |
class Migration(migrations.Migration):
dependencies = [('frontend', '0067_auto__1354')]
operations = [migrations.AddField(model_name='measure', name='denominator_bnf_codes_filter', field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=16), null=True, size=None)), migrations.AddF... |
def get_clusters_from_doc(doc: Doc, *, use_heads: bool=False, prefix: Optional[str]=None) -> List[List[Tuple[(int, int)]]]:
out = []
keys = sorted(list(doc.spans.keys()))
for key in keys:
if ((prefix is not None) and (not matches_coref_prefix(prefix, key))):
continue
val = doc.sp... |
.django_db
def test_uei_keyword_filter(client, monkeypatch, spending_by_award_test_data, elasticsearch_award_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_award_index)
resp = client.post('/api/v2/search/spending_by_award', content_type='application/json', data=json.dumps({'filters': {'award_type_c... |
def test_attention_sequential():
in_dict = build_multi_input_dict(dims=[(2, 7, 10), (2, 7, 10), (2, 7, 10)])
self_attn_block = MultiHeadAttentionBlock(in_keys=['in_key_0', 'in_key_1', 'in_key_2'], out_keys='self_attention', in_shapes=[(7, 10), (7, 10), (7, 10)], num_heads=10, dropout=0.0, bias=False, add_input_... |
class OptionPlotoptionsDependencywheelSonificationTracksMappingGapbetweennotes(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 conn_tracking_zone_masked(oxm):
type_len = 120068
def __init__(self, value=None, value_mask=None):
if (value != None):
self.value = value
else:
self.value = 0
if (value_mask != None):
self.value_mask = value_mask
else:
self.va... |
def test_data_model():
params = dict(name='test', type_=str, is_required=True)
data_model = DataModel('test', [Attribute(**params)])
data_model._check_validity()
with pytest.raises(ValueError, match="Invalid input value for type 'DataModel': duplicated attribute name."):
data_model = DataModel('... |
def extractBlancabloggingblockWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Mahousekai', 'Mahousekai no Uketsukejou ni Naritaidesu', 'translated'), ('Matsurikade... |
class OptionSeriesBubbleSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionSeriesBubbleSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesBubbleSonificationDefaultinstrumentoptionsMappingTremoloDepth)
def speed(... |
def get_commands(wf, query):
result = execute(wf, ['brew', 'commands']).splitlines()
commands = [x for x in result if (' ' not in x)]
query_filter = query.split()
if (len(query_filter) > 1):
return wf.filter(query_filter[1], commands, match_on=MATCH_SUBSTRING)
return commands |
def test_ros2_decoder_msg_eq():
with generate_sample_data() as m:
reader = make_reader(m, decoder_factories=[DecoderFactory()])
decoded_messages = reader.iter_decoded_messages('/chatter')
(_, _, _, msg0) = next(decoded_messages)
(_, _, _, msg1) = next(decoded_messages)
assert... |
_list
def block_hashes_in_range(w3: 'Web3', block_range: Tuple[(BlockNumber, BlockNumber)]) -> Iterable[Hash32]:
(from_block, to_block) = block_range
if ((from_block is None) or (to_block is None)):
return
for block_number in range(from_block, (to_block + 1)):
(yield getattr(w3.eth.get_block... |
def findCert():
curFile = os.path.abspath(__file__)
curDir = os.path.split(curFile)[0]
caCert = os.path.abspath(os.path.join(curDir, './certs/cacert.pem'))
cert = os.path.abspath(os.path.join(curDir, './certs/cert.pem'))
keyf = os.path.abspath(os.path.join(curDir, './certs/key.pem'))
assert os.p... |
def test_idv_transactions_csv_sources(db):
original = VALUE_MAPPINGS['idv_transaction_history']['filter_function']
VALUE_MAPPINGS['idv_transaction_history']['filter_function'] = MagicMock(returned_value='')
csv_sources = download_generation.get_download_sources({'download_types': ['idv_transaction_history']... |
def generate_aggregated_capacity_config_dict(capacity_config: list[dict[(str, Any)]], parent_zone: ZoneKey) -> (dict[(str, Any)] | None):
datetime_values = set([capacity_config['datetime'] for capacity_config in capacity_config])
sources = set([capacity_config['source'] for capacity_config in capacity_config])
... |
class RankingHistory(models.Model):
class Meta():
verbose_name = ''
verbose_name_plural = ''
constraints = [models.UniqueConstraint(fields=['game', 'player', 'category'], name='ranking_history_uniq')]
id = models.IntegerField(**_('ID'), primary_key=True)
game = models.ForeignKey(Game... |
.parametrize('sampling', ['None', 'bilinear'])
.parametrize('coords, expected_val', [pytest.param(((10.0 - 0.009), 10.0), None, id='(xori - 9e-3, yori)'), pytest.param((10.0, (20.0 + 0.009)), None, id='(xori, ymax - 9e-3)'), pytest.param(((20.0 + 0.009), 10.0), None, id='(xmax + 9e-3, yori)'), pytest.param(((20.0 + 0.0... |
class CustomSysRole(db.Model):
__tablename__ = 'custom_sys_roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, unique=True)
def can_access(self, panel_name):
panel = PanelPermission.query.filter_by(panel_name=panel_name).first()
for role in panel.custom_system... |
class TestIterativeMethods(proteus.test_utils.TestTools.BasicTest):
def setup_method(self, method):
self.petsc_options = PETSc.Options()
self.petsc_options.clear()
for k in self.petsc_options.getAll():
self.petsc_options.delValue(k)
self._scriptdir = os.path.dirname(__fil... |
class conn_tracking_state(oxm):
type_len = 119300
def __init__(self, value=None):
if (value != None):
self.value = value
else:
self.value = 0
return
def pack(self):
packed = []
packed.append(struct.pack('!L', self.type_len))
packed.appe... |
class Case(object):
def __init__(self, cs: ConditionalSection, expr: Optional[Union[(ComparisonExpression, ConjunctionExpression)]], stmt: str='elif'):
self._cs = cs
if (expr is not None):
if isinstance(expr, bool):
raise AssertionError(f'Logical (and/or/is/not) operation... |
class TestProposedPESQ(unittest.TestCase):
def setUp(self):
self.ref_path = get_file_path('speech.wav')
self.deg_path = get_file_path('speech_bab_0dB.wav')
self.ref_array = pb.io.load_audio(self.ref_path)
self.deg_array = pb.io.load_audio(self.deg_path)
def test_wb_scores_with_li... |
.parametrize('max_count,max_size', [(3, None), (None, (3 * SIZEOF_TEST_TX_SMALL)), (3, (3 * SIZEOF_TEST_TX_SMALL))])
def test_lrucache_add_past_limit_lru_ordering(max_count: int, max_size: int, test_tx_small) -> None:
cache = LRUCache(max_count=max_count, max_size=max_size)
cache.set(b'1', test_tx_small)
ca... |
_icmp_type(ICMP_ECHO_REPLY, ICMP_ECHO_REQUEST)
class echo(_ICMPv4Payload):
_PACK_STR = '!HH'
_MIN_LEN = struct.calcsize(_PACK_STR)
def __init__(self, id_=0, seq=0, data=None):
super(echo, self).__init__()
self.id = id_
self.seq = seq
self.data = data
def parser(cls, buf, ... |
class MyObject(event.Component):
foo = event.Property(0)
def set_foo(self, v):
self._mutate_foo(v)
def set_foo_add(self, *args):
self._mutate_foo(sum(args))
def increase_foo(self):
self.set_foo((self.foo + 1))
self.set_foo((self.foo + 1))
def do_silly(self):
r... |
class PlatformDdosResponseData(ModelSimple):
allowed_values = {}
validations = {}
additional_properties_type = None
_nullable = False
_property
def openapi_types():
lazy_import()
return {'value': ([PlatformDdosEntry],)}
_property
def discriminator():
return None
... |
class TestTurnBattleItemsFunc(BaseEvenniaTest):
('evennia.contrib.game_systems.turnbattle.tb_items.tickerhandler', new=MagicMock())
def setUp(self):
super().setUp()
self.testroom = create_object(DefaultRoom, key='Test Room')
self.attacker = create_object(tb_items.TBItemsCharacter, key='A... |
class BranchNotFoundError(FoundryAPIError):
def __init__(self, dataset_rid: str, branch: str, transaction_rid: (str | None)=None, response: (requests.Response | None)=None):
super().__init__((((f'Dataset {dataset_rid} ' + (f'on transaction {transaction_rid}' if (transaction_rid is not None) else '')) + f'''... |
def test_lifespan_scope_asgi2app():
def asgi2app(scope):
assert (scope == {'type': 'lifespan', 'asgi': {'version': '2.0', 'spec_version': '2.0'}, 'state': {}})
async def asgi(receive, send):
pass
return asgi
async def test():
config = Config(app=asgi2app, lifespan='on... |
class PhantomClient(object):
def __init__(self, user, password, base_url, verify_ssl=True):
self._user = user
self._password = password
self._base_url = base_url
self._verify_ssl = verify_ssl
def create_container(self, container):
response = requests.post((self._base_url ... |
def eager(_fn=None, *, remote: Optional[FlyteRemote]=None, client_secret_group: Optional[str]=None, client_secret_key: Optional[str]=None, timeout: Optional[timedelta]=None, poll_interval: Optional[timedelta]=None, local_entrypoint: bool=False, **kwargs):
if (_fn is None):
return partial(eager, remote=remot... |
def exceptHook(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
mainLogger = logging.getLogger('Main')
mainLogger.critical('Uncaught exception!')
mainLogger.critical('Uncaught exception', exc_in... |
def SetTransform(kwargs: dict) -> OutgoingMessage:
compulsory_params = ['id']
optional_params = ['position', 'rotation', 'scale', 'is_world']
utility.CheckKwargs(kwargs, compulsory_params)
msg = OutgoingMessage()
msg.write_int32(kwargs['id'])
msg.write_string('SetTransform')
position = None
... |
class OptionAccessibilityKeyboardnavigationFocusborder(Options):
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def hideBrowserFocusOutline(self):
return self._config_get(True)
def hideBrowserFocusOutline(self, fl... |
def extractHidamarisoutranslationsWordpressCom(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, ... |
class OptionSeriesSankeySonificationDefaultspeechoptionsMappingPlaydelay(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):... |
.django_db
def test_non_matching_schedule_is_removed(client):
baker.make('submissions.DABSSubmissionWindowSchedule', id=2010121, submission_reveal_date='2010-12-23', submission_due_date='2010-12-23', submission_fiscal_year=2010)
call_command('load_dabs_submission_window_schedule', file=SCHEDULE_FILE)
schedu... |
.evm_tools
.parametrize('test_case', find_test_fixtures(), ids=idfn)
def test_b11r(test_case: Dict) -> None:
if (test_case['name'] in IGNORE_TESTS):
pytest.xfail('Undefined behavior for specs')
elif test_case['success']:
b11r_tool_test(test_case)
else:
with pytest.raises(FatalExcepti... |
def init_supervisor(ns, node, outputs=tuple(), state_outputs=tuple()):
tp_scheduler = ThreadPoolScheduler(max_workers=5)
reset_disp = CompositeDisposable()
done_outputs = []
for s in state_outputs:
s['done'] = Subject()
done_outputs.append(dict(name=s['name'], address=(s['address'] + '/d... |
class stats_sprint_burndown1(StdOutputParams, ExecutorTopicContinuum, CreateMakeDependencies):
def __init__(self, oconfig):
tracer.info('Called.')
StdOutputParams.__init__(self, oconfig)
CreateMakeDependencies.__init__(self)
def cmad_topic_continuum_pre(self, _):
tracer.debug('Ca... |
def gen_dim_calculator(dim_info: DimInfo, is_ptr: bool) -> str:
prefix = ('*' if is_ptr else '')
if (dim_info.source == Source.INPUT):
if (dim_info.tensor_idx == 0):
prefix += 'a_dim'
else:
assert (dim_info.tensor_idx == 1), f'Unsupported gemm dim: {dim_info}'
... |
class OefSearchHandler(Handler):
SUPPORTED_PROTOCOL = OefSearchMessage.protocol_id
def setup(self) -> None:
def handle(self, message: Message) -> None:
oef_search_msg = cast(OefSearchMessage, message)
oef_search_dialogues = cast(OefSearchDialogues, self.context.oef_search_dialogues)
... |
def extractReondellWordpressCom(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) ... |
class FilterAction(Action):
metadata = Instance(Metadata)
mayavi = Instance('mayavi.plugins.script.Script')
enabled = False
def __init__(self, **traits):
super(FilterAction, self).__init__(**traits)
self.mayavi.engine.on_trait_change(self._update_enabled, ['current_selection', 'current_o... |
def test_simple_renaming_with_arguments(renaming_graph, arg1, arg2, variable_v, variable_v_new, variable_u, variable_u_new, variable_x, variable_x_new, variable_y, variable_y_new):
(task, interference_graph) = renaming_graph
simple_variable_renamer = SimpleVariableRenamer(task, interference_graph)
arg1_new ... |
def test_valid_schema_decimal():
spark_schema = foundry_schema_to_spark_schema({'fieldSchemaList': [{'type': 'DECIMAL', 'name': 'price', 'nullable': None, 'userDefinedTypeClass': None, 'customMetadata': {}, 'arraySubtype': None, 'precision': 17, 'scale': 2, 'mapKeyType': None, 'mapValueType': None, 'subSchemas': No... |
def check_tflite_gcs_format(model, validation_error=None):
assert (model.validation_error == validation_error)
assert (model.published is False)
assert model.model_format.model_source.gcs_tflite_uri.startswith('gs://')
if validation_error:
assert (model.model_format.size_bytes is None)
a... |
def test_replace_version():
assert (replace_version('saas_config:\n version: 0.0.1\n key: example', '0.0.2') == 'saas_config:\n version: 0.0.2\n key: example')
assert (replace_version('saas_config:\n version: 0.0.1\n key: example', '0.0.2') == 'saas_config:\n version: 0.0.2\n key: example')
(replac... |
def update_number(num: str, delta: float, precision=3):
try:
fmt = (('%.' + str(precision)) + 'f')
value = (float(num) + delta)
neg = (value < 0)
result = (fmt % abs(value))
result = result.rstrip('0').rstrip('.')
if (((num[0] == '.') or (num[0:2] == '-.')) and (resul... |
.integration_postgres
.integration
class TestPostgresConnector():
def test_postgres_db_connector(self, api_client: TestClient, db: Session, generate_auth_header, connection_config, postgres_integration_db, postgres_example_secrets) -> None:
connector = get_connector(connection_config)
assert (connec... |
(no_gui_test_assistant, 'No GuiTestAssistant')
class TestConfirm(unittest.TestCase, GuiTestAssistant):
def setUp(self):
GuiTestAssistant.setUp(self)
def tearDown(self):
GuiTestAssistant.tearDown(self)
(no_modal_dialog_tester, 'ModalDialogTester unavailable')
def test_extras(self):
... |
def extractMulotranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Aiming For Harem Queen in Different World', 'Aiming For Harem Queen in Different... |
def fortios_certificate(data, fos, check_mode):
fos.do_member_operation('certificate', 'ca')
if data['certificate_ca']:
resp = certificate_ca(data, fos, check_mode)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'certificate_ca'))
if check_mode:
return resp
return... |
.parametrize('comparison, expected_value', maxauthtries_fail_params)
def test_integration_audit_sshd_config_option_fail_maxauthtries(setup_sshd_config, expected_value, comparison):
state = CISAudit().audit_sshd_config_option(parameter='maxauthtries', expected_value=expected_value, comparison=comparison)
assert ... |
class conv3d(Operator):
def __init__(self, stride, pad, dilate=1, group=1) -> None:
super().__init__()
self._attrs['op'] = 'conv3d'
self._attrs['stride'] = stride
if isinstance(stride, int):
self._attrs['stride'] = (stride, stride, stride)
self._attrs['pad'] = pad... |
class FacetSplitPC(PCBase):
needs_python_pmat = False
_prefix = 'facet_'
_permutation_cache = {}
def get_permutation(self, V, W):
key = (V, W)
if (key not in self._permutation_cache):
indices = get_permutation_map(V, W)
if V._comm.allreduce(numpy.all((indices[:(- ... |
def run(fips_dir, proj_dir, args):
sdk_name = None
if (len(args) > 0):
sdk_name = args[0]
if (sdk_name == 'emscripten'):
emsdk.install(fips_dir, None)
elif (sdk_name == 'android'):
android.setup(fips_dir)
elif (sdk_name == 'wasisdk'):
wasisdk.setup(fips_dir)
else:... |
class OptionSeriesGaugeSonificationDefaultspeechoptionsMappingRate(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 IGVideoCopyrightCheckMatchesInformation(AbstractObject):
def __init__(self, api=None):
super(IGVideoCopyrightCheckMatchesInformation, self).__init__()
self._isIGVideoCopyrightCheckMatchesInformation = True
self._api = api
class Field(AbstractObject.Field):
copyright_matches... |
class MappingForm(FlaskForm):
distro = SelectField('Distribution', [validators.DataRequired()], choices=[])
package_name = StringField('Package name', [validators.DataRequired()])
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if ('distros' in kwargs):
sel... |
class TestExpansionNode(TestCase):
def setUp(self):
self.expansion_node = ExpansionNode(node_type='foo', name='foo', source_field='foo_id', destination_field='foo', service='foo', action='get_foo', request_field='id', response_field='foo')
def test_to_strings_with_expansions(self):
bar_expansion... |
def text_on_image(image, text, font_size, color):
img = Image.open(image)
font = ImageFont.truetype('arial.ttf', font_size)
draw = ImageDraw.Draw(img)
(iw, ih) = img.size
(fw, fh) = font.getsize(text)
draw.text((((iw - fw) / 2), ((ih - fh) / 2)), text, fill=color, font=font)
img.save('last_i... |
class JobKind():
NAME: Optional[str] = None
TYPICAL_DURATION_SECS: Optional[int] = None
REQFS_FIELDS = ['job_script', 'portal_script', 'ssh_okay']
RESFS_FIELDS = ['pidfile', 'logfile']
Request: Type[_utils.Metadata] = requests.Request
Result: Type[_utils.Metadata] = requests.Result
def set_r... |
class TensorAccessor():
def __init__(self, original_tensor: Tensor) -> None:
super().__init__()
self.offset = 0
self.original_shapes = original_tensor._attrs['shape']
self.tensor_dtype = original_tensor.dtype()
self.is_contiguous = True
self.is_from_strided_tensor = F... |
class Top():
def __init__(self):
pass
def copy(self):
return Top()
def __hash__(self):
return hash('Top')
def __eq__(self, other):
return isinstance(other, Top)
def __str__(self):
return 'Top'
def __repr__(self):
return str(self) |
class Solution():
def findMin(self, nums: List[int]) -> int:
(start, end) = (0, (len(nums) - 1))
while (start < end):
if (start == (end - 1)):
return (nums[start] if (nums[start] < nums[end]) else nums[end])
mid = ((start + end) // 2)
if (nums[star... |
class OptionPlotoptionsItemSonificationTracksMappingTremoloDepth(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):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.