code stringlengths 281 23.7M |
|---|
def load_models(app_config: AppConfig, app_context: AppContext, fulltext_processor_config: FullTextProcessorConfig) -> FullTextModels:
segmentation_model = load_model(app_config, app_context, 'segmentation', SegmentationModel)
header_model = load_model(app_config, app_context, 'header', HeaderModel)
name_he... |
class Gpu_nvidia(Gpu_interface):
primeoffload: bool
def __init__(self, os, model):
super().__init__(os, GPU_VENDOR, model)
_interface.model.setter
def model(self, value: str):
self._model = value
def get_temp(self):
if (self.os == 'windows'):
raise NotImplementedE... |
class ChatHistoryStorageOperator(MapOperator[(ChatContext, ChatContext)]):
def __init__(self, history: BaseChatHistoryMemory=None, **kwargs):
super().__init__(**kwargs)
self._history = history
async def map(self, input_value: ChatContext) -> ChatContext:
if self._history:
ret... |
.xfail(reason='Need to properly add authorization as of 8/10/2022')
def test_pm_release_package(empty_sol_registry, w3):
w3.pm.registry = empty_sol_registry
w3.pm.release_package('escrow', '1.0.0', 'ipfs://QmTpYHEog4yfmgx5GgvNCRQyDeQyBD4FWxTkiUP64AH1QC')
w3.pm.release_package('owned', '1.0.0', 'ipfs://Qmcxv... |
.longrun
.parametrize('target_reward, hydra_overrides', trainings)
def test_train(hydra_overrides: Dict[(str, str)], target_reward: float):
with Timeout(seconds=300):
run_maze_job(hydra_overrides, config_module='maze.conf', config_name='conf_train')
tf_summary_files = glob.glob('*events.out.tfevents*')
... |
class AITSimpleModel(nn.Module):
def __init__(self, hidden, eps: float=1e-05):
super().__init__()
self.dense1 = nn.Linear(hidden, (4 * hidden), specialization='fast_gelu')
self.dense2 = nn.Linear((4 * hidden), hidden)
self.layernorm = nn.LayerNorm(hidden, eps=eps)
def forward(sel... |
.integrationtest
.skipif((pymongo.version_tuple < (2, 7)), reason='New in 2.7')
.skipif((pymongo.version_tuple >= (4, 0)), reason='Removed in 4.0')
def test_bulk_execute(instrument, elasticapm_client, mongo_database):
elasticapm_client.begin_transaction('transaction.test')
bulk = mongo_database.test_bulk.initia... |
def sqrt_c_c(gen, t, srcs):
xnonzero = gen.symbols.newLabel()
done = gen.symbols.newLabel()
dst_re = gen.newTemp(Float)
dst_im = gen.newTemp(Float)
gen.emit_cjump(srcs[0].re, xnonzero)
temp = sqrt_f_f(gen, t, [abs_f_f(gen, t, [gen.emit_binop('/', [srcs[0].im, ConstFloatArg(2.0)], Float)])])
... |
class TestHCT(util.ColorAssertsPyTest):
COLORS = [('red', 'color(--hct 27.41 113.36 53.237)'), ('orange', 'color(--hct 71.257 60.528 74.934)'), ('yellow', 'color(--hct 111.05 75.504 97.139)'), ('green', 'color(--hct 142.23 71.136 46.228)'), ('blue', 'color(--hct 282.76 87.228 32.301)'), ('indigo', 'color(--hct 310.... |
('flytekitplugins.identity_aware_proxy.cli.id_token.fetch_id_token')
('keyring.get_password')
('keyring.set_password')
def test_sa_id_token_no_token_in_keyring(kr_set_password, kr_get_password, mock_fetch_id_token):
test_audience = 'test_audience'
service_account_email = 'default'
tmp_test_keyring_store = {... |
class StarredFileRequest(DatClass):
drive_id: str = None
file_id: str = None
starred: bool = True
custom_index_key: str = None
def __post_init__(self):
if self.starred:
self.custom_index_key = 'starred_yes'
else:
self.custom_index_key = ''
super().__po... |
('validate-manifest', 'parse a manifest and validate that it is correct')
class ValidateManifest(SubCmd):
def run(self, args):
try:
ManifestParser(file_name=args.file_name)
print('OK', file=sys.stderr)
return 0
except Exception as exc:
print(('ERROR: %... |
class TestProtectedRequest():
def test___init__(self):
request = testing.DummyRequest()
request.buildinfo = mock.MagicMock()
request.db = mock.MagicMock()
request.validated = mock.MagicMock()
request.dontcopy = mock.MagicMock()
pr = security.ProtectedRequest(request)
... |
.asyncio
.workspace_host
class TestUpdateUserField():
async def test_unauthorized(self, unauthorized_api_assertions: HTTPXResponseAssertion, test_client_api: test_data: TestData):
user_field = test_data['user_fields']['given_name']
response = (await test_client_api.patch(f'/user-fields/{user_field.... |
def test_is_valid_opcode_invalidates_bytes_after_PUSHXX_opcodes():
code_stream = CodeStream(b'\x02`\x02\x04')
assert (code_stream.is_valid_opcode(0) is True)
assert (code_stream.is_valid_opcode(1) is True)
assert (code_stream.is_valid_opcode(2) is False)
assert (code_stream.is_valid_opcode(3) is Tru... |
.parametrize('method,expected', (('test_endpoint', 'value-a'), ('not_implemented', NotImplementedError)))
def test_error_middleware(w3, method, expected):
def _callback(method, params):
return params[0]
w3.middleware_onion.add(construct_error_generator_middleware({'test_endpoint': _callback}))
if (i... |
def add_datafiles_tests(klass, regex, ofp, pyversion=3):
for filename in test_data.list_files():
match = re.match(regex, filename)
if (not match):
continue
def make_test(filename):
def fn(self):
test_datafile(filename, ofp, pyversion)
retur... |
def file_is_empty(file_path: Path) -> bool:
try:
if file_path.is_symlink():
file_path = file_path.resolve()
return (file_path.lstat().st_size == 0)
except (FileNotFoundError, PermissionError, OSError):
return False
except Exception as exception:
logging.error(f'Un... |
def get_dataset_drift(drift_metrics: Dict[(str, ColumnDataDriftMetrics)], drift_share=0.5) -> DatasetDrift:
number_of_drifted_columns = sum([(1 if drift.drift_detected else 0) for (_, drift) in drift_metrics.items()])
share_drifted_columns = (number_of_drifted_columns / len(drift_metrics))
dataset_drift = b... |
class Dunofausto(Sprite):
def __init__(self, torradas):
super().__init__()
self.image = load('images/dunofausto_small.png')
self.rect = self.image.get_rect()
self.torradas = torradas
self.velocidade = 2
def tacar_torradas(self):
if (len(self.torradas) < 15):
... |
def find_functions_by_identifier(contract_abi: ABI, w3: Union[('Web3', 'AsyncWeb3')], address: ChecksumAddress, callable_check: Callable[(..., Any)], function_type: Type[TContractFn]) -> List[TContractFn]:
fns_abi = filter_by_type('function', contract_abi)
return [function_type.factory(fn_abi['name'], w3=w3, co... |
def test_level_user_error():
with Image(width=100, height=100, pseudo='gradient:') as img:
with raises(TypeError):
img.level(black='NaN')
with raises(TypeError):
img.level(white='NaN')
with raises(TypeError):
img.level(gamma='NaN')
with raises(Valu... |
def test_operator_registry(valid_operator_registry):
operator_config = {'name': 'my-operator', 'type': 'base'}
operator = valid_operator_registry.get(operator_config)
operator.resolve_properties(execution_context=ExecutionContext(None, {}), default_task_args={}, base_operator_loader=valid_operator_registry.... |
class TerminusCheckin(AnswerBotCheckin):
name = ''
bot_username = 'EmbyPublicBot'
bot_checkin_cmd = ['/cancel', '/checkin']
bot_text_ignore = ['', '']
bot_checked_keywords = ['']
additional_auth = ['visual']
max_retries = 1
async def on_photo(self, message: Message):
if message.r... |
class TestStatusNameStability(unittest.TestCase):
def _check_status_names(self, path: pathlib.Path) -> None:
with open(path) as f:
for line in f:
line = line.strip()
if ((not line.startswith('#')) and (len(line) > 0)):
status_name = line
... |
class DataProperties():
def __init__(self, context: dict):
self._context = context
def add(self, records, js_funcs: list=None, profile=None):
data_id = len(self._context['sources'])
self._context['sources'][data_id] = records
self._context['schema'][data_id] = {'containers': {}, ... |
.gui()
def test_frame_count_progresses(monkeypatch, qtbot):
counter_values = []
def mocked_paint_event(cls, event):
counter_values.append(cls.counter)
monkeypatch.setattr(LoadingIndicator, 'paintEvent', mocked_paint_event)
window = QtWidgets.QMainWindow()
indicator = LoadingIndicator(parent=... |
('deploy', cls=FandoghCommand)
('--image', help='The image name', default=None)
('--version', '-v', prompt='The image version', help='The image version you want to deploy')
('--name', prompt='Your service name', help='Choose a unique name for your service')
('--env', '-e', 'envs', help='Environment variables (format: V... |
.register_header_type(inet.IPPROTO_FRAGMENT)
class fragment(header):
TYPE = inet.IPPROTO_FRAGMENT
_PACK_STR = '!BxHI'
_MIN_LEN = struct.calcsize(_PACK_STR)
def __init__(self, nxt=inet.IPPROTO_TCP, offset=0, more=0, id_=0):
super(fragment, self).__init__(nxt)
self.offset = offset
... |
def highlight_genes(axis, genes, y_posn):
ngenes = len(genes)
text_size = ('small' if (ngenes <= 6) else 'x-small')
if (ngenes <= 3):
text_rot = 'horizontal'
elif (ngenes <= 6):
text_rot = 30
elif (ngenes <= 10):
text_rot = 45
elif (ngenes <= 20):
text_rot = 60
... |
def test_read16(la: LogicAnalyzer, slave: SPISlave):
la.capture(4, block=False)
value = slave.read16()
la.stop()
(sck, sdo, cs, sdi) = la.fetch_data()
sdi_initstate = la.get_initial_states()[SDI[0]]
assert (len(cs) == (CS_START + CS_STOP))
assert (len(sck) == SCK_WRITE16)
assert (len(sdo... |
class TestApp(unittest.TestCase):
module = browsepy
generic_page_class = Page
list_page_class = ListPage
confirm_page_class = ConfirmPage
page_exceptions = {404: Page404Exception, 400: Page400Exception, 302: Page302Exception, None: PageException}
def setUp(self):
self.app = self.module.a... |
.parametrize('capacity', [1, 2, 4, 10])
def test_consume_multiple_tokens_at_a_time(capacity):
rate = 100
num_tokens = capacity
key = 'key'
storage = token_bucket.MemoryStorage()
limiter = token_bucket.Limiter(rate, capacity, storage)
assert (not limiter.consume(key, num_tokens=(capacity + 1)))
... |
def _strip_award_id(api_dict):
field_mapping = {'broker_subaward_id': 'id', 'subaward_number': 'subaward_number', 'subaward_description': 'description', 'sub_action_date': 'action_date', 'subaward_amount': 'amount', 'sub_awardee_or_recipient_legal': 'recipient_name'}
return {field_mapping[k]: v for (k, v) in ap... |
(name='neighbor.delete', req_args=[neighbors.IP_ADDRESS])
def delete_neighbor(neigh_ip_address):
neigh_conf = _get_neighbor_conf(neigh_ip_address)
if neigh_conf:
neigh_conf.enabled = False
CORE_MANAGER.neighbors_conf.remove_neighbor_conf(neigh_ip_address)
return True
return False |
class TestGetreadsFunction(unittest.TestCase):
def setUp(self):
self.wd = tempfile.mkdtemp()
self.example_fastq_data = u':43:HL3LWBBXX:8:1101:21440:1121 1:N:0:CNATGT\nGCCNGACAGCAGAAAT\n+\nAAF#FJJJJJJJJJJJ\:43:HL3LWBBXX:8:1101:21460:1121 1:N:0:CNATGT\nGGGNGTCATTGATCAT\n+\nAAF#FJJJJJJJJJJJ\:43:HL3LWBB... |
def remove_view_op_from_sorted_graph(op: Operator) -> None:
if (op._attrs['op'] != 'reshape'):
remove_single_tensor_op_from_sorted_graph(op)
return
input_tensor = op._attrs['inputs'][0]
output_tensor = op._attrs['outputs'][0]
input_tensor._attrs['dst_ops'].remove(op)
input_tensor._at... |
def test_saveload_lmer(df, tmp_path):
model = Lmer('DV ~ IV3 + IV2 + (IV2|Group) + (1|IV3)', data=df)
model.fit(summarize=False)
output_file = (tmp_path / 'model.joblib')
rds_file = (tmp_path / 'model.rds')
save_model(model, output_file)
assert output_file.exists()
assert rds_file.exists()
... |
class RepresentationGenerator(object):
def __init__(self, version=None):
local_session = LocalSession()
self.logged_in_user = local_session.logged_in_user
if (not self.logged_in_user):
raise RuntimeError('Please login first!')
from anima.dcc.mayaEnv import Maya
se... |
def load_cfda(original_df, new_df):
if new_df.equals(original_df):
logger.info('Skipping CFDA load, no new data')
return False
(Reporter['new_record_count'], Reporter['updated_record_count']) = (0, 0)
logger.info('Inserting new CFDA data')
for row in new_df.itertuples():
record =... |
def find_conn_info() -> ConnInfo:
global _CACHED_CONN_INFO
if (_CACHED_CONN_INFO is not None):
return _CACHED_CONN_INFO
conn_str = os.environ.get(ENV_VAR)
if (not conn_str):
root = Path('/')
path = Path.cwd()
while (path != root):
try:
conn_str... |
class role_request(message):
version = 5
type = 24
def __init__(self, xid=None, role=None, generation_id=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (role != None):
self.role = role
else:
self.role = 0
... |
_meta(basic.UseAttack)
class UseAttack():
def choose_card_text(self, act, cards):
if act.cond(cards):
return (True, '?!')
else:
return (False, '...')
def effect_string(self, act):
if (not act.succeeded):
return None
t = act.target
retur... |
class SyncSQServer(SyncServer):
def __init__(self, *, global_model: IFLModel, channel: Optional[ScalarQuantizationChannel]=None, **kwargs):
init_self_cfg(self, component_class=__class__, config_class=SyncSQServerConfig, **kwargs)
super().__init__(global_model=global_model, channel=channel, **kwargs)... |
class bsn_vlan_counter_stats_reply(bsn_stats_reply):
version = 4
type = 19
stats_type = 65535
experimenter = 6035143
subtype = 9
def __init__(self, xid=None, flags=None, entries=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flag... |
class ListeningAnimator(Animator):
def __init__(self, window, **properties):
super().__init__(**properties)
self.window = window
self.tc = 0
def draw(self, ctx, width, height):
self.tc += 0.2
self.tc %= (2 * math.pi)
for i in range((- 4), 5):
ctx.set_s... |
(boundscheck=False, wraparound=False, cdivision=True, nonecheck=False)
def row_sum_loops(arr: V2d, columns: V1d_i):
i: T_index
j: T_index
sum_: T
dtype = type(arr[(0, 0)])
res: V1d = np.empty(arr.shape[0], dtype=dtype)
for i in range(arr.shape[0]):
sum_ = dtype(0)
for j in range(... |
def _prepare_outputs(output_tensors):
def _to_int_list(shape):
result = []
for d in shape:
assert isinstance(d, IntImm)
result.append(d._attrs['values'][0])
return result
output_shapes = [_to_int_list(output._attrs['shape']) for output in output_tensors]
outpu... |
def migrate_comparisons(mongo: MigrationMongoInterface):
count = 0
compare_db = ComparisonDbInterface()
for entry in mongo.compare_results.find({}):
results = {key: value for (key, value) in entry.items() if (key not in ['_id', 'submission_date'])}
comparison_id = entry['_id']
if (no... |
def _import_irap_ascii(mfile):
logger.debug('Enter function...')
cfhandle = mfile.get_cfhandle()
xlist = _cxtgeo.surf_import_irap_ascii(cfhandle, 0, 1, 0)
nvn = (xlist[1] * xlist[2])
xlist = _cxtgeo.surf_import_irap_ascii(cfhandle, 1, nvn, 0)
(ier, ncol, nrow, _, xori, yori, xinc, yinc, rot, val... |
class MyDialog(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
button1 = Button('Redraw')
button2 = Button('Redraw')
_trait_change('button1')
def redraw_scene1(self):
self.redraw_scene(self.scene1)
_trait_change('button2')
def redraw_scene2... |
class CpuLoad(SensorInterface):
def __init__(self, hostname='', interval=5.0, warn_level=0.9):
self._cpu_load_warn = warn_level
self._count_processes = 3
SensorInterface.__init__(self, hostname, sensorname='CPU Load', interval=interval)
def reload_parameter(self, settings):
self.... |
def _detect_unpack_loss(binary: bytes, extracted_files: List[Path], meta_data: Dict, header_overhead: int):
decoding_overhead = (1 - meta_data.get('encoding_overhead', 0))
cleaned_size = ((get_binary_size_without_padding(binary) * decoding_overhead) - header_overhead)
size_of_extracted_files = _total_size_o... |
class TestDownsampleParamSource():
def test_downsample_all_params(self):
source = params.DownsampleParamSource(track.Track(name='unit-test'), params={'source-index': 'test-source-index', 'target-index': 'test-target-index', 'fixed-interval': '1m'})
p = source.params()
assert (p['fixed-interv... |
class BlockCursor(StmtCursorPrototype, ListCursorPrototype):
def as_block(self):
return self
def expand(self, delta_lo=None, delta_hi=None):
if ((delta_lo is not None) and (delta_lo < 0)):
raise ValueError('delta_lo must be non-negative')
if ((delta_hi is not None) and (delta... |
def install_activate(env_dir, args):
if is_WIN:
files = {'activate.bat': ACTIVATE_BAT, 'deactivate.bat': DEACTIVATE_BAT, 'Activate.ps1': ACTIVATE_PS1}
bin_dir = join(env_dir, 'Scripts')
shim_node = join(bin_dir, 'node.exe')
shim_nodejs = join(bin_dir, 'nodejs.exe')
else:
... |
class EmvistaApi(ProviderInterface, TextInterface):
provider_name = 'emvista'
def __init__(self, api_keys: Dict={}):
self.api_settings = load_provider(ProviderDataEnum.KEY, self.provider_name, api_keys=api_keys)
self.api_key = self.api_settings['api_key']
self.base_url = '
def text__... |
.parametrize('pool', [ThreadPoolExecutor, ProcessPoolExecutor], ids=['threads', 'processes'])
def test_make_local_storage_parallel(pool, monkeypatch):
makedirs = os.makedirs
def mockmakedirs(path, exist_ok=False):
time.sleep(1.5)
makedirs(path, exist_ok=exist_ok)
monkeypatch.setattr(os, 'mak... |
class HealthCheckTestCase(TestCase):
def test_health_check_url_returns_200_status(self):
self.response = self.client.get('/health/ok/')
self.assertEqual(self.response.status_code, 200)
def test_version_info_url_returns_200_status(self):
self.response = self.client.get('/health/version/')... |
def yotpo_reviews_runner(db, cache, yotpo_reviews_secrets, yotpo_reviews_external_references, yotpo_reviews_erasure_external_references) -> ConnectorRunner:
return ConnectorRunner(db, cache, 'yotpo_reviews', yotpo_reviews_secrets, external_references=yotpo_reviews_external_references, erasure_external_references=yo... |
def tokenize(expr):
tokens = []
escape = False
cur_token = ''
for c in expr:
if (escape == True):
cur_token += c
escape = False
elif (c == '\\'):
escape = True
continue
elif (c == '['):
if (len(cur_token) > 0):
... |
class AlertType(str, _enum.Enum):
CRASHLYTICS_NEW_FATAL_ISSUE = 'crashlytics.newFatalIssue'
CRASHLYTICS_NEW_NONFATAL_ISSUE = 'crashlytics.newNonfatalIssue'
CRASHLYTICS_REGRESSION = 'crashlytics.regression'
CRASHLYTICS_STABILITY_DIGEST = 'crashlytics.stabilityDigest'
CRASHLYTICS_VELOCITY = 'crashlyti... |
def chunked_post(env, start_response):
start_response('200 OK', [('Content-type', 'text/plain')])
if (env['PATH_INFO'] == '/a'):
return [env['wsgi.input'].read()]
elif (env['PATH_INFO'] == '/b'):
return [x for x in iter((lambda : env['wsgi.input'].read(4096)), b'')]
elif (env['PATH_INFO'... |
class TaskExecutionIdentifier(_core_identifier.TaskExecutionIdentifier):
def promote_from_model(cls, base_model):
return cls(task_id=base_model.task_id, node_execution_id=base_model.node_execution_id, retry_attempt=base_model.retry_attempt)
def from_flyte_idl(cls, pb2_object):
base_model = super... |
class ThingsResource():
def __init__(self, db):
self.db = db
self.logger = logging.getLogger(('thingsapp.' + __name__))
def on_get(self, req, resp, user_id):
marker = (req.get_param('marker') or '')
limit = (req.get_param_as_int('limit') or 50)
try:
result = s... |
def upgrade():
op.add_column('events', sa.Column('has_organizer_info', sa.Boolean(), nullable=True))
op.add_column('events_version', sa.Column('has_organizer_info', sa.Boolean(), autoincrement=False, nullable=True))
op.alter_column('events', 'event_url', new_column_name='external_event_url')
op.alter_co... |
def _nice(x, round=False):
if (x <= 0):
import warnings
warnings.warn('Invalid (negative) range passed to tick interval calculation')
x = abs(x)
expv = floor(log10(x))
f = (x / pow(10, expv))
if round:
if (f < 1.75):
nf = 1.0
elif (f < 3.75):
... |
def clip_channels(color: Color, nans: bool=True) -> bool:
clipped = False
cs = color._space
for (i, value) in enumerate(cs.normalize(color[:(- 1)])):
chan = cs.CHANNELS[i]
if ((not chan.bound) or math.isnan(value) or (chan.flags & FLG_ANGLE)):
color[i] = value
continu... |
class SearchResult(Html.Html):
name = 'Search Result'
tag = 'div'
requirements = ('jquery',)
_option_cls = OptText.OptSearchResult
def __init__(self, page: primitives.PageModel, records, width, height, options, profile):
super(SearchResult, self).__init__(page, records, options=options, prof... |
class PartialSnapshot():
def __init__(self, snapshot: Optional['Snapshot']=None) -> None:
self._realization_states: Dict[(str, Dict[(str, Union[(bool, datetime.datetime, str)])])] = defaultdict(dict)
self._forward_model_states: Dict[(Tuple[(str, str)], Dict[(str, Union[(str, datetime.datetime)])])] ... |
def convert_save(save_stats: dict[(str, Any)]) -> dict[(str, Any)]:
gvs = ['en', 'jp', 'kr', 'tw']
helper.colored_text('WARNING: This may cause issues, and both apps must be the same version (e.g both 12.1.0)!', helper.RED)
if (save_stats['version'] in gvs):
gvs.remove(save_stats['version'])
gv_... |
('sys.argv', ['flakehell'])
def test_baseline(capsys, tmp_path: Path):
code_path = (tmp_path / 'example.py')
code_path.write_text('a\nb\n')
with chdir(tmp_path):
result = main(['baseline', str(code_path)])
assert (result == (0, ''))
captured = capsys.readouterr()
assert (captured.err == ... |
class ForeignKey(ModelField):
class ForeignKeyValidator(typesystem.Field):
def validate(self, value):
return value.pk
def __init__(self, to, allow_null: bool=False, on_delete: typing.Optional[str]=None):
super().__init__(allow_null=allow_null)
self.to = to
self.on_del... |
.parametrize('screenshot_manager', [{}, {'show_image': True, 'show_text': False}, {'show_image': True, 'show_text': False, 'wifi_shape': 'rectangle', 'wifi_rectangle_width': 10}], indirect=True)
def ss_iwd(dbus_thread, screenshot_manager):
wait_for_text(screenshot_manager.c.widget['iwd'], 'qtile_extras (50%)')
... |
def v1_sort_packages(packages, fdroid_signing_key_fingerprints):
GROUP_DEV_SIGNED = 1
GROUP_FDROID_SIGNED = 2
GROUP_OTHER_SIGNED = 3
def v1_sort_keys(package):
packageName = package.get('packageName', None)
signer = package.get('signer', None)
dev_signer = common.metadata_find_de... |
def get_factory(get_manifest, escrow_manifest, w3):
def _get_factory(package, factory_name):
manifest = get_manifest(package)
if (package == 'escrow'):
manifest = escrow_manifest
Pkg = Package(manifest, w3)
factory = Pkg.get_contract_factory(factory_name)
return f... |
def ensure_data_dir_is_initialized(trinity_config: TrinityConfig) -> None:
if (not is_data_dir_initialized(trinity_config)):
try:
initialize_data_dir(trinity_config)
except AmbigiousFileSystem:
parser.error(TRINITY_AMBIGIOUS_FILESYSTEM_INFO)
except MissingPath as e:
... |
class LiteScopeIODriver():
def __init__(self, regs, name):
self.regs = regs
self.name = name
self.build()
def build(self):
self.input = getattr(self.regs, (self.name + '_in'))
self.output = getattr(self.regs, (self.name + '_out'))
def write(self, value):
self.... |
def tlscontext_for_tcpmapping(irgroup: IRTCPMappingGroup, config: 'V3Config') -> Optional['IRTLSContext']:
group_host = irgroup.get('host')
if (not group_host):
return None
for irhost in sorted(config.ir.get_hosts(), key=(lambda h: h.hostname)):
if (irhost.context and hostglob_matches(irhost... |
def call_func_in_js(func, classes, extra_nodejs_args=None):
all_classes = []
for cls in classes:
for c in cls.mro():
if ((c is Component) or (c is Property) or (c in all_classes)):
break
all_classes.append(c)
code = JS_EVENT
for c in reversed(all_classes):... |
class TypeDeclarationTestCase(unittest.TestCase):
def setUp(self):
ast = parserFactory(**smiV1Relaxed)().parse(self.__class__.__doc__)[0]
(mibInfo, symtable) = SymtableCodeGen().genCode(ast, {}, genTexts=True)
(self.mibInfo, pycode) = PySnmpCodeGen().genCode(ast, {mibInfo.name: symtable}, ge... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'policyid'
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_pa... |
.parametrize('data,key,expected', [(None, 'x', None), ({}, 'x', None), ({'x': 1}, 'x', 1), ({'x': {'y': 1}}, 'x.y', 1), ({'x': 1}, 'x.y', None), ({'x': {'y': {}}}, 'x.y.z', None)])
def test_nested_key(data, key, expected):
r = nested_key(data, *key.split('.'))
if (expected is None):
assert (r is expecte... |
class FragmentGenerator():
def __init__(self):
pass
def get_args(self) -> List[bytes]:
raise NotImplementedError()
def get_initial_frame(self) -> FrameWithArgs:
raise NotImplementedError()
def get_continue_frame(self) -> FrameWithArgs:
raise NotImplementedError()
def ... |
def test_finish_same_task_twice():
ti = OrderedTaskPreparation(TwoPrereqs, identity, (lambda x: (x - 1)))
ti.set_finished_dependency(1)
ti.register_tasks((2,))
ti.finish_prereq(TwoPrereqs.PREREQ1, (2,))
with pytest.raises(ValidationError):
ti.finish_prereq(TwoPrereqs.PREREQ1, (2,)) |
class PasswordManager():
data: Optional[StorageData]
hass: HomeAssistant
crypto: Fernet
def __init__(self, hass: HomeAssistant):
self.hass = hass
self.data = None
async def _load_key(self):
if (self.data is None):
storage_manager = StorageManager(self.hass)
... |
def tf_model(n_hidden, input_size):
import tensorflow as tf
tf_model = tf.keras.Sequential([tf.keras.layers.Dense(n_hidden, input_shape=(input_size,)), tf.keras.layers.LayerNormalization(), tf.keras.layers.Dense(n_hidden, activation='relu'), tf.keras.layers.LayerNormalization(), tf.keras.layers.Dense(10, activa... |
class ColumnsDriftParameters(ConditionTestParameters):
features: Dict[(str, ColumnDriftParameter)]
def from_data_drift_table(cls, table: DataDriftTableResults, condition: TestValueCondition):
return ColumnsDriftParameters(features={feature: ColumnDriftParameter.from_metric(data) for (feature, data) in t... |
class OptionSeriesDependencywheelLevelsStatesSelect(Options):
def animation(self) -> 'OptionSeriesDependencywheelLevelsStatesSelectAnimation':
return self._config_sub_data('animation', OptionSeriesDependencywheelLevelsStatesSelectAnimation)
def borderColor(self):
return self._config_get('#000000... |
def run():
print('\nmodule top();\n ')
params = {}
sites = list(gen_sites())
for ((tile_name, sites), isone) in zip(sites, util.gen_fuzz_states(len(sites))):
site_name = sites[0]
params[tile_name] = (site_name, isone)
print('\n wire clk_{site};\n (* KEEP,... |
def create_privacy_notices_util(db: Session, privacy_notice_schemas: List[PrivacyNoticeCreation], should_escape: bool=True) -> Tuple[(List[PrivacyNotice], Set[PrivacyNoticeRegion])]:
validate_notice_data_uses(privacy_notice_schemas, db)
existing_notices = PrivacyNotice.query(db).filter(PrivacyNotice.disabled.is... |
def test_address():
reg = Register(address=5)
assert (reg.address == 5)
reg = Register(address='0x5')
assert (reg.address == 5)
reg.address = 3
assert (reg.address == 3)
reg.address = '0x6'
assert (reg.address == 6)
with pytest.raises(ValueError):
reg.address = 'zz'
reg.a... |
def verify_private_keys_ctx(ctx: Context, aea_project_path: Path=ROOT, password: Optional[str]=None) -> None:
try:
AgentConfigManager.verify_private_keys(aea_project_path, private_key_helper=private_key_verify, substitude_env_vars=False, password=password).dump_config()
agent_config = AgentConfigMan... |
class TestComponentProperties():
def setup_class(self):
self.configuration = ProtocolConfig('name', 'author', '0.1.0', protocol_specification_id='some/author:0.1.0')
self.configuration.build_directory = 'test'
self.component = Component(configuration=self.configuration)
self.director... |
class HelpCentreApi(HelpCentreApiBase):
def __init__(self, config):
super(HelpCentreApi, self).__init__(config, endpoint=EndpointFactory('help_centre'), object_type='help_centre')
self.articles = ArticleApi(config, self.endpoint.articles, object_type='article')
self.comments = CommentApi(con... |
_event
class Presence(Event):
statuses = attr.ib(type=Mapping[(str, '_models.ActiveStatus')])
full = attr.ib(type=bool)
def _parse(cls, session, data):
statuses = {str(d['u']): _models.ActiveStatus._from_orca_presence(d) for d in data['list']}
return cls(statuses=statuses, full=(data['list_t... |
_shopify_session
def _resync_product(product):
savepoint = 'shopify_resync_product'
try:
item = Product.find(product)
frappe.db.savepoint(savepoint)
for variant in item.variants:
shopify_product = ShopifyProduct(product, variant_id=variant.id)
shopify_product.sync... |
class FillMaskInferenceOptions(InferenceConfig):
def __init__(self, *, tokenization: NlpTokenizationConfig, results_field: t.Optional[str]=None, num_top_classes: t.Optional[int]=None):
super().__init__(configuration_type='fill_mask')
self.num_top_classes = num_top_classes
self.tokenization =... |
.skipif((not has_hf_transformers), reason='requires huggingface transformers')
.parametrize('torch_device', TORCH_DEVICES)
def test_torch_sdp_causal_with_mask(torch_device):
model = GPTNeoXDecoder.from_hf_hub(name='trl-internal-testing/tiny-random-GPTNeoXForCausalLM', device=torch_device)
model.eval()
torch... |
def similarities(obj, limit=5):
if isinstance(obj, models.Model):
cache_key = ('recommends:similarities:%s:%s.%s:%s:%s' % (settings.SITE_ID, obj._meta.app_label, obj._meta.object_name.lower(), obj.id, limit))
similarities = cache.get(cache_key)
if (similarities is None):
provider... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.