code stringlengths 281 23.7M |
|---|
(frozen=True, init=False)
class FalScript():
model: Optional[DbtModel]
path: Path
faldbt: FalDbt
hook_arguments: Optional[Dict[(str, Any)]]
is_hook: bool
timing_type: Optional[TimingType]
def __init__(self, faldbt: FalDbt, model: Optional[DbtModel], path: Union[(str, Path)], hook_arguments: ... |
(name='handle_side_and_related_tags', ignore_result=True)
def handle_side_and_related_tags_task(builds: typing.List[str], pending_signing_tag: str, from_tag: str, pending_testing_tag: typing.Optional[str]=None, candidate_tag: typing.Optional[str]=None):
from .handle_side_and_related_tags import main
log.info('R... |
class Date(TraitType):
default_value_type = DefaultValue.constant
def __init__(self, default_value=None, *, allow_datetime=False, allow_none=False, **metadata):
super().__init__(default_value, **metadata)
self.allow_datetime = allow_datetime
self.allow_none = allow_none
def validate(... |
_required
def user_email_settings(request, username):
(user, user_is_house_admin_somewhere) = _get_user_and_perms(request, username)
return render(request, 'user_email.html', {'u': user, 'user_is_house_admin_somewhere': user_is_house_admin_somewhere, 'stripe_publishable_key': settings.STRIPE_PUBLISHABLE_KEY}) |
class TestOFPGetConfigReply(unittest.TestCase):
class Datapath(object):
ofproto = ofproto
ofproto_parser = ofproto_v1_0_parser
c = OFPGetConfigReply(Datapath)
def setUp(self):
pass
def tearDown(self):
pass
def test_init(self):
pass
def test_parser(self):
... |
class TestMaximumLikelihood(unittest.TestCase):
def test_maximum_likelihood_recovery(self):
rng = np.random.default_rng(18434)
data = rng.uniform((- 2), 2, size=(10, 100))
unique_var = rng.uniform(0.2, 2, size=10)
cor_matrix = np.cov(data)
(loadings, eigenvalues, _) = pca(cor... |
_or_admin_required
def room_occupancy(request, location_slug, room_id, year):
room = get_object_or_404(Resource, id=room_id)
year = int(year)
response = HttpResponse(content_type='text/csv')
output_filename = ('%s Occupancy Report %d.csv' % (room.name, year))
response['Content-Disposition'] = ('atta... |
_os(*metadata.platforms)
def main():
commands = '\n .($env:public[13]+$env:public[5]+\'x\')("Write-Host \'This is my test command\' -ForegroundColor Green; start c:\\windows\\system32\\calc.exe")\n iex(((\'W\'+\'rite-Hos\'+\'t no\'+\'HThi\'+\'s\'+\' is\'+\' my test comma\'+\'n\'+\'dnoH\'+\' \'+\'-F\'+... |
class NaturalKeyTest(TestBase):
def setUp(self):
reversion.register(TestModelInlineByNaturalKey, use_natural_foreign_keys=True)
reversion.register(TestModelWithNaturalKey)
def testNaturalKeyInline(self):
with reversion.create_revision():
inline = TestModelWithNaturalKey.objec... |
def format_document_to_dict(document: Document) -> List[dict]:
extracted_data = []
for idx in range(0, len(Document.to_dict(document).get('pages'))):
summary = {'line_items': []}
for entity in document.entities:
entity_dict = Document.Entity.to_dict(entity)
page_anchor = ... |
def _read_csv(path: str, schema=None, read_options=None):
if (not schema):
(schema, read_options) = _load_spark_schema(path=path)
reader = get_spark_session().read.format('csv')
if read_options:
for (dict_key, value) in read_options.items():
reader = reader.option(dict_key, value... |
class BaseSoC(SoCCore):
def __init__(self, sys_clk_freq=int(.0), mode=mode.DOUBLE, **kwargs):
platform = arty.Platform(variant='a7-35', toolchain='vivado')
SoCCore.__init__(self, platform, sys_clk_freq, ident='LiteX SoC on Arty A7-35', **kwargs)
self.submodules.crg = _CRG(platform, sys_clk_f... |
class TestReplaceComponentIdsInAgentConfig(BaseTestReplaceComponentIds):
def setup_class(cls):
cls.expected_custom_component_configuration = dict(foo='bar')
cls.agent_config = AgentConfig(agent_name='agent_name', author='author', version='0.1.0', default_routing={str(cls.old_protocol_id): str(cls.ol... |
def handle_settings_update(cmd: str):
name = cmd.split()[0]
value = ' '.join(cmd.split()[1:])
if (name == 'searchpane.zoom'):
config[name] = float(value)
UI._editor.web.setZoomFactor(float(value))
elif (name == 'hideSidebar'):
m = ((value == 'true') or (value == 'on'))
co... |
class ChainDatabaseAPI(HeaderDatabaseAPI):
def get_block_uncles(self, uncles_hash: Hash32) -> Tuple[(BlockHeaderAPI, ...)]:
...
def persist_block(self, block: BlockAPI, genesis_parent_hash: Hash32=None) -> Tuple[(Tuple[(Hash32, ...)], Tuple[(Hash32, ...)])]:
...
def persist_unexecuted_block(... |
class WebAppHandler(SimpleHTTPRequestHandler):
APP_CLASS = None
def do_POST(self):
return self.run_cgi()
def send_head(self):
return self.run_cgi()
def run_cgi(self):
rest = self.path
i = rest.rfind('?')
if (i >= 0):
(rest, query) = (rest[:i], rest[(i ... |
.parametrize('argument_names,expected', (([], {'func_1', 'func_2', 'func_3', 'func_4'}), (['a'], {'func_2', 'func_3', 'func_4'}), (['a', 'c'], {'func_4'}), (['c'], {'func_4'}), (['b'], {'func_3', 'func_4'})))
def test_filter_by_arguments_1(argument_names, expected):
actual_matches = filter_by_argument_name(argument... |
class TestICalendarParser():
def test_get_class_finds_rie(self):
assert (ICalendarParser.get_class('rie') is not None)
def test_get_class_finds_ics(self):
assert (ICalendarParser.get_class('ics') is not None)
def test_get_class_does_not_find_unknown(self):
assert (ICalendarParser.get... |
_view(['GET'])
def org_codes(request, format=None):
org_codes = utils.param_to_list(request.query_params.get('q', None))
org_types = utils.param_to_list(request.query_params.get('org_type', None))
is_exact = request.GET.get('exact', '')
if (not org_types):
org_types = ['']
if (not org_codes)... |
def test_policy_document_renders_to_json():
pd = PolicyDocument(Version='2012-10-17', Statement=[Statement(Effect='Allow', Action=[Action('autoscaling', 'DescribeLaunchConfigurations')], Resource=['*']), Statement(Effect='Allow', Action=[Action('sts', 'AssumeRole')], Resource=['arn:aws:iam:::role/someRole'])])
... |
def period(action, config):
retval = [filter_elements.unit(period=True), filter_elements.range_from(), filter_elements.range_to(), filter_elements.week_starts_on(), filter_elements.epoch(), filter_elements.exclude(), filter_elements.period_type(), filter_elements.date_from(), filter_elements.date_from_format(), fil... |
def execute(conn: sqlite3.Connection) -> None:
conn.execute('CREATE TABLE IF NOT EXISTS WalletEvents (event_id INTEGER PRIMARY KEY,event_type INTEGER NOT NULL,event_flags INTEGER NOT NULL,account_id INTEGER,date_created INTEGER NOT NULL,date_updated INTEGER NOT NULL,FOREIGN KEY(account_id) REFERENCES Accounts (acco... |
def emitMetric(identifier='PyTorchObserver', **kwargs):
data = {}
if (('type' not in kwargs) or ('metric' not in kwargs) or ('unit' not in kwargs)):
return ''
data['type'] = kwargs['type']
data['metric'] = kwargs['metric']
data['unit'] = kwargs['unit']
if ('value' in kwargs):
dat... |
class OptionSeriesSplineSonificationTracksMappingVolume(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._co... |
def dumpxml(out, obj, mode=None):
if (obj is None):
out.write('<null />')
return
if isinstance(obj, dict):
out.write(('<dict size="%d">\n' % len(obj)))
for (k, v) in obj.items():
out.write(('<key>%s</key>\n' % k))
out.write('<value>')
dumpxml(o... |
_required
_required
_POST
def multi_settings_form(request):
if (not request.user.is_admin(request)):
raise PermissionDenied
if (request.POST['action'] == 'delete'):
for hostname in request.POST.getlist('hostname'):
vm = get_vm(request, hostname, auto_dc_switch=False)
res ... |
class View(ScrollableControl):
def __init__(self, route: Optional[str]=None, controls: Optional[List[Control]]=None, appbar: Union[(AppBar, CupertinoAppBar, None)]=None, bottom_appbar: Optional[BottomAppBar]=None, floating_action_button: Optional[FloatingActionButton]=None, floating_action_button_location: Optional... |
class TestAddQueryParamInUrl():
def test_add_query_param_in_url_empty_query_string(self):
url = '
query_params = {'param1': 'value1', 'param2': 'value2'}
expected_url = '
output_url = add_query_param_in_url(url, query_params)
assert (output_url == expected_url), f'Expected `{... |
class LunaStringPlaceCard(GenericAction):
def __init__(self, target, card):
self.source = self.target = target
self.card = card
def apply_action(self):
g = self.game
tgt = self.target
direction = g.user_input([tgt], ChooseOptionInputlet(self, ('front', 'back')))
s... |
class OptionSeriesArcdiagramSonificationContexttracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesArcdiagramSonificationContexttracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesArcdiagramSonificationContexttracksMappingTremoloDepth)
def speed(self) -> 'OptionSerie... |
class set_config(message):
version = 4
type = 9
def __init__(self, xid=None, flags=None, miss_send_len=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:
self.flags = 0
... |
def aggregate_rsem(fnames):
prev_row_count = None
sample_cols = {}
length_cols = []
length_colname = 'length'
for fname in fnames:
d = pd.read_csv(fname, sep='\t', usecols=['gene_id', length_colname, 'expected_count'], converters={'gene_id': rna.before('.')}).set_index('gene_id')
if ... |
.django_db
def test_correct_response(client, monkeypatch, elasticsearch_transaction_index, basic_award, subagency_award):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
resp = client.post('/api/v2/search/spending_by_category/funding_agency', content_type='application/json', data=json.dum... |
class GameUtility():
def __init__(self, our_hand: np.ndarray, board: np.ndarray, cards: np.ndarray):
self._evaluator = Evaluator()
unavailable_cards = np.concatenate([board, our_hand], axis=0)
self.available_cards = np.array([c for c in cards if (c not in unavailable_cards)])
self.ou... |
def make_group(indexer, estimators, preprocessing, learner_kwargs=None, transformer_kwargs=None, name=None):
(preprocessing, estimators) = check_instances(estimators, preprocessing)
if (learner_kwargs is None):
learner_kwargs = {}
if (transformer_kwargs is None):
transformer_kwargs = {}
... |
(name='api.mon.base.tasks.mon_hostgroup_get', base=MgmtTask)
_task(log_exception=False)
def mon_hostgroup_get(task_id, dc_id, hostgroup_name, dc_bound=True, **kwargs):
dc = Dc.objects.get_by_id(int(dc_id))
mon = get_monitoring(dc)
try:
return mon.hostgroup_detail(hostgroup_name, dc_bound=dc_bound)
... |
class GELU(Module):
def __init__(self, approximate: str='none'):
super().__init__()
self.approximate = approximate
def forward(self, *args):
assert (len(args) == 1)
input_val = args[0]
if (self.approximate == 'tanh'):
result = elementwise(FuncEnum.FASTGELU)(in... |
def get_candidate_list(kwargs):
candidate = db.session.query(CandidateHistory.candidate_id.label('candidate_id'), CandidateHistory.two_year_period.label('two_year_period'), CandidateHistory.candidate_election_year.label('candidate_election_year')).filter((CandidateHistory.candidate_id.in_(kwargs.get('candidate_id')... |
def main(same_annotation_for_both_str: str, same_annotation_for_both_converter: pathlib.Path, *, optional_value: typing.Annotated[(typing.Optional[int], Clize[int])]=None, optional_parameter: typing.Annotated[(int, Clize[int])]=1, aliased: typing.Annotated[(int, Clize['n'])], file_opener: typing.Annotated[(typing.Any, ... |
class MycobotTest(object):
def __init__(self):
self.mycobot = None
self.win = tkinter.Tk()
self.win.title(' Mycobot ')
self.win.geometry('918x480+10+10')
self.port_label = tkinter.Label(self.win, text=':')
self.port_label.grid(row=0)
self.port_list = ttk.Combo... |
.parametrize('val, expected', ((b'\x00', 0), (b'\x01', 1), (b'\x00\x01', 1), (b'\x01\x00', 256), (bytearray(b'\x00'), 0), (bytearray(b'\x01'), 1), (bytearray(b'\x00\x01'), 1), (bytearray(b'\x01\x00'), 256), (True, 1), (False, 0), ('255', TypeError), ('-1', TypeError), ('0x0', TypeError), ('0x1', TypeError)))
def test_t... |
('os.symlink')
.object(scavenging_benchmark.Benchmark, 'execute_benchmark')
.object(docker_image.DockerImage, 'pull_image')
.object(source_manager.SourceManager, 'have_build_options')
.object(source_manager.SourceManager, 'get_envoy_hashes_for_benchmark')
def test_execute_using_images_only(mock_hashes_for_benchmarks, m... |
class Storage():
def __init__(self, host, logger):
self.host = host
self.logger = logger
self.request_handler = RequestHandler()
self.storage_urls_found = set()
self.num_files_found = 0
file_list_path = os.path.join(MY_PATH, '../wordlists/storage_sensitive')
w... |
('aea.cli.scaffold._scaffold_dm_handler')
('aea.cli.utils.decorators._check_aea_project')
class ScaffoldDecisionMakerHandlerTestCase(TestCase):
def setUp(self):
self.runner = CliRunner()
def test_scaffold_decision_maker_handler_command_positive(self, *mocks):
result = self.runner.invoke(cli, [*C... |
class OptionSeriesColumnDataEvents(Options):
def click(self):
return self._config_get(None)
def click(self, value: Any):
self._config(value, js_type=False)
def drag(self):
return self._config_get(None)
def drag(self, value: Any):
self._config(value, js_type=False)
def... |
class Snooker(Ruleset):
def __init__(self, *args, **kwargs):
Ruleset.__init__(self, *args, **kwargs)
self.phase: GamePhase = GamePhase.ALTERNATING
def active_group(self):
return BallGroup.get(self.shot_constraints.hittable)
def build_shot_info(self, shot: System) -> ShotInfo:
... |
class General_For_Statement(For_Loop_Statement):
def __init__(self, t_for):
super().__init__(t_for)
assert ((t_for.kind == 'KEYWORD') and (t_for.value == 'for'))
self.n_expr = None
def set_expression(self, n_expr):
assert isinstance(n_expr, Expression)
self.n_expr = n_exp... |
class Revision(object):
nextrev = frozenset()
_all_nextrev = frozenset()
revision = None
down_revision = None
def __init__(self, revision, down_revision, dependencies=None, branch_labels=None):
self.revision = revision
self.down_revision = tuple_or_value(down_revision)
def __repr... |
def main() -> None:
parser = ArgumentParser(description='Parse source files and print the abstract syntax tree (AST).')
parser.add_argument('-g', action='store_true', help='generate graph')
parser.add_argument('FILE', nargs='*', help='files to parse')
args = parser.parse_args()
if args.g:
fo... |
class BaseParser(argparse.ArgumentParser):
def __init__(self, add_help=False, data_dir=True, model_dir=True, train_epochs=True, epochs_between_evals=True, stop_threshold=True, batch_size=True, multi_gpu=False, num_gpu=True, hooks=True):
super(BaseParser, self).__init__(add_help=add_help)
if data_dir... |
def test_firestore():
client = firestore.client()
expected = {'name': u'Mountain View', 'country': u'USA', 'population': 77846, 'capital': False}
doc = client.collection('cities').document()
doc.set(expected)
data = doc.get().to_dict()
assert (data == expected)
doc.delete()
assert (doc.g... |
def build_spending_update_query(query_base, update_data):
values_string = ''
for (count, row) in enumerate(update_data, 1):
values_string += '('
values_string += ','.join((['%s'] * len(row)))
values_string += ')'
if (count != len(update_data)):
values_string += ','
... |
class List(CLICommand):
doc = 'List instances that match the arguments.\n List all if no arguments given.'
args_optional = ['query']
def run(cli):
instances = cli.get_instances_for_action()
lines = []
if (len(instances) == 0):
return
instances_synced = []
... |
class TestAdminACLFactory(base.BasePyTestCase):
def test___acl__(self):
r = testing.DummyRequest()
r.registry.settings = {'admin_groups': ['cool_gals', 'cool_guys']}
f = security.AdminACLFactory(r)
acls = f.__acl__()
assert (acls == ([(Allow, 'group:cool_gals', ALL_PERMISSION... |
def test_gas_price_strategy_calls(w3):
transaction = {'to': '0x0', 'value': }
my_gas_price_strategy = Mock(return_value=5)
w3.eth.set_gas_price_strategy(my_gas_price_strategy)
assert (w3.eth.generate_gas_price(transaction) == 5)
my_gas_price_strategy.assert_called_once_with(w3, transaction) |
class SearchFileRequest(DatClass):
query: str
drive_id: str = None
limit: int = field(default=100, repr=False)
image_thumbnail_process: str = field(default='image/resize,w_160/format,jpeg', repr=False)
image_url_process: str = field(default='image/resize,w_1920/format,jpeg', repr=False)
marker: ... |
class CameraData():
id: str
name: str
has_audio: bool
is_online: bool
is_group: bool
is_system: bool
group_cameras: dict
type: str
data: dict
def __init__(self, camera):
self.id = camera.get(BI_ATTR_ID)
self.name = camera.get(BI_ATTR_NAME)
self.is_online =... |
.parametrize('compiled', [True, False])
def test_bytes_integer_struct_unsigned_be(compiled):
d = '\n struct test {\n uint24 a;\n uint24 b[2];\n uint24 len;\n uint24 dync[len];\n uint24 c;\n };\n '
c = cstruct.cstruct()
c.load(d, compiled=compiled)
c.endia... |
class Weelo(BikeShareSystem):
authed = True
meta = {'system': 'Weelo', 'company': ['Bicincitta Italia S.r.l.']}
def __init__(self, tag, meta, city_ids, key):
super(Weelo, self).__init__(tag, meta)
self.city_ids = city_ids
self.key = key
def update(self, scraper=None):
scr... |
_visible
def detect_wikkawiki(source_file, regexp):
if (not (os.path.isfile(source_file) and regexp)):
return
logging.debug('Dectecting WikkaWiki from: %s', source_file)
version = grep_from_file(source_file, regexp[0])
if (not version):
logging.debug('Could not find version from: %s', so... |
def test_perf_wrap(signed=True, n_word=8, repeat=10):
exec_time_vals = np.zeros(repeat)
for i in range(repeat):
start_time = time.time()
utils.wrap(np.random.uniform(low=(- 512), high=512, size=[1000, 2]), signed=signed, n_word=n_word)
exec_time_vals[i] = (time.time() - start_time)
p... |
def test_decimal_fixed_accommodates_precision():
'
schema = {'type': 'record', 'name': 'test_scale_is_an_int', 'fields': [{'name': 'field', 'type': {'name': 'fixed_decimal', 'logicalType': 'decimal', 'precision': 10, 'scale': 2, 'type': 'fixed', 'size': 2}}]}
with pytest.raises(SchemaParseException, match="... |
.integrationtest
.skipif((pymongo.version_tuple < (3, 0)), reason='New in 3.0')
def test_collection_find_one(instrument, elasticapm_client, mongo_database):
blogpost = {'author': 'Tom', 'text': 'Foo', 'date': datetime.datetime.utcnow()}
r = mongo_database.blogposts.insert_one(blogpost)
elasticapm_client.beg... |
class MonthByMonthCommitsJob(CompanyPushCommitsRankingJob):
REPORT_FACTORY = MBMCommitsFactory
def transform(self, df: DataFrame, **kwargs) -> DataFrame:
report_schema = self.report_cls.schema
return get_month_by_month_commits_amounts(df=df, commits_id_field=self.commits_schema.sha, datetime_fie... |
class Generator(nn.Module):
def __init__(self, latent_dim: int, feature_maps: int, image_channels: int) -> None:
super().__init__()
self.gen = Sequential(self._make_gen_block(latent_dim, (feature_maps * 8), kernel_size=4, stride=1, padding=0), self._make_gen_block((feature_maps * 8), (feature_maps *... |
class TestDialogues(ERC1155ClientTestCase):
def test_contract_api_dialogue(self):
contract_api_dialogue = ContractApiDialogue(DialogueLabel(('', ''), COUNTERPARTY_AGENT_ADDRESS, self.skill.skill_context.agent_address), self.skill.skill_context.agent_address, role=ContractApiDialogue.Role.AGENT)
with... |
class OptionSeriesAreaEvents(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._config(val... |
def withdraw(validator_index: num):
assert (self.current_epoch >= self.validators[validator_index].withdrawal_epoch)
prev_login_epoch = self.dynasty_start_epoch[self.validators[validator_index].dynasty_start]
prev_logout_epoch = self.dynasty_start_epoch[(self.validators[validator_index].dynasty_end + 1)]
... |
class TestReleaseCritpathMinKarma(BasePyTestCase):
.dict(config, {'critpath.min_karma': 2, 'f17.beta.critpath.min_karma': 42, 'f17.status': 'beta'})
def test_setting_status_min(self):
release = model.Release.query.first()
assert (release.critpath_min_karma == 42)
.dict(config, {'critpath.min... |
class OptionSeriesAreaSonificationTracksMappingRate(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._config... |
def class_book() -> Class:
return Class(name='ClassBook', members={0: ComplexTypeMember(size=32, name='title', offset=0, type=Pointer(Integer.char())), 4: ComplexTypeMember(size=32, name='num_pages', offset=4, type=Integer.int32_t()), 8: ComplexTypeMember(size=32, name='author', offset=8, type=Pointer(Integer.char(... |
class FipaDialogues(BaseFipaDialogues):
def __init__(self, self_address: Address, **kwargs) -> None:
def role_from_first_message(message: Message, receiver_address: Address) -> Dialogue.Role:
return FipaDialogue.Role.BUYER
BaseFipaDialogues.__init__(self, self_address=self_address, role_... |
class GetBlockHeadersExchange(BaseGetBlockHeadersExchange):
_normalizer = DefaultNormalizer(BlockHeaders, tuple, normalize_fn=(lambda res: res.payload.headers))
tracker_class = GetBlockHeadersTracker
_request_command_type = GetBlockHeaders
_response_command_type = BlockHeaders
async def __call__(sel... |
def test_en_tagger_attribute_ruler_lemma_contractions(NLP):
doc = NLP.make_doc("didn't")
doc[0].morph = MorphAnalysis(NLP.vocab, 'Mood=Ind|Tense=Past|VerbForm=Fin')
doc[0].tag_ = 'VBD'
doc[1].morph = MorphAnalysis(NLP.vocab, 'Polarity=Neg')
doc[1].tag_ = 'RB'
doc = NLP.get_pipe('attribute_ruler'... |
.django_db
def test_program_activity_count_success(client, monkeypatch, agency_account_data, helpers):
helpers.mock_current_fiscal_year(monkeypatch)
resp = client.get(url.format(code='007', filter=''))
assert (resp.status_code == status.HTTP_200_OK)
assert (resp.data['program_activity_count'] == 4)
... |
class TestQAACLFactory(base.BaseTestCase):
def test___acl__(self):
r = testing.DummyRequest()
r.registry.settings = {'mandatory_packager_groups': ['packagers'], 'qa_groups': ['fedora-ci-users']}
f = security.QAACLFactory(r)
acls = f.__acl__()
self.assertCountEqual(acls, [(All... |
class StructuredDatasetParamType(click.ParamType):
name = 'structured dataset path (dir/file)'
def convert(self, value: typing.Any, param: typing.Optional[click.Parameter], ctx: typing.Optional[click.Context]) -> typing.Any:
if isinstance(value, str):
return StructuredDataset(uri=value)
... |
.param_file((FIXTURE_PATH / 'sphinx_directives.md'))
def test_sphinx_directives(file_params, sphinx_doctree_no_tr: CreateDoctree):
if (file_params.title.startswith('SKIP') or file_params.title.startswith('SPHINX4-SKIP')):
pytest.skip(file_params.title)
sphinx_doctree_no_tr.set_conf({'extensions': ['myst... |
def get_logger(name: str, logger_class: Union[(Type[TLogger], None)]=None) -> TLogger:
if (logger_class is None):
return cast(TLogger, logging.getLogger(name))
else:
with _use_logger_class(logger_class):
manager = logging.Logger.manager
if (name in manager.loggerDict):
... |
def load_primary_xml(dirname):
packages = {}
hrefs = set()
names = set()
primary = glob.glob(os.path.join(dirname, '*primary*xml*'))[0]
xml_content = extract(primary)
dom = minidom.parseString(xml_content)
for d_package in dom.getElementsByTagName('package'):
name = d_package.getElem... |
def test_gh():
try:
from fpylll.numpy import dump_r
except ImportError:
return
for n in dimensions:
set_random_seed(n)
A = make_integer_matrix(n)
try:
M = GSO.Mat(A, float_type='ld')
except ValueError:
M = GSO.Mat(A, float_type='d')
... |
class Verbose(Command):
HELP = 'Prints or changes verbosity level, accepts integer or True/False'
CMD = ':verbose'
def __init__(self):
super(Verbose, self).__init__()
self._built_in = True
def run_interactive(self, cmd, args, raw):
ctx = context.get_context()
if args:
... |
def test_sign_and_recover_message(ethereum_private_key_file):
account = EthereumCrypto(ethereum_private_key_file)
sign_bytes = account.sign_message(message=b'hello')
assert (len(sign_bytes) > 0), 'The len(signature) must not be 0'
recovered_addresses = EthereumApi.recover_message(message=b'hello', signa... |
def test_block():
assert (unicodedata.block('\x00') == 'Basic Latin')
assert (unicodedata.block('\x7f') == 'Basic Latin')
assert (unicodedata.block('\x80') == 'Latin-1 Supplement')
assert (unicodedata.block('') == 'Georgian Extended')
assert (unicodedata.block('') == 'Arabic Extended-B')
assert ... |
class StateGraph(object):
def __init__(self, net):
self.net = net.copy()
self._todo = []
self._done = set([])
self._removed = set([])
self._state = {}
self._marking = {}
self._succ = {}
self._pred = {}
self._last = (- 1)
self._create_st... |
class StackableBaseEdge(BaseEdge):
char = 's'
description = 'Abstract Stackable class'
bottom = True
def __init__(self, boxes, settings, fingerjointsettings) -> None:
super().__init__(boxes, settings)
self.fingerjointsettings = fingerjointsettings
def __call__(self, length, **kw):
... |
class OptionSeriesPieSonificationTracksMappingTremoloDepth(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 JsPercentage(JsRecFunc):
def extendColumns(jsSchema, params):
if ((params[0] is not None) and (params[1] is not None)):
jsSchema['keys'] |= set(params[0])
jsSchema['values'] |= set(params[1])
alias = 'percentage'
params = ('keys', 'values')
value = ' \n if ((keys... |
def quadrupole3d_20(ax, da, A, bx, db, B, R):
result = numpy.zeros((6, 6, 1), dtype=float)
x0 = ((ax + bx) ** (- 1.0))
x1 = (x0 * ((ax * A[0]) + (bx * B[0])))
x2 = (- x1)
x3 = (x2 + R[0])
x4 = (x3 ** 2)
x5 = (3.0 * x0)
x6 = (x2 + A[0])
x7 = (x3 * x6)
x8 = (x0 * ((((- 2.0) * x1) +... |
class SceneManager(HasTraits):
scenes = Dict
figure_to_id = Dict
clients = List
call_later = Callable
def add_client(self, client):
self.clients.append(client)
def remove_client(self, client):
self.clients.remove(client)
def register_figure(self, figure):
remote = Rem... |
def get_endpoint_users(session, endpoint_id, users):
times = get_user_data_grouped(session, (lambda x: simplify(x, 100)), (Request.endpoint_id == endpoint_id))
first_requests = get_first_requests(session, endpoint_id)
return [{'user': u, 'date': get_value(first_requests, u), 'values': get_value(times, u), '... |
.only_on_targets(['bigquery'])
def test_wildcard_name_table_volume_anomalies(test_id: str, dbt_project: DbtProject):
utc_today = datetime.utcnow().date()
data = [{TIMESTAMP_COLUMN: cur_date.strftime(DATE_FORMAT)} for cur_date in generate_dates(base_date=utc_today) if (cur_date < (utc_today - timedelta(days=1)))... |
def CreateConv2dFwdOperator(manifest, operation_kind, out_element_op, out_data_op=''):
a_element_desc = library.TensorDesc(library.DataType.f16, library.LayoutType.G_NHW_C)
b_element_desc = library.TensorDesc(library.DataType.f16, library.LayoutType.G_K_YX_C)
c_element_desc = library.TensorDesc(library.Data... |
class Stats():
def __init__(self, binary):
self.binary = binary
self.corrects = dict()
self.errors = dict()
self.stated = False
def stat(self):
if (not self.stated):
self.stated = True
self.binary.nodes.stat()
self.binary.edges.stat()
... |
def gen_function_call(func_attrs, indent=' ', bias_ptr_arg=None):
a = func_attrs['inputs'][0]
ashapes = func_attrs['input_accessors'][0].original_shapes
b = func_attrs['inputs'][1]
bshapes = func_attrs['input_accessors'][1].original_shapes
c = func_attrs['outputs'][0]
cshapes = func_attrs['outp... |
def test_difference_with_two_frames_and_default_values(traces):
expected = _read('difference_result_frame2_10.npz')
frame = slice(None, 50)
frame_2 = slice(None, 10)
result = scared.preprocesses.high_order.Difference(frame_1=frame, frame_2=frame_2)(traces)
assert np.array_equal(expected, result) |
class TestValueCondition(ExcludeNoneMixin):
class Config():
arbitrary_types_allowed = True
use_enum_values = True
smart_union = True
eq: Optional[NumericApprox] = None
gt: Optional[NumericApprox] = None
gte: Optional[NumericApprox] = None
is_in: Optional[List[Union[(Numeric, ... |
.usefixtures('use_tmpdir')
def test_that_missing_report_steps_errors():
assert_that_config_leads_to_error(config_file_contents=dedent('\nNUM_REALIZATIONS 1\nGEN_DATA RFT_3-1_R_DATA INPUT_FORMAT:ASCII RESULT_FILE:RFT_3-1_R%d\n\n '), expected_error=ExpectedErrorInfo(match='REPORT_STEPS', line=3, column=1,... |
def clamp_f_f(gen, t, srcs):
smaller_than_one = gen.symbols.newLabel()
done = gen.symbols.newLabel()
one = ConstFloatArg(1.0)
zero = ConstFloatArg(0.0)
src = srcs[0]
dst = TempArg(gen.symbols.newTemp(Float), Float)
gen.emit_move(src, dst)
lte1 = gen.emit_binop('<=', [src, one], Float)
... |
def do_job(links_file, contigs_file, reference_file):
scaffolds = parse_links_file(links_file)
alignment = get_alignment(scaffolds, contigs_file, reference_file)
alignment = filter_by_coverage(alignment, 0.45)
alignment = join_collinear(alignment)
(entry_ord, chr_len, contig_len) = get_order(alignme... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.