code stringlengths 281 23.7M |
|---|
def extractErynaluWordpressCom(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) i... |
class matrix(unittest.TestCase):
def setUp(self):
super().setUp()
self.data = numpy.array([((2, 4), 10), ((3, 4), 20), ((2, 3), 1), ((1, 2), 30), ((0, 1), 40), ((1, 2), 50), ((2, 3), (- 1)), ((3, 0), 0), ((2, 0), 60)], dtype=sparse.dtype([4, 5], int))
self.full = numpy.array([[0, 40, 0, 0, 0... |
class ServiceFile(object):
def __init__(self, path):
self.path = os.path.abspath(path)
def get_file(self):
return os.path.join(self.path, 'src', 'service.py')
def _has_service_class(self):
search_string = 'class Service('
with open(self.get_file(), 'r') as f:
for ... |
def dilate_and_mask_metric(subject_id, native_mesh_settings, dscalars):
for map_name in dscalars.keys():
if (not dscalars[map_name]['mask_medialwall']):
continue
for hemisphere in ['L', 'R']:
metric_map = metric_file(subject_id, map_name, hemisphere, native_mesh_settings)
... |
class APIRootView(views.APIView):
_ignore_model_permissions = True
schema = None
api_root_dict = None
def get(self, request, *args, **kwargs):
ret = {}
namespace = request.resolver_match.namespace
for (key, url_name) in self.api_root_dict.items():
if namespace:
... |
class _BaseLink(Pypher):
_CLEAR_PRECEEDING_WS = False
_ADD_PRECEEDING_WS = False
_ADD_SUCEEDING_WS = True
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
super(_BaseLink, self).__init__()
def __unicode__(self):
return self.__class__.__name__... |
class VCPythonEngine(object):
_class_key = 'x'
_gen_python_module = True
def __init__(self, verifier):
self.verifier = verifier
self.ffi = verifier.ffi
self._struct_pending_verification = {}
self._types_of_builtin_functions = {}
def patch_extension_kwds(self, kwds):
... |
class OptionSeriesTreemapSonificationDefaultinstrumentoptions(Options):
def activeWhen(self) -> 'OptionSeriesTreemapSonificationDefaultinstrumentoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesTreemapSonificationDefaultinstrumentoptionsActivewhen)
def instrument(self):
... |
class OptionSeriesSunburstMarker(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):
self._config(num, js... |
def request_data(catch_dc=True, force_dc=None, permissions=()):
def request_data_decorator(fun):
def wrap(request, *args, **kwargs):
if (kwargs.get('data', None) is None):
if (request.method == 'GET'):
data_key = 'query_params'
else:
... |
_os(*metadata.platforms)
def main():
common.log('MsiExec HTTP Download')
(server, ip, port) = common.serve_web()
common.clear_web_cache()
common.execute(['msiexec.exe', '/quiet', '/i', (' % (ip, port))])
common.log('Cleanup', log_type='-')
common.execute(['msiexec', '/quiet', '/uninstall', (' % ... |
class HealthcareServiceUnit(NestedSet):
nsm_parent_field = 'parent_healthcare_service_unit'
def onload(self):
load_address_and_contact(self)
def validate(self):
self.set_service_unit_properties()
def autoname(self):
if self.company:
suffix = (' - ' + frappe.get_cached... |
def export_storm_binary(self, mfile):
scopy = self.copy()
if (abs(scopy.rotation) > 1e-20):
scopy.unrotate()
zmin = scopy.values.min()
zmax = scopy.values.max()
yinc = (scopy._yinc * scopy._yflip)
ier = _cxtgeo.surf_export_storm_bin(mfile.get_cfhandle(), scopy._ncol, scopy._nrow, scopy._... |
class AccessCodeDetail(ResourceDetail):
def before_get(self, args, kwargs):
if kwargs.get('access_event_identifier'):
event = safe_query(Event, 'identifier', kwargs['access_event_identifier'], 'event_identifier')
kwargs['access_event_id'] = event.id
if (kwargs.get('code') and... |
class table_feature_prop_instructions(table_feature_prop):
type = 0
def __init__(self, instruction_ids=None):
if (instruction_ids != None):
self.instruction_ids = instruction_ids
else:
self.instruction_ids = []
return
def pack(self):
packed = []
... |
def test_load_contract_type(plugintester):
plugintester.makeconftest('\nimport pytest\nfrom brownie import BrownieTester\n\(params=[BrownieTester, BrownieTester])\ndef brownie_tester(request):\n yield request.param')
plugintester.makepyfile("\ndef test_call_and_transact(brownie_tester, accounts, web3, fn_iso... |
.skipif((sys.version_info < (3, 7)), reason='This part of code is only defined for python version >= 3.7')
def test_dialogue_message_python_3_7():
dialogue_message = DialogueMessage(DefaultMessage.Performative.BYTES)
assert isinstance(dialogue_message.performative, Message.Performative)
assert (dialogue_mes... |
.integration
class TestLibp2pConnectionPublicDHTDelegateAEACli(AEATestCaseMany):
.parametrize('delegate_uris_public_keys', [(PUBLIC_DHT_DELEGATE_URIS, PUBLIC_DHT_PUBLIC_KEYS), (PUBLIC_STAGING_DHT_DELEGATE_URIS, PUBLIC_STAGING_DHT_PUBLIC_KEYS)], indirect=True)
def test_connectivity(self, delegate_uris_public_key... |
def fortios_monitor_fact(params, fos):
(valid, result) = validate_parameters(params, fos)
if (not valid):
return (True, False, result)
selector = params['selector']
url_params = dict()
if (params['filters'] and len(params['filters'])):
filter_body = quote(params['filters'][0])
... |
def test_reload_excluded_subdirectories_are_removed(reload_directory_structure: Path) -> None:
app_dir = (reload_directory_structure / 'app')
app_sub_dir = (app_dir / 'sub')
with as_cwd(reload_directory_structure):
config = Config(app='tests.test_config:asgi_app', reload=True, reload_excludes=[str(a... |
def oids_block_from_setup(molsetup, name='LigandFromMeeko'):
if len(molsetup.restraints):
raise NotImplementedError("molsetup has restraints but these aren't written to oids block yet")
offchrg_type = 'OFFCHRG'
offchrg_by_parent = {}
for i in molsetup.atom_pseudo:
if (molsetup.atom_type[... |
class BaseVersioning(object):
default_version = api_settings.DEFAULT_VERSION
allowed_versions = api_settings.ALLOWED_VERSIONS
version_param = api_settings.VERSION_PARAM
def determine_version(self, request, *args, **kwargs):
msg = '{cls}.determine_version() must be implemented.'
raise Not... |
class SerializerExtensionsAPIViewMixinTests(TestCase):
fixtures = ['test_data.json']
def setUp(self):
self.owner = test_models.Owner.objects.get()
self.organization = test_models.Organization.objects.get()
self.sku_p100d = test_models.Sku.objects.get(variant='P100D')
self.carmode... |
class OptionPlotoptionsWindbarbSonificationDefaultspeechoptionsMappingPlaydelay(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... |
def main(args):
for arg in args:
with open(arg) as f:
s = f.read()
result = parser.parse(s)
for formula in result.children:
print(formula.leaf)
t = T(formula)
if (t.errors != []):
print(('Errors translating %s:' % formula.leaf))... |
class M3InferenceDataset(Dataset):
def __init__(self, data: list, use_img=True):
self.tensor_trans = transforms.ToTensor()
self.use_img = use_img
self.data = []
for entry in data:
entry = DotDict(entry)
if use_img:
self.data.append([entry.id, e... |
()
def check_legacy_render_layers(progress_controller=None):
if (progress_controller is None):
progress_controller = ProgressControllerBase()
maya_version = pm.about(v=1)
if (int(maya_version) >= 2017):
legacy_render_layers = []
all_render_layers = pm.ls(type='renderLayer')
d... |
def get_unbilled_inpatient_docs(doc, inpatient_record):
filters = {'patient': inpatient_record.patient, 'inpatient_record': inpatient_record.name, 'docstatus': 1}
if (doc in ['Service Request', 'Medication Request']):
filters.update({'billing_status': 'Pending'})
else:
if (doc == 'Patient En... |
class ObjectTypeBasicTestCase(unittest.TestCase):
def setUp(self):
ast = parserFactory()().parse(self.__class__.__doc__)[0]
(mibInfo, symtable) = SymtableCodeGen().genCode(ast, {}, genTexts=True)
(self.mibInfo, pycode) = PySnmpCodeGen().genCode(ast, {mibInfo.name: symtable}, genTexts=True)
... |
def test_form_args():
(app, db, admin) = setup()
class Model(db.Document):
test = db.StringField(required=True)
shared_form_args = {'test': {'validators': [validators.Regexp('test')]}}
view = CustomModelView(Model, form_args=shared_form_args)
admin.add_view(view)
create_form = view.creat... |
class OptionSeriesVariablepieSonificationContexttracksMappingTremoloSpeed(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 Solution(object):
def isUnivalTree(self, root):
if (root is None):
return True
if (root.left is not None):
if (root.val != root.left.val):
return False
if (root.right is not None):
if (root.val != root.right.val):
retu... |
class TestJavaScriptStrings(util.PluginTestCase):
def setup_fs(self):
config = self.dedent("\n matrix:\n - name: javascript\n sources:\n - '{}/**/*.txt'\n aspell:\n lang: en\n d: en_US\n hunspell:\n ... |
def create_inpatient(patient):
patient_obj = frappe.get_doc('Patient', patient)
inpatient_record = frappe.new_doc('Inpatient Record')
inpatient_record.patient = patient
inpatient_record.patient_name = patient_obj.patient_name
inpatient_record.gender = patient_obj.sex
inpatient_record.blood_group... |
class ComparisonReporter():
def __init__(self, config):
self.report_file = config.opts('reporting', 'output.path')
self.report_format = config.opts('reporting', 'format')
self.numbers_align = config.opts('reporting', 'numbers.align', mandatory=False, default_value='decimal')
self.cwd... |
class FaucetUntaggedInfluxTest(FaucetUntaggedTest):
GAUGE_CONFIG_DBS = ("\n influx:\n type: 'influx'\n influx_db: 'faucet'\n influx_host: '127.0.0.1'\n influx_port: %(gauge_influx_port)d\n influx_user: 'faucet'\n influx_pwd: ''\n influx_retries: 1\n" + ('\n ... |
class OptionSeriesXrangeSonificationTracksMappingHighpassFrequency(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 compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs})
correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})... |
class OptionPlotoptionsTreemapSonificationContexttracksMappingPlaydelay(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 OptionPlotoptionsTreegraphStatesSelectMarker(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):
se... |
def test_share():
share_request = ali.share_files(file_id_list=[test_share_file, test_share_file2], share_pwd='2021', description='aligo share test')
assert isinstance(share_request, CreateShareLinkResponse)
assert isinstance(share_request.created_at, str)
assert isinstance(share_request.creator, str)
... |
('ReluK.v1')
def ReluK(nO: Optional[int]=None, nI: Optional[int]=None, *, init_W: Optional[Callable]=None, init_b: Optional[Callable]=None, dropout: Optional[float]=None, normalize: bool=False, k: float=6.0) -> Model[(Floats2d, Floats2d)]:
if (init_W is None):
init_W = glorot_uniform_init
if (init_b is ... |
(st.integers(min_value=0, max_value=MAX_WEI).map(make_ether_string_value))
def test_conversion_revers_round_trip_trip(amount_in_ether):
intermediate_amount = to_wei(amount_in_ether, 'ether')
result_amount = from_wei(intermediate_amount, 'ether')
assert (decimal.Decimal(result_amount) == decimal.Decimal(str(... |
.parametrize('uri,expected', (('ipfs:QmTKB75Y73zhNbD3Y73xeXGjYrZHmaXXNxoZqGCagu7r8u', True), ('ipfs:/QmTKB75Y73zhNbD3Y73xeXGjYrZHmaXXNxoZqGCagu7r8u', True), ('ipfs://QmTKB75Y73zhNbD3Y73xeXGjYrZHmaXXNxoZqGCagu7r8u', True), (' False), (' False), ('bzz://679bde3ccb6fb911db96a0ea1586c04899c6c0cc6d3426e9ee361137b270a463', F... |
def extractEmmsunofficialtranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ((item['tags'] == ['Uncategorized']) or (item['tags'] == ['Novel']) or (item['tags'] ==... |
class DahoasSFTStaticPromptsDataset(Dataset):
def __init__(self, block_size, max_examples=None, tokenizer_name='tiktoken/gpt2') -> None:
super().__init__()
dataset = load_dataset('Dahoas/rm-static', split='train')
self.prompts = []
if (tokenizer_name == 'huggingface/gpt2'):
... |
(params=[TEST_UFO3, TEST_UFOZ])
def testufo(request):
name = request.param
with fs.tempfs.TempFS() as tmp:
if TESTDATA.isdir(name):
fs.copy.copy_dir(TESTDATA, name, tmp, name)
else:
fs.copy.copy_file(TESTDATA, name, tmp, name)
(yield tmp.getsyspath(name)) |
def test_throw_free_tickets(client, db, jwt):
tickets = _create_tickets([0, 0], event=EventFactoryBasic(), type='free')
db.session.commit()
response = client.post('/v1/orders/create-order', content_type='application/json', headers=jwt, data=json.dumps({'tickets': _create_ticket_dict(tickets, [1, 2])}))
... |
def generate_wilson(generate=None, out_fn='derivatives.py', use_mpmath=False):
(m0, m1, m2, n0, n1, n2, o0, o1, o2, p0, p1, p2) = sym.symbols('m:3 n:3 o:3 p:3')
Sys = CoordSys3D('Sys')
M = Sys.origin.locate_new('M', (((m0 * Sys.i) + (m1 * Sys.j)) + (m2 * Sys.k)))
N = Sys.origin.locate_new('N', (((n0 * S... |
class TestMergeRanges(unittest.TestCase):
def test_merge_ranges(self):
solution = Solution()
self.assertRaises(TypeError, solution.merge_ranges, None)
self.assertEqual(solution.merge_ranges([]), [])
array = [(2, 3), (7, 9)]
expected = [(2, 3), (7, 9)]
self.assertEqual... |
.signal_handling
def test_hanging_cleanup_of_signaled_child_fails_dispatcher_and_sends_to_dlq(fake_sqs_queue):
logger = logging.getLogger(((__name__ + '.') + inspect.stack()[0][3]))
logger.setLevel(logging.DEBUG)
msg_body = randint(1111, 9998)
queue = fake_sqs_queue
queue.send_message(MessageBody=ms... |
class OptionSeriesGaugeSonificationDefaultspeechoptionsMappingPlaydelay(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 _async_w3_fixture_logic(request):
use_filter_middleware = request.param
provider = AsyncEthereumTesterProvider()
async_w3 = AsyncWeb3(provider, modules={'eth': [AsyncEth]}, middlewares=[])
if use_filter_middleware:
async_w3.middleware_onion.add(async_local_filter_middleware)
return async... |
class STM32_TIM(BPHandler):
def __init__(self, model=TimerModel):
self.model = model
self.org_lr = None
self.current_channel = 0
self.addr2isr_lut = {: 45}
self.irq_rates = {}
self.name = 'STM32_TIM'
_handler(['HAL_TIM_Base_Init'])
def tim_init(self, qemu, bp_... |
def edit_note_and_tags(request, note_id, *args, **kwargs):
template_name = 'index.html'
folder_id = request.GET.get('folder_id', '')
tag_id = request.GET.get('tag_id', '')
if folder_id:
notes = joplin.get_folders_notes(folder_id)
elif tag_id:
notes = joplin.get_tags_notes(tag_id)
... |
class OptionSeriesPyramidSonificationTracksMappingPlaydelay(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... |
class MagiclinkRepositoryPattern(_MagiclinkShorthandPattern):
ANCESTOR_EXCLUDES = ('a',)
def handleMatch(self, m, data):
text = m.group('mention')[1:]
parts = text.split(':')
if (len(parts) > 1):
provider = parts[0]
user = parts[1]
else:
provid... |
class SentryAction(AskForCard):
card_usage = 'launch'
def __init__(self, source, target):
AskForCard.__init__(self, source, source, AttackCard)
self.victim = target
def process_card(self, c):
g = self.game
(src, tgt) = (self.source, self.victim)
c = SentryAttack.wrap(... |
class Button():
def __init__(self, ai_game, msg):
self.screen = ai_game.screen
self.screen_rect = self.screen.get_rect()
(self.width, self.height) = (200, 50)
self.button_color = (100, 5, 5)
self.text_color = (255, 255, 255)
self.font = pygame.font.SysFont(None, 48)
... |
class ColorControlPoint():
def __init__(self, active_channels, fixed=False):
self.color = Color()
self.pos = 0.0
self.fixed = fixed
if ('a' != active_channels):
self.active_channels = 'rgb'
self.activate_channels(active_channels)
else:
self... |
def test_list_with_structured_config(instantiate_func: Any) -> None:
class ListValuesConf():
_target_: str = 'tests.instantiate.test_instantiate.ListValues'
d: List[User] = MISSING
schema = OmegaConf.structured(ListValuesConf)
cfg = OmegaConf.merge(schema, {'d': [{'name': 'Bond', 'age': 7}]}... |
def funcparser_callable_search(*args, caller=None, access='control', **kwargs):
search_kwargs = {key: value for (key, value) in kwargs.items() if (key not in ('funcparser', 'raise_errors', 'type', 'return_list'))}
return_list = (str(kwargs.pop('return_list', 'false')).lower() == 'true')
if (not args):
... |
class Flow():
def __init__(self, root: FlowRoot, requestor: Identifier, initial_context: Mapping[(str, Any)]):
self._root = root
self._current_step = self._root
self.ctx = dict(initial_context)
self.requestor = requestor
def next_autosteps(self) -> List[FlowNode]:
return ... |
def prepare_timeline_gpu_events(df: pd.DataFrame, symbol_table: TraceSymbolTable, ranks: Optional[List[int]]=None, iterations: Optional[List[int]]=None, streams: Optional[List[int]]=None, duration_threshold: int=1000) -> pd.DataFrame:
t0 = perf_counter()
required_columns: List[str] = ['iteration', 'name', 'cat'... |
def init_user_configfile() -> Path:
config_file_path = find_config_file()
if (config_file_path is None):
config_file_path = build_config_search_path()[0]
try:
config_file_path.parent.mkdir(exist_ok=True)
except (AttributeError, FileNotFoundError):
raise ConfigInit... |
def test_validate_gas_limit_almost_too_low(noproof_consensus_chain):
block1 = noproof_consensus_chain.mine_block()
block2 = noproof_consensus_chain.mine_block()
max_reduction = ((block1.header.gas_limit // constants.GAS_LIMIT_ADJUSTMENT_FACTOR) - 1)
barely_valid_low_gas_limit = (block1.header.gas_limit ... |
def _clear_cache():
L2_cache_size = {70: ((6 * 1024) * 1024), 80: ((40 * 1024) * 1024)}
capability = torch.cuda.get_device_capability()
device_type = ((capability[0] * 10) + capability[1])
with record_function('[param|clear_cache]'):
_ = (torch.zeros((L2_cache_size[device_type] // 4)).float() * ... |
def test_chain_builder_initialize_chain_default(chain_class):
chain = pipe(chain_class, genesis())
header = chain.get_canonical_head()
assert (header == chain.get_canonical_block_by_number(0).header)
assert (header.parent_hash == constants.GENESIS_PARENT_HASH)
assert (header.uncles_hash == constants... |
def pytest_generate_tests(metafunc):
if ('perf_bwo' in metafunc.fixturenames):
bwos = [8, 16, 32]
ids = ['8x8', '16x16', '32x32']
metafunc.parametrize('perf_bwo', bwos, ids=ids)
if ('perf_shape' in metafunc.fixturenames):
mem_limit = (2 ** 20)
sizes = [16, 32, 64, 256, 51... |
class Pairing(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.Pairing_swiginit(self, _blst.new_Pairing(*args))
__swig_destroy__ = _blst.delete_Pairing
aggregate = _swig_new_i... |
class SplitTableBatchedEmbeddingBagsCodegenInputDataGenerator():
def get_data(self, config, device, alpha=1):
logger.debug(f'data generator config: {config}')
num_tables = config['args'][0]['value']
if (num_tables > 1):
rows = config['args'][1]['value']
pooling_factor... |
def _post_init(self, config, should_cast, sampler, type_caster):
for (name, field) in getattr(self, '__dataclass_fields__', {}).items():
value = getattr(self, name)
if (value is Required):
raise TypeError(f'Field {name} requires a value')
type_ = _get_field_type(type_caster, fiel... |
def test_read_headers():
with pytest.warns(UserWarning, match='Unknown simulator code'):
(intehead, logihead, _) = xtg_im_ecl.peek_headers(iter([MockEntry('INTEHEAD', np.zeros(411, dtype=np.int32)), MockEntry('LOGIHEAD', np.zeros(128, dtype=bool))]))
assert (intehead == InteHead(np.zeros(411, dtype=... |
class TransformBase(ReprMixIn, metaclass=ABCMeta):
def __init__(self, *, config: Config, name: str, module_configuration: ConfigDict) -> None:
self._name = name
def name(self) -> str:
return self._name
def module(self) -> str:
return self.__class__.__module__.split('.')[(- 1)]
de... |
def validate_compressed_public_key_bytes(value: Any) -> None:
validate_bytes(value)
validate_bytes_length(value, 33, 'compressed public key')
first_byte = value[0:1]
if (first_byte not in (b'\x02', b'\x03')):
raise ValidationError('Unexpected compressed public key format: Must start with 0x02 or... |
class AcyclicProcessor(Processor):
def preprocess_condition_refinement(self) -> None:
self.asforest.remove_empty_nodes(self.asforest.current_root)
self._remove_redundant_reaching_conditions_from_condition_nodes(self.asforest.current_root)
self.asforest.clean_up(self.asforest.current_root)
... |
.parametrize('ops', XP_OPS)
def test_hash_gives_distinct_keys(ops):
ids = ops.alloc1f(5, dtype='uint64')
keys = ops.hash(ids, 0)
assert (keys.shape == (5, 4))
assert (keys.dtype == 'uint32')
for i in range(len(ids)):
for j in range(keys.shape[1]):
assert (keys[(i, j)] != 0) |
.usefixtures('prepare_lars_optimizer_test')
class TestLarsOptimizer():
def test_lars_multiple_steps(self) -> None:
dict_config_lars = {'lr': 0.01, 'weight_decay': 0}
lars_aggregator = FedLARSSyncAggregator(**OmegaConf.structured(FedLARSSyncAggregatorConfig(**dict_config_lars)), global_model=self.qua... |
class FlowNode():
def __init__(self, command: str=None, hints: bool=True) -> None:
self.command = command
self.children = []
self.hints = hints
def connect(self, node_or_command: Union[('FlowNode', str)], predicate: Predicate=(lambda _: False), hints: bool=True) -> 'FlowNode':
no... |
class LControl():
def __init__(self, component=None, options=None, set_var=None):
self.component = component
(self._js, self.set_var) = ([], set_var)
(self.varId, self.varName) = (('L.control()' if (options is None) else ('L.control(%s)' % JsUtils.jsConvertData(options, None))), None)
de... |
def sort(data):
def key(o):
if (o is None):
return None
elif isinstance(o, str):
return extract_numbers(o)
elif isinstance(o, int):
return o
elif isinstance(o, (list, tuple)):
return tuple((key(i) for i in o))
elif isinstance(o,... |
def edit_locale(_: Any) -> None:
all_locales = locale_handler.LocalManager.get_locales()
locale_manager = locale_handler.LocalManager.from_config()
locale = get_config_value('LOCALE')
locale = all_locales[(user_input_handler.select_single(all_locales, locale_manager.search_key('select_l'), (locale_manag... |
def extractIdlechiWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ((item['tags'] == ['Chinese Novel']) or (item['tags'] == ['Uncategorized'])):
titlemap = [('The Fe... |
def _cli(csp):
config = Config.from_file(csp.config_filename())
cfg = partial(config.get, 'CLI', type=Str)
parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False, formatter_class=RawAndDefaultsFormatter, description=SHORT_DESCRIPTION)
acct_group = parser.add_argument_group('account selectio... |
def info_cmd():
_cli.command(short_help='Get model information', help='Get model information')
('--as_json', is_flag=True, default=False, help='Output as JSON format')
def info(as_json):
session = Session(config_json=None)
model_id = session.current_model_id()
service_class = session... |
def test_route_converters(client):
response = client.get('/int/5')
assert (response.status_code == 200)
assert (response.json() == {'int': 5})
assert (app.url_path_for('int-convertor', param=5) == '/int/5')
response = client.get('/path-with-parentheses(7)')
assert (response.status_code == 200)
... |
class Client():
events = ('apiStart', 'apiEnd', 'apiError', 'throttleStart', 'throttleEnd')
MaxRequests = 45
RequestsInterval = 1
MinClientVersion = 157
MaxClientVersion = 178
(DISCONNECTED, CONNECTING, CONNECTED) = range(3)
def __init__(self, wrapper):
self.wrapper = wrapper
... |
class _AppEngineAppsServicesVersionsRepository(repository_mixins.GetQueryMixin, repository_mixins.ListQueryMixin, _base_repository.GCPRepository):
def __init__(self, **kwargs):
super(_AppEngineAppsServicesVersionsRepository, self).__init__(component='apps.services.versions', key_field='appsId', entity_field... |
_dependency(plt, 'matplotlib')
def plot_scatter_2(data_0, label_0, data_1, label_1, title=None, ax=None):
ax = check_ax(ax)
ax1 = ax.twinx()
plot_scatter_1(data_0, label_0, ax=ax)
plot_scatter_1(data_1, label_1, x_val=1, ax=ax1)
if title:
ax.set_title(title, fontsize=TITLE_FONTSIZE)
ax.s... |
class OptionSeriesPyramidSonificationTracksMappingHighpassResonance(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 TestHStack(I3LayoutScenario):
def test_scenario(self):
for params in self.layout_params():
self.senario(params)
self._close_all()
def layout(self, params: List) -> str:
(ratio, position) = params
return f'hstack {ratio} {position}'
def layout_params(self... |
class YearLimitedDownloadViewSet(BaseDownloadViewSet):
endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/bulk_download/awards.md'
def post(self, request):
request.data['constraint_type'] = 'year'
return BaseDownloadViewSet.post(self, request, origination='bulk_download', validator_type=... |
class CharSplitter(SplitterBase):
def split_component(self, instr):
ret = []
agg = ''
for letter in instr:
if (letter in SPLIT_ON):
if agg:
ret.append(agg)
agg = ''
ret.append(letter)
else:
... |
def _skip_first_arg(template: Any, attr_name: str) -> bool:
if inspect.ismodule(template):
return False
if inspect.isclass(template):
mro = template.__mro__
else:
mro = template.__class__.__mro__
for klass in mro:
if (attr_name not in klass.__dict__):
continue... |
def preprocess_file(contents_split: list, file_path: str=None, pp_defs: dict=None, include_dirs: set=None, debug: bool=False):
def eval_pp_if(text, defs: dict=None):
def replace_ops(expr: str):
expr = expr.replace('&&', ' and ')
expr = expr.replace('||', ' or ')
expr = ex... |
class OptionSeriesSunburstSonificationTracks(Options):
def activeWhen(self) -> 'OptionSeriesSunburstSonificationTracksActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesSunburstSonificationTracksActivewhen)
def instrument(self):
return self._config_get('piano')
def instrumen... |
class OptionPlotoptionsGaugeEvents(Options):
def afterAnimate(self):
return self._config_get(None)
def afterAnimate(self, value: Any):
self._config(value, js_type=False)
def checkboxClick(self):
return self._config_get(None)
def checkboxClick(self, value: Any):
self._conf... |
def test_fy_failure(client, download_test_data):
download_generation.retrieve_db_string = Mock(return_value=get_database_dsn_string())
resp = client.post('/api/v2/download/accounts/', content_type='application/json', data=json.dumps({'account_level': 'federal_account', 'filters': {'submission_types': ['award_fi... |
def train(pretrain, batch_size, exp_name):
device = 'cuda'
cfg = get_configs('gpt2-medium/dropout')
cfg.max_steps = (200000 // batch_size)
cfg.batch_size = batch_size
cfg.pretrain = pretrain
assert (pretrain == 'huggingface')
cfg.exp_name = exp_name
model = GPT.from_pretrained(cfg)
t... |
def test_aggregation_chain_multi_attribute():
class _EventInterface(ABC):
_epoch_stats(sum, input_name='attr1')
_epoch_stats(sum, input_name='attr2')
_episode_stats(sum, input_name='attr1')
_episode_stats(sum, input_name='attr2')
_step_stats(sum, input_name='attr1')
_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.