code stringlengths 281 23.7M |
|---|
_deserializable
class PoeBot(BaseBot, PoeBot):
def __init__(self):
self.history_length = 5
super().__init__()
async def get_response(self, query):
last_message = query.query[(- 1)].content
try:
history = ([f'{m.role}: {m.content}' for m in query.query[(- (self.history... |
class TestExample(TestDSLBase):
def test_can_be_named_from_decorator(self):
name = 'example name'
def top_context(context):
(name)
def whatever(self):
pass
self.assertEqual(str(Context.all_top_level_contexts[0].examples[0]), name)
def test_can_be_n... |
def verify_asset(fledge_url, total_assets, count, wait_time):
for i in range(count):
get_url = '/fledge/asset'
result = utils.get_request(fledge_url, get_url)
asset_created = len(result)
if (total_assets == asset_created):
print('Total {} asset created'.format(asset_creat... |
class MyEpochType(sqlalchemy.types.TypeDecorator):
impl = sqlalchemy.Integer
epoch = datetime.date(1970, 1, 1)
def process_bind_param(self, value, dialect):
return (value - self.epoch).days
def process_result_value(self, value, dialect):
return (self.epoch + datetime.timedelta(days=value... |
class EmailSubjectLoader():
def __init__(self, templates: list['EmailTemplate'], *, templates_overrides: (dict[(EmailTemplateType, 'EmailTemplate')] | None)=None):
self.templates_map = _templates_list_to_map(templates)
if templates_overrides:
for (type, template) in templates_overrides.i... |
class CmdTalk(EvAdventureCommand):
key = 'talk'
def func(self):
target = self.caller.search(self.args)
if (not target):
return
if (not inherits_from(target, EvAdventureTalkativeNPC)):
self.caller.msg(f'{target.get_display_name(looker=self.caller)} does not seem ve... |
()
def graph_phi_fct_in_head1(variable_u, variable_v) -> Tuple[(List[BasicBlock], ControlFlowGraph)]:
instructions = [Phi(variable_v[1], [variable_v[0], variable_u[1]]), Phi(variable_u[1], [variable_v[0], variable_u[2]]), Assignment(variable_u[2], BinaryOperation(OperationType.plus, [variable_v[1], Constant(10)]))]... |
def test_cursor_outside_of_data_path_not_found(response_with_body):
config = CursorPaginationConfiguration(cursor_param='after', field='meta.next')
request_params: SaaSRequestParams = SaaSRequestParams(method=HTTPMethod.GET, path='/conversations')
paginator = CursorPaginationStrategy(config)
next_reques... |
(base=RequestContextTask, name='send.after.event.mail')
def send_after_event_mail():
current_time = datetime.datetime.now()
events = Event.query.filter_by(state='published', deleted_at=None).filter((Event.ends_at < current_time), ((current_time - Event.ends_at) < datetime.timedelta(days=1))).all()
for event... |
def get_limb_direction(arm, closest_degrees=45):
dy = (arm[2]['y'] - arm[0]['y'])
dx = (arm[2]['x'] - arm[0]['x'])
angle = degrees(atan((dy / dx)))
if (dx < 0):
angle += 180
mod_close = (angle % closest_degrees)
angle -= mod_close
if (mod_close > (closest_degrees / 2)):
angle... |
class AutoReconnect(threading.Thread):
def __init__(self, ami_client, delay=0.5, on_disconnect=(lambda *args: None), on_reconnect=(lambda *args: None)):
super(AutoReconnect, self).__init__()
self.on_reconnect = on_reconnect
self.on_disconnect = on_disconnect
self.delay = delay
... |
class _DummyModelBase(type):
def __new__(mcs, name, bases, attrs):
meta = attrs.pop('Meta', None)
new_class = type.__new__(mcs, name, bases, attrs)
if meta:
meta.model_name = name.lower()
meta.concrete_model = new_class
setattr(new_class, '_meta', meta)
... |
def BuildTree(records):
parent_dict = {}
node_dict = {}
ordered_id = sorted((idx.record_id for idx in records))
for record in records:
validate_record(record)
parent_dict[record.record_id] = record.parent_id
node_dict[record.record_id] = Node(record.record_id)
root_id = 0
... |
def StockCutter(child_rects, parent_rects, output_json=True):
model = cp_model.CpModel()
horizon = parent_rects[0]
total_parent_area = (horizon[0] * horizon[1])
sheet_type = collections.namedtuple('sheet_type', 'x1 y1 x2 y2 x_interval y_interval is_extra')
all_vars = {}
total_child_area = 0
... |
class GaussianTimeOutSimulatorConfig(TimeOutSimulatorConfig):
_target_: str = fullclassname(GaussianTimeOutSimulator)
timeout_wall_per_round: float = 1.0
fl_stopping_time: float = 1.0
duration_distribution_generator: PerExampleGaussianDurationDistributionConfig = PerExampleGaussianDurationDistributionCo... |
def key_201_CosSin_2012():
dlf = DigitalFilter('Key 201 CosSin (2012)', 'key_201_CosSin_2012')
dlf.base = np.array([9.e-07, 1.e-06, 1.e-06, 1.e-06, 1.e-06, 1.e-06, 2.e-06, 2.e-06, 2.e-06, 3.e-06, 3.e-06, 4.e-06, 4.e-06, 5.e-06, 6.e-06, 7.e-06, 8.e-06, 9.e-06, 1.e-05, 1.e-05, 1.e-05, 1.e-05, 1.e-05, 2.e-05, 2.e-... |
def test_all_uids_found_in_database(backend_db, common_db):
backend_db.insert_object(TEST_FW)
assert (common_db.all_uids_found_in_database([TEST_FW.uid]) is True)
assert (common_db.all_uids_found_in_database([TEST_FW.uid, TEST_FO.uid]) is False)
backend_db.insert_object(TEST_FO)
assert (common_db.al... |
def test_should_merge_deny_statments():
statement1 = Statement(Effect='Deny', Action=[Action('some-service', 'some-action')], Resource=['*'])
statement2 = Statement(Effect='Deny', Action=[Action('some-service', 'some-other-action')], Resource=['*'])
merged = Statement(Effect='Deny', Action=[Action('some-ser... |
class OptMark(Options):
def type(self):
return self._config_get()
def type(self, text):
self._config(text)
def interactive(self):
return self._config_get()
def interactive(self, flag):
self._config(flag)
def name(self):
return self._config_get()
def name(s... |
def get_pseudo_3D_cylinder_box_domain(x0=(0.0, 0.0, 0.0), L=(1.0, 1.0, 1.0), x2=None, x3=None, radius=0.1, center=(0.5, 0.5), n_points_on_obstacle=((2 * 21) - 2), cross_section=circular_cross_section, thetaOffset=0.0, he=1.0, he2=None, he3=None):
if (he2 == None):
he2 = he
if (he3 == None):
he3 ... |
class BgpProcessor(Activity):
MAX_DEST_PROCESSED_PER_CYCLE = 100
_DestQueue = circlist.CircularListType(next_attr_name='next_dest_to_process', prev_attr_name='prev_dest_to_process')
def __init__(self, core_service, work_units_per_cycle=None):
Activity.__init__(self)
self._core_service = core... |
_os(*metadata.platforms)
def main():
cal_dir = Path(f'{Path.home()}/Library/Calendars/')
cal_calendar = cal_dir.joinpath('test.calendar', 'Events')
cal_calendar.mkdir(parents=True, exist_ok=True)
cal_path = str(cal_calendar.joinpath('test.ics'))
common.log(f'Executing file modification on {cal_path}... |
_deserializable
class SlackChunker(BaseChunker):
def __init__(self, config: Optional[ChunkerConfig]=None):
if (config is None):
config = ChunkerConfig(chunk_size=1000, chunk_overlap=0, length_function=len)
text_splitter = RecursiveCharacterTextSplitter(chunk_size=config.chunk_size, chunk... |
('cuda.gemm_rcr_softmax.func_decl')
def gen_function_decl(func_attrs, **kwargs):
func_name = func_attrs['name']
input_ndims = len(func_attrs['input_accessors'][0].original_shapes)
weight_ndims = len(func_attrs['input_accessors'][1].original_shapes)
return common_softmax.FUNC_DECL_TEMPLATE.render(func_na... |
def test_int_promotion():
int_schema = {'type': 'int'}
long_schema = {'type': 'long'}
result = roundtrip(1, int_schema, long_schema)
assert (result == 1)
assert isinstance(result, int)
float_schema = {'type': 'float'}
result = roundtrip(1, int_schema, float_schema)
assert (result == 1.0)... |
.skipif((not path_data_tests.exists()), reason='no data tests')
.skipif((nb_proc > 1), reason='No dist in MPI')
def test_detect_backend_extensions():
shutil.rmtree((path_data_tests / f'__{backend_default}__'), ignore_errors=True)
names = ['assign_func_boost.py', 'assign_func_jit.py', 'block_fluidsim.py', 'block... |
class TestDeclEnumType(BasePyTestCase):
def test_create_does_not_raise_exception(self):
t = model.DeclEnumType(model.UpdateStatus)
t.create(self.engine)
def test_drop_does_not_raise_exception(self):
t = model.DeclEnumType(model.UpdateStatus)
t.drop(self.engine)
def test_proce... |
class OptionSeriesVectorSonificationTracksMappingPitch(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('y')
def mapTo(self, text: str):
self._conf... |
class DecoratorsTests(TestCase):
def test_psa_missing_backend(self):
_auth
def wrapped(cls, root, info, provider, *args):
with self.assertRaises(exceptions.GraphQLSocialAuthError):
wrapped(self, None, self.info(), 'unknown', 'token')
_auth_mock
_settings(SOCIAL_AUTH_PIPEL... |
class almostequal64(TestCase):
maxDiff = 5000
actual = numpy.arange(16).reshape(2, 4, 2)
desired = 'eNpjYAgyX2tRbsluVW51yUreOsl6rvVFa0YbXZtQmyqbOTYAmAYJvQ=='
def test_equal(self):
self.assertAlmostEqual64(self.actual, self.desired)
def test_notequal(self):
with self.assertRaises(Asse... |
def _cmd_metrics(args):
if ((len(args.cnarrays) > 1) and args.segments and (len(args.segments) > 1) and (len(args.cnarrays) != len(args.segments))):
raise ValueError('Number of coverage/segment filenames given must be equal, if more than 1 segment file is given.')
cnarrs = map(read_cna, args.cnarrays)
... |
class TorchDeltaStateCritic(TorchStateCritic):
(StateCritic)
def predict_values(self, critic_input: StateCriticInput) -> StateCriticOutput:
critic_output = StateCriticOutput()
key_0 = critic_input[0].actor_id.step_key
value_0 = self.networks[key_0](critic_input[0].tensor_dict)['value'][(... |
def main(page: ft.Page):
def on_chart_event(e: ft.BarChartEvent):
for (group_index, group) in enumerate(chart.bar_groups):
for (rod_index, rod) in enumerate(group.bar_rods):
rod.hovered = ((e.group_index == group_index) and (e.rod_index == rod_index))
chart.update()
c... |
def RunCommand(args, timeout=None, logfile=None):
child = pexpect.spawn(args[0], args=args[1:], timeout=timeout, logfile=logfile)
child.expect(pexpect.EOF)
child.close()
if child.exitstatus:
print(args)
raise RuntimeError('Error: {}\nProblem running command. Exit status: {}'.format(child... |
def resnet(conf, arch=None):
resnet_size = int((arch if (arch is not None) else conf.arch).replace('resnet', ''))
dataset = conf.data
if (('cifar' in conf.data) or ('svhn' in conf.data)):
model = ResNet_cifar(dataset=dataset, resnet_size=resnet_size, freeze_bn=conf.freeze_bn, freeze_bn_affine=conf.f... |
class TestParserAndGrammarErrors(unittest.TestCase):
def test_no_file(self):
parser = ServiceTestPlanFixtureParser('/path/to/fake/fixture', 'test_no_file')
with self.assertRaises(FixtureLoadError):
parser.parse_test_fixture()
def test_empty_file(self):
with _temp_fixture_file... |
def serve(sock, handle, concurrency=1000):
pool = greenpool.GreenPool(concurrency)
server_gt = greenthread.getcurrent()
while True:
try:
(conn, addr) = sock.accept()
gt = pool.spawn(handle, conn, addr)
gt.link(_stop_checker, server_gt, conn)
(conn, add... |
class Solution(object):
def findTilt(self, root):
def find_tilt(root):
if (root is None):
return (0, 0)
(lstilt, ls) = find_tilt(root.left)
(rstilt, rs) = find_tilt(root.right)
return (((abs((ls - rs)) + lstilt) + rstilt), ((ls + rs) + root.val... |
class Screen():
def __init__(self, screen):
self._screen = screen
curses.start_color()
curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
self._screen.clear()
self._screen.refresh()
(self._height, self._width) = self._screen.getmaxyx()
self._header_ba... |
class OptionSeriesErrorbarOnpointConnectoroptions(Options):
def dashstyle(self):
return self._config_get(None)
def dashstyle(self, text: str):
self._config(text, js_type=False)
def stroke(self):
return self._config_get(None)
def stroke(self, text: str):
self._config(text,... |
def test_cli_with_pdm(pdm_venv_factory: PDMVenvFactory) -> None:
with pdm_venv_factory('project_with_pdm') as virtual_env:
issue_report = f'{uuid.uuid4()}.json'
result = virtual_env.run(f'deptry . -o {issue_report}')
assert (result.returncode == 1)
assert (get_issues_report(Path(issu... |
def extractTriangleNovels(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return False
if ('WFTT' in item['tags']):
return buildReleaseMessageWithType(item, 'Waiting For The Train', vol, chp, ... |
def test_control_doc_parse():
control_json = '\n {\n "remote": true,\n "scavengingBenchmark": true,\n "source": [\n {\n "identity": SRCID_NIGHTHAWK,\n "source_url": " "branch": "master"\n },\n {\n "identity": SRCID_ENVOY,\n "source_... |
class Monitor(Thread):
def __init__(self, req, proxy, logger, task, exit_check=None, ignored_errors=[]):
Thread.__init__(self, name=('monitor%s' % task.guid))
Thread.setDaemon(self, True)
self.vote_result = {}
self.vote_cleared = set().union(ignored_errors)
self.thread_last_s... |
class Example():
def __init__(self, init_arg1=None, init_arg2=None, init_arg3=None, init_arg4=None):
self.init_arg1 = init_arg1
self.init_arg2 = init_arg2
self.init_arg3 = init_arg3
self.init_arg4 = init_arg4
self.attribute1 = None
self.attribute2 = None |
.django_db
def test_failure_with_invalid_group(client, monkeypatch, elasticsearch_transaction_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
resp = client.post('/api/v2/search/spending_over_time', content_type='application/json', data=json.dumps({'group': 'not a valid group', 'fi... |
def restart_systemd_processes(bench_path='.', web_workers=False, _raise=True):
bench_name = get_bench_name(bench_path)
exec_cmd(f'sudo systemctl stop -- $(systemctl show -p Requires {bench_name}.target | cut -d= -f2)', _raise=_raise)
exec_cmd(f'sudo systemctl start -- $(systemctl show -p Requires {bench_nam... |
def results_store(cfg):
logger = logging.getLogger(__name__)
if (cfg.opts('reporting', 'datastore.type') == 'elasticsearch'):
logger.info('Creating ES results store')
return EsResultsStore(cfg)
else:
logger.info('Creating no-op results store')
return NoopResultsStore() |
def reorg(address):
if is_account_state_active(state[address]):
return
for (i, r) in enumerate(alt_states[address]):
if is_account_state_active(r):
(state[address], alt_states[address][i]) = (alt_states[address][i], state[address])
return
raise Exception('wtf m8') |
class structured_sparsity(func):
def __init__(self, lambda_=1, groups=[[]], weights=[0], **kwargs):
super(structured_sparsity, self).__init__(**kwargs)
if (lambda_ < 0):
raise ValueError('The scaling factor must be non-negative.')
self.lambda_ = lambda_
if (not isinstance... |
def _nested_set(configuration_obj: PackageConfiguration, keys: List, value: Any) -> None:
def get_nested_ordered_dict_from_dict(input_dict: Dict) -> Dict:
_dic = {}
for (_key, _value) in input_dict.items():
if isinstance(_value, dict):
_dic[_key] = OrderedDict(get_nested_... |
class queue_op_failed_error_msg(error_msg):
version = 1
type = 1
err_type = 5
def __init__(self, xid=None, code=None, data=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (code != None):
self.code = code
else:
... |
class OptionSeriesOrganizationSonificationTracksPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
... |
def _str_2_callable(val: str, **kwargs):
str_field = str(val)
(module, fn) = str_field.rsplit('.', 1)
try:
call_ref = getattr(importlib.import_module(module), fn)
except Exception as e:
raise _SpockValueError(f'Attempted to import module {module} and callable {fn} however it could not be... |
class Solution():
def maxProduct(self, nums: List[int]) -> int:
max_prod = None
(positive, negative) = (1, 1)
for n in nums:
(t1, t2) = (positive, negative)
positive = max((t1 * n), (t2 * n))
negative = min((t1 * n), (t2 * n))
if ((max_prod is ... |
def initialise(pkg, lib_file, map_file):
pkg_dir = os.path.dirname(__file__)
pkg_module = sys.modules[pkg]
cppyy.add_include_path((pkg_dir + '/include'))
cppyy.add_include_path((pkg_dir + '/include/bx'))
cppyy.add_include_path((pkg_dir + '/include/bimg'))
cppyy.add_include_path((pkg_dir + '/incl... |
class BetterEmExtension(Extension):
def __init__(self, *args, **kwargs):
self.config = {'smart_enable': ['underscore', 'Treat connected words intelligently - Default: underscore']}
super().__init__(*args, **kwargs)
def extendMarkdown(self, md):
md.registerExtension(self)
self.mak... |
class OptionSeriesPieDataAccessibility(Options):
def description(self):
return self._config_get(None)
def description(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_... |
class OptionPlotoptionsScatter3dSonificationTracksMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsScatter3dSonificationTracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsScatter3dSonificationTracksMappingLowpassFrequency)
def resonance(self) -> '... |
class TestSoftTargetCrossEntropyLoss(testslide.TestCase):
def _get_outputs(self) -> torch.Tensor:
return torch.tensor([[1.0, 7.0, 0.0, 0.0, 2.0]])
def _get_targets(self) -> torch.Tensor:
return torch.tensor([[1, 0, 0, 0, 1]])
def _get_loss(self) -> float:
return 5.
def test_soft_... |
class JobQueues():
def from_config(cls, cfg: 'JobsConfig', fs: JobQueuesFS):
return cls(cfg, fs)
def __init__(self, cfg: 'JobsConfig', fs: JobQueuesFS):
self._cfg = cfg
self._fs = fs
def __len__(self):
return len(self._cfg.workers)
def __iter__(self) -> Iterator[JobQueue]... |
class FuseBmmCrrAddCase(unittest.TestCase):
def _test_bmm_crr_add(self, Bs, M, N, K, testname, dtype='float16', do_not_fuse=False):
batch_dim = shape_utils.gen_int_var_min_max(Bs, name='batch_size')
A_shape = [batch_dim, K, M]
B_shape = [batch_dim, K, N]
if do_not_fuse:
a... |
def test_save_and_load(conversation: StorageConversation, conv_storage, message_storage):
conversation.start_new_round()
conversation.add_user_message('hello')
conversation.add_ai_message('hi')
conversation.end_current_round()
saved_conversation = StorageConversation(conv_uid=conversation.conv_uid, ... |
.integration()
def test_schema_inference(client):
rnd = ''.join((choice(ascii_uppercase) for i in range(5)))
dataset_path = os.fspath((INTEGRATION_TEST_COMPASS_ROOT_PATH / f'test_api_schema_{rnd}'))
ds = client.create_dataset(dataset_path)
client.create_branch(ds['rid'], 'master')
transaction_rid = ... |
class Solution():
def maxProfit(self, prices: List[int], fee: int) -> int:
(m0, m1) = (0, None)
for price in prices:
old_m0 = m0
if (m1 is not None):
m0 = max(m0, ((m1 + price) - fee))
m1 = max(m1, (old_m0 - price))
else:
... |
.parametrize('dtype', SUPPORTED_DTYPES)
def test_feature_quantizer_simple(dtype):
rng = numpy.random.default_rng()
a = rng.normal(size=(10, 3))
f = Quantizer(dtype=dtype, max_value=10.0)
f.fit(a)
out = f.transform(a)
assert (out.dtype == numpy.dtype(dtype))
oo = f.inverse_transform(out)
... |
class ErrorResponse(JsonApiException):
headers = {'Content-Type': 'application/vnd.api+json'}
def __init__(self, source: Union[(dict, str)], detail=None, title=None, status=None):
if (isinstance(source, str) and (detail is None)):
super().__init__(None, source)
else:
supe... |
class AmazonSPAPISettings(Document):
def before_validate(self):
if (not self.amazon_fields_map):
self.set_default_fields_map()
def validate(self):
self.validate_amazon_fields_map()
self.validate_after_date()
if (self.is_active == 1):
self.validate_credenti... |
class ModifyChrootForm(ChrootForm):
buildroot_pkgs = wtforms.StringField('Additional packages to be always present in minimal buildroot')
repos = wtforms.TextAreaField('Additional repos to be used for builds in chroot', validators=[UrlRepoListValidator(), wtforms.validators.Optional()], filters=[StringListFilte... |
class TestGetConnections():
def test_get_connections_not_authenticated(self, api_client: TestClient, generate_auth_header, connection_config, url) -> None:
resp = api_client.get(url, headers={})
assert (resp.status_code == HTTP_401_UNAUTHORIZED)
def test_get_connections_with_invalid_system(self,... |
_os(*metadata.platforms)
def main():
powershell = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
path = 'C:\\Users\\Public\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup'
argpath = "C:\\Users\\Public\\AppData\\Roaming\\Microsoft\\Windows\\'Start Menu'\\Programs\\Start... |
def get_event_filter() -> 'EventFilter':
country_id = request.args.get('country', None)
leader_id = request.args.get('leader', None)
system_id = request.args.get('system', None)
war_id = request.args.get('war', None)
planet_id = request.args.get('planet', None)
min_date = request.args.get('min_d... |
class OptionSeriesColumnpyramidSonificationTracksMappingTime(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):
sel... |
def test_slave_message_get_node_text():
xml = '<?xml version="1.0" encoding="UTF-8"?>\n <root>\n <item>\n <child>Text</child>\n </item>\n <emptyItem/>\n </root>\n '
root = ETree.fromstring(xml)
assert (SlaveMessageManager.get_node_text(root, './item/child', '') == 'T... |
class Point(object):
swagger_types = {'coordinates': 'Vect2D', 'type': 'str'}
attribute_map = {'coordinates': 'coordinates', 'type': 'type'}
def __init__(self, coordinates=None, type='Point'):
self._coordinates = None
self._type = None
self.discriminator = None
if (coordinate... |
class DummyIPFSBackend(BaseIPFSBackend):
_assets: Dict = {}
_path = Path('./tests/data/ipfs-cache-mock').resolve()
def fetch_uri_contents(self, ipfs_uri: str) -> bytes:
ipfs_uri = ipfs_uri.replace('ipfs://', '')
if (ipfs_uri not in self._assets):
with self._path.joinpath(ipfs_uri... |
def count_pairpos_bytes(font: TTFont) -> int:
bytes = 0
gpos = font['GPOS']
for lookup in font['GPOS'].table.LookupList.Lookup:
if (lookup.LookupType == 2):
w = OTTableWriter(tableTag=gpos.tableTag)
lookup.compile(w, font)
bytes += len(w.getAllData())
elif... |
class TraversedPartialPath(Exception):
def __init__(self, nibbles_traversed: NibblesInput, node: HexaryTrieNode, untraversed_tail: NibblesInput, *args) -> None:
super().__init__(Nibbles(nibbles_traversed), node, Nibbles(untraversed_tail), *args)
self._simulated_node = self._make_simulated_node()
... |
class RegexValidator(object):
def __init__(self, regex, verbose_pattern=None) -> None:
self.regex = regex
self.verbose_pattern = (verbose_pattern or regex)
def __call__(self, value, field_name):
value = str(value)
match = re.match(self.regex, value)
if match:
... |
def upgrade():
op.add_column('settings', sa.Column('admin_billing_state', sa.String(), nullable=True))
op.add_column('settings', sa.Column('invoice_sending_day', sa.Integer(), server_default='1', nullable=False))
op.add_column('settings', sa.Column('invoice_sending_timezone', sa.String(), server_default='UT... |
def test_websocket_iter_text(test_client_factory):
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
(await websocket.accept())
async for data in websocket.iter_text():
(await websocket.send_text(('Message ... |
def _start():
global patch, name, path, monitor
global delay, winx, winy, winwidth, winheight, input_name, input_variable, variable, app, window, timer
delay = patch.getfloat('general', 'delay')
winx = patch.getint('display', 'xpos')
winy = patch.getint('display', 'ypos')
winwidth = patch.getint... |
class OptionPlotoptionsBarSonificationContexttracksMappingVolume(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 BlockWitnessHashesExchange(BaseExchange[(GetBlockWitnessHashes, BlockWitnessHashes, BlockWitnessHashesPayload)]):
_request_command_type = GetBlockWitnessHashes
_response_command_type = BlockWitnessHashes
_normalizer = DefaultNormalizer(BlockWitnessHashes, BlockWitnessHashesPayload)
tracker_class =... |
def analyzinggraph(scenarios_dic, index, scenarios):
z = 'IT'
unit = '[21] - IT_P2HT_OTH'
GenerationOutput = pd.DataFrame()
demand = pd.DataFrame()
shedload = pd.DataFrame()
powerconsumption = pd.DataFrame()
storagelevel = pd.DataFrame()
curtailment = pd.DataFrame()
for SCEN in scena... |
class OptionPlotoptionsCylinderTooltip(Options):
def clusterFormat(self):
return self._config_get('Clustered points: {point.clusterPointsAmount}')
def clusterFormat(self, text: str):
self._config(text, js_type=False)
def dateTimeLabelFormats(self) -> 'OptionPlotoptionsCylinderTooltipDatetime... |
(suppress_health_check=[HealthCheck.function_scoped_fixture])
(grid_properties())
def test_roff_prop_read_xtgeo(tmp_path, xtgeo_property):
filepath = (tmp_path / 'property.roff')
xtgeo_property.to_file(filepath, name=xtgeo_property.name)
xtgeo_property2 = xtgeo.gridproperty_from_file(filepath, name=xtgeo_pr... |
('/dbsearch/<sstr>/<page>')
def dbsearch(sstr, page=0):
if ((not sstr) or (sstr == '0')):
sstr = keyboard()
if ((not sstr) or (sstr == '0')):
return
try:
sstr = re.sub('\\s+', '', sstr)
url = (' % (parse.quote_plus(sstr), (int(page) + 1)))
xbmc.log(msg=url, le... |
_vrrp_version(VRRP_VERSION_V2, 1)
class vrrpv2(vrrp):
_PACK_STR = '!BBBBBBH'
_MIN_LEN = struct.calcsize(_PACK_STR)
_CHECKSUM_PACK_STR = '!H'
_CHECKSUM_OFFSET = 6
_AUTH_DATA_PACK_STR = '!II'
_AUTH_DATA_LEN = struct.calcsize('!II')
def __len__(self):
return ((self._MIN_LEN + (self._IPV... |
class HiddenExpander(Gtk.Bin):
__gtype_name__ = 'HiddenExpander'
expanded = GObject.property(type=bool, default=False)
label = GObject.property(type=str, default='')
def __init__(self, label='', visible=False):
super(HiddenExpander, self).__init__()
self.label = label
self.set_vi... |
class MPDWrapper(object):
def __init__(self, params):
self.client = mpd.MPDClient()
self._dbus = dbus
self._params = params
self._dbus_service = None
self._can_single = False
self._can_idle = False
self._errors = 0
self._poll_id = None
self._wa... |
class port_status(message):
version = 6
type = 12
def __init__(self, xid=None, reason=None, desc=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (reason != None):
self.reason = reason
else:
self.reason = 0
... |
def f(fs):
f = Function(fs, name='f')
f_split = f.subfunctions
x = SpatialCoordinate(fs.mesh())[0]
for fi in f_split:
fs_i = fi.function_space()
if (fs_i.rank == 1):
fi.interpolate(as_vector(((x,) * fs_i.value_size)))
elif (fs_i.rank == 2):
fi.interpolate(... |
def sample_IHDP(fn_data, test_frac=0.2):
Dataset = draw_ihdp_data(fn_data)
num_samples = len(Dataset)
train_size = int(np.floor((num_samples * (1 - test_frac))))
train_index = list(np.random.choice(range(num_samples), train_size, replace=False))
test_index = list((set(list(range(num_samples))) - set... |
class _QueryBuilder():
def __init__(self) -> None:
self._parser = self._define_parser()
def _define_parser() -> Any:
pyparsing.ParserElement.enablePackrat()
class Buildable():
def build(self) -> sqlalchemy.sql.ColumnElement:
raise NotImplementedError()
... |
def test_procurement_success(setup_test_data, client):
resp = client.get(url.format(toptier_code='043', fiscal_year=2020, fiscal_period=8, type='procurement'))
assert (resp.status_code == status.HTTP_200_OK)
response = resp.json()
expected_results = {'unlinked_file_c_award_count': 14, 'unlinked_file_d_a... |
class ShadowIGMediaBuilder(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isShadowIGMediaBuilder = True
super(ShadowIGMediaBuilder, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
copyright_check_status = 'copyright_check_statu... |
def test___setitem__checks_the_given_data_6():
wh = WorkingHours()
with pytest.raises(RuntimeError) as cm:
wh['sun'] = [['no 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 [['... |
def upgrade():
op.create_table('fidescloud', sa.Column('id', sa.String(length=255), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), sa.Column('co... |
class Test(Testbase.ClassSetup):
def setUpClass(cls):
super().setUpClass()
cls.mandelbrot_compiled_formula = MandelbrotCompiledFormula(cls.g_comp)
def tearDownClass(cls):
super().tearDownClass()
del cls.mandelbrot_compiled_formula
def setUp(self):
library_path = self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.