code stringlengths 281 23.7M |
|---|
class FrameProfilingRenderer():
def __init__(self, title: str='Pandas Profiling Report'):
self._title = title
def to_html(self, df: 'pd.DataFrame') -> str:
assert isinstance(df, pd.DataFrame)
import ydata_profiling
profile = ydata_profiling.ProfileReport(df, title=self._title)
... |
()
('--prompt', type=str, default='The quick brown fox jumps over the lazy dog.', help='The prompt to give BERT.')
('--activation', type=str, default='fast_gelu', help='Activation function applied on BERT, currently only support gelu and fast_gelu')
('--graph_mode', type=bool, default=True, help='Use CUDA graph or not.... |
class OptionPlotoptionsNetworkgraphSonificationDefaultspeechoptions(Options):
def activeWhen(self) -> 'OptionPlotoptionsNetworkgraphSonificationDefaultspeechoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsNetworkgraphSonificationDefaultspeechoptionsActivewhen)
def languag... |
class CGenerator(object):
def __init__(self):
self.indent_level = 0
def _make_indent(self):
return (' ' * self.indent_level)
def visit(self, node):
method = ('visit_' + node.__class__.__name__)
return getattr(self, method, self.generic_visit)(node)
def generic_visit(self,... |
class OptionSeriesAreasplinerangeDataDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._conf... |
.external
.parametrize('generate_type, generate_target', [('systems', 'aws'), ('systems', 'okta'), ('datasets', 'db'), ('datasets', 'bigquery'), ('datasets', 'dynamodb')])
def test_generate(test_config: FidesConfig, generate_type: str, generate_target: str, test_client: TestClient) -> None:
data = {'organization_ke... |
def pytest_configure(config):
from django.conf import settings
settings.configure(DEBUG_PROPAGATE_EXCEPTIONS=True, DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}, SITE_ID=1, SECRET_KEY='not very secret in tests', USE_I18N=True, STATIC_URL='/static/', ROOT_URLCONF='tests.urls... |
class EspSecureHSMTestCase():
def setup_class(self):
self.cleanup_files = []
def teardown_class(self):
for f in self.cleanup_files:
f.close()
def _open(self, image_file):
f = open(os.path.join(TEST_DIR, 'secure_images', image_file), 'rb')
self.cleanup_files.append... |
def on_window_focus(layouts: Layouts, state: State):
def _on_window_focus(i3l: Connection, e: WindowEvent):
logger.debug(f'[ipc] window focus event - container:{e.container.id}:{e.container.window}')
context = state.sync_context(i3l)
layout = layouts.get(context.workspace.name)
focus... |
def train_function(n_epochs: int, distributed_env_cls) -> PPO:
envs = distributed_env_cls([(lambda : GymMazeEnv(env='CartPole-v0')) for _ in range(2)])
eval_env = distributed_env_cls([(lambda : GymMazeEnv(env='CartPole-v0')) for _ in range(2)], logging_prefix='eval')
env = GymMazeEnv(env='CartPole-v0')
... |
def test_input_stream():
with open('tests/lipsum.txt', 'r') as fin:
data = fin.read()
runner = CliRunner()
result = runner.invoke(cli, ['-s', '0'], input=data)
assert (result.exit_code == 0)
lines = iter(result.output.split('\r'))
filt = []
(prev, curr) = (None, next(lines))
whil... |
('/search')
def search_notes():
notes = []
if current_user.is_authenticated:
query = request.args.get('query', None)
if (query is not None):
query = ('%%%s%%' % str(query))
notes = Note.query.filter(Note.body.like(query), (Note.owner_id == current_user.id)).limit(100).all... |
class Value(KqlNode):
__slots__ = ('value',)
precedence = 1
def __init__(self, value):
self.value = value
def from_python(cls, value):
if (value is None):
return Null()
elif (is_string(value) and (('*' in value) or ('?' in value))):
return Wildcard(value)
... |
def regtest_generate_nblocks(nblocks: int, address: str) -> List:
payload1 = json.dumps({'jsonrpc': '2.0', 'method': 'generatetoaddress', 'params': [nblocks, address], 'id': 0})
result = requests.post(BITCOIN_NODE_URI, data=payload1)
result.raise_for_status()
block_hashes = []
for block_hash in resu... |
class TestTopicSubscriptionListView(BaseClientTestCase):
(autouse=True)
def setup(self):
self.u1 = UserFactory.create()
self.g1 = GroupFactory.create()
self.u1.groups.add(self.g1)
self.user.groups.add(self.g1)
self.perm_handler = PermissionHandler()
self.top_level... |
class Seq2Pat():
def __init__(self, sequences: List[list], max_span: Optional[int]=10, batch_size=None, discount_factor=0.2, n_jobs=2, seed=_Constants.default_seed):
validate_sequences(sequences)
validate_max_span(max_span)
validate_batch_args(batch_size, discount_factor, n_jobs, seed)
... |
def test_add_code_node():
asforest = AbstractSyntaxForest(condition_handler=ConditionHandler())
asforest.add_code_node((code_node_1 := asforest.factory.create_code_node([])))
assert ((len(asforest) == 2) and (set(asforest.get_roots) == {code_node_1, asforest._current_root}))
asforest.add_code_node((code... |
class _MenuItem(HasTraits):
checked = Bool(False)
controller = Any()
enabled = Bool(True)
visible = Bool(True)
group = Any()
def __init__(self, parent, menu, item, controller):
self.item = item
self.control_id = 1
self.control = None
if (controller is not None):
... |
def source_folder():
parent_temp = tempfile.mkdtemp()
src_dir = os.path.join(parent_temp, 'source', '')
nested_dir = os.path.join(src_dir, 'nested')
local.mkdir(nested_dir)
local.touch(os.path.join(src_dir, 'original.txt'))
with open(os.path.join(src_dir, 'original.txt'), 'w') as fh:
fh.... |
class PreviewHandler(Handler):
def get_object(self):
page = get_object_or_404(self.page_model, pk=self.args[1])
self.request.path = page.get_absolute_url()
return page
def handler(self, request, *args, **kwargs):
if (not request.user.is_staff):
raise Http404('Not foun... |
def test_pod_security_policy():
config = ''
resources = ('role', 'rolebinding', 'serviceaccount', 'podsecuritypolicy')
r = helm_template(config)
for resource in resources:
assert (resource not in r)
assert ('serviceAccountName' not in r['statefulset'][uname]['spec']['template']['spec'])
... |
class OptionSeriesAreaSonificationDefaultspeechoptionsMappingTime(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 character_aware_vertical_mirror(art: str) -> str:
art_lines = art.split('\n')
art_lines.reverse()
output = ''
for line in art_lines:
output_line = ''.join([(vmirror_character_alternatives[char] if (char in vmirror_character_alternatives.keys()) else char) for char in line])
output +=... |
class DatasetCorrelation(MetricResult):
class Config():
dict_exclude_fields = {'correlation', 'correlations_calculate'}
pd_exclude_fields = {'correlation', 'correlations_calculate'}
correlation: Dict[(str, pd.DataFrame)]
stats: Dict[(str, CorrelationStats)]
correlations_calculate: Option... |
class AuditCategoryRelation(db.Model):
__table_args__ = {'schema': 'auditsearch'}
__tablename__ = 'finding_rel_vw'
primary_category_id = db.Column(db.String, index=True, primary_key=True, doc=docs.PRIMARY_CATEGORY_ID)
primary_category_name = db.Column(db.String, doc=docs.PRIMARY_CATEGORY_NAME)
sub_c... |
def get_cosineannealing_scheduler_with_warmup(optimizer: torch.optim.Optimizer, max_epochs: int=12, warmup_epochs: float=0.1):
warmup_milestone_epoch = max(1.0, int((warmup_epochs * max_epochs)))
warmup_scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=0.01, end_factor=1.0, total_iters=max(1... |
.parametrize('antialias', [True, False])
def test_project_grid_antialias(antialias):
shape = (50, 40)
lats = np.linspace(2, 10, shape[1])
lons = np.linspace((- 10), 2, shape[0])
data = np.ones(shape, dtype='float')
grid = xr.DataArray(data, coords=[lons, lats], dims=('latitude', 'longitude'))
pr... |
class OptionPlotoptionsGaugeSonificationContexttracksMapping(Options):
def frequency(self) -> 'OptionPlotoptionsGaugeSonificationContexttracksMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsGaugeSonificationContexttracksMappingFrequency)
def gapBetweenNotes(self) -> 'Option... |
def test_config_dataclasses():
cat = Cat('testcat', value_in=1, value_out=2)
config = {'cfg': {'': 'catsie.v3', 'arg': cat}}
result = my_registry.resolve(config)['cfg']
assert isinstance(result, Cat)
assert (result.name == cat.name)
assert (result.value_in == cat.value_in)
assert (result.val... |
class OptionSeriesVennSonificationContexttracksMappingLowpass(Options):
def frequency(self) -> 'OptionSeriesVennSonificationContexttracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionSeriesVennSonificationContexttracksMappingLowpassFrequency)
def resonance(self) -> 'OptionSer... |
class ExaMetaData(object):
snapshot_execution_hint = '/*snapshot execution*/'
def __init__(self, connection):
self.connection = connection
self.sql_keywords = None
def sql_columns(self, query, query_params=None):
st = self.connection.cls_statement(self.connection, query, query_params... |
_renderer(wrap_type=TestRocAuc)
class TestRocAucRenderer(TestRenderer):
def render_html(self, obj: TestRocAuc) -> TestHtmlInfo:
info = super().render_html(obj)
curr_roc_curve: Optional[ROCCurve] = obj._roc_curve.get_result().current_roc_curve
ref_roc_curve: Optional[ROCCurve] = obj._roc_curv... |
class Migration(migrations.Migration):
dependencies = [('search', '0021_partition_transaction_search_pt1_index_prep_and_tables')]
operations = [migrations.RunPython(code=check_data_load_limit, reverse_code=migrations.RunPython.noop), migrations.RunSQL(sql='\n INSERT INTO temp.transaction_search_f... |
class TestLinuxKernelUnpacker(TestUnpackerBase):
def test_unpacker_selection_generic(self):
self.check_unpacker_selection('linux/kernel', 'LinuxKernel')
.parametrize('input_file, expected', [('bzImage_bzip2', 'vmlinux_BZIP_17001'), ('bzImage_gzip', 'vmlinux_GZIP_17001'), ('bzImage_lz4', 'vmlinux_LZ4_170... |
class LittleLegionHoldAction(UserAction):
def apply_action(self):
src = self.source
g = self.game
g.process_action(DrawCards(src, 1))
turn = PlayerTurn.get_current(g)
try:
turn.pending_stages.remove(DropCardStage)
except Exception:
pass
... |
class RegisterDialogue(BaseRegisterDialogue):
def __init__(self, dialogue_label: DialogueLabel, self_address: Address, role: BaseDialogue.Role, message_class: Type[RegisterMessage]) -> None:
BaseRegisterDialogue.__init__(self, dialogue_label=dialogue_label, self_address=self_address, role=role, message_clas... |
def get_contract_from_blockchain(address, key_file=None):
key = get_api_key(key_file)
api = Contract(address=address, api_key=key)
sourcecode = api.get_sourcecode()
with open(contract_dir, 'w') as contract_file:
contract_file.write(sourcecode[0]['SourceCode'])
return contract_dir |
_drop_double_transpose.register(Negative)
_drop_double_transpose.register(Add)
_drop_double_transpose.register(Mul)
_drop_double_transpose.register(Solve)
_drop_double_transpose.register(Inverse)
_drop_double_transpose.register(DiagonalTensor)
_drop_double_transpose.register(Reciprocal)
def _drop_double_transpose_distr... |
def _remove_no_op_expands(sorted_graph: List[Tensor]) -> List[Tensor]:
ops = graph_utils.get_sorted_ops(sorted_graph)
for op in ops:
if (op._attrs['op'] != 'expand'):
continue
outputs = op._attrs['outputs']
assert (len(outputs) == 1), 'expand must only have 1 output'
... |
def _validate_map(datum, schema, named_schemas, parent_ns, raise_errors, options):
return (isinstance(datum, Mapping) and all((isinstance(k, str) for k in datum)) and all((_validate(datum=v, schema=schema['values'], named_schemas=named_schemas, field=parent_ns, raise_errors=raise_errors, options=options) for v in d... |
class CommandsTestCase(TestCase):
def test_import_qof_prevalence(self):
args = []
fixture_dir = 'frontend/tests/fixtures/commands/'
opts = {'by_ccg': (fixture_dir + 'prevalencebyccg.csv'), 'by_practice': (fixture_dir + 'prevalencebyprac.csv'), 'start_year': 2013}
call_command('import... |
def test_doc_empty_overwrite_type_bound_procedure_fun():
string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)})
file_path = ((test_dir / 'subdir') / 'test_free.f90')
string += hover_request(file_path, 22, 17)
string += hover_request(file_path, 22, 32)
(errcode, results) = run_reque... |
def has_reference(fname1, fname2):
try:
with open(url_to_fname(fname1), encoding='UTF-8') as fptr:
content1 = fptr.read()
with open(url_to_fname(fname2), encoding='UTF-8') as fptr:
content2 = fptr.read()
return ((basename(fname1) in content2) or (basename(fname2) in c... |
def test_buildPF_pass_1():
d = d_pass[1]
pf = build_portfolio(**d)
assert isinstance(pf, Portfolio)
assert isinstance(pf.get_stock(names_yf[0]), Stock)
assert isinstance(pf.data, pd.DataFrame)
assert isinstance(pf.portfolio, pd.DataFrame)
assert (len(pf.stocks) == len(pf.data.columns))
a... |
.unit_saas
def test_saas_request_without_method_or_path():
with pytest.raises(ValidationError) as exc:
SaaSRequest(path='/test')
assert ('A request must specify a method' in str(exc.value))
with pytest.raises(ValidationError) as exc:
SaaSRequest(method='GET')
assert ('A request must spec... |
class OptionPlotoptionsArearangeStatesHover(Options):
def animation(self) -> 'OptionPlotoptionsArearangeStatesHoverAnimation':
return self._config_sub_data('animation', OptionPlotoptionsArearangeStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bo... |
class bsn_forward_error_correction(bsn):
type = 65535
experimenter = 6035143
exp_type = 2
def __init__(self, configured=None, enabled=None):
if (configured != None):
self.configured = configured
else:
self.configured = 0
if (enabled != None):
s... |
class loopback(operation):
_PACK_STR = '!4BI'
_MIN_LEN = struct.calcsize(_PACK_STR)
_TLV_OFFSET = 4
def __init__(self, md_lv, version, transaction_id, tlvs):
super(loopback, self).__init__(md_lv, version, tlvs)
self._flags = 0
self.transaction_id = transaction_id
def parser(c... |
def get_roc_auc_tab_data(curr_roc_curve: ROCCurve, ref_roc_curve: Optional[ROCCurve], color_options: ColorOptions) -> List[Tuple[(str, BaseWidgetInfo)]]:
additional_plots = []
cols = 1
subplot_titles = ['']
if (ref_roc_curve is not None):
cols = 2
subplot_titles = ['current', 'reference'... |
def test_attach_external_modules_that_do_not_inherit_from_module_class(module1_unique, module2_unique, module3_unique, module4_unique):
w3 = Web3(EthereumTesterProvider(), external_modules={'module1': module1_unique, 'module2': (module2_unique, {'submodule1': (module3_unique, {'submodule2': module4_unique})})})
... |
class AgentPipeline(GenericAgent):
pipeline: List = []
def __init__(self, module_list: List[GenericAgent]) -> None:
self.module_list = module_list
self.check_pipeline_types()
def check_pipeline_types(self):
if (len(self.pipeline) > 1):
for i in range(1, len(self.pipeline)... |
class TimeTreeTracer(Tracer):
def __init__(self, instance, verbosity=False, root_label='root', start_clocks=False, max_depth=1024):
Tracer.__init__(self, instance, verbosity, max_depth)
self.trace = Node(root_label)
self.current = self.trace
if start_clocks:
self.reenter(... |
class Sensor(GenericSensor):
SENSOR_SCHEMA: CerberusSchemaType = {'pin_echo': {'type': 'integer', 'required': True, 'empty': False}, 'pin_trigger': {'type': 'integer', 'required': True, 'empty': False}, 'burst': {'type': 'integer', 'required': True, 'empty': False}}
def setup_module(self) -> None:
impor... |
class EditGroup(MethodView):
decorators = [allows.requires(IsAdmin, on_fail=FlashAndRedirect(message=_('You are not allowed to modify groups.'), level='danger', endpoint='management.overview'))]
form = EditGroupForm
def get(self, group_id):
group = Group.query.filter_by(id=group_id).first_or_404()
... |
def get_bug_traqs_lists_from_online_mode(bid_list):
items = set()
output_array = []
extended_info_array = []
for line in bid_list:
try:
json_data = json.loads(line)
parse_bid_from_json(json_data, items)
del json_data['vuln_products']
extended_info_... |
def populate_broker_data(broker_server_dblink_setup):
broker_data = {'sam_recipient': json.loads(Path('usaspending_api/recipient/tests/data/broker_sam_recipient.json').read_text()), 'subaward': json.loads(Path('usaspending_api/awards/tests/data/subaward.json').read_text()), 'cd_state_grouped': json.loads(Path('usas... |
class ParallelBuildExt(*build_ext_classes):
def logger(self):
logger = get_logger(self.logger_name)
return logger
def initialize_options(self):
super().initialize_options()
self.logger_name = 'transonic'
self.num_jobs_env_var = ''
self.ignoreflags = ('-Wstrict-pro... |
class TestBashOperator(unittest.TestCase):
def test_start_bash(self):
test_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), '.test_start_bash.test')
open(test_file, 'a').close()
self.assertTrue(os.path.isfile(test_file))
with Workflow(name='workflow') as workflow:
... |
class HomeWindow():
def __init__(self):
self.id_string = 'plugin.video.embycon-%s'
self.window = xbmcgui.Window(10000)
def get_property(self, key):
key = (self.id_string % key)
value = self.window.getProperty(key)
return value
def set_property(self, key, value):
... |
class Auth(object):
def __init__(self):
self.hosts_yml = os.path.join(str(Path.home()), '.config', 'gh', 'hosts.yml')
if os.path.exists(self.hosts_yml):
with open(self.hosts_yml, 'r') as f:
self.hosts = yaml.safe_load(f)
else:
self.hosts = None
... |
def _get_prescribing_for_codes(db, bnf_code_prefixes):
if bnf_code_prefixes:
where_clause = ' OR '.join((['bnf_code LIKE ?'] * len(bnf_code_prefixes)))
params = [(code + '%') for code in bnf_code_prefixes]
sql = '\n SELECT\n matrix_sum(items) AS items,\n ... |
class OptionSeriesTilemapSonificationTracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesTilemapSonificationTracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesTilemapSonificationTracksMappingTremoloDepth)
def speed(self) -> 'OptionSeriesTilemapSonificationTracksMapp... |
def _filter_constant_calls(calls: List[ast.Call]) -> List[ast.Call]:
def _is_constant(arg: ast.expr):
import sys
if (sys.version_info < (3, 8)):
return isinstance(arg, ast.Str)
else:
return isinstance(arg, ast.Constant)
return [call for call in calls if all(map(_i... |
def test_that_run_workflow_component_enabled_when_workflows(qapp, tmp_path):
config_file = (tmp_path / 'config.ert')
with open(config_file, 'a+', encoding='utf-8') as ert_file:
ert_file.write('NUM_REALIZATIONS 1\n')
ert_file.write('LOAD_WORKFLOW_JOB workflows/UBER_PRINT print_uber\n')
er... |
def _to_notations(pitch: Pitch) -> List[str]:
notations = []
pitch_class = (pitch % 12)
octave = ((pitch // 12) - 1)
for alter in range((- 2), 3):
pc = (pitch_class - alter)
if (pc < 0):
o = (octave - 1)
elif (pc > 11):
o = (octave + 1)
else:
... |
def pwn():
payload = ('A' * (64 + 8))
payload += com_gadget(part1, part2, elf.got['read'], 0, binsh_addr, 8)
payload += p64(_start_addr)
payload = payload.ljust(200, 'A')
io.send(payload)
io.sendafter('bye~\n', '/bin/sh\x00')
payload = ('A' * (64 + 8))
payload += com_gadget(part1, part2,... |
class OptionSeriesAreaSonificationTracksMappingHighpass(Options):
def frequency(self) -> 'OptionSeriesAreaSonificationTracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionSeriesAreaSonificationTracksMappingHighpassFrequency)
def resonance(self) -> 'OptionSeriesAreaSonificatio... |
(scope='function')
def saas_external_example_connection_config(db: Session, saas_external_example_config: Dict[(str, Any)], saas_example_secrets: Dict[(str, Any)]) -> Generator:
fides_key = saas_external_example_config['fides_key']
connection_config = ConnectionConfig.create(db=db, data={'key': fides_key, 'name... |
def test_default_value_missing():
'
schema = {'type': 'record', 'name': 'test_default_value_missing', 'fields': [{'name': 'string', 'type': 'string'}]}
record = {}
new_file = StringIO(json.dumps(record))
with pytest.raises(ValueError, match='no value and no default'):
next(json_reader(new_fi... |
def split_simple_multistream_parallel_ops(ops_by_order, max_parallel_ops: int):
assert (max_parallel_ops > 0)
output = []
execution_orders = sorted(ops_by_order.keys())
for execution_order in execution_orders:
ops = ops_by_order[execution_order]
ops_parallel = []
for op in ops:
... |
def to_action(dic, ofp, parser, action_type, util):
actions = {COPY_TTL_OUT: parser.OFPActionCopyTtlOut, COPY_TTL_IN: parser.OFPActionCopyTtlIn, DEC_MPLS_TTL: parser.OFPActionDecMplsTtl, POP_VLAN: parser.OFPActionPopVlan, DEC_NW_TTL: parser.OFPActionDecNwTtl}
if (ofp.OFP_VERSION > ofproto_v1_2.OFP_VERSION):
... |
class Installer(BaseInstaller):
def __init__(self, check_install_log=True, config_json=None, credentials_json=None):
BaseInstaller.__init__(self, check_install_log=check_install_log, config_json=config_json, credentials_json=credentials_json)
def profile(self):
if self._is_done('profile'):
... |
def test_service_create(service: Service, default_entity_dict):
entity: ServerResponse = service.create(ServeRequest(**default_entity_dict))
with db.session() as session:
db_entity: ServeEntity = session.get(ServeEntity, entity.id)
assert (db_entity.id == entity.id)
assert (db_entity.cha... |
class Migration(migrations.Migration):
dependencies = [('admin_interface', '0024_remove_theme_css')]
operations = [migrations.AddField(model_name='theme', name='language_chooser_control', field=models.CharField(choices=[('default-select', 'Default Select'), ('minimal-select', 'Minimal Select')], default='defaul... |
.parametrize('remote_caps,local_caps,expected', (((A1,), (A1,), (A1,)), ((B1,), (B1,), (B1,)), ((A1, B1), (A1, B1), (A1, B1)), ((A1, B1), (B1, A1), (A1, B1)), ((B1, A1), (A1, B1), (A1, B1)), ((B1, A1), (B1, A1), (A1, B1)), ((A1, A2), (A2,), (A2,)), ((A1, A2), (A1,), (A1,)), ((A1,), (A1, A2), (A1,)), ((A2,), (A1, A2), (... |
.compilertest
def test_mapping_host_authority_and_host():
test_yaml = '\n---\napiVersion: getambassador.io/v3alpha1\nkind: Mapping\nmetadata:\n name: good-host-mapping\n namespace: default\nspec:\n headers:\n ":authority": bar.example.com\n host: foo.example.com\n prefix: /wanted_group/\n service: star\n'
... |
class ParametrizingString(text_type):
def __new__(cls, formatting, normal=None):
new = text_type.__new__(cls, formatting)
new._normal = normal
return new
def __call__(self, *args):
try:
parametrized = tparm(self.encode('latin1'), *args).decode('latin1')
re... |
(PRIVACY_REQUEST_MANUAL_WEBHOOK_ERASURE_INPUT, status_code=HTTP_200_OK, dependencies=[Security(verify_oauth_client, scopes=[PRIVACY_REQUEST_UPLOAD_DATA])], response_model=None)
def upload_manual_webhook_erasure_data(*, connection_config: ConnectionConfig=Depends(_get_connection_config), privacy_request_id: str, db: Ses... |
class Wrapper():
ib: 'IB'
accountValues: Dict[(tuple, AccountValue)]
acctSummary: Dict[(tuple, AccountValue)]
portfolio: Dict[(str, Dict[(int, PortfolioItem)])]
positions: Dict[(str, Dict[(int, Position)])]
trades: Dict[(OrderKeyType, Trade)]
permId2Trade: Dict[(int, Trade)]
fills: Dict[... |
def format_str(s):
s = s.replace('/*', '')
s = s.replace('*/', '')
s = s.replace('*', '')
lines = s.split('\n')
lines = lines[1:(- 1)]
for i in range(len(lines)):
lines[i] = lines[i].lstrip()
docstring = []
p = ''
params = False
for i in range(len(lines)):
if (lin... |
def test_apply_withdrawals():
if (not is_supported_pyevm_version_available()):
pytest.skip('PyEVM is not available')
backend = PyEVMBackend(vm_configuration=((0, ShanghaiVM),))
tester = EthereumTester(backend=backend)
withdrawals = [{'index': 0, 'validator_index': 0, 'address': f"0x{('01' * 20)}... |
class OptionSeriesLineZones(Options):
def className(self):
return self._config_get(None)
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get(None)
def color(self, text: str):
self._config(text, js_type=False)
def ... |
def get_container_tag_from_ref(ref: str) -> str:
if (not ref.startswith('refs/')):
raise SystemExit(f'expected an absolute ref, e.g. `refs/heads/master`, but got `{ref}`')
elif (ref == 'refs/heads/master'):
return 'latest'
elif ref.startswith('refs/heads/release/'):
return ref[19:]
... |
class Topic(BaseObject):
def __init__(self, api=None, body=None, created_at=None, forum_id=None, id=None, locked=None, pinned=None, position=None, search_phrases=None, submitter_id=None, tags=None, title=None, topic_type=None, updated_at=None, updater_id=None, url=None, **kwargs):
self.api = api
sel... |
class ContinuousPoll(_TextBox):
defaults = [('cmd', None, 'Command to execute.'), ('parse_line', None, 'Function to parse output of line. See docs for more.')]
def __init__(self, **config):
_TextBox.__init__(self, **config)
self.add_defaults(ContinuousPoll.defaults)
self._process = None
... |
def test_repcode_different_no_value(tmpdir, merge_files_oneLR, assert_log, assert_info):
path = os.path.join(str(tmpdir), 'different-repcode-no-value.dlis')
content = ['data/chap3/start.dlis.part', 'data/chap3/template/default.dlis.part', 'data/chap3/object/object.dlis.part', 'data/chap3/objattr/csingle-novalue... |
class OptionSeriesTimelineSonificationDefaultspeechoptionsActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num: ... |
_fixture
def branches(origin):
branches = ['f20', 'epel7', 'el6', 'fedora/26', 'rhel-7']
middle_branches = ['el6', 'fedora/26']
border_branches = ['f20', 'epel7', 'rhel-7']
assert (0 == os.system(' set -e\n cd work\n for branch in {branches}\n do\n git branch $branch\n git checkou... |
class TestConstants(unittest.TestCase):
def test_defaults(self):
assert constants.use_fast_pyparsing_reprs
assert (not constants.embed_on_internal_exc)
def test_fixpath(self):
assert (os.path.basename(fixpath('CamelCase.py')) == 'CamelCase.py')
def test_immutable(self):
for (... |
def make() -> PresetType:
return {'options': {'maxNesting': 20, 'html': True, 'linkify': False, 'typographer': False, 'quotes': '', 'xhtmlOut': True, 'breaks': False, 'langPrefix': 'language-', 'highlight': None}, 'components': {'core': {'rules': ['normalize', 'block', 'inline', 'text_join']}, 'block': {'rules': ['... |
def make_server_manager(port, authkey):
job_q = queue.Queue()
result_q = queue.Queue()
class JobQueueManager(SyncManager):
pass
JobQueueManager.register('get_job_q', callable=(lambda : job_q))
JobQueueManager.register('get_result_q', callable=(lambda : result_q))
manager = JobQueueManage... |
def test_paginate_query(in_memory_storage):
for i in range(10):
resource_id = MockResourceIdentifier(str(i))
item = MockStorageItem(resource_id, f'test_data{i}')
in_memory_storage.save(item)
page_size = 3
query_spec = QuerySpec(conditions={})
page_result = in_memory_storage.pagin... |
class TaskWindowLayout(MainWindowLayout):
consumed = List()
state = Instance('pyface.tasks.task_window.TaskState')
def _get_dock_widget(self, pane):
for dock_pane in self.state.dock_panes:
if (dock_pane.id == pane.id):
self.consumed.append(dock_pane.control)
... |
class ColorHelperChangesCommand(sublime_plugin.WindowCommand):
def run(self):
try:
import mdpopups
has_phantom_support = ((mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3124))
except Exception:
has_phantom_support = False
text = sublime.... |
def _normalize_url(url):
parsed = parse.urlparse(url)
if parsed.query:
parsed_query = parse.parse_qsl(parsed.query)
query = parse.urlencode(sorted(parsed_query))
parsed = parsed._replace(query=query)
if (('=' in parsed.fragment) and ('&' in parsed.fragment)):
parsed_fragment ... |
class OptionSeriesPieSonificationTracksMappingTime(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):
self._config(... |
def multiary_multiplication_fixer(bmg: BMGraphBuilder) -> NodeFixer:
maf = MultiaryOperatorFixer(bmg, bn.MultiplicationNode)
def multiary_multiplication_fixer(node: bn.BMGNode) -> NodeFixerResult:
if (not maf._needs_fixing(node)):
return Inapplicable
acc = maf.accumulate_input_nodes(... |
class OptionSeriesWaterfallZones(Options):
def className(self):
return self._config_get(None)
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get(None)
def color(self, text: str):
self._config(text, js_type=False)
... |
('foremast.datapipeline.datapipeline.boto3.Session.client')
('foremast.datapipeline.datapipeline.get_details')
('foremast.datapipeline.datapipeline.get_properties')
def test_get_pipeline_id(mock_get_properties, mock_get_details, mock_boto3):
test_pipelines = [{'pipelineIdList': [{'name': 'Test Pipeline', 'id': '123... |
class OptionPlotoptionsSankeySonificationContexttracksMappingFrequency(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.