code stringlengths 281 23.7M |
|---|
class OptionSeriesSolidgaugeSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionSeriesSolidgaugeSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesSolidgaugeSonificationDefaultinstrumentoptionsMappingTremoloDepth)
... |
class _coconut_SupportsMinus(_coconut.typing.Protocol):
def __sub__(self, other):
raise NotImplementedError('Protocol methods cannot be called at runtime ((-) in a typing context is a Protocol)')
def __neg__(self):
raise NotImplementedError('Protocol methods cannot be called at runtime ((-) in a... |
class OptionPlotoptionsArcdiagramLevelsStatesSelect(Options):
def animation(self) -> 'OptionPlotoptionsArcdiagramLevelsStatesSelectAnimation':
return self._config_sub_data('animation', OptionPlotoptionsArcdiagramLevelsStatesSelectAnimation)
def borderColor(self):
return self._config_get('#000000... |
('aea.cli.utils.package_utils._compute_fingerprint', return_value={'correct': 'fingerprint'})
class IsFingerprintCorrectTestCase(TestCase):
def test_is_fingerprint_correct_positive(self, *mocks):
item_config = mock.Mock()
item_config.fingerprint = {'correct': 'fingerprint'}
item_config.finge... |
class Bluetooth(IntervalModule):
interval = 1
settings = (('format', 'formatp string'), ('color', 'Text color'), ('connected_color', 'Connected device color'), ('show_disconnected', 'Show disconnected but paired devices'))
format = '{name}: {dev_addr}'
color = '#ffffff'
connected_color = '#00ff00'
... |
class Command(DanubeCloudCommand):
default_config_file = DanubeCloudCommand._path(DanubeCloudCommand.PROJECT_DIR, 'core', 'gunicorn-sio.py')
help = 'Runs a production server (Gunicorn).'
options = (CommandOption('-c', '--config', action='store', dest='config', default=default_config_file, help=('The Gunicor... |
def set_capacities_edge_communicability(topology, capacities, capacity_unit='Mbps'):
communicability = nx.communicability(topology)
centrality = {(u, v): communicability[u][v] for (u, v) in topology.edges()}
_set_capacities_proportionally(topology, capacities, centrality, capacity_unit=capacity_unit) |
def extractRaspommeTumblrCom(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 ... |
class TestNameGenerator(BaseEvenniaTest):
def test_fantasy_name(self):
single_name = namegen.fantasy_name()
self.assertEqual(type(single_name), str)
fluid_name = namegen.fantasy_name(style='fluid')
self.assertEqual(type(fluid_name), str)
three_names = namegen.fantasy_name(num... |
.skipif((sys.platform == 'win32'), reason='Cannot (yet) use expandvars on Windows')
def test_user_2():
s = load_source('file', climetlab_file('docs/examples/test.grib'))
home_file = os.path.expanduser('~/.climetlab/test.grib')
try:
s.save(home_file)
s = load_source('file', '$HOME/.climetlab/... |
def generate_numeric_anomalies_training_and_validation_files(rows_count_per_day=200):
def get_training_row(date, row_index, rows_count):
return {'updated_at': date.strftime(DATE_FORMAT), 'occurred_at': (date - timedelta(hours=1)).strftime(DATE_FORMAT), 'min': random.randint(100, 200), 'max': random.randint(... |
def parse_rocketfuel_isp_map(path):
topology = DirectedTopology(type='rocket_fuel')
comment_char = '#'
with open(path, 'r') as f:
for line in f.readlines():
if (comment_char in line):
(line, _) = line.split(comment_char, 1)
line = line.strip()
... |
class BypassNormExtension(Extension):
def __init__(self, *args, **kwargs):
self.inlinehilite = []
self.config = {}
super().__init__(*args, **kwargs)
def extendMarkdown(self, md):
md.preprocessors.register(PreNormalizePreprocessor(md), 'pymdownx-pre-norm-ws', 35)
md.prepro... |
class CustomFormTranslateListPost(ResourceList):
def before_post(data):
require_relationship(['custom_form'], data)
if (not has_access('is_coorganizer', custom_form=data['custom_form'])):
raise ObjectNotFound({'parameter': 'custom_form'}, f"Custom Form: {data['custom_form']} not found")
... |
def test_reward_clipping_wrapper():
observation_conversion = ObservationConversion()
env = DummyEnvironment(core_env=DummyCoreEnvironment(observation_conversion.space()), action_conversion=[DictActionConversion()], observation_conversion=[observation_conversion])
env.reset()
action = env.action_space.sa... |
class RobotArmMm(_RobotArm):
def __call__(self, length, move=None):
t = self.thickness
w = self.servo.height
w2 = self.servo2.height
l = max((self.servo.length * 2), (length + (2 * self.servo.axle_pos)))
th = max(((2 * self.thickness) + l), (((w + w2) + (4 * t)) + self.spacin... |
def forward(model: Model, X: Any, is_train: bool) -> Tuple[(Any, Callable)]:
convert_inputs = model.attrs['convert_inputs']
convert_outputs = model.attrs['convert_outputs']
(Xmxnet, get_dX) = convert_inputs(model, X, is_train)
(Ymxnet, mxnet_backprop) = model.shims[0](Xmxnet, is_train)
(Y, get_dYmxn... |
def library_paths():
libwand = None
libmagick = None
versions = ('', '-7', '-7.Q8', '-7.Q16', '-6', '-Q16', '-Q8', '-6.Q16')
options = ('', 'HDRI', 'HDRI-2')
system = platform.system()
magick_home = os.environ.get('MAGICK_HOME')
magick_suffix = os.environ.get('WAND_MAGICK_LIBRARY_SUFFIX')
... |
def conditional_process() -> None:
conditional_append_reference_faces()
for frame_processor_module in get_frame_processors_modules(facefusion.globals.frame_processors):
if (not frame_processor_module.pre_process('output')):
return
if is_image(facefusion.globals.target_path):
proc... |
class AmbiguousBaseFilterTestCase(unittest.TestCase):
def setUp(self):
self.records = [SeqRecord(Seq('ACGT')), SeqRecord(Seq('NNNN')), SeqRecord(Seq('NACT')), SeqRecord(Seq('ACGTN')), SeqRecord(Seq('GGNTTACT'))]
def test_drop(self):
instance = quality_filter.AmbiguousBaseFilter('drop')
a... |
def queue_options(draw, systems):
queue_system = draw(systems)
name = draw(st.sampled_from(valid_queue_options(queue_system)))
do_set = draw(booleans)
if do_set:
return [queue_system, name, draw(valid_queue_values(name, queue_system))]
else:
return [queue_system, name] |
class BugzillaProcessor(InlineProcessor):
def handleMatch(self, m: 're.Match', data: str) -> typing.Tuple[('xml.etree.ElementTree.Element', int, int)]:
tracker = markdown.util.AtomicString(m.group(1))
idx = markdown.util.AtomicString(m.group(2))
url = bug_url(tracker, idx[1:])
if (ur... |
(_dill._locate_function)
def by_value_locator(obj, pickler=None, og_locator=_dill._locate_function):
module_name = getattr(obj, '__module__', None)
if (module_name is not None):
if (module_name in _MODULES):
return False
(package_name, *_) = module_name.partition('.')
if (pac... |
def path_distance(path: List[int], distance_matrix: List[List[float]]):
dist = 0
last_idx = path[0]
tour = path[1:]
if (len(path) != (len(distance_matrix[0]) + 1)):
tour.append(path[0])
for idx in tour:
dist += distance_matrix[last_idx][idx]
last_idx = idx
return dist |
def distance_mask(data_coordinates, maxdist, coordinates=None, grid=None, projection=None):
(coordinates, shape) = _get_grid_coordinates(coordinates, grid)
if (projection is not None):
data_coordinates = projection(*n_1d_arrays(data_coordinates, 2))
coordinates = projection(*n_1d_arrays(coordina... |
class UserManagerMock(BaseTestUserManager[models.UP]):
get_by_email: MagicMock
request_verify: MagicMock
verify: MagicMock
forgot_password: MagicMock
reset_password: MagicMock
on_after_register: MagicMock
on_after_request_verify: MagicMock
on_after_verify: MagicMock
on_after_forgot_p... |
def env_list(name: str, separator: str=',', required: bool=False, default: Union[(Type[empty], List[Any])]=empty) -> List[Any]:
value = get_env_value(name, required=required, default=default)
if (value is empty):
return []
return list(filter(bool, [v.strip() for v in value.split(separator)])) |
class TestLoadApp():
.parametrize('name', ('_APP', 'make_app'))
def test_load_app(self, name):
parser = inspect_app.make_parser()
args = Namespace(app_module='{}:{}'.format(_MODULE, name), route_only=False, verbose=False)
app = inspect_app.load_app(parser, args)
assert isinstance... |
class OptionPlotoptionsWaterfallStates(Options):
def hover(self) -> 'OptionPlotoptionsWaterfallStatesHover':
return self._config_sub_data('hover', OptionPlotoptionsWaterfallStatesHover)
def inactive(self) -> 'OptionPlotoptionsWaterfallStatesInactive':
return self._config_sub_data('inactive', Opt... |
class WafTagsResponse(ModelComposed):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
lazy_import()
... |
.gpu
.skipif((not has_torch_cuda_gpu), reason='needs GPU & CUDA')
def test_torch_dtype():
nlp = spacy.blank('en')
cfg = {**_PIPE_CFG, **{'model': {'_models': 'spacy.Dolly.v1', 'name': 'dolly-v2-3b'}}}
cfg['model']['config_init'] = {'torch_dtype': 'float16'}
llm = nlp.add_pipe('llm', name='llm1', config=... |
def test_expiring_value_caching():
with freeze_time() as frozen_datetime:
ev = cache.ExpiringValue(random.random, max_age=300)
initial_value = ev.value()
frozen_datetime.tick(delta=timedelta(seconds=60))
assert (ev.value() == initial_value), 'value was different, should have been cac... |
def test_recurse_check_structure_valid():
sample = dict(string='Foobar', list=['Foo', 'Bar'], dict={'foo': 'Bar'}, none=None, true=True, false=False)
to_check = dict(string='Foobar', list=['Foo', 'Bar', 'Bas'], dict={'foo': 'Bar'}, none=None, true=True, false=False)
recurse_check_structure(sample, to_check) |
def extractGameOfScanlation(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, pos... |
def postgres_example_test_dataset_config_skipped_login_collection(read_connection_config: ConnectionConfig, db: Session, example_datasets: List[Dict]) -> Generator:
postgres_dataset = example_datasets[0].copy()
fides_key = postgres_dataset['fides_key']
skipped_collection = next((col for col in postgres_data... |
def action_handler(action_name, button_name=None, pad_n=None, pad_ij=None, encoder_name=None):
def wrapper(func):
action = action_name
if ((action_name in [ACTION_BUTTON_PRESSED, ACTION_BUTTON_RELEASED]) and (button_name is not None)):
action = get_individual_button_action_name(action_na... |
('/models/{model_slug}', response_model=Model)
def update_models(model_slug: str, model_params: dict, connector: Connector=Depends(get_connection)):
try:
updated_model = connector.update_model(model_slug, model_params)
except exc.SlugDoesNotExist as ex:
raise HTTPException(status_code=404, detai... |
class DecisionId():
decision_target: DecisionTarget
decision_event_id: int
def __str__(self):
return f'{self.decision_target}:{self.decision_event_id}'
def __hash__(self):
return hash(self.__str__())
def __eq__(self, other: object):
if (not isinstance(other, DecisionId)):
... |
def upgrade():
op.alter_column('call_for_papers', 'privacy', existing_type=sa.VARCHAR(), nullable=False)
op.alter_column('call_for_papers', 'timezone', existing_type=sa.VARCHAR(), nullable=False)
op.add_column('events', sa.Column('thumbnail', sa.String(), nullable=True))
op.add_column('events_version', ... |
class PlanePoiseuilleFlow_w2(PlaneBase):
def __init__(self, plane_theta=0.0, plane_phi=old_div(math.pi, 2.0), v_theta=old_div(math.pi, 2.0), v_phi=None, v_norm=1.0, mu=1.0, grad_p=1.0, L=[1.0, 1.0, 1.0]):
PlaneBase.__init__(self, plane_theta, plane_phi, v_theta, v_phi, v_norm, mu, grad_p, L)
def uOfX(se... |
class RuleVisitorTests(TestCase):
def test_round_trip(self):
tree = rule_grammar.parse('number = ~"[0-9]+"\n')
(rules, default_rule) = RuleVisitor().visit(tree)
text = '98'
self.assertEqual(default_rule.parse(text), Node(default_rule, text, 0, 2))
def test_undefined_rule(self):
... |
def main():
p = argparse.ArgumentParser(description='Utility for performing various checks and operations on SOLiD run directories. If a single solid_run_dir is specified then %(prog)s automatically finds and operates on all associated directories from the same instrument and with the same timestamp.')
p.add_ar... |
class TestIssues(TestCase):
def test_auto_multi_int(self):
class Measurement(int, MultiValueEnum, AddValueEnum):
_order_ = 'one two three'
_start_ = 0
one = ''
two = ''
three = ''
self.assertEqual([m.value for m in Measurement], [0, 1, 2])
... |
.parametrize('telescope', ['ut1', 'ut2', 'ut3', 'antu', 'kueyen', 'melipal'])
.parametrize('with_spiders', [True, False])
def test_vlt_ut_123_aperture(telescope, with_spiders):
name = 'vlt/pupil_ut123'
name += ('_without_spiders' if (not with_spiders) else '')
check_aperture(make_vlt_aperture, 8.0, name, ch... |
class AnalysisPlugin(YaraBasePlugin):
NAME = 'known_vulnerabilities'
DESCRIPTION = 'Rule based detection of known vulnerabilities like Heartbleed'
DEPENDENCIES = ['file_hashes', 'software_components']
VERSION = '0.2.1'
FILE = __file__
def process_object(self, file_object):
file_object = ... |
def get_earliest_load_date(keys, default=None):
earliest_date = None
for key in keys:
key_date = get_last_load_date(key)
if key_date:
if (earliest_date is None):
earliest_date = key_date
elif (key_date < earliest_date):
earliest_date = key_... |
class AsyncMultiplexer(Runnable, WithLogger):
DISCONNECT_TIMEOUT = 5
CONNECT_TIMEOUT = 60
SEND_TIMEOUT = 60
_lock: asyncio.Lock
def __init__(self, connections: Optional[Sequence[Connection]]=None, default_connection_index: int=0, loop: Optional[AbstractEventLoop]=None, exception_policy: ExceptionPol... |
()
('operation')
('params', nargs=(- 1))
('--path', type=click.Path(exists=True, dir_okay=False))
('--format', type=FORMAT_SCHEMA_CHOICES)
('--encoding', type=ENCODING_CHOICES)
('--verbose', '-v', is_flag=True, default=False)
_context
def request(ctx, operation, params, path, format, encoding, verbose):
options = {... |
class TestDockerProvisioner():
('uuid.uuid4')
def test_provisioning_with_defaults(self, uuid4):
uuid4.return_value = '9dbc682e-d32a-4669-8fbe-56fb77120dd4'
node_ip = '10.17.22.33'
node_root_dir = tempfile.gettempdir()
log_dir = os.path.join(node_root_dir, 'logs', 'server')
... |
class OptionSeriesGaugeSonificationTracksMappingLowpassResonance(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):
... |
def _start():
global patch, name, path, monitor
global filename, f, chanindx, channels, channelz, fSample, nSamples, replace, i, s, z, blocksize, begsample, endsample, block
filename = patch.getstring('playback', 'file')
monitor.info(('Reading data from ' + filename))
f = EDF.EDFReader()
f.open(... |
def search_by_query(query: str, platform: Platforms=None) -> Iterator[dict]:
hits_per_page = 50
options = {'hitsPerPage': hits_per_page}
page = (- 1)
while True:
page += 1
options['page'] = page
items = _search_index(query, **options)
for item in items:
if (it... |
_each
def before_each(transaction):
with stash['app'].app_context():
db.engine.execute('drop schema if exists public cascade')
db.engine.execute('create schema public')
db.engine.execute('create extension if not exists citext')
db.create_all()
create_super_admin(api_username,... |
def get_documents(case_id, bucket):
documents = []
with db.engine.connect() as conn:
rs = conn.execute(CASE_DOCUMENTS, case_id)
for row in rs:
document = {'document_id': row['document_id'], 'category': row['category'], 'description': row['description'], 'length': row['length'], 'text... |
class OptionPlotoptionsLineStatesHoverMarker(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):
self._co... |
class windowsof(_coconut_has_iter):
__slots__ = ('size', 'fillvalue', 'step')
def __new__(cls, size, iterable, fillvalue=_coconut_sentinel, step=1):
self = _coconut.super(_coconut_windowsof, cls).__new__(cls, iterable)
self.size = _coconut.operator.index(size)
if (self.size < 1):
... |
def fortios_log_fortiguard(data, fos):
fos.do_member_operation('log.fortiguard', 'filter')
if data['log_fortiguard_filter']:
resp = log_fortiguard_filter(data, fos)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'log_fortiguard_filter'))
return ((not is_successful_status(resp... |
class TestMPCService(IsolatedAsyncioTestCase):
def setUp(self):
cspatcher = patch('fbpcp.service.container.ContainerService')
gspatcher = patch('fbpcs.private_computation.service.mpc.mpc_game.MPCGameService')
container_svc = cspatcher.start()
mpc_game_svc = gspatcher.start()
... |
_type(ofproto.OFPPSPT_OPTICAL)
class OFPPortStatsPropOptical(OFPPortStatsProp):
def __init__(self, type_=None, length=None, flags=None, tx_freq_lmda=None, tx_offset=None, tx_grid_span=None, rx_freq_lmda=None, rx_offset=None, rx_grid_span=None, tx_pwr=None, rx_pwr=None, bias_current=None, temperature=None):
... |
(LOOK_DEV_TYPES)
def check_multiple_connections_for_textures(progress_controller=None):
if (progress_controller is None):
progress_controller = ProgressControllerBase()
plugins = ['matrixNodes', 'quatNodes']
for plugin in plugins:
if (not pm.pluginInfo(plugin, q=1, l=1)):
pm.load... |
def upgrade():
op.add_column('currentprivacypreference', sa.Column('purpose_consent', sa.Integer(), nullable=True))
op.add_column('currentprivacypreference', sa.Column('purpose_legitimate_interests', sa.Integer(), nullable=True))
op.add_column('currentprivacypreference', sa.Column('vendor_consent', sa.Strin... |
def test_custom_model_composer():
env = build_dummy_structured_env()
policies = {'_target_': 'maze.perception.models.policies.ProbabilisticPolicyComposer', 'networks': [{'_target_': 'maze.test.shared_test_utils.dummy_models.actor_model.DummyPolicyNet', 'non_lin': 'torch.nn.SELU'}, {'_target_': 'maze.test.shared... |
def get_cat_name(cat_id: int, is_jp: bool, cc: str) -> str:
file_data = game_data_getter.get_file_latest('resLocal', f'Unit_Explanation{(cat_id + 1)}_{cc}.csv', is_jp)
if (file_data is None):
helper.error_text('Failed to get cat names')
return ''
cat_name = csv_handler.parse_csv(file_data.de... |
class TestScheduleDView(ApiBaseTest):
def test_fields(self):
[factories.ScheduleDViewFactory()]
results = self._results(api.url_for(ScheduleDView))
assert (len(results) == 1)
assert (results[0].keys() == ScheduleDSchema().fields.keys())
def test_filters(self):
filters = [... |
def commit_prediction_drift_metrics_to_db(drift_report_metrics: Dict, timestamp: float, db_uri: Text) -> None:
engine = create_engine(db_uri)
session = open_sqa_session(engine)
data_drift_prediction = PredictionDriftTable(**drift_report_metrics, timestamp=timestamp)
add_or_update_by_ts(session, data_dri... |
class JobFS(types.SimpleNamespace):
CONTEXT: str = ''
_jobs: 'JobsFS'
def from_jobsfs(cls, jobsfs: 'JobsFS', reqid: requests.ToRequestIDType) -> 'JobFS':
requestfs = JobRequestFS.from_raw(f'{jobsfs.requests}/{reqid}')
resultfs = JobResultFS.from_raw(f'{jobsfs.results}/{reqid}')
workf... |
class LocalDeclarationGenerator(BaseAstDataflowObjectVisitor):
def __init__(self, vars_per_line: int=1):
self._variables: Set[Variable] = set()
self._vars_per_line: int = vars_per_line
def from_task(cls, task: DecompilerTask):
param_names = list((param.name for param in task.function_par... |
def test_string():
validator = String()
validated = validator.validate_or_error('abc')
assert validated
assert (validated.value == 'abc')
assert (validated.error is None)
validator = String()
(value, error) = validator.validate_or_error('')
assert (error == ValidationError(text='Must not... |
class SaveCommentSchema(CSRFProtectedSchema, colander.MappingSchema):
def deserialize(self, cstruct):
appstruct = SaveCommentSchema().unflatten(cstruct)
return super(SaveCommentSchema, self).deserialize(appstruct)
update = colander.SchemaNode(colander.String())
text = colander.SchemaNode(col... |
def test_get_authenticator_basic():
cfg = PlatformConfig(auth_mode=AuthType.BASIC)
with pytest.raises(ValueError, match='Client ID and Client SECRET both are required'):
get_authenticator(cfg, None)
cfg = PlatformConfig(auth_mode=AuthType.BASIC, client_credentials_secret='xyz', client_id='id')
a... |
def do_braid(maze_path, maze_verts, braid_amount=1.0):
ends = [vert for vert in maze_verts if (len(maze_nghbrs(vert, maze_path)) == 1)]
random.shuffle(ends)
braid_links = maze_path[:]
for vert in ends:
vert_neghbrs = maze_nghbrs(vert, braid_links)
if ((len(vert_neghbrs) == 1) and (random... |
class SliceScatterLargeInputsTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(SliceScatterLargeInputsTestCase, self).__init__(*args, **kwargs)
self.test_count = 1
def setUpClass(cls) -> None:
torch.manual_seed(0)
def _test_slice_scatter(self, input_shape, start... |
_server.peripheral_model
class UARTPublisher(object):
rx_buffers = defaultdict(deque)
_server.tx_msg
def write(cls, uart_id, chars):
log.info(('Writing: %s' % chars))
msg = {'id': uart_id, 'chars': chars}
return msg
def read(cls, uart_id, count=1, block=False):
log.debug(... |
def test_piggybacking_resource_post_and_delete(app_client):
for number in range(1, 8):
resp = app_client.simulate_post('/items', json={'number': number})
assert (resp.status_code == 201)
assert (resp.headers['X-Hook-Applied'] == '1')
assert (len(app_client.simulate_get('/items').json... |
def load_config():
config = configparser.ConfigParser()
config.read(args.config)
for power_source in ('AC', 'BATTERY'):
for option in ('Update_Rate_s', 'PL1_Tdp_W', 'PL1_Duration_s', 'PL2_Tdp_W', 'PL2_Duration_S'):
value = config.getfloat(power_source, option, fallback=None)
... |
class OptionPlotoptionsVectorSonificationContexttracksMappingGapbetweennotes(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: s... |
def fetch_consumption(zone_key: ZoneKey=ZoneKey('KR'), session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list[dict]:
session = (session or Session())
if target_datetime:
raise ParserException('KPX.py', 'This parser is not yet able to parse pa... |
def test_mutate_grow(tree, r2_growable):
old_tree_len = tree.num_nodes()
l3 = LeafNode(depth=3, composite_rules=CompositeRules(all_dims=[0], all_split_rules=[SplitRule(grow_dim=0, grow_val=3, operator=Operator.le)]), val=15)
r3 = LeafNode(depth=3, composite_rules=CompositeRules(all_dims=[0], all_split_rules... |
def test_get_accounts_for_deletion_returns(computation, canonical_address_a, canonical_address_b):
computation.register_account_for_deletion(canonical_address_a)
assert (computation.get_accounts_for_deletion() == ((canonical_address_a, canonical_address_a),))
computation.msg.storage_address = canonical_addr... |
class TestWorkflowOps(unittest.TestCase):
def setUp(self) -> None:
self.workflow_file_path = os.path.join(os.path.dirname(__file__), 'workflow_for_unittest.py')
('ai_flow.ops.workflow_ops.get_scheduler_client')
def test_upload_new_workflows(self, mock_scheudler_client):
mock_scheudler_client... |
class TestCreatePrivacyRequestAuthenticated():
(scope='function')
def url(self) -> str:
return f'{V1_URL_PREFIX}{PRIVACY_REQUEST_AUTHENTICATED}'
def verification_config(self, db):
original = CONFIG.execution.subject_identity_verification_required
CONFIG.execution.subject_identity_ver... |
def test_ubq_to_dict():
ubq = UpdateByQuery()
assert ({} == ubq.to_dict())
ubq = ubq.query('match', f=42)
assert ({'query': {'match': {'f': 42}}} == ubq.to_dict())
assert ({'query': {'match': {'f': 42}}, 'size': 10} == ubq.to_dict(size=10))
ubq = UpdateByQuery(extra={'size': 5})
assert ({'si... |
def _add_apikey_handler(security, user_datastore):
_manager.request_loader
def load_user_from_request(request):
api_key = request.headers.get('Authorization')
if api_key:
user = user_datastore.find_user(api_key=api_key)
if user:
return user
return ... |
class Solution():
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
def build_levels(node, vl, hl, track):
if (node is None):
return
if (vl not in track):
track[vl] = []
track[vl].append([hl, node.val])
build_level... |
_models('spacy.GPT-3-5.v2')
def openai_gpt_3_5_v2(config: Dict[(Any, Any)]=SimpleFrozenDict(temperature=_DEFAULT_TEMPERATURE), name: Literal[('gpt-3.5-turbo', 'gpt-3.5-turbo-16k', 'gpt-3.5-turbo-0613', 'gpt-3.5-turbo-0613-16k', 'gpt-3.5-turbo-instruct')]='gpt-3.5-turbo', strict: bool=OpenAI.DEFAULT_STRICT, max_tries: i... |
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('dataset', choices=['addresses', 'chemicals'])
def handle(self, *args, **kwargs):
url = '
rsp = requests.get(url)
doc = BeautifulSoup(rsp.content, 'html.parser')
tag = doc.find('script', type... |
class ApexRest(commons.BaseRequest):
def __init__(self, session_id, instance_url, action, request_params, request_body, **kwargs):
if (request_params is not None):
p = urlencode(request_params)
action = ('%s?%s' % (action, p))
super().__init__(session_id, instance_url, requ... |
class TestImportDmd2(TestCase):
def setUpTestData(cls):
for (bnf_code, name) in [('0203020C0AAAAAA', 'Adenosine_I/V Inf 3mg/ml 2ml Vl'), ('1003020U0AAAIAI', 'Diclofenac Sod_Gel 2.32%'), ('1003020U0BBADAI', 'Voltarol 12 Hour Emulgel P_Gel 2.32%'), ('1305020C0AAFVFV', 'Coal Tar 10%/Salic Acid 5%/Aq_Crm'), ('1... |
class SnmpUSMSecurityModel(AbstractSecurityModel):
SECURITY_MODEL_ID = 3
AUTH_SERVICES = {hmacmd5.HmacMd5.SERVICE_ID: hmacmd5.HmacMd5(), hmacsha.HmacSha.SERVICE_ID: hmacsha.HmacSha(), hmacsha2.HmacSha2.SHA224_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA224_SERVICE_ID), hmacsha2.HmacSha2.SHA256_SERVICE_ID... |
def test_clock_decision_context_from_replay(version_decision_context):
with pytest.raises(Exception) as exc_info:
version_decision_context.workflow_clock.set_replaying(True)
version = version_decision_context.workflow_clock.get_version('abc', 1, 5)
assert ('Version -1 of changeID abc is not supp... |
def create_admin(username, password, email, job_title, silent=False):
query = FlicketUser.query.filter_by(username=username)
if (query.count() == 0):
add_user = FlicketUser(username=username, name=username, password=hash_password(password), email=email, job_title=job_title, date_added=datetime.datetime.... |
def process_new_build_pypi(copr, add_view, url_on_success):
def factory(**build_options):
BuildsLogic.create_new_from_pypi(flask.g.user, copr, form.pypi_package_name.data, form.pypi_package_version.data, form.spec_generator.data, form.spec_template.data, form.python_versions.data, form.selected_chroots, **b... |
class OptionSeriesPictorialStatesInactive(Options):
def animation(self) -> 'OptionSeriesPictorialStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesPictorialStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
... |
def extractSecretcouncildcWordpressCom(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... |
class RunTest(TestCase):
def setUp(self) -> None:
self.db = DB(DBType.MEMORY)
create_models(self.db)
self.fakes = FakeObjectGenerator()
if (self.shortDescription() == 'No setUp'):
return
run1 = self.fakes.run()
run2 = self.fakes.run()
run3 = self.f... |
def set_font_size(window, size):
font = window.GetFont()
clone = clone_font(font)
clone.SetPointSize(size)
window.SetFont(clone)
sizer = window.GetSizer()
if (sizer is not None):
sizer.Layout()
window.Refresh()
for child in window.GetChildren():
set_font_size(child, size) |
class OptionSeriesVectorDragdrop(Options):
def draggableX(self):
return self._config_get(None)
def draggableX(self, flag: bool):
self._config(flag, js_type=False)
def draggableY(self):
return self._config_get(None)
def draggableY(self, flag: bool):
self._config(flag, js_t... |
def add_IsolateControllerServicer_to_server(servicer, server):
rpc_method_handlers = {'Run': grpc.unary_stream_rpc_method_handler(servicer.Run, request_deserializer=controller__pb2.HostedRun.FromString, response_serializer=controller__pb2.HostedRunResult.SerializeToString), 'Map': grpc.unary_stream_rpc_method_handl... |
.django_db
def test_category_county_subawards(geo_test_data):
test_payload = {'category': 'county', 'subawards': True, 'page': 1, 'limit': 50}
spending_by_category_logic = CountyViewSet().perform_search(test_payload, {})
expected_response = {'category': 'county', 'limit': 50, 'page_metadata': {'page': 1, 'n... |
def get_first_matching_media_type(accept_media_types: Sequence[str], available_media_types: Sequence[str]) -> Optional[str]:
if (not available_media_types):
return None
if (not accept_media_types):
return available_media_types[0]
for accept_media_type in accept_media_types:
if (accep... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.