code stringlengths 281 23.7M |
|---|
class GraphApiTraceLoggingService(TraceLoggingService):
def __init__(self, access_token: str, endpoint_url: str) -> None:
super().__init__()
self.access_token = access_token
self.endpoint_url = endpoint_url
self.scrubber = SecretScrubber()
self.msg_queue: SimpleQueue[Dict[(st... |
class OptionSeriesOrganizationSonificationTracksMappingTremoloSpeed(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 Space(Plugin, metaclass=SpaceMeta):
BASE = ''
NAME = ''
SERIALIZE = ()
CHANNELS = ()
CHANNEL_ALIASES = {}
COLOR_FORMAT = True
GAMUT_CHECK = None
EXTENDED_RANGE = False
WHITE = (0.0, 0.0)
def __init__(self, **kwargs: Any) -> None:
self.channels = (self.CHANNELS + (al... |
def t_OtherN(n):
def t_OtherN(self, src: Character, tl: Sequence[Character]) -> Tuple[(List[Character], bool)]:
tl = [t for t in tl if (not t.dead)]
try:
tl.remove(src)
except ValueError:
pass
return (tl[:n], bool((len(tl) >= n)))
t_OtherN._for_test_OtherN... |
class P2_Affine(object):
thisown = property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
_blst.P2_Affine_swiginit(self, _blst.new_P2_Affine(*args))
dup = _swig_new_instance_method(_blst.P2_Affine_dup)
to_j... |
class OptionSonificationGlobalcontexttracksMappingHighpassFrequency(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 test___setitem__checks_the_given_data_1():
wh = WorkingHours()
with pytest.raises(TypeError) as cm:
wh[0] = 'not a proper data'
assert (str(cm.value) == 'WorkingHours.working_hours value should be a list of lists of two integers between and the range of integers should be 0-1440, not str') |
.parametrize('event, payload', [(Events.SESSION_READY, create_session_payload(duration=random.randint(1, 100))), (Events.SESSION_INTERRUPT, create_session_payload(duration=random.randint(1, 100))), (Events.SESSION_CHANGE, create_session_payload(duration=random.randint(1, 100))), (Events.TIMER_UPDATE, TimerPayload(time_... |
class NullProgresser(Progresser):
def __init__(self):
super(NullProgresser, self).__init__()
self.errors = 0
self.inventory_index_id = int(time.time())
self.objects = 0
self.warnings = 0
def on_new_object(self, resource):
self.objects += 1
def on_warning(self,... |
class TestTutorialWorldMob(BaseEvenniaTest):
def test_mob(self):
mobobj = create_object(mob.Mob, key='mob')
self.assertEqual(mobobj.db.is_dead, True)
mobobj.set_alive()
self.assertEqual(mobobj.db.is_dead, False)
mobobj.set_dead()
self.assertEqual(mobobj.db.is_dead, Tr... |
def extractAmesubsTumblrCom(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 t... |
def _call_or_get(value, menu=None, choice=None, string=None, obj=None, caller=None):
if callable(value):
kwargs = {}
spec = getfullargspec(value)
args = spec.args
if spec.varkw:
kwargs.update(dict(menu=menu, choice=choice, string=string, obj=obj, caller=caller))
e... |
def find_dataset_using_name(dataset_name):
dataset_filename = (('third_party.omnimatte.data.' + dataset_name) + '_dataset')
datasetlib = importlib.import_module(dataset_filename)
dataset = None
target_dataset_name = (dataset_name.replace('_', '') + 'dataset')
for (name, cls) in datasetlib.__dict__.i... |
def test_task_set_environment(task_definition):
assert (len(task_definition.containers[0]['environment']) == 3)
task_definition.set_environment(((u'webserver', u'foo', u'baz'), (u'webserver', u'some-name', u'some-value')))
assert (len(task_definition.containers[0]['environment']) == 4)
assert ({'name': ... |
.parametrize('bonds', [[(0, 4, 1)], [(0, 4, (- 1))]])
def test_N_raw(bonds):
geom = geom_loader('lib:baker_ts/08_formyloxyethyl.xyz')
dimer_kwargs = {'calculator': None, 'bonds': bonds}
dimer = Dimer(**dimer_kwargs)
dimer.set_N_raw(geom.coords)
N = dimer.N.reshape((- 1), 3)
(from_, to_, weight) ... |
def main():
script_dir = Path(__file__).parent
stub_dir = ((script_dir / '..') / 'stub')
modules = {'CpForeDib': CPFOREDIB_CLSID, 'CpForeTrade': CPFORETRADE_CLSID, 'CpSysDib': CPSYSDIB_CLSID, 'CpTrade': CPTRADE_CLSID, 'CpUtil': CPUTIL_CLSID, 'DsCbo1': DSCBO1_CLSID}
for (name, clsid) in modules.items():
... |
class Xml1():
def __init__(self, topic_set, param):
self.topic_set = topic_set
self.output_filename = param[0]
def cmad(self, reqscont, ofile):
ofile.write(('%s: ${REQS}\n\t${CALL_RMTOO}\n' % self.output_filename))
def name2xmltag(name):
return name.replace(' ', '_').lower()
... |
def _validate_outbound_access_list(access_list):
if (not is_list_like(access_list)):
raise ValidationError('access_list is not list-like.')
for entry in access_list:
if ((not is_list_like(entry)) and (len(entry) != 2)):
raise ValidationError(f'access_list entry not properly formatted... |
def extractWwwJessepirnatCom(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 ... |
def export_text(color_list):
plain_text = ''
for idx in range(len(color_list)):
rule_str = color_list[idx][1]
rule_str = (rule_str[0].upper() + rule_str[1:].lower())
if (color_list[idx][4][0] < 0):
time_str = 'Unknown'
else:
time_str = time.strftime('%Y-%m... |
class ESLocalRunner(ESMasterRunner):
n_train_workers: int
n_eval_workers: int
start_method: str
(ESMasterRunner)
def create_distributed_rollouts(self, env: Union[(StructuredEnv, StructuredEnvSpacesMixin)], shared_noise: SharedNoiseTable, agent_instance_seed: int) -> ESDistributedRollouts:
BC... |
class TimestepEmbedding(nn.Module):
def __init__(self, channel: int, time_embed_dim: int, act_fn: str='silu'):
super().__init__()
self.linear_1 = nn.Linear(channel, time_embed_dim, specialization='swish')
self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim)
def forward(self, sample)... |
def test_receive_function(receive_function_contract, call):
initial_value = call(contract=receive_function_contract, contract_function='getText')
assert (initial_value == '')
receive_function_contract.receive.transact()
final_value = call(contract=receive_function_contract, contract_function='getText')
... |
class OptionPlotoptionsVariablepieSonificationContexttracksMappingPan(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 test_records_stats():
env = LogStatsWrapper.wrap(build_dummy_maze_env())
agent_deployment = AgentDeployment(policy=DummyGreedyPolicy(), env=env)
test_core_env = build_dummy_maze_env().core_env
maze_state = test_core_env.reset()
(reward, done, info) = (0, False, {})
for i in range(5):
... |
class GetNodeDataValidator(ValidatorAPI[NodeDataBundles]):
def __init__(self, node_hashes: Sequence[Hash32]) -> None:
self.logger = get_logger('trinity.protocol.eth.validators.GetNodeDataValidator')
self.node_hashes = node_hashes
num_requested = len(node_hashes)
num_unique = len(set(... |
class SemanticMixedContentWrapper(SemanticContentWrapper):
mixed_content: List[SemanticContentWrapper] = field(default_factory=list)
content_id: Optional[str] = None
layout_block: dataclasses.InitVar[LayoutBlock] = None
def __post_init__(self, layout_block: Optional[LayoutBlock]=None):
if (layou... |
def get_public_id_from_yaml(configuration_file: Path) -> PublicId:
data = unified_yaml_load(configuration_file)
author = data.get('author', None)
if (not author):
raise KeyError(f'No author field in {str(configuration_file)}')
try:
name = (data['name'] if ('name' in data) else data['agen... |
class OptionSeriesGaugeDatalabels(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._config(flag, js_ty... |
class TestDumpDB(TestCase):
def test_serializer_deve_transformar_todos_os_dados_em_dicionarios(self):
fake_tasks = TaskFactory.create_batch(10)
results = dump_db(fake_tasks, task_serializer)
for r in results:
with self.subTest(r=r):
self.assertIsInstance(r, dict) |
class Plugin(plugin.PluginProto):
PLUGIN_ID = 106
PLUGIN_NAME = 'Environment - BME680'
PLUGIN_VALUENAME1 = 'Temperature'
PLUGIN_VALUENAME2 = 'Humidity'
PLUGIN_VALUENAME3 = 'Pressure'
PLUGIN_VALUENAME4 = 'Gas'
def __init__(self, taskindex):
plugin.PluginProto.__init__(self, taskindex)... |
class StarBILU(LinearSolver):
from . import csmoothers
def __init__(self, connectionList, L, bs=1, weight=1.0, sym=False, rtol_r=0.0001, atol_r=1e-16, rtol_du=0.0001, atol_du=1e-16, maxIts=100, norm=l2Norm, convergenceTest='r', computeRates=True, printInfo=True):
LinearSolver.__init__(self, L, rtol_r, a... |
def fetch_production(zone_key: str='HR', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)):
if target_datetime:
raise NotImplementedError('This parser is not yet able to parse past dates')
r = (session or Session())
response = r.get(URL)
... |
class CrossfadingPreference(widgets.CheckPreference, EngineConditional):
default = False
name = 'player/crossfading'
conditional_engine = 'gstreamer'
def __init__(self, preferences, widget):
widgets.CheckPreference.__init__(self, preferences, widget)
EngineConditional.__init__(self) |
def start_north(fledge_url, enabled=True):
conn =
data = {'name': TASK_NAME, 'plugin': NORTH_PLUGIN, 'type': 'north', 'enabled': enabled, 'config': {'PIServerEndpoint': {'value': 'Edge Data Store'}, 'NamingScheme': {'value': 'Backward compatibility'}}}
post_url = '/fledge/service'
utils.post_request(fl... |
class Channel():
def __init__(self, callbacks, configTab, baseRequestResponse, insertionPoint, payloadPosition):
self._callbacks = callbacks
self._helpers = callbacks.getHelpers()
self._configTab = configTab
self._baseRequestResponse = baseRequestResponse
self._insertionPoint... |
def flt_quota_check(func):
def _(r, suc, fail):
sz = None
p = RE_IMGHASH.findall(r.url)
if (p and (len(p) > 0) and (len(p[(- 1)]) > 1)):
sz = int(p[(- 1)][1])
if (r.status_code == 600):
fail((ERR_CONNECTION_ERROR, r._real_url, r.url))
elif (r.status_co... |
class Section():
def __init__(self, name: str, content: typing.Sequence[typing.Union[('Section', 'Link')]]=None, title: str='', description: str=''):
content = ([] if (content is None) else list(content))
seen_fields = set()
seen_sections = set()
for item in content:
if i... |
def test_linkage_change_in_instance(f, assert_log):
ch1 = f.object('CHANNEL', 'CHANN1')
ch2 = f.object('CHANNEL', 'CHANN2')
tool = f.object('TOOL', 'TOOL1')
assert (ch1.source == tool)
assert (ch2.source == tool)
try:
ch1.linkage = dict(ch1.linkage)
ch1.linkage['SOURCE'] = linkag... |
def check_for_overlapping_entries(entries):
try:
entries = [ipaddress.ip_network(x, strict=False) for x in entries]
except ValueError:
return
if (len(entries) == 0):
return
entries.sort()
prev_network = entries.pop(0)
for current_network in entries:
if prev_networ... |
class DataTransformBlock(ConfigBlock):
__name__ = 'DataTransformBlock'
def tree(self):
return Tree(self.__name__, [Tree('data_transform', [Tree('steps', self.steps), Tree('termination', self.termination)])])
def __init__(self, steps=None):
self.steps = []
self.termination = []
... |
class RuntimeMetadata(_common.FlyteIdlEntity):
class RuntimeType(object):
OTHER = 0
FLYTE_SDK = 1
def __init__(self, type, version, flavor):
self._type = type
self._version = version
self._flavor = flavor
def type(self):
return self._type
def version(self)... |
def ctype_module(dtype, ignore_alignment=False):
dtype = normalize_type(dtype)
if (dtype.names is None):
return ctype(dtype)
else:
if ((not ignore_alignment) and (not dtype.isalignedstruct)):
raise ValueError('The data type must be an aligned struct')
if (len(dtype.shape)... |
def downgrade():
op.add_column('video_stream_moderators', sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=False))
op.create_foreign_key('video_stream_moderators_user_id_fkey', 'video_stream_moderators', 'users', ['user_id'], ['id'], ondelete='CASCADE')
op.create_unique_constraint('user_vide... |
class SD_Qubes_VM_Tests(unittest.TestCase):
def setUp(self):
self.app = Qubes()
def tearDown(self):
pass
def test_current_fedora_for_sys_vms(self):
sys_vms = ['sys-firewall', 'sys-net', 'sys-usb', 'default-mgmt-dvm']
sys_vms_maybe_disp = ['sys-firewall', 'sys-usb']
sy... |
def test_invalid_arc_argument_value():
pen = ArcRecordingPen()
with pytest.raises(ValueError, match='Invalid arc command') as e:
parse_path('M0,0 A0,0,0,2,0,0,0', pen)
cause = e.value.__cause__
assert isinstance(cause, ValueError)
assert ("Invalid argument for 'large-arc-flag' parameter: '2'... |
.parametrize('test_input, expected', [('test', False), (10, True), (1.0, True), (True, False), ([], False), ({}, False)])
def test_or_type(test_input, expected):
assert (config.Or(config.Int, config.Float).type_check(test_input) == expected)
assert (str(config.Or(config.Int, config.Float)) == '(int or float)') |
def example():
return ft.Column(controls=[ft.Text('Display Large', style=ft.TextThemeStyle.DISPLAY_LARGE), ft.Text('Display Medium', style=ft.TextThemeStyle.DISPLAY_MEDIUM), ft.Text('Display Small', style=ft.TextThemeStyle.DISPLAY_SMALL), ft.Text('Headline Large', style=ft.TextThemeStyle.HEADLINE_LARGE), ft.Text('H... |
class CustomSystemRoleDetail(ResourceDetail):
def before_get_object(self, view_kwargs):
if (view_kwargs.get('role_id') is not None):
panel_perm = safe_query_kwargs(PanelPermission, view_kwargs, 'role_id')
if (panel_perm.role_id is not None):
view_kwargs['id'] = panel_... |
class Address(QuickbooksBaseObject):
def __init__(self):
self.Id = None
self.Line1 = ''
self.Line2 = ''
self.Line3 = ''
self.Line4 = ''
self.Line5 = ''
self.City = ''
self.CountrySubDivisionCode = ''
self.Country = ''
self.PostalCode = ... |
class SyncState():
def __init__(self) -> None:
self._key_history: Dict[(int, List[Tuple[(str, int)]])] = {}
self._tx_keys: Dict[(str, Set[int])] = {}
def get_key_history(self, key_id: int) -> List[Tuple[(str, int)]]:
return self._key_history.get(key_id, [])
def set_key_history(self, ... |
class Connector():
def __init__(self, connections: list[tuple[(Road, int)]], flinger: Flinger) -> None:
self.connections: list[tuple[(Road, int)]] = connections
self.road_1: Road
self.index_1: int
(self.road_1, self.index_1) = connections[0]
self.priority = self.road_1.matche... |
def read_fun_def(line: str, result: ResultSig=None, mod_flag: bool=False) -> (tuple[(Literal['fun'], FunSig)] | None):
keywords = re.findall(FRegex.SUB_MOD, line)
line = re.sub(FRegex.SUB_MOD, '', line)
if keywords:
tmp_var = read_var_def(line, fun_only=True)
if (tmp_var is not None):
... |
class ConvertMode(Enum):
NONE = 'none'
PARTIAL = 'partial'
OBJECT = 'object'
ALL = 'all'
def __eq__(self, other: Any) -> Any:
if isinstance(other, ConvertMode):
return (other.value == self.value)
elif isinstance(other, str):
return (other.upper() == self.name.... |
class DensityThresholdTestCase():
def setUp(self):
self.density_threshold = 0.63
def test_prime_series(self):
data = [19, 17, 13, 11, 7, 5, 3, 2, 1]
actual = circ.circlify(data, show_enclosure=True)
display(actual, reversed((data + [None])))
self.assertGreater(density(act... |
class UtilsTest(TestCase):
def test_get_object(self):
self.assertRaises(AttributeError, (lambda : get_object('feincms.does_not_exist')))
self.assertRaises(ImportError, (lambda : get_object('feincms.does_not_exist.fn')))
self.assertEqual(get_object, get_object('feincms.utils.get_object'))
... |
class areceivethread(QThread):
def __init__(self, parent: clientreceivemanager, receivesocket: socket.socket):
super(areceivethread, self).__init__()
self.parent = parent
self.receivesocket = receivesocket
def run(self):
streambytes = ''.encode()
while self.parent.onrecei... |
def process_text(text: str, speaker, sdp_ratio, noise_scale, noise_scale_w, length_scale, language, reference_audio, emotion, style_text=None, style_weight=0):
audio_list = []
if (language == 'mix'):
(bool_valid, str_valid) = re_matching.validate_text(text)
if (not bool_valid):
retur... |
def ellipticGaussian(coord, pseudo, planeVec, centroid=None, dist=None, ellipticity=1.0, g_ymax=1.0, g_center=0.0, g_spread=1.2, g_invert=True):
vec = vector(coord, pseudo)
theta = vecAngle(vec, planeVec)
if (dist is None):
d = quickdist(coord, pseudo, sq=1)
else:
d = dist
d += ((d *... |
class TestInfosLanguageDetectionDataClass():
.parametrize(('confidence', 'expected_confidence'), [pytest.param(0.0, 0.0, marks=[pytest.mark.translation, pytest.mark.language_detection]), pytest.param(1, 1.0, marks=[pytest.mark.translation, pytest.mark.language_detection]), pytest.param(0.578, 0.58, marks=[pytest.ma... |
_handler(commands=['stop'])
def stop(message: types.Message):
global freeid
if (message.chat.id in users):
bot.send_message(message.chat.id, 'Stopping...')
bot.send_message(users[message.chat.id], 'Your opponent is leavin`...')
del users[users[message.chat.id]]
del users[message.... |
def crawl_index_quote():
for (_, security_item) in get_security_list(security_type='index').iterrows():
logger.info('{} get index kdata start'.format(security_item['code']))
(start_date, _) = get_latest_download_trading_date(security_item, source='163')
end_date = pd.Timestamp.today()
... |
_FrrZebraMessageBody.register_type(FRR_ZEBRA_INTERFACE_LINK_PARAMS)
_ZebraMessageBody.register_type(ZEBRA_INTERFACE_LINK_PARAMS)
class ZebraInterfaceLinkParams(_ZebraMessageBody):
_HEADER_FMT = '!I'
HEADER_SIZE = struct.calcsize(_HEADER_FMT)
def __init__(self, ifindex, link_params):
super(ZebraInter... |
def test_unsigned_to_eip155_signed_transaction(txn_fixture, transaction_class):
if (txn_fixture['chainId'] is None):
pytest.skip('No chain id for EIP155 signing')
elif (transaction_class in {FrontierTransaction, HomesteadTransaction}):
pytest.skip('Transaction class is not chain aware')
key ... |
def turbo_comp():
calc_kwargs = {'xc': 'pbe', 'method': 'tddft', 'basis': 'def2-SVP', 'pal': 4, 'nstates': 2, 'root': 1, 'track': True}
pyscf_ = PySCF(**calc_kwargs)
geom = geom_from_xyz_file('cytosin.xyz')
geom.set_calculator(pyscf_)
f = geom.forces.reshape((- 1), 3)
print('pyscf')
print(f.... |
(array=arrays(np.float32, shape=array_shapes(min_dims=3, max_dims=3)), name=st.text(ascii_letters, min_size=8, max_size=8))
(suppress_health_check=[HealthCheck.function_scoped_fixture])
def test_that_text_export_and_import_are_inverses(array, name, tmp_path):
masked_array = np.ma.masked_invalid(array)
export_gr... |
class autorun():
autorun_file_name = '/etc/rc.local'
runfilename = 'run.sh'
run2filename = 'RPIEasy.py'
DISABLE_HDMI = '/usr/bin/tvservice -o&'
ENABLE_RPIAUTOSTART = ((('/usr/bin/screen -d -m ' + os.path.dirname(os.path.realpath(__file__))) + '/') + runfilename)
ENABLE_RPIAUTOSTART2 = (((os.path... |
def hsluv_to_lch(hsluv: Vector) -> Vector:
(h, s, l) = hsluv
c = 0.0
if (l > (100 - 1e-07)):
l = 100.0
elif (l < 1e-08):
l = 0.0
elif (not alg.is_nan(h)):
_hx_max = max_chroma_for_lh(l, h)
c = ((_hx_max / 100.0) * s)
if (c < ACHROMATIC_THRESHOLD):
... |
def save_order(order):
order_tickets = {}
for holder in order.ticket_holders:
save_to_db(holder)
if (not order_tickets.get(holder.ticket_id)):
order_tickets[holder.ticket_id] = 1
else:
order_tickets[holder.ticket_id] += 1
order.user = current_user
for tick... |
class bulk_run_local_args():
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
def isUnion():
return False
def read(self, iprot):
if ((isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProt... |
def wait_for_process(process, start_time, download_job):
log_time = time.perf_counter()
sleep_count = 0
while process.is_alive():
if (download_job and (not download_job.monthly_download) and ((time.perf_counter() - start_time) > MAX_VISIBILITY_TIMEOUT)):
break
if (sleep_count < 1... |
def extractLunebrilletranslationsWordpressCom(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, n... |
def test_subproc_distributed_rollouts():
(policy, env, trainer) = train_setup(n_epochs=2)
rollouts = ESSubprocDistributedRollouts(env_factory=(lambda : GymMazeEnv(env='CartPole-v0')), n_training_workers=2, n_eval_workers=1, shared_noise=trainer.shared_noise, env_seeds=([1337] * 3), agent_seed=1337)
trainer.... |
class JsonFileStorage(ExtractedInformationStorage):
log = None
cfg = None
def process_item(self, item, spider):
file_path = (item['abs_local_path'] + '.json')
self.log.info('Saving JSON to %s', file_path)
dir_ = os.path.dirname(item['abs_local_path'])
os.makedirs(dir_, exist_... |
class Ui_FartDialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName('Dialog')
Dialog.resize(959, 452)
self.gridLayout_6 = QtWidgets.QGridLayout(Dialog)
self.gridLayout_6.setObjectName('gridLayout_6')
self.groupBox_3 = QtWidgets.QGroupBox(Dialog)
self.groupBox... |
def test_order_get(client, db, user, jwt):
user1 = UserFactory(is_admin=False)
order_id = create_order(db, user1)
order = Order.query.get(order_id)
attendee = AttendeeSubFactory(order=order, email=user.email)
db.session.commit()
response = client.get(f'/v1/orders/{order_id}?include=user', conten... |
def extractTaint(item):
titletmp = (item['title'] + ' '.join(item['tags']))
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(titletmp)
if ((not (chp or vol or frag)) and (not ('preview' in item['title']))):
return False
if (('Chapter Release' in item['tags']) and ('Taint' in item['ta... |
(scope='module')
def aliased_app() -> Generator[(tuple[(str, str)], None, None)]:
import uuid
app_alias = str(uuid.uuid4()).replace('-', '')[:10]
app_revision = addition_app.host.register(func=addition_app.func, options=addition_app.options, application_name=app_alias, application_auth_mode='private')
(... |
_missing_dep
def test_both_schemas_validation_success(asgi):
req = MockReq(asgi)
resp = MockResp()
result = call_method(asgi, 'both_validated', req, resp)
assert (result[0] is req)
assert (result[1] is resp)
client = testing.TestClient(create_app(asgi))
resource = (ResourceAsync() if asgi el... |
class Oper(Insn):
def __init__(self, assem, src, dst, jumps=[]):
super().__init__(assem)
self.src = src
self.dst = dst
self.jumps = jumps
def dest(self):
return self.dst
def source(self):
return self.src
def __str__(self):
return ('OPER(%s,[%s],[%s... |
()
('password')
def cmd_crypto_gppref(password):
iv = (b'\x00' * 16)
password += ('=' * ((4 - (len(password) % 4)) % 4))
password = b64decode(password)
key = '\n 4e 99 06 e8 fc b6 6c c9 fa f4 93 10 62 0f fe e8\n f4 96 e8 06 cc 05 79 90 20 9b 09 a4 33 b6 6c 1b\n '.replace(' ', '').replace(... |
class TestOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self.parser.add_argument('--ntest', type=int, default=float('inf'), help='# of test examples.')
self.parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here.')
sel... |
_PREPARE_FOR_EXPORT_REGISTRY.register()
def default_fcos_prepare_for_export(self, cfg, inputs, predictor_type):
pytorch_model = self
preprocess_info = FuncInfo.gen_func_info(D2RCNNInferenceWrapper.Preprocess, params={})
preprocess_func = preprocess_info.instantiate()
return PredictorExportConfig(model=F... |
def execute_code(message: Message, env: Environment) -> Evm:
code = message.code
valid_jump_destinations = get_valid_jump_destinations(code)
evm = Evm(pc=Uint(0), stack=[], memory=bytearray(), code=code, gas_left=message.gas, env=env, valid_jump_destinations=valid_jump_destinations, logs=(), refund_counter=... |
_tag(takes_context=True)
def post_to_telegram_url(context, title, obj_or_url):
request = context['request']
title = compile_text(context, title)
url = _build_url(request, obj_or_url)
context['telegram_url'] = mark_safe((TELEGRAM_ENDPOINT % (urlencode(title), urlencode(url))))
return context |
class HWB(base.HWB):
def to_string(self, parent: 'Color', *, alpha: Optional[bool]=None, precision: Optional[int]=None, fit: Union[(str, bool)]=True, none: bool=False, color: bool=False, percent: bool=True, **kwargs: Any) -> str:
return serialize.serialize_css(parent, func='hwb', alpha=alpha, precision=prec... |
class DiskUsage():
def __init__(self, path):
path = os.path.realpath(path)
self.path = path
if (platform.system() == 'Windows'):
avail = ctypes.c_ulonglong()
total = ctypes.c_ulonglong()
free = ctypes.c_ulonglong()
ctypes.windll.kernel32.GetDis... |
class LatentDiffusionAutoencoder(Chain):
encoder_scale = 0.18125
def __init__(self, device: ((Device | str) | None)=None, dtype: (DType | None)=None) -> None:
super().__init__(Encoder(device=device, dtype=dtype), Decoder(device=device, dtype=dtype))
def encode(self, x: Tensor) -> Tensor:
enc... |
class TeachingTest(Helper):
def __init__(self, mycobot) -> None:
super().__init__()
self.mc = mycobot
self.recording = False
self.playing = False
self.record_list = []
self.record_t = None
self.play_t = None
self.path = (os.path.dirname(os.path.abspath... |
def request_thermo_device(busnum=0, devnum=0, dtype=6675):
global thermo_devices
for i in range(len(thermo_devices)):
if ((thermo_devices[i].devnum == int(devnum)) and (thermo_devices[i].busnum == int(busnum))):
return thermo_devices[i]
thermo_devices.append(ThermoEntity(busnum, devnum, ... |
('new')
def drop(uid, item_id):
s = current_session()
item = s.query(Item).filter((Item.id == item_id)).filter((Item.owner_id == uid)).filter((Item.status == 'backpack')).first()
if (not item):
raise exceptions.ItemNotFound
item.owner_id = None
item.status = 'dropped'
s.add(ItemActivity(... |
def test_multi_tasks_failure_avoids_next_execution(test_client_factory: Callable[(..., TestClient)]) -> None:
TASK_COUNTER = 0
def increment():
nonlocal TASK_COUNTER
TASK_COUNTER += 1
if (TASK_COUNTER == 1):
raise Exception('task failed')
async def app(scope, receive, sen... |
class BasePHY(Module, AutoCSR):
def __init__(self, pads, sys_clk_freq, write_ser_latency, read_des_latency, phytype):
if (not isinstance(pads, RPCPads)):
pads = RPCPads(pads)
self.pads = pads
self.memtype = memtype = 'RPC'
self.nranks = nranks = 1
self.databits = ... |
class InteractiveTest(TestCase):
def setUp(self) -> None:
self.db = DB(DBType.MEMORY)
create_models(self.db)
self.interactive = Interactive(database=self.db, repository_directory='', parser_class=Parser)
self.stdout = StringIO()
self.stderr = StringIO()
sys.stdout = s... |
class Chemical(models.Model):
bnf_code = models.CharField(max_length=9, primary_key=True, validators=[isAlphaNumeric])
chem_name = models.CharField(max_length=200)
is_current = models.BooleanField(default=True)
def __str__(self):
return ('%s: %s' % (self.bnf_code, self.chem_name))
def bnf_se... |
def test_continuous_parameter_range():
pr = parameter_ranges.ContinuousParameterRange(max_value=10, min_value=0.5, scaling_type=parameter_ranges.HyperparameterScalingType.REVERSELOGARITHMIC)
pr2 = parameter_ranges.ContinuousParameterRange.from_flyte_idl(pr.to_flyte_idl())
assert (pr == pr2)
assert (type... |
class TestOFPActionSetTpDst(unittest.TestCase):
type_ = {'buf': b'\x00\n', 'val': ofproto.OFPAT_SET_TP_DST}
len_ = {'buf': b'\x00\x08', 'val': ofproto.OFP_ACTION_TP_PORT_SIZE}
tp = {'buf': b'\x06m', 'val': 1645}
zfill = (b'\x00' * 2)
buf = (((type_['buf'] + len_['buf']) + tp['buf']) + zfill)
c =... |
class FlexibilityBuilder():
def __call__(self, setup, freeze_bonds=None, root_atom_index=None, break_combo_data=None, bonds_in_rigid_rings=None, glue_pseudo_atoms=None):
self.setup = setup
self.flexibility_models = {}
self._frozen_bonds = []
if (not (freeze_bonds is None)):
... |
def generate_correlation_table(n, metric, lookback_days=180):
df = top_n_correlations(n, metric, lookback_days)
df['Pos Corr Coef.'] = df['Pos Corr Coef.'].map('{:,.3f}'.format)
df['Neg Corr Coef.'] = df['Neg Corr Coef.'].map('{:,.3f}'.format)
return dash_table.DataTable(id=(metric + '-correlation-table... |
class LineageSchema(BaseModel):
nodes: Optional[List[LineageNodeSchema]] = None
edges: Optional[List[Tuple[(NodeUniqueIdType, NodeUniqueIdType)]]] = None
('nodes', pre=True, always=True)
def set_nodes(cls, nodes):
return (nodes or [])
('edges', pre=True, always=True)
def set_edges(cls, e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.