code stringlengths 281 23.7M |
|---|
class BMGInference():
_fix_observe_true: bool = False
_pd: Optional[prof.ProfilerData] = None
def __init__(self):
pass
def _begin(self, s: str) -> None:
pd = self._pd
if (pd is not None):
pd.begin(s)
def _finish(self, s: str) -> None:
pd = self._pd
... |
def test_event_role_delete(db, client, user, jwt):
uer = UsersEventsRolesSubFactory(user=user)
RoleInviteSubFactory(status='accepted', event=uer.event, email=user.email, role=uer.role)
db.session.commit()
assert (RoleInvite.query.filter_by(email=user.email, event=uer.event, role=uer.role).count() == 1)
... |
class TestElections(ApiBaseTest):
def setUp(self):
super().setUp()
self.candidate = factories.CandidateDetailFactory()
self.candidates = [factories.CandidateHistoryFactory(candidate_id=self.candidate.candidate_id, state='NY', two_year_period=2012, election_years=[2010, 2012], cycles=[2010, 2... |
class DEXLDAPAuthenticator(AbstractAuthenticator):
_type = SupportedAuthProviders.DEX_LDAP
def authenticate(self, kf_endpoint: str, runtime_config_name: str, username: str=None, password: str=None) -> Optional[str]:
if (_empty_or_whitespaces_only(username) or _empty_or_whitespaces_only(password)):
... |
def test_disable_tuple_notation_option():
'
schema = {'namespace': 'namespace', 'name': 'name', 'type': 'record', 'fields': [{'name': 'foo', 'type': ['string', {'type': 'array', 'items': 'string'}]}]}
new_record = roundtrip(schema, {'foo': ('string', '0')}, writer_kwargs={'disable_tuple_notation': True})
... |
class PersistentWebSocket():
def __init__(self, endpoint_uri: URI, websocket_kwargs: Any) -> None:
self.ws: Optional[WebSocketClientProtocol] = None
self.endpoint_uri = endpoint_uri
self.websocket_kwargs = websocket_kwargs
async def __aenter__(self) -> WebSocketClientProtocol:
if... |
def process_crosslinks(crystallized_state, crosslinks):
main_crosslink = {}
for c in crosslinks:
vote_count = 0
mask = bytearray(c.voter_bitmask)
for byte in mask:
for j in range(8):
vote_count += ((byte >> j) % 2)
if (vote_count > main_crosslink.get(c... |
_os(*metadata.platforms)
def main():
winword = 'C:\\Users\\Public\\winword.exe'
svchost = 'C:\\Users\\Public\\svchost.exe'
user32 = 'C:\\Windows\\System32\\user32.dll'
dll = 'C:\\Users\\Public\\taskschd.dll'
ps1 = 'C:\\Users\\Public\\Invoke-ImageLoad.ps1'
rcedit = 'C:\\Users\\Public\\rcedit.exe'... |
class C3():
def y(data: List[dict], y_columns: List[str], x_axis: str, options: dict=None) -> dict:
is_data = {'labels': OrderedSet(), 'datasets': [], 'series': [], 'python': True}
if ((data is None) or (y_columns is None)):
return is_data
if ((options is not None) and (options.g... |
def _join_tokens_list(tokens: List[bytes]) -> str:
decoded = tokens[:1]
skip = True
for token in tokens:
if skip:
skip = False
continue
token_partial = token[:2]
try:
decoded.append((_HEX_TO_BYTE[token_partial] + token[2:]))
except KeyError... |
def remove_role(moderator: ModeratorModel, role: str):
_check_roles([role])
with session() as s:
moderator_orm_model = s.query(ModeratorOrmModel).filter_by(id=moderator.id).one()
if (role not in moderator_orm_model.roles):
raise ArgumentError('Role not added')
moderator_orm_m... |
def extractMentallycrippledtranslationsBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Summoner of Miracles', 'Summoner of Miracles', 'translated'), ('One Punch of ... |
.feature('unit')
.story('tasks', 'purge')
class TestPurge():
def test_init(self):
mock_storage_client_async = MagicMock(spec=StorageClientAsync)
mock_audit_logger = AuditLogger(mock_storage_client_async)
with patch.object(FledgeProcess, '__init__') as mock_process:
with patch.obj... |
def test_branch_node():
nm = _get_sample_node_metadata()
task = _workflow.TaskNode(reference_id=_generic_id)
bd = _literals.BindingData(scalar=_literals.Scalar(primitive=_literals.Primitive(integer=5)))
bd2 = _literals.BindingData(scalar=_literals.Scalar(primitive=_literals.Primitive(integer=99)))
b... |
('reset', cls=FandoghCommand)
('-s', '--service', '--name', 'name', prompt='Service Name')
def service_reset(name):
_RESTART_SERVICE = 'RESTART'
if click.confirm(format_text('Restarting service may cause downtime, are you sure about this action?', TextStyle.WARNING)):
response = request_service_action(n... |
class GymConnection(Connection):
connection_id = PUBLIC_ID
def __init__(self, gym_env: Optional[gym.Env]=None, **kwargs: Any) -> None:
super().__init__(**kwargs)
if (gym_env is None):
gym_env_package = cast(str, self.configuration.config.get('env'))
if (gym_env_package is... |
def test_change_parents():
model = DynamicModel()
world = World(initialize_fn=(lambda d: torch.zeros_like(d.sample())))
with world:
model.baz()
assert (model.foo() in world.get_variable(model.baz()).parents)
assert (model.bar(0) in world.get_variable(model.baz()).parents)
assert (model.b... |
class Solution():
def minPathSum(self, grid: List[List[int]]) -> int:
if ((not grid) or (not grid[0])):
return 0
dp = [([0] * len(grid[0])) for _ in range(len(grid))]
for (i, row) in enumerate(grid):
for (j, elem) in enumerate(row):
if ((i == 0) and (j... |
class module_file_upload2web():
failed_retrieve_info = 'Failed retrieve web root information'
failed_resolve_path = 'Failed resolve path, please check remote path and permissions'
error_s_not_under_webroot_s = "Error, '%s' is not under the web root folder '%s'"
failed_search_writable_starting_s = "Error... |
(name='setup_case')
def fixture_setup_case(tmp_path_factory, source_root, monkeypatch):
def copy_case(path, config_file):
tmp_path = tmp_path_factory.mktemp(path.replace('/', '-'))
shutil.copytree(os.path.join(source_root, 'test-data', path), (tmp_path / 'test_data'))
monkeypatch.chdir((tmp_... |
class OnAfterRegisterTask(TaskBase):
__name__ = 'on_after_register'
async def run(self, user_id: str, workspace_id: str):
workspace = (await self._get_workspace(uuid.UUID(workspace_id)))
user = (await self._get_user(uuid.UUID(user_id), workspace))
tenant = (await self._get_tenant(user.te... |
def test_deposits(concise_casper, funded_accounts, validation_keys, deposit_amount, new_epoch, induct_validators):
induct_validators(funded_accounts, validation_keys, ([deposit_amount] * len(funded_accounts)))
assert (concise_casper.total_curdyn_deposits_in_wei() == (deposit_amount * len(funded_accounts)))
... |
def _find_parallel_gemm_ops(cat_inputs: List[Tensor], f_check_src_op: Callable) -> List[Tuple[(List[Operator], int)]]:
all_groups = []
gemm_ops = []
def add_gemm_groups(gemm_ops):
if (len(gemm_ops) >= 2):
all_groups.append(gemm_ops.copy())
for cat_input in cat_inputs:
if (not... |
class SocialAuthMixin():
_auth_mock
('graphql_social_auth.decorators._do_login')
def test_social_auth(self, *args):
response = self.execute({'provider': 'google-oauth2', 'accessToken': '-token-'})
social = response.data['socialAuth']['social']
self.assertEqual('test', social['uid']) |
def get_website_metas(url, html_doc=None):
from bs4 import BeautifulSoup
if (not html_doc):
html_doc = get_website(url)
soup = BeautifulSoup(html_doc, 'html.parser')
meta_tags = soup.find_all('meta')
metas = []
for meta in meta_tags:
if (('name' in meta.attrs) and (meta.attrs['na... |
class TestGetPrivacyNoticeDetail():
(scope='function')
def url(self, privacy_notice) -> str:
return (V1_URL_PREFIX + PRIVACY_NOTICE_DETAIL.format(privacy_notice_id=privacy_notice.id))
def test_get_privacy_notice_unauthenticated(self, url, api_client):
resp = api_client.get(url)
asser... |
def bank_deposits():
deposits = {}
for row in reader:
if (row['NAMEFULL'] not in deposits):
deposits[row['NAMEFULL']] = 0
deposits[row['NAMEFULL']] += int(row['DEPSUM'].replace(',', ''))
deplist = []
for (k, v) in deposits.items():
deplist.append({'name': k, 'deposits... |
def forward(apps, schema_editor):
Reservation = apps.get_model('core', 'Reservation')
Bill = apps.get_model('core', 'Bill')
ReservationBill = apps.get_model('core', 'ReservationBill')
reservations = Reservation.objects.all()
for r in reservations:
r.bill = ReservationBill.objects.create(bill... |
.external
.skipif((has_openai_key is False), reason='OpenAI API key not available')
def test_ner_config(config: Config):
nlp = assemble_from_config(config)
assert (nlp.pipe_names == ['llm'])
component_cfg = dict(config['components']['llm'])
component_cfg.pop('factory')
nlp2 = spacy.blank('en')
n... |
class Pre(MixHtmlState.HtmlStates, Html.Html):
name = 'Pre formatted text'
tag = 'pre'
_option_cls = OptText.OptionsText
def __init__(self, page: primitives.PageModel, vals, color, width, height, html_code, options, helper, profile):
super(Pre, self).__init__(page, vals, html_code=html_code, pro... |
class EnumTopCalc(Enums):
def concat(self):
return self._set_value()
def count(self):
return self._set_value()
def avg(self, precision: Union[(int, bool)]=None):
if (precision is not None):
if (self.key == 'bottomCalc'):
self._set_value('bottomCalcParams',... |
class TestSwitchedAction(unittest.TestCase):
def test_action_one_switch_twelve(self):
settings = {'foo': 'bar'}
action = SwitchedActionOne(cast(ServerSettings, settings))
response = action(EnrichedActionRequest(action='one', body={'planet': 'Mars'}, switches=[12]))
self.assertEqual([... |
def draw(G: nx.Graph, pos: Dict[(Hashable, np.ndarray)], lines_func: Callable, color_by: Hashable=None, node_color_by: Hashable=None, lw_by: Hashable=None, alpha_by: Hashable=None, ax=None, encodings_kwargs: Dict={}, **linefunc_kwargs):
nt = node_table(G)
et = edge_table(G)
if (ax is None):
ax = plt... |
class OptionPlotoptionsVectorSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionPlotoptionsVectorSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionPlotoptionsVectorSonificationDefaultinstrumentoptionsMappingTremoloDepth)... |
class RateLimitVerTest(AmbassadorTest):
target: ServiceType
specified_protocol_version: Literal[('v2', 'v3', 'default')]
expected_protocol_version: Literal[('v3', 'invalid')]
rls: ServiceType
def variants(cls) -> Generator[(Node, None, None)]:
for protocol_version in ['v2', 'v3', 'default']:... |
def create_base_model(inherit_from=models.Model):
class Base(inherit_from, ExtensionsMixin):
class Meta():
abstract = True
_cached_django_content_type = None
def register_regions(cls, *regions):
if hasattr(cls, 'template'):
warnings.warn('Ignoring seco... |
class Connections():
def __init__(self) -> None:
self.connections: Dict[(str, Union[(BaseConnector, BaseEmailConnector)])] = {}
def get_connector(self, connection_config: ConnectionConfig) -> Union[(BaseConnector, BaseEmailConnector)]:
key = connection_config.key
if (key not in self.conn... |
class TestRemoveSkillFailsWhenExceptionOccurs():
def setup_class(cls):
cls.runner = CliRunner()
cls.agent_name = 'myagent'
cls.cwd = os.getcwd()
cls.t = tempfile.mkdtemp()
dir_path = Path('packages')
tmp_dir = (cls.t / dir_path)
src_dir = (cls.cwd / Path(ROOT_... |
class TransactionDecorator(object):
def __init__(self, user):
self.user = user
def __call__(self, fn):
(fn)
def wrapper(fn, fn_self, *args):
user = getattr(fn_self, self.user)
with fn_self.setup_user_session(user):
return fn(fn_self, *args)
... |
('duplicate', dataset=('The dataset to save to', 'positional', None, str), file_path=('The jsonl file with matched items', 'positional', None, str))
def check_duplicate(dataset, file_path):
stream = JSONL(file_path)
stream = add_options(stream)
return {'dataset': dataset, 'view_id': 'choice', 'stream': stre... |
class TicketFactoryBase(BaseFactory):
class Meta():
model = Ticket
name = common.string_
description = common.string_
type = common.string_
price = common.float_
quantity = 10
is_description_visible = True
position = 10
is_fee_absorbed = True
sales_starts_at = common.date... |
def test_sync_filter_against_log_events(w3, emitter, wait_for_transaction, emitter_contract_event_ids):
txn_filter = w3.eth.filter({})
txn_hashes = set()
txn_hashes.add(emitter.functions.logNoArgs(emitter_contract_event_ids.LogNoArguments).transact())
for txn_hash in txn_hashes:
wait_for_transac... |
.feature('unit')
.story('core', 'api', 'schedule')
class TestScheduledProcesses():
def client(self, loop, test_client):
app = web.Application(loop=loop)
routes.setup(app)
return loop.run_until_complete(test_client(app))
def setup_method(self):
server.Server.scheduler = Scheduler(... |
def gen_sites():
db = Database(util.get_db_root(), util.get_part())
grid = db.grid()
for tile_name in sorted(grid.tiles()):
loc = grid.loc_of_tilename(tile_name)
gridinfo = grid.gridinfo_at_loc(loc)
if (gridinfo.tile_type not in ['PCIE_BOT']):
continue
for (site_n... |
def get_gamatoto_helpers(is_jp: bool) -> Optional[dict[(str, Any)]]:
if is_jp:
country_code = 'ja'
else:
country_code = 'en'
file_data = game_data_getter.get_file_latest('resLocal', f'GamatotoExpedition_Members_name_{country_code}.csv', is_jp)
if (file_data is None):
helper.error... |
class SequentialRolloutRunner(RolloutRunner):
def __init__(self, n_episodes: int, max_episode_steps: int, deterministic: bool, record_trajectory: bool, record_event_logs: bool, render: bool):
super().__init__(n_episodes=n_episodes, max_episode_steps=max_episode_steps, deterministic=deterministic, record_tra... |
def _get_mnist(conf, root, split, transform, target_transform, download):
is_train = (split == 'train')
normalize = (transforms.Normalize((0.1307,), (0.3081,)) if conf.pn_normalize else None)
transform = transforms.Compose(([transforms.ToTensor()] + ([normalize] if (normalize is not None) else [])))
ret... |
class AIOKafkaConsumerThreadFixtures():
()
def cthread(self, *, consumer):
return AIOKafkaConsumerThread(consumer)
()
def tracer(self, *, app):
tracer = app.tracer = Mock(name='tracer')
tobj = tracer.get_tracer.return_value
def start_span(operation_name=None, **kwargs):
... |
class fartBinForm(QDialog, Ui_FartBinDialog):
def __init__(self, parent=None):
super(fartBinForm, self).__init__(parent)
self.setupUi(self)
self.setWindowOpacity(0.93)
self.btnSubmit.clicked.connect(self.submit)
self.btnSelectBinPath.clicked.connect(self.selectBinPath)
... |
class MatrixBase(ufl.Matrix):
def __init__(self, a, bcs, mat_type):
if isinstance(a, tuple):
self.a = None
(test, trial) = a
arguments = a
else:
self.a = a
(test, trial) = a.arguments()
arguments = None
ufl.Matrix.__init... |
class LinkedinUser(scrapy.Item):
lastName = scrapy.Field()
firstName = scrapy.Field()
locale = scrapy.Field()
headline = scrapy.Field()
linkedinUrl = scrapy.Field()
connection_msg = scrapy.Field()
email_address = scrapy.Field()
phone_numbers = scrapy.Field()
education = scrapy.Field(... |
class OptionPlotoptionsVariablepieSonificationContexttracksMappingGapbetweennotes(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, te... |
class GUIServerController(ControllerBase):
def __init__(self, req, link, data, **config):
super(GUIServerController, self).__init__(req, link, data, **config)
path = ('%s/html/' % PATH)
self.static_app = DirectoryApp(path)
('topology', '/{filename:[^/]*}')
def static_handler(self, re... |
class T(configparser.ConfigParser):
def __init__(self, file):
_shared_formula_dir = T.get_data_path('formulas')
_shared_map_dir = T.get_data_path('maps')
comp = 'gcc'
_defaults = OrderedDict((('compiler', OrderedDict((('name', comp), ('options', self.get_default_compiler_options())))... |
class OptionSeriesItemSonificationContexttracksMappingTime(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.... |
('tomate.plugin', scope=SingletonScope)
class PluginEngine():
(bus='tomate.bus', config='tomate.config', graph=Graph)
def __init__(self, bus: Bus, config: Config, graph: Graph):
self._bus = bus
self._graph = graph
logger.debug('action=init paths=%s', config.plugin_paths())
self._... |
class CustomBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
user = User.objects.filter((Q(username=username) | Q(email=username))).first()
if user:
if user.check_password(password):
return user
return None |
def _discover_dependencies(test: Union[(Metric, Test)]) -> Iterator[Tuple[(str, Union[(Metric, Test)])]]:
if hasattr(test, '__evidently_dependencies__'):
(yield from test.__evidently_dependencies__())
return
for (field_name, field) in test.__dict__.items():
if issubclass(type(field), (Me... |
_settings(TIME_ZONE='UTC', USE_TZ=True)
class TestDefaultTZDateTimeField(TestCase):
def setup_class(cls):
cls.field = serializers.DateTimeField()
cls.kolkata = ZoneInfo('Asia/Kolkata')
def assertUTC(self, tzinfo):
assert ((tzinfo is utc) or ((getattr(tzinfo, 'key', None) or getattr(tzinf... |
.skipif((arg_chip in ['esp8266', 'esp32']), reason='get_security_info command is supported on ESP32S2 and later')
class TestSecurityInfo(EsptoolTestCase):
def test_show_security_info(self):
res = self.run_esptool('get_security_info')
assert ('Flags' in res)
assert ('Crypt Count' in res)
... |
class TestCoprUpdatePermissions(CoprsTestCase):
('u2')
def test_cancel_permission(self, f_users, f_coprs, f_copr_permissions, f_db):
self.db.session.add_all([self.u2, self.c2])
r = self.test_client.post('/coprs/{0}/{1}/update_permissions/'.format(self.u2.name, self.c2.name), data={'copr_builder_... |
class Bits(OctetString):
namedValues = namedval.NamedValues()
def __new__(cls, *args, **kwargs):
if ('namedValues' in kwargs):
Bits = cls.withNamedBits(**kwargs.pop('namedValues'))
return Bits(*args, **kwargs)
return OctetString.__new__(cls)
def prettyIn(self, bits):
... |
def main(server, username, startpage, fromuts, touts, outfile, infotype='recenttracks'):
trackdict = dict()
page = startpage
totalpages = (- 1)
n = 0
try:
for (page, totalpages, tracks) in get_tracks(server, username, fromuts, touts, startpage, tracktype=infotype):
print(('Got pa... |
class ipv6_src(oxm):
type_len =
def __init__(self, value=None):
if (value != None):
self.value = value
else:
self.value = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
return
def pack(self):
packed = []
packed.append(struc... |
def run_line_search(f, df, get_p, x0, alpha_0=1, alpha_max=1):
x = x0
alpha_prev = None
gradients = list()
step_dirs = list()
for i in range(50):
f_0 = f(x)
grad = np.array(df(x))
norm = np.linalg.norm(grad)
print(f'{i:02d} norm(grad)={norm:.6f}')
if (norm < 0... |
class Solution():
def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
if ((root1 is None) and (root2 is None)):
return True
elif ((root1 is None) or (root2 is None)):
return False
if (root1.val != root2.val):
return False
return ((self.f... |
class TestNursingTask(FrappeTestCase):
def setUp(self) -> None:
nursing_checklist_templates = frappe.get_test_records('Nursing Checklist Template')
self.activity = frappe.get_doc(nursing_checklist_templates[0]).insert(ignore_if_duplicate=True)
self.nc_template = frappe.get_doc(nursing_checkl... |
def test_registering_to_multiple_types_with_lists(prepare_publishers):
called = []
(['Test', 'Test2'])
def func1():
called.append('func1')
(['Test', 'Test3'])
def func2():
called.append('func2')
(['Test2', 'Test3'])
def func3():
called.append('func3')
def func4():... |
class TriggerObject():
def __init__(self, **kwargs) -> None:
self.trigger_name = kwargs.get('name')
self.trigger = kwargs.get('trigger', None)
self.responses = kwargs.get('responses', None)
self.owner = kwargs.get('owner', None)
self.guild = kwargs.get('guild', None)
... |
def create_jobs_json(realization: Realization) -> None:
jobs = {'global_environment': {}, 'config_path': '/dev/null', 'config_file': '/dev/null', 'jobList': [{'name': forward_model.name, 'executable': forward_model.executable, 'argList': forward_model.arglist} for forward_model in realization.forward_models], 'run_... |
('foundry_dev_tools.foundry_api_client.FoundryRestClient.get_dataset_identity', MagicMock())
def test_branch_extracted():
parsed = FoundryFileSystem._get_kwargs_from_urls('foundry://dev-iteration:super-secret-.main.dataset.fake1bb5-be92-4ad9-aa3e-07c/test.txt')
assert (parsed['token'] == 'super-secret-token')
... |
.parametrize('key, plot_name', [('FOPR', STATISTICS), ('FOPR', ENSEMBLE), ('SNAKE_OIL_PARAM:OP1_OCTAVES', CROSS_CASE_STATISTICS), ('SNAKE_OIL_PARAM:OP1_OCTAVES', DISTRIBUTION), ('SNAKE_OIL_PARAM:OP1_OCTAVES', GAUSSIAN_KDE), ('SNAKE_OIL_PARAM:OP1_OCTAVES', HISTOGRAM)])
def test_that_all_snake_oil_visualisations_matches_... |
def dataclassNonDefaults(obj) -> dict:
if (not is_dataclass(obj)):
raise TypeError(f'Object {obj} is not a dataclass')
values = [getattr(obj, field.name) for field in fields(obj)]
return {field.name: value for (field, value) in zip(fields(obj), values) if ((value != field.default) and (value == valu... |
class WorkerGroupSpec(_common.FlyteIdlEntity):
def __init__(self, group_name: str, replicas: int, min_replicas: typing.Optional[int]=0, max_replicas: typing.Optional[int]=None, ray_start_params: typing.Optional[typing.Dict[(str, str)]]=None):
self._group_name = group_name
self._replicas = replicas
... |
def test_restructure_cfg_loop_two_back_edges_condition_5(task):
task.graph.add_nodes_from((vertices := [BasicBlock(0, instructions=[Assignment(variable(name='i'), Constant(0)), Assignment(variable(name='x'), Constant(42))]), BasicBlock(1, instructions=[Assignment(variable(name='i'), BinaryOperation(OperationType.pl... |
.parametrize('return_code', [SUCCESS, FAILURE])
def test_fal_model_task_when_dbt_succeeds(mocker, return_code):
task = FalModelTask(['a', 'b'], script=FalLocalHookTask('something.py', bound_model=FakeModel('model')))
task.set_run_index(DynamicIndexProvider())
fal_dbt = FakeFalDbt('/test')
mock_dbt_run(m... |
class OptionPlotoptionsErrorbarLabelStyle(Options):
def fontSize(self):
return self._config_get('0.8em')
def fontSize(self, num: float):
self._config(num, js_type=False)
def fontWeight(self):
return self._config_get('bold')
def fontWeight(self, text: str):
self._config(te... |
class SystemInfo(BaseTest):
def setUp(self):
self.session = SessionURL(self.url, self.password, volatile=True)
modules.load_modules(self.session)
self.run_argv = modules.loaded['shell_sh'].run_argv
def _spoil_vectors_but(self, vector_safe_name):
for i in range(0, len(modules.load... |
def swag_from(specs=None, filetype=None, endpoint=None, methods=None, validation=False, schema_id=None, data=None, definition=None, validation_function=None, validation_error_handler=None):
def resolve_path(function, filepath):
try:
from pathlib import Path
if isinstance(filepath, Pa... |
class TestESP32Image(BaseTestCase):
def _test_elf2image(self, elfpath, binpath, extra_args=[]):
try:
self.run_elf2image('esp32', elfpath, extra_args=extra_args)
image = esptool.bin_image.LoadFirmwareImage('esp32', binpath)
self.assertImageInfo(binpath, 'esp32', (True if (... |
class Query(_Expr):
def to_fauna_json(self):
return {'': self.value}
def __repr__(self):
return ('Query(%s)' % repr(self.value))
def __eq__(self, other):
return (isinstance(other, Query) and (self.value == other.value))
def __ne__(self, other):
return (not (self == other)... |
def test_gradient():
c = ft.Container(gradient=ft.LinearGradient(colors=[], tile_mode='mirror'))
cmd = c._build_add_commands()
assert (cmd[0].attrs['gradient'] == '{"colors":[],"tile_mode":"mirror","begin":{"x":-1,"y":0},"end":{"x":1,"y":0},"type":"linear"}')
c = ft.Container(gradient=ft.LinearGradient(... |
class BGPMessage(packet_base.PacketBase, TypeDisp):
_HDR_PACK_STR = '!16sHB'
_HDR_LEN = struct.calcsize(_HDR_PACK_STR)
_class_prefixes = ['BGP']
def __init__(self, marker=None, len_=None, type_=None):
super(BGPMessage, self).__init__()
if (marker is None):
self._marker = _MAR... |
def extractMitchytranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('The Anarchic Consort of the Prince', 'The Anarchic Consort of the Prince', 'translated... |
('firebase_auth_user_access', [SaaSRequestType.READ])
def firebase_auth_user_access(client: AuthenticatedClient, node: TraversalNode, policy: Policy, privacy_request: PrivacyRequest, input_data: Dict[(str, List[Any])], secrets: Dict[(str, Any)]) -> List[Row]:
app = initialize_firebase(secrets)
processed_data = ... |
def glue(ways: List[OSMWay]) -> List[List[OSMNode]]:
result: List[List[OSMNode]] = []
to_process: Set[Tuple[OSMNode]] = set()
for way in ways:
if way.is_cycle():
result.append(way.nodes)
else:
to_process.add(tuple(way.nodes))
while to_process:
nodes: List[... |
class Whitelist(object):
def __init__(self, db, config):
self.db = db
self.config = config
if self.config['DEBUG']:
print('Initializing Whitelist')
sql = 'CREATE TABLE IF NOT EXISTS Whitelist (\n PhoneNo TEXT PRIMARY KEY,\n Name TEXT,\n Re... |
def extractNoveltyreadersBlogspotCom(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_t... |
def create_arg_from_val(type, val):
if ((type == Int) or (type == Bool) or (type == Image)):
return ConstIntArg(val)
elif (type == Float):
return ConstFloatArg(val)
elif (type == Complex):
return ComplexArg(ConstFloatArg(val[0]), ConstFloatArg(val[1]))
elif (type == Hyper):
... |
class MenuBar(Control):
def __init__(self, controls: Optional[List[Control]]=None, ref: Optional[Ref]=None, expand: Union[(None, bool, int)]=None, col: Optional[ResponsiveNumber]=None, opacity: OptionalNumber=None, visible: Optional[bool]=None, disabled: Optional[bool]=None, data: Any=None, clip_behavior: Optional[... |
.skipif((SclConvertor is None), reason='spec2scl not installed')
class TestSclIntegration(object):
sphinx_spec = '{0}/test_data/python-sphinx_autonc.spec'.format(tests_dir)
def setup_class(cls):
with open(cls.sphinx_spec, 'r') as spec:
cls.test_spec = spec.read()
def setup_method(self, m... |
def test_drift_delta_with_drift():
measurements = np.arange(1, 11)
rng = default_rng(0)
noise = rng.normal(0, 0.5, (100, 10))
drift = (np.arange(1, 101) / 100).reshape((1, (- 1)))
measurements = ((measurements + noise) + drift.T)
correct_drifts = np.array([0., 0., 0., 0.9782566, 0., 0., 0., 0., ... |
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.')
def test_deck():
import pandas as pd
df = pd.DataFrame({'Name': ['Tom', 'Joseph'], 'Age': [1, 22]})
ctx = FlyteContextManager.current_context()
ctx.user_space_params._decks = [ctx.user_space_params.default_deck]
renderer = Top... |
class OptionPlotoptionsStreamgraphStatesHoverMarker(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):
s... |
def test():
assert (len(pattern1) == 2), 'pattern1'
assert (len(pattern2) == 2), 'pattern2'
assert (len(pattern1[0]) == 1), 'pattern1'
assert any(((pattern1[0].get(l) == 'iphone') for l in ('LOWER', 'lower'))), 'pattern1`iphone`'
assert (len(pattern1[1]) == 1), 'pattern1'
assert any(((pattern1[1... |
class HierarchyBase(object):
def __init__(self, meshes, coarse_to_fine_cells, fine_to_coarse_cells, refinements_per_level=1, nested=False):
from firedrake_citations import Citations
Citations().register('Mitchell2016')
self._meshes = tuple(meshes)
self.meshes = tuple(meshes[::refinem... |
class TransportAddressType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec
subtypeSpec += ConstraintsUnion(SingleValueConstraint(*(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)))
namedValues = NamedValues(*(('local', 13), ('sctpDns', 16), ('sctpIpv4', 9)... |
class OptionSeriesLineSonificationDefaultinstrumentoptionsMappingLowpassResonance(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, te... |
def _get_accel(callback: Union[(Accelerator, Callable, None)], display_name: Optional[str]) -> Tuple[(Optional[Accelerator], Optional[Callable], Optional[str])]:
accelerator: Optional[Accelerator] = None
if isinstance(callback, Accelerator):
accelerator = callback
if (display_name is None):
... |
def untangle(trees, cost_function=None, iterations=None, verbose=False):
from itertools import permutations
if (iterations == None):
iterations = 3
if (cost_function == None):
cost_function = (lambda pair: math.pow(abs((pair[0] - pair[1])), 2))
y_positions = {T: {k.name: k.y for k in T.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.