code stringlengths 281 23.7M |
|---|
def test_share_from_graphql_link():
data = {'description': {'text': ''}, 'media': {'animated_image': None, 'image': None, 'playable_duration_in_ms': 0, 'is_playable': False, 'playable_url': None}, 'source': {'text': 'a.com'}, 'style_list': ['share', 'fallback'], 'title_with_entities': {'text': 'a.com'}, 'properties... |
def boost(obj=None, backend: str=None, inline=False, boundscheck=True, wraparound=True, cdivision=False, nonecheck=True, nogil=False):
if ((backend is not None) and (not isinstance(backend, str))):
raise TypeError
ts = _get_transonic_calling_module(backend_name=backend)
decor = ts.boost(inline=inlin... |
def get_node_storages(request, hostname, sr=('storage', 'node', 'storage__owner'), pr=('dc',), order_by=('zpool',)):
node = get_node(request, hostname, exists_ok=True, noexists_fail=True)
qs = node.nodestorage_set.select_related(*sr).order_by(*order_by)
extended = output_extended(request)
if extended:
... |
class github_issue_0027_test_case(unittest.TestCase):
def test_append_to_list_with_empty_index(self):
d = benedict({'results': [{'locations': ['Torino', 'Milano', 'Napoli']}]})
d['results[0].locations'].append('Roma')
self.assertEqual(d['results[0].locations'], ['Torino', 'Milano', 'Napoli',... |
def main():
if sys.version.startswith('2'):
sys.exit('Works with Python3 only.')
banner()
while True:
menu()
option = int(input('\x1b[92m> Enter Selection: '))
if (option == 1):
while True:
print('\n\t\t\t\t\x1b[96m\n\t\t\t\t[1] Get IPs by port\n\t... |
def markdown_unescape(input_: str) -> str:
return input_.replace('\\_', '_').replace('\\*', '*').replace('\\[', '[').replace('\\]', ']').replace('\\(', '(').replace('\\)', ')').replace('\\~', '~').replace('\\`', '`').replace('\\>', '>').replace('\\#', '#').replace('\\+', '+').replace('\\-', '-').replace('\\=', '=')... |
class OptionPlotoptionsOrganizationSonificationContexttracksMappingTime(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 OptionPlotoptionsArcdiagramLevelsStates(Options):
def hover(self) -> 'OptionPlotoptionsArcdiagramLevelsStatesHover':
return self._config_sub_data('hover', OptionPlotoptionsArcdiagramLevelsStatesHover)
def inactive(self) -> 'OptionPlotoptionsArcdiagramLevelsStatesInactive':
return self._con... |
class IpTos(base_tests.SimpleDataPlane):
def runTest(self):
logging.info('Running Ip_Tos test')
of_ports = config['port_map'].keys()
of_ports.sort()
self.assertTrue((len(of_ports) > 1), 'Not enough ports for test')
delete_all_flows(self.controller)
in_port = of_ports[... |
class TestAssignmentVisitor():
def code_node_ast(self) -> AbstractSyntaxTree:
root = SeqNode(LogicCondition.initialize_true(LogicCondition.generate_new_context()))
ast = AbstractSyntaxTree(root, {})
cn_1 = ast._add_code_node([Assignment(var('c'), const(5))])
cn_2 = ast._add_code_node... |
class MyTestCase(unittest.TestCase):
('netplot.config.config.Config')
def test_tcp_incoming_arg_incoming_True(self, config):
packets = sniff(offline='./test/packets/tcp_incoming.pcap')
config.incoming = True
processor = RawProcessor(config)
processor.process(packets[0])
s... |
def test_no_events():
class Emitter():
def __aiter__(self):
return self
async def __anext__(self):
raise StopAsyncIteration
class SomeResource():
async def on_get(self, req, resp):
self._called = True
resp.sse = Emitter()
assert... |
def load_osci_commits_ranking_to_bq(date: datetime.datetime, date_period: str=DatePeriodType.YTD):
if (date_period not in (DatePeriodType.MTD, DatePeriodType.YTD)):
raise ValueError(f'Unsupported {date_period}')
report = OSCICommitsRankingFactory().get_cls(date_period=date_period)(date=date)
table =... |
class Rayleigh(Distribution):
def __init__(self, scale):
if (scale is None):
self.scale = 1.0
else:
self.scale = scale
self.bounds = np.array([0.999, np.inf])
if (self.scale < 0):
raise ValueError('Invalid parameters in Rayleigh distribution. Scale... |
def fetch_generation_forecast(zone_key: ZoneKey=ZoneKey('BO'), session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list:
(raw_data, query_date) = fetch_data(session=session, target_datetime=target_datetime)
generation_forecast = parse_generation_foreca... |
def transfer_shaders(source, target, allow_component_assignments=False):
if isinstance(source, pm.nt.Transform):
source_shape = source.getShape()
else:
source_shape = source
shapes_and_engines = source_shape.outputs(type=pm.nt.ShadingEngine, c=1)
if len(shapes_and_engines):
for (... |
class MetaEngine():
def __init__(self, db: MetaData):
self.db = db
def create_table(self, name, columns, primary_keys, **kwargs):
self.db.create_table(name, columns, primary_keys, **kwargs)
def drop_table(self, name):
self.db.drop_table(name)
def add_column(self, table_name, colu... |
class PluginHubParam(BaseModel):
channel: Optional[str] = Field('git', description='Plugin storage channel')
url: Optional[str] = Field(' description='Plugin storage url')
branch: Optional[str] = Field('main', description='github download branch', nullable=True)
authorization: Optional[str] = Field(None... |
(('cfg', 'expected'), [param({'_target_': 'tests.instantiate.ArgsClass'}, ArgsClass(), id='config:no_params'), param({'_target_': 'tests.instantiate.ArgsClass', '_args_': [1]}, ArgsClass(1), id='config:args_only'), param({'_target_': 'tests.instantiate.ArgsClass', '_args_': [1], 'foo': 10}, ArgsClass(1, foo=10), id='co... |
class OptionPlotoptionsErrorbarSonificationContexttracksMappingRate(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 TemperatureMonitor(HeatMonitor):
unstructured: bool = pd.Field(False, title='Unstructured Grid', description='Return data on the original unstructured grid.')
conformal: bool = pd.Field(False, title='Conformal Monitor Meshing', description="If ``True`` the heat simulation mesh will conform to the monitor'... |
class TestHTTPIO(unittest.TestCase):
_remote_uri = '
_filename = 'facebook.html'
_pathmgr = PathManager()
def run(self, result=None):
with patch('iopath.common.event_logger.EventLogger.log_event'):
super(TestHTTPIO, self).run(result)
def _patch_download(self) -> Generator[(None, ... |
def print_proper_context_variations(logfile, freqs, cats, lemma_count):
cwords = set()
varrat_c = dict()
for cat in cats:
varrat_c[cat] = dict()
cwords.update(set(freqs[cat].keys()))
for cword in cwords:
fsum = 0
maxf = 0
for cat in cats:
if (cword in ... |
def load_locks_from_tag(remote: str, tag: str) -> (str, dict, dict):
import json
git = utils.make_git()
exists_args = ['ls-remote']
if remote:
exists_args.append(remote)
exists_args.append(f'refs/tags/{tag}')
assert git(*exists_args), f"tag: {tag} does not exist in {(remote or 'local')}"... |
class OptionPlotoptionsBoxplotSonificationDefaultspeechoptionsMappingRate(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)... |
_in_both(CompWithInit4, Foo)
def test_component_init4():
c1 = Foo(a_prop=0)
c2 = Foo(a_prop=0)
c3 = CompWithInit4(c1, 8)
print(c1.a_prop, c3.a_prop)
loop.iter()
print(c1.a_prop, c3.a_prop)
c3.create(c2, 9)
loop.iter()
print(c2.a_prop, c3.a_prop)
loop.iter()
print(c2.a_prop, c... |
class TrackerContentProxy(ContentProxy):
def _fetch_content_type_counts(self):
if ('counts' not in self._cache):
if (self.item._ct_inventory and (self.item._ct_inventory.get('_version_', (- 1)) == INVENTORY_VERSION)):
try:
self._cache['counts'] = self._from_in... |
def generate_legacy_template_version(ecs_version: str, mappings_section: Dict, out_dir: str, template_settings_file: str) -> None:
ecs_helpers.make_dirs(join(out_dir, 'elasticsearch', 'legacy'))
template: Dict = template_settings(ecs_version, mappings_section, template_settings_file, is_legacy=True)
filenam... |
def test():
assert ('token_texts' not in __solution__), 'token_texts?'
assert ('pos_tags' not in __solution__), 'pos_tags?'
assert ('token.pos_ ==' in __solution__), '?'
assert (('token.i + 1' in __solution__) or ('token.i+1' in __solution__)), '?'
__msg__.good('Great work!docdoc[token.i + 1]token.i... |
class TestFBNetV3MaskRCNNQATEager(RCNNBaseTestCases.TemplateTestCase):
def setup_custom_test(self):
super().setup_custom_test()
self.cfg.merge_from_file('detectron2go://mask_rcnn_fbnetv3a_dsmask_C4.yaml')
self.cfg.merge_from_list(['QUANTIZATION.BACKEND', 'qnnpack', 'QUANTIZATION.QAT.ENABLED'... |
_deserializable
class AppConfig(BaseAppConfig):
def __init__(self, log_level: str='WARNING', id: Optional[str]=None, name: Optional[str]=None, collect_metrics: Optional[bool]=True, **kwargs):
self.name = name
super().__init__(log_level=log_level, id=id, collect_metrics=collect_metrics, **kwargs) |
class OptionSeriesSankeySonificationDefaultspeechoptionsMappingTime(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):
... |
_os(*metadata.platforms)
def main():
masquerade = '/tmp/bifrost'
common.create_macos_masquerade(masquerade)
common.log('Launching fake bifrost attack with kerberoast commands')
common.execute([masquerade, '-action', '-kerberoast'], timeout=10, kill=True)
common.remove_file(masquerade) |
.parametrize(('input_dts', 'expected_result'), [('', ''), ('data = [01 23 45 67 89 ab cd ef 01 23 45 67 89 ab cd ef];', 'data = (BINARY DATA ...);'), ('data = <0x01 0x2345 0x67 0x89 0xabcdef 0x1234 0x56 0x78 0x90 0xab 0xcd>;', 'data = (BINARY DATA ...);'), ('data = [01 23 45 67];', 'data = [01 23 45 67];'), ('data = <0... |
class TestContacts(unittest.TestCase):
def test_contacts_load(self):
storage = MockStorage()
c1 = contacts.Contacts(storage)
self.assertEqual(0, len(c1._entries))
c1.add_contact(contacts.IdentitySystem.OnChain, 'name', pk_hex_1)
self.assertEqual(1, len(c1._entries))
c... |
def bech32_decode(bech):
if (any((((ord(x) < 33) or (ord(x) > 126)) for x in bech)) or ((bech.lower() != bech) and (bech.upper() != bech))):
return (None, None, None)
bech = bech.lower()
pos = bech.rfind('1')
if ((pos < 1) or ((pos + 7) > len(bech))):
return (None, None, None)
if (no... |
def test_trigger_webhooks(workspace: Workspace, test_data: TestData, send_task_mock: MagicMock):
object = test_data['clients']['default_tenant']
trigger_webhooks(ClientCreated, object, schemas.client.Client, workspace_id=workspace.id, send_task=send_task_mock)
send_task_mock.assert_called_once()
assert ... |
(name='api.mon.base.tasks.mon_hostgroup_list', base=MgmtTask)
_task(log_exception=False)
def mon_hostgroup_list(task_id, dc_id, dc_bound=True, full=False, extended=False, **kwargs):
dc = Dc.objects.get_by_id(int(dc_id))
return get_monitoring(dc).hostgroup_list(dc_bound=dc_bound, full=full, extended=extended) |
def test_measure_interval(la):
la.configure_trigger('LA1', 'falling')
interval = la.measure_interval(channels=['LA1', 'LA2'], modes=['rising', 'falling'], timeout=0.1)
expected_interval = (((FREQUENCY ** (- 1)) * MICROSECONDS) * 0.5)
assert (expected_interval == pytest.approx(interval, abs=TWO_CLOCK_CYC... |
def test_swap_keys():
test = {'Recipient Name': 'recipient_name', 'Action Date': 'action_date', 'Transaction Amount': 'federal_action_obligation'}
results = swap_keys(test)
assert (results == {'recipient_name': 'recipient_name', 'action_date': 'action_date', 'federal_action_obligation': 'federal_action_obli... |
def test_write_union_tuple_primitive():
schema = {'name': 'test_name', 'namespace': 'test', 'type': 'record', 'fields': [{'name': 'val', 'type': ['string', 'int']}]}
data = [{'val': ('int', 1)}, {'val': ('string', 'string')}]
expected_data = [{'val': 1}, {'val': 'string'}]
new_file = BytesIO()
fasta... |
('init', cls=FandoghCommand)
('-n', '--name', 'name', prompt='Service Name')
def init(name):
service_name_pattern = re.compile('^([a-z]+(-*[a-z0-9]+)*){1,100}$')
if (not service_name_pattern.match(name)):
click.echo(format_text('manifest.name:service names must match regex "[a-z]([-a-z0-9]*[a-z0-9])?" a... |
def pp_ext_inquiry_rsp(ext_inq_rsp):
print('Extended inquiry response: ', end='')
if (ext_inq_rsp[0] == 0):
print(red('None'))
return
print()
while (ext_inq_rsp[0] != 0):
length = ext_inq_rsp[0]
data = ext_inq_rsp[1:(1 + length)]
data_type = data[0]
ext_in... |
.parametrize('stattest_func, feature_type, expected', [(_custom_stattest, 'num', custom_stattest), ('ks', 'num', ks_stat_test), ('z', 'cat', z_stat_test), ('chisquare', 'cat', chi_stat_test), ('jensenshannon', 'num', jensenshannon_stat_test), ('kl_div', 'num', kl_div_stat_test), ('psi', 'num', psi_stat_test), ('wassers... |
class TreasureHuntAction(FatetellAction):
def __init__(self, source, target):
self.source = source
self.target = target
self.fatetell_target = target
def fatetell_action(self, ft):
if ft.succeeded:
self.card = c = ft.card
migrate_cards([c], self.target.car... |
def _coconut_mk_anon_namedtuple(fields, types=None, of_kwargs=None):
if (types is None):
NT = _coconut.collections.namedtuple('_namedtuple_of', fields)
else:
NT = _coconut.typing.NamedTuple('_namedtuple_of', [(f, t) for (f, t) in _coconut.zip(fields, types)])
_coconut.copyreg.pickle(NT, (lam... |
def test_remove_all_from_compare_basket(web_frontend):
with web_frontend.app.test_request_context():
session['uids_for_comparison'] = [TEST_FW.uid, TEST_FW_2.uid]
session.modified = True
assert ('uids_for_comparison' in session)
assert (TEST_FW.uid in session['uids_for_comparison'])
... |
def is_local(hostname, wait=False):
if (hostname is None):
return True
with _LOCK:
if (hostname in HOSTS_CACHE):
if isinstance(HOSTS_CACHE[hostname], threading.Thread):
return False
return HOSTS_CACHE[hostname]
try:
local_addresses = (['localho... |
class EnumFilterInList(FilterInList):
def __init__(self, column, name, options=None, enum_class=None, **kwargs):
self.enum_class = enum_class
super(EnumFilterInList, self).__init__(column, name, options, **kwargs)
def clean(self, value):
values = super(EnumFilterInList, self).clean(value... |
def unpack_function(file_path, tmp_dir):
meta = {}
for password in PW_LIST:
execution_string = f'fakeroot {UNPACKER_EXECUTABLE} x -y -p{password} -o{tmp_dir} {file_path}'
output = execute_shell_command(execution_string)
meta['output'] = output
if ('Wrong password' not in output):... |
def upgrade():
op.execute('alter type connectiontype rename to connectiontype_old')
op.execute("create type connectiontype as enum('postgres', 'mongodb', 'mysql', ' 'snowflake', 'redshift', 'mssql', 'mariadb', 'bigquery', 'saas', 'manual', 'email')")
op.execute('alter table connectionconfig alter column con... |
class TpoolLongTests(tests.LimitedTestCase):
TEST_TIMEOUT = 60
def test_a_buncha_stuff(self):
class Dummy():
def foo(self, when, token=None):
assert (token is not None)
time.sleep((random.random() / 200.0))
return token
def sender_loop(... |
class TestPointsReader(DataReaderTestBase):
def setup_reader(self):
r = PolyDataReader()
r.initialize(get_example_data('points.txt'))
self.e.add_source(r)
self.bounds = (0.0, 1.0, 0.0, 1.0, 0.0, 1.0)
def test_points_data_reader(self):
self.check(self.scene, self.bounds)
... |
.backend_config_overwrite({'plugin': {'printable_strings': {'name': 'printable_strings', 'min-length': '4'}}})
.AnalysisPluginTestConfig(plugin_class=AnalysisPlugin)
class TestAnalysisPlugInPrintableStrings():
strings = ['first string', 'second<>_$tring!', 'third:?-+012345/\\string']
offsets = [(3, strings[0]),... |
def test_bundler_inserter(fc_node_builder):
node0 = OperatorNode({}, {'name': 'test0', 'type': 'none'})
node1 = OperatorNode({}, {'name': 'test1', 'type': 'none'})
node2 = OperatorNode({}, {'name': 'test2', 'type': 'none', 'upstream_dependencies': ['test0']})
node3 = OperatorNode({}, {'name': 'test3', '... |
class G2MessageAugmentation(BaseG2Ciphersuite):
DST = b'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_AUG_'
def Sign(cls, SK: int, message: bytes) -> BLSSignature:
PK = cls.SkToPk(SK)
return cls._CoreSign(SK, (PK + message), cls.DST)
def Verify(cls, PK: BLSPubkey, message: bytes, signature: BLSSign... |
def _is_valid_gemm_op(tensor: Tensor, f_check_src_op: Callable) -> bool:
if ((len(tensor.dst_ops()) != 1) or (len(tensor.src_ops()) != 1)):
return False
if tensor._attrs['is_output']:
return False
gemm_op = list(tensor.src_ops())[0]
if (gemm_op._attrs['op'] != 'gemm_rcr_bias'):
r... |
(scope='module')
def simple_nonsingular_sparse_mat():
nr = 3
nc = 3
nnz = 7
nzval = np.array([1.0, 2.0, (- 1.0), 2.0, 4.0, 1.0, (- 1.0)], dtype=np.float64)
rowptr = np.array([0, 3, 5, 7], dtype=np.int32)
colind = np.array([0, 1, 2, 0, 1, 1, 2], dtype=np.int32)
A = superluWrappers.SparseMatri... |
class Crater(Tagged):
def __init__(self, tags: dict[(str, str)], coordinates: np.ndarray, point: np.ndarray) -> None:
super().__init__(tags)
self.coordinates: np.ndarray = coordinates
self.point: np.ndarray = point
def draw(self, svg: Drawing, flinger: Flinger) -> None:
scale: fl... |
def count_versions(obj):
session = sa.orm.object_session(obj)
if (session is None):
return 0
manager = get_versioning_manager(obj)
table_name = (manager.option(obj, 'table_name') % obj.__table__.name)
criteria = [('%s = %r' % (pk, getattr(obj, pk))) for pk in get_primary_keys(obj)]
query... |
class ITask():
decider: ReplayDecider = None
task: Task = None
status: Status = Status.CREATED
awaited: Future = None
def is_done(self):
return (self.status == Status.DONE)
def destroy(self):
if (self.status == Status.RUNNING):
self.status = Status.DONE
se... |
def extractWondabunnyCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('hi, my sweet little wife', 'Hi, my sweet little wife', 'translated'), ("the idol's spoiled wife", 'The ... |
class Proxy():
def __init__(self, url: URLTypes, *, ssl_context: typing.Optional[ssl.SSLContext]=None, auth: typing.Optional[typing.Tuple[(str, str)]]=None, headers: typing.Optional[HeaderTypes]=None) -> None:
url = URL(url)
headers = Headers(headers)
if (url.scheme not in (' ' 'socks5')):
... |
def award_data_fixture(db):
baker.make('search.TransactionSearch', is_fpds=True, transaction_id=1, award_id=1, action_date='2010-10-01', type='A', recipient_location_zip5='abcde', piid='IND12PB00323', recipient_location_county_code='059', recipient_location_state_code='VA', recipient_location_congressional_code='11... |
('This IE test is not working. We need to move it to using some other win32 API.')
class TestCase(unittest.TestCase):
def setUp(self):
self.ie = CreateObject('InternetExplorer.application')
def tearDown(self):
self.ie.Quit()
del self.ie
def test(self):
ie = self.ie
i... |
def merge(timings_list, site):
merged_timings = dict()
for timings in timings_list:
divider = '/'
if ('divider' in timings['header']):
divider = timings['header']['divider']
for cell in timings['cells']:
for cell_instance in timings['cells'][cell]:
... |
def extractBookloversZone(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('juliet marillier' in item['tags']):
return None
tagmap = [('how to escape from an implacable man'... |
class ReduceCursor(StmtCursor):
def name(self) -> str:
assert isinstance(self._impl, C.Node)
assert isinstance(self._impl._node, LoopIR.Reduce)
return self._impl._node.name.name()
def idx(self) -> ExprListCursor:
assert isinstance(self._impl, C.Node)
assert isinstance(sel... |
def generate_contract_objects(contract_to_build_data, hash_to_func_name):
contract_name_to_contract = {}
lib_name_to_address = {}
utils.get_next_lib_address()
for (contract_name, contract_json_data) in contract_to_build_data.items():
src_code = contract_json_data['source']
runtime_byteco... |
class Common():
def __init__(self):
self.working_dir = 'mega/working_dir'
self.on_heroku = False
self.is_env = bool(os.environ.get('ENV', None))
if self.is_env:
self.tg_app_id = int(os.environ.get('TG_APP_ID'))
self.tg_api_key = os.environ.get('TG_API_HASH')
... |
def test_encode_structured_data_ignores_additional_data_in_a_custom_type():
message_with_additonal_data = {'types': {'EIP712Domain': [{'name': 'name', 'type': 'string'}], 'Person': [{'name': 'name', 'type': 'string'}]}, 'primaryType': 'Person', 'domain': {'name': 'Name'}, 'message': {'name': 'Bob', 'pet': {'animal'... |
(name='info')
_errors
('name')
_option
_options(openid_options)
_option
_option
def info_release(name: str, url: str, id_provider: str, client_id: str, **kwargs):
client = bindings.BodhiClient(base_url=url, client_id=client_id, id_provider=id_provider, staging=kwargs['staging'])
res = client.send_request(f'rele... |
def _get_highlights(build, coverage_eval):
results = {'statements': {}, 'branches': {}}
for (name, eval_) in coverage_eval.items():
try:
coverage_map = build.get(name)['coverageMap']
except KeyError:
continue
results['statements'][name] = _statement_highlights(eva... |
class OptionSeriesTreegraphSonificationContexttracksMappingPan(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):
s... |
class OptionPlotoptionsCylinderSonificationDefaultinstrumentoptionsMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsCylinderSonificationDefaultinstrumentoptionsMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsCylinderSonificationDefaultinstrumentoptionsMa... |
class OptionSeriesBubbleStatesInactive(Options):
def animation(self) -> 'OptionSeriesBubbleStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesBubbleStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
se... |
def test_bad_creation() -> None:
with pytest.raises(ValueError):
staticmaps.Line([])
with pytest.raises(ValueError):
staticmaps.Line([staticmaps.create_latlng(48, 8)])
with pytest.raises(ValueError):
staticmaps.Line([staticmaps.create_latlng(48, 8), staticmaps.create_latlng(49, 9)], ... |
class TrainConfig(WorkflowConfig):
output: str
checkpoint: (str | None)
seed: int
debug: bool
n_steps: int
validation: dict[(str, ValidationConfig)]
fg_losses: dict[(str, ObjectConfig)]
bg_losses: dict[(str, ObjectConfig)]
scheduler: SchedulerConfig
save_checkpoint: CheckpointCon... |
class Generator(AbstractODSGenerator):
OUTPUT_FILE: str = 'open_positions.ods'
HEADER_ROWS = 3
__legend: List[List[str]] = []
__asset_header_names_row_1: List[str] = []
__asset_header_names_row_2: List[str] = []
__asset_exchange_header_names_row_1: List[str] = []
__asset_exchange_header_name... |
def test_underscore_execute_fall_back_remote_attributes(remote, mock_wf_exec):
mock_wf_exec.return_value = True
mock_client = MagicMock()
remote._client = mock_client
options = Options(raw_output_data_config=common_models.RawOutputDataConfig(output_location_prefix='raw_output'), security_context=securit... |
def process_specimen(fasm_file, params_json):
(sites, diff_tiles) = create_sites_from_fasm(fasm_file)
with open(params_json) as f:
params = json.load(f)
count = 0
for p in params['tiles']:
tile = p['tile']
for site in p['site'].split(' '):
site_y = (int(site[(site.fin... |
class UpDownButtonDelegate(QItemDelegate):
clicked = pyqtSignal(int, QtCore.QModelIndex)
UP = (- 1)
DOWN = 1
def paint(self, painter, option, index):
if (isinstance(self.parent(), QAbstractItemView) and (self.parent().model() is index.model())):
self.parent().openPersistentEditor(ind... |
def get_episodes(html, url):
id = re.search('manhua/([^/]+)', url).group(1)
pattern = '<a href="(/manhua/{}/\\d+.html)"[^>]+?>\\s*<span>([^<]+)'.format(id)
def create_ep(match):
(ep_url, title) = [unescape(t) for t in match.groups()]
return Episode(title, urljoin(url, ep_url))
return [cr... |
class DynamicGroup(lg.Group):
_connections: List[List[str]] = []
_configs: dict = {}
def add_node(cls, name: str, _type: type, connection: List[str]=None, config: lg.Config=None) -> None:
setattr(cls, name, None)
cls.__annotations__[name] = _type
cls.__children_types__[name] = _type
... |
class AbstractGroupForumPermission(BaseAuthForumPermission):
group = models.ForeignKey(Group, on_delete=models.CASCADE, verbose_name=_('Group'))
class Meta():
abstract = True
unique_together = ('permission', 'forum', 'group')
app_label = 'forum_permission'
verbose_name = _('Group... |
.parametrize('cabin', [None, 'letter_only', 'drop'])
def test_cabin(cabin):
data = load_titanic(cabin=None)
assert ('cabin' in data.columns)
assert (list(data['cabin'].head(4).values) == ['B5', 'C22 C26', 'C22 C26', 'C22 C26'])
data = load_titanic(cabin='letter_only')
assert (list(data['cabin'].head... |
class ConstantShrinkWidgets(QtWidgets.QDialog):
_DEFAULT_WINDOW_WIDTH = 500
def __init__(self, parent=None) -> None:
super().__init__(parent)
self.setModal(False)
self.setWindowTitle('constant shrink')
self.initUI()
def initUI(self):
self.setFixedWidth(self._DEFAULT_W... |
class WeevelyFormatter(logging.Formatter):
FORMATS = {logging.DEBUG: '[D][%(module)s] %(message)s', logging.INFO: '%(message)s', logging.WARNING: '[-][%(module)s] %(message)s', logging.ERROR: '[!][%(module)s] %(message)s', logging.CRITICAL: '[!][%(module)s] %(message)s', 'DEFAULT': '[%(levelname)s] %(message)s'}
... |
def radio_menu_item(name: str, after, display_name: str, groupname, selected_func, callback) -> 'RadioMenuItem':
def factory(menu, parent, context):
for (index, item) in enumerate(menu._items):
if (hasattr(item, 'groupname') and (item.groupname == groupname)):
break
else:... |
def __nfur_func(topology, edges, betweenness):
nfur = betweenness.copy()
topology = topology.copy()
for (u, v) in edges:
edge_attr = topology.adj[u][v]
topology.remove_edge(u, v)
betw = nx.betweenness_centrality(topology, normalized=False, weight='weight')
for node in betw.ke... |
def external_h_top_matter(out, name):
common_top_matter(out, name)
out.write('\n#include <loci/loci_base.h>\n#include <loci/of_message.h>\n#include <loci/of_match.h>\n#include <loci/of_object.h>\n#include <loci/loci_classes.h>\n#include <loci/loci_class_metadata.h>\n\n/\n *\n * This file is divided into the fol... |
class TestHTMLFormRenderer(TestCase):
def setUp(self):
class TestSerializer(serializers.Serializer):
test_field = serializers.CharField()
self.renderer = HTMLFormRenderer()
self.serializer = TestSerializer(data={})
def test_render_with_default_args(self):
self.seriali... |
def _slice_cube_v2_resample(self, cube, zsurf=None, sampling='nearest', mask=True, deadtraces=True):
scube = xtgeo.surface_from_cube(cube, 0)
if self.compare_topology(scube, strict=False):
return _slice_cube_v2(self, cube, zsurf, sampling, mask, deadtraces)
scube.resample(self)
zcube = None
... |
def extractCavendishclubWordpressCom(item):
badwords = ['Manga']
if any([(bad in item['tags']) for bad in badwords]):
return None
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
t... |
def extractDrizzlebumreadsHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Sect Master and Psycho', 'Sect Master and Psycho', 'translated'), ('PRC', 'PRC', 'translated'... |
class TestIssueCertificatesWrongConnectionKey(BaseTestIssueCertificates):
def setup_class(cls):
super().setup_class()
cls.cert_id_1 = 'cert_id_1'
cls.cert_request_1 = CertRequest(identifier=cls.cert_id_1, ledger_id=FetchAICrypto.identifier, not_after='2020-01-02', not_before='2020-01-01', pu... |
def custom_build_submit(copr, package, copr_dir=None):
storage = HookContentStorage()
if (not copr.active_copr_chroots):
return ('NO_ACTIVE_CHROOTS_IN_PROJECT\n', 500)
try:
build = BuildsLogic.rebuild_package(package, storage.rebuild_dict(), copr_dir=copr_dir)
db.session.commit()
... |
def test_error_split_col_not_in_df(df):
transformer = DropHighPSIFeatures(variables=None, split_col='var_0')
data = df.copy()
data = data.drop(['var_0'], axis=1)
msg = 'var_0 is not in the dataframe.'
with pytest.raises(ValueError) as record:
transformer.fit(data)
assert (str(record.valu... |
class OptionSeriesSunburstSonificationTracksMappingLowpassResonance(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 UrlsRemoveQueryParamTests(TestCase):
def test_valid_unicode_removed(self):
q = '/?page=2345&q=%E6%9F%A5%E8%AF%A2'
key = 'page'
value = '2345'
removed_key = 'q'
assert (key in remove_query_param(q, removed_key))
assert (value in remove_query_param(q, removed_key)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.