code stringlengths 281 23.7M |
|---|
class SqlSelection(SqlFilter):
def create_view_statement(self, db, old_view, new_view):
conditions = []
for (k, v) in self.kwargs.items():
if ((v is None) or (v is cml.ALL)):
continue
name = entryname_to_dbname(k)
dbkey = db.dbkeys[name]
... |
def test_custom_sellmeier():
b1 = td.SpatialDataArray(np.random.random((Nx, Ny, Nz)), coords=dict(x=X, y=Y, z=Z))
c1 = td.SpatialDataArray(np.random.random((Nx, Ny, Nz)), coords=dict(x=X, y=Y, z=Z))
b2 = td.SpatialDataArray(np.random.random((Nx, Ny, Nz)), coords=dict(x=X, y=Y, z=Z))
c2 = td.SpatialDataA... |
def test_line_search():
ls = (True, False)
recalc = (None, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
results = list()
for key in it.product(ls, recalc):
(line_search, hessian_recalc) = key
(conv, cycs) = run_opt(line_search, hessian_recalc)
res = (line_search, hessian_recalc, conv, cycs)
... |
class Font(object):
def __init__(self, height=8, width=0, escapement=0, orientation=0, weight=0, italic=0, underline=0, strikeout=0, char_set=0, out_precision=0, clip_precision=0, quality=0, pitch_and_family=0, face_name='MS Shell Dlg'):
self.height = height
self.width = width
self.escapemen... |
class ImpalaAlgorithmConfig(AlgorithmConfig):
n_epochs: int
epoch_length: int
patience: int
critic_burn_in_epochs: int
n_rollout_steps: int
lr: float
gamma: float
policy_loss_coef: float
value_loss_coef: float
entropy_coef: float
max_grad_norm: float
device: str
queue... |
def _walk_subclasses(cls, indent=0):
if (cls.__module__ == '__main__'):
modname = 'puresnmp.types'
else:
modname = cls.__module__
cname = '.'.join([modname, cls.__qualname__])
ref = (':py:class:`%s`' % cname)
print('\n', (' ' * indent), '* ', ref)
for subclass in sorted(cls.__s... |
class OptionSeriesColumnpyramidSonificationDefaultspeechoptionsActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, ... |
def expand_languages_for_user(list_languages: list) -> list:
appended_list = []
for language in list_languages:
if (language == AUTO_DETECT):
appended_list.append(language)
continue
if ('-' in language):
if ('Unknown language' not in Language.get(language.spli... |
class Support(Skill):
associated_action = SupportAction
skill_category = ['character', 'active']
target = t_OtherOne()
usage = 'handover'
no_drop = True
no_reveal = True
def check(self):
cl = self.associated_cards
return (cl and all((((c.resides_in is not None) and (c.resides... |
def main():
print('\nmodule top(\n input wire in,\n output wire out\n);\n\nassign out = in;\n')
luts = LutMaker()
primitives_list = list()
for (tile_name, tile_type, site_name, site_type) in gen_sites('GTPE2_CHANNEL'):
params_list = list()
params_dict = dict()
params_dict['... |
def upgrade():
op.execute('alter type resourcetypes rename to resourcetypesold')
op.execute("create type resourcetypes as enum ('system', 'data_use', 'data_category', 'data_subject', 'privacy_declaration');")
op.execute('alter table plus_custom_field_definition alter column resource_type type resourcetypes ... |
def main():
logging.basicConfig(format=LOGGING_FORMAT)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
add_region(parser)
args = parser.parse_args()
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
assert d... |
class SampleGeneratorConfig(GeneratorConfig):
temperature: float = 1.0
top_k: int = 0
top_p: float = 1.0
def logits_transform(self) -> LogitsTransform:
transforms: List[LogitsTransform] = []
if (self.masked_pieces is not None):
transforms.append(VocabMaskTransform(self.masked... |
class ColorField(CharField):
default_validators = []
def __init__(self, *args, **kwargs):
self.samples = kwargs.pop('samples', None)
self.format = kwargs.pop('format', 'hex').lower()
if (self.format not in ['hex', 'hexa', 'rgb', 'rgba']):
raise ValueError(f'Unsupported color ... |
class MPCService(RunBinaryBaseService):
def __init__(self, container_svc: ContainerService, task_definition: str, mpc_game_svc: MPCGameService) -> None:
if ((container_svc is None) or (mpc_game_svc is None)):
raise ValueError(f'Dependency is missing. container_svc={container_svc}, mpc_game_svc={... |
class AddCredit(object):
def Field(cls, **kw):
return gh.Field(Player, id=gh.Int(required=True, description='ID'), jiecao=gh.Int(description=''), games=gh.Int(description=''), drops=gh.Int(description=''), resolver=cls.mutate, **kw)
def mutate(root, info, id, jiecao=0, games=0, drops=0):
ctx = i... |
class TestValidator(TestCase):
TEST_REGION = 'us-east-1'
TEST_REGION_AZS = ['us-east-1-bos-1a', 'us-east-1-chi-1a', 'us-east-1-dfw-1a']
TEST_VPC_ID = 'test_vpc_id'
TEST_PCE_ID = 'test_pce_id'
TEST_ACCOUNT_ID =
TEST_TASK_ROLE_NOT_RELATED_NAME = 'test_task_role_bad_name'
TEST_TASK_ROLE_NAME =... |
class OptionSeriesFunnel3dMarker(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 test_matmul_paper(golden):
NN = 128
MM = 128
KK = 128
gemmini = rename(matmul_algorithm(), 'matmul_on_gemmini')
gemmini = gemmini.partial_eval(NN, MM, KK)
gemmini = stage_mem(gemmini, 'for k in _: _', 'C[i, j]', 'res')
gemmini = bind_expr(gemmini, 'A[_]', 'a')
gemmini = bind_expr(gem... |
class Progress(Thread):
def __init__(self, event: Event, initial_message: str='') -> None:
super().__init__()
self.states = ['', '', '', '', '', '']
self.message = ''
self.finished = event
if (initial_message is not None):
self.update(initial_message)
def run(... |
class TestViews(SingleCreateApiTestCase, SingleUpdateApiTestCase, SingleDeleteApiTestCase, PaginationTestCase):
__test__ = True
ZenpyType = View
object_kwargs = dict(title='testView{}', all=[{'field': 'status', 'operator': 'less_than', 'value': 'solved'}])
api_name = 'views'
pagination_limit = 10
... |
def pathparse(value, sep=os.pathsep, os_sep=os.sep):
escapes = []
normpath = (ntpath.normpath if (os_sep == '\\') else posixpath.normpath)
if ('\\' not in (os_sep, sep)):
escapes.extend((('\\\\', '<ESCAPE-ESCAPE>', '\\'), ('\\"', '<ESCAPE-DQUOTE>', '"'), ("\\'", '<ESCAPE-SQUOTE>', "'"), (('\\%s' % s... |
class GodotWebSocketClient(webclient.WebSocketClient):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.protocol_key = 'godotclient/websocket'
def send_text(self, *args, **kwargs):
if args:
args = list(args)
text = args[0]
if... |
class OptionPlotoptionsPictorialSonificationTracksPointgrouping(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 main():
buttons = SpecialKeysMseButtons()
cids = print_cid_info(buttons)
print()
print_cid_reporting(buttons, cids)
print()
print('### REMAP CID 0xD0 TO 0x53 ###')
buttons.set_cid_reporting(208, False, False, True, True, False, False, 83)
print()
print_cid_reporting(buttons, cids... |
class ModulationSpec(Tidy3dBaseModel):
permittivity: SpaceTimeModulation = pd.Field(None, title='Space-time modulation of relative permittivity', description='Space-time modulation of relative permittivity at infinite frequency applied on top of the base permittivity at infinite frequency.')
conductivity: Space... |
def choose_master_channel(data: DataModel):
(channel_names, channel_ids) = data.get_master_lists()
list_widget = KeyValueBullet(prompt=_('1. Choose master channel'), choices=channel_names, choices_id=channel_ids)
default_idx = None
default_instance = ''
if (('master_channel' in data.config) and data... |
class TransactionsTests(N26TestBase):
_requests(method=GET, response_file='transactions.json')
def test_transactions_cli(self):
from n26.cli import transactions
result = self._run_cli_cmd(transactions, ['--from', '01/30/2019', '--to', '30.01.2020'])
self.assertIsNotNone(result.output) |
def step3():
with open('../local.settings.json') as fd:
settings = json.load(fd)
connectionString = settings['Values']['AzureWebJobsStorage']
container_name = 'opengameart'
with open('allblobs2.txt') as fd:
files = []
sizes = []
for line in fd.readlines():
(fn... |
.parallel
.parametrize(('MeshClass', 'hdiv_family'), [(UnitIcosahedralSphereMesh, 'BDM'), (UnitCubedSphereMesh, 'RTCF')])
def test_hybrid_conv_parallel(MeshClass, hdiv_family):
errors = [run_hybrid_poisson_sphere(MeshClass, r, hdiv_family) for r in range(2, 5)]
errors = np.asarray(errors)
l2conv = np.log2((... |
class CREDHIST_ENTRY(Structure):
structure = (('Version', '<L=0'), ('HashAlgo', '<L=0'), ('Rounds', '<L=0'), ('SidLen', '<L=0'), ('_Sid', '_-Sid', 'self["SidLen"]'), ('CryptAlgo', '<L=0'), ('shaHashLen', '<L=0'), ('ntHashLen', '<L=0'), ('Salt', '16s=b'), ('Sid', ':'), ('_data', '_-data', '(self["shaHashLen"]+self["... |
def test_attributedict_dict_in_list_in_dict():
data = {'instructions': [0, 1, 'neither shalt thou count, excepting that thou then proceedeth to three', {'if_naughty': 'snuff it'}, 'shalt thou not count', 'right out']}
attrdict = AttributeDict.recursive(data)
assert (attrdict.instructions[3].if_naughty == 's... |
class H2Protocol(asyncio.Protocol):
def __init__(self, upstream_resolver=None, upstream_port=None, uri=None, logger=None, debug=False, ecs=False):
config = H2Configuration(client_side=False, header_encoding='utf-8')
self.conn = H2Connection(config=config)
self.logger = logger
if (log... |
class WebSocketTestSession():
def __init__(self, app: ASGI3App, scope: Scope, portal_factory: _PortalFactoryType) -> None:
self.app = app
self.scope = scope
self.accepted_subprotocol = None
self.portal_factory = portal_factory
self._receive_queue: 'queue.Queue[Message]' = que... |
def test_task_node_metadata():
task_id = identifier.Identifier(identifier.ResourceType.TASK, 'project', 'domain', 'name', 'version')
wf_exec_id = identifier.WorkflowExecutionIdentifier('project', 'domain', 'name')
node_exec_id = identifier.NodeExecutionIdentifier('node_id', wf_exec_id)
te_id = identifie... |
def rank_quadgrams(corpus, metric, path=None):
ngrams = QuadgramCollocationFinder.from_words(corpus.words())
scored = ngrams.score_ngrams(metric)
if path:
with open(path, 'w') as f:
f.write('Collocation\tScore ({})\n'.format(metric.__name__))
for (ngram, score) in scored:
... |
def d2q_rd1(m0, m1, m2, o0, o1, o2, p0, p1, p2, n0, n1, n2):
x0 = (m0 - o0)
x1 = (- x0)
x2 = (n0 - p0)
x3 = (x2 ** 2)
x4 = (n1 - p1)
x5 = (x4 ** 2)
x6 = (n2 - p2)
x7 = (x6 ** 2)
x8 = ((x3 + x5) + x7)
x9 = (1 / math.sqrt(x8))
x10 = (x0 ** 2)
x11 = (m1 - o1)
x12 = (x11 ... |
class RSProxyDataManager(object):
def __init__(self):
self.data = []
def load(self, path):
import json
with open(path, 'r') as f:
data = json.load(f)
for i in range(len(data['instance_file'])):
data_obj = RSProxyDataObject()
self.data.append(da... |
class BaseTransaction(LegacyTransactionFieldsAPI, BaseTransactionFields, SignedTransactionMethods, TransactionBuilderAPI):
fields = BASE_TRANSACTION_FIELDS
def decode(cls, encoded: bytes) -> SignedTransactionAPI:
return rlp.decode(encoded, sedes=cls)
def encode(self) -> bytes:
return rlp.enc... |
def test_normalize_smallest_h5(capsys):
outfile_one = NamedTemporaryFile(suffix='.h5', delete=False)
outfile_one.close()
outfile_two = NamedTemporaryFile(suffix='.h5', delete=False)
outfile_two.close()
args = '--matrices {} {} --normalize smallest -o {} {}'.format(matrix_one_h5, matrix_two_h5, outfi... |
def train_model():
(model, weights_file, start_iter, checkpoints, output_dir) = create_model()
if ('final' in checkpoints):
return checkpoints
setup_model_for_training(model, weights_file, output_dir)
training_stats = TrainingStats(model)
CHECKPOINT_PERIOD = int((cfg.TRAIN.SNAPSHOT_ITERS / c... |
class BodyLevel(BodyElement):
VALIDATE_ONLY_BOOLEAN_OR_STR = False
def __init__(self):
self.bodyElements = []
def __repr__(self):
return ('%s( bodyElements = %s )' % (self.__class__.__name__, repr(self.bodyElements)))
def appendBodyElement(self, bodyElement):
self.bodyElements.ap... |
.django_db
def test_really_old_transaction(client, agency_data):
TransactionNormalized.objects.update(fiscal_year=(fy(settings.API_SEARCH_MIN_DATE) - 1))
resp = client.get(URL.format(code='001', filter=''))
assert (resp.status_code == status.HTTP_200_OK)
assert (resp.data['toptier_code'] == '001')
a... |
class FBHeapFromCommand(fb.FBCommand):
def name(self):
return 'heapfrom'
def description(self):
return 'Show all nested heap pointers contained within a given variable.'
def run(self, arguments, options):
var = self.context.frame.var(arguments[0])
if ((not var) or (not var.Is... |
class ChannelWebSocket(Channel):
def __init__(self, ws: WebSocket):
self._ws: WebSocket = ws
def close(self):
self._ws.close()
def send_message(self, message: Any):
if self._ws.closed:
raise ChannelError('Unable to send data to the remote host (not connected)')
tr... |
def test_source_code_renderer():
renderer = SourceCodeRenderer()
source_code = "def hello_world():\n print('Hello, world!')"
result = renderer.to_html(source_code)
assert ('hello_world' in result)
assert ('Hello, world!' in result)
assert ('#ffffff' in result)
assert ('#fff0f0' not in res... |
def create_log_config_set_mask(equip_id, last_item, *bits):
diag_log_config_mask_header = struct.pack('<LLLL', DIAG_LOG_CONFIG_F, LOG_CONFIG_SET_MASK_OP, equip_id, last_item)
diag_log_config_mask_payload = bytearray((b'\x00' * bytes_reqd_for_bit(last_item)))
for bit in bits:
if (bit > last_item):
... |
.parametrize('subcommand', SUB_COMMANDS)
def test_subcommand_with_no_nodes(subcommand, kubeflow_pipelines_runtime_instance):
if (subcommand == 'describe'):
return
runner = CliRunner()
with runner.isolated_filesystem():
pipeline_file = 'pipeline_with_zero_nodes.pipeline'
pipeline_file... |
def _vm_backup_cb_failed(result, task_id, bkp, action, vm=None):
if (action == 'POST'):
bkp.delete()
bkp.update_zpool_resources()
elif (action == 'PUT'):
bkp.status = bkp.OK
bkp.save_status()
vm.revert_notready()
elif (action == 'DELETE'):
bkp.status = bkp.OK
... |
def extractArcanedreamOrg(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 tag... |
(scope='function')
def segment_erasure_data(segment_connection_config, segment_erasure_identity_email) -> str:
segment_secrets = segment_connection_config.secrets
if (not segment_identity_email):
return
api_domain = segment_secrets['api_domain']
user_token = segment_secrets['user_token']
fak... |
class TestStripQuery(unittest.TestCase):
def test_strip_query(self):
url = '
expected = '
self.assertEqual(strip_query(url), expected)
def test_preserve_nice_query(self):
url = '
expected = url
self.assertEqual(strip_query(url), expected)
def test_preserve_aut... |
def test_dispatch_to_response_pure_notification_invalid_params_auto() -> None:
def foo(colour: str, size: str) -> Result:
return Success()
assert (dispatch_to_response_pure(deserializer=default_deserializer, validator=default_validator, post_process=identity, context=NOCONTEXT, methods={'foo': foo}, req... |
class TestIndia(unittest.TestCase):
def test_read_datetime_from_span_id(self):
html_span = '<p><span id="lbldate">9/4/2017 5:17:00 PM</span></p>'
html = BeautifulSoup(html_span, 'html.parser')
india_date_time = IN.read_datetime_from_span_id(html, 'lbldate', 'D/M/YYYY h:mm:ss A')
self... |
class TestCreateDataStreamParamSource():
def test_create_data_stream(self):
source = params.CreateDataStreamParamSource(track.Track(name='unit-test'), params={'data-stream': 'test-data-stream'})
assert (source.params() == {'data-stream': 'test-data-stream', 'data-streams': ['test-data-stream'], 'req... |
class MeterStats(base_tests.SimpleProtocol):
def runTest(self):
request = ofp.message.meter_stats_request(meter_id=ofp.OFPM_ALL)
logging.info('Sending meter stats request')
stats = get_stats(self, request)
logging.info('Received %d meter stats entries', len(stats))
for entry ... |
_view(('GET',))
_data(permissions=(IsAdminOrReadOnly,))
_required('VMS_VM_SNAPSHOT_ENABLED')
def vm_define_snapshot_list_all(request, data=None):
extra = output_extended_snap_count(request, data)
snap_define = SnapshotDefine.objects.select_related('vm', 'periodic_task', 'periodic_task__crontab').filter(vm__in=g... |
class BenchThread(threading.Thread):
def __init__(self, event, wait_event):
threading.Thread.__init__(self)
self.counter = 0
self.event = event
self.wait_event = wait_event
def run(self):
while (self.counter <= CONTEXT_SWITCHES):
self.wait_event.wait()
... |
class TestAny(unittest.TestCase):
def test_default_default(self):
class A(HasTraits):
foo = Any()
a = A()
self.assertEqual(a.foo, None)
def test_list_default(self):
message_pattern = "a default value of type 'list'.* will be shared"
with self.assertWarnsRegex(... |
def _test_correct_response_for_time_period(client):
resp = client.post('/api/v2/search/spending_by_award', content_type='application/json', data=json.dumps({'filters': {'award_type_codes': ['A'], 'time_period': [{'start_date': '2014-01-01', 'end_date': '2008-12-31'}]}, 'fields': ['Award ID'], 'page': 1, 'limit': 60... |
class ConsumptionTestCase(unittest.TestCase):
def test_positive_consumption(self):
self.assertFalse(validate_consumption(c1, 'FR'), msg='Positive consumption is fine!')
def test_negative_consumption(self):
with self.assertRaises(ValueError, msg='Negative consumption is not allowed!'):
... |
.parametrize('types, expected', (({'Person': [{'name': 'name', 'type': 'string'}]}, 'Person'), ({'Person': [{'name': 'name', 'type': 'string'}], 'Mail': [{'name': 'from', 'type': 'Person'}]}, 'Mail'), ({'Person': [{'name': 'name', 'type': 'string'}, {'name': 'friend', 'type': 'Person'}]}, 'Person'), ({'Person': [{'name... |
class Crypt(Validator):
def __init__(self, key=None, algorithm='pbkdf2(1000,20,sha512)', salt=True, message=None):
super().__init__(message=message)
self.key = key
self.digest_alg = algorithm
self.salt = salt
def __call__(self, value):
if getattr(value, '_emt_field_hashed... |
class BaseIntegrityValueTest(ConditionFromReferenceMixin[DatasetSummary], ABC):
group: ClassVar = DATA_INTEGRITY_GROUP.id
_metric: DatasetSummaryMetric
def __init__(self, eq: Optional[NumericApprox]=None, gt: Optional[Numeric]=None, gte: Optional[Numeric]=None, is_in: Optional[List[Union[(Numeric, str, bool... |
def job_viz(jobs: typing.List[job.Job]) -> str:
result = ''
result += '1'
for i in range(0, 8):
result += n_to_char(n_at_ph(jobs, job.Phase(1, i)))
result += '2'
for i in range(0, 8):
result += n_to_char(n_at_ph(jobs, job.Phase(2, i)))
result += '3'
for i in range(0, 7):
... |
class EmptyImporter(object):
def __init__(self, session, readonly_session, model, dao, _, *args, **kwargs):
del args, kwargs
self.session = session
self.readonly_session = readonly_session
self.model = model
self.dao = dao
def run(self):
self.session.add(self.mode... |
class ReflectionService(object):
def GetAuthnDescriptor(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None):
return grpc.experimental.unary_unary(request, target, '/cosmos.base.reflection.v2alpha1.R... |
(custom_vjp, nondiff_argnums=tuple(range(1, 6)))
def run_local(simulation: JaxSimulation, task_name: str, folder_name: str='default', path: str='simulation_data.hdf5', callback_url: str=None, verbose: bool=True) -> JaxSimulationData:
(sim_tidy3d, jax_info) = simulation.to_simulation()
sim_data_tidy3d = tidy3d_r... |
def upsert_entry(database_connection: Connection, warning_messages_table: Table, code: int, message: str) -> None:
warning = database_connection.execute(warning_messages_table.select().where((warning_messages_table.c.code == code))).first()
if (warning and (warning.message != message)):
database_connect... |
def upgrade_from_old_version(app):
if app.config['migrate_from_0_3_2']:
if app.is_old_database():
click.echo('Upgrading from old Stellar version...')
def after_rename(old_name, new_name):
click.echo(('* Renamed %s to %s' % (old_name, new_name)))
app.update... |
def test_Monitor_init():
config = get_test_config()
sdnc = SDNConnect(config, logger, prom, faucetconfgetsetter_cl=FaucetLocalConfGetSetter)
sdne = SDNEvents(logger, prom, sdnc)
monitor = Monitor(logger, config, schedule, sdne.job_queue, sdnc, prom)
hosts = [{'active': 0, 'source': 'poseidon', 'role... |
class Event(object):
match_regex = re.compile('^Event: .*', re.IGNORECASE)
parsers = {}
def register_parser(*event_name):
def wrapper(parser):
for name in event_name:
Event.parsers[name] = parser
return wrapper
def read(event):
lines = event.splitlines... |
class WorkflowExecutionMeta(Base):
__tablename__ = 'workflow_execution'
id = Column(Integer, autoincrement=True, primary_key=True)
workflow_id = Column(Integer, ForeignKey('workflow.id'))
begin_date = Column(DateTime)
end_date = Column(DateTime)
status = Column(String(256))
run_type = Column... |
def test_goerli_eip1085_matches_goerli_chain(goerli_genesis_config):
genesis_data = extract_genesis_data(goerli_genesis_config)
genesis_state = {address: account.to_dict() for (address, account) in genesis_data.state.items()}
genesis_params = genesis_data.params.to_dict()
chain = Chain.configure(vm_conf... |
def _escape(value: Any) -> str:
if isinstance(value, (list, tuple)):
value = ','.join([_escape(item) for item in value])
elif isinstance(value, (date, datetime)):
value = value.isoformat()
elif isinstance(value, bool):
value = str(value).lower()
elif isinstance(value, bytes):
... |
def single_line_beta_description(schema_or_field: FieldEntry, strict: Optional[bool]=True) -> None:
if ('\n' in schema_or_field['field_details']['beta']):
msg: str = 'Beta descriptions must be single line.\n'
msg += f"Offending field or field set: {schema_or_field['field_details']['name']}"
... |
def addWidget(type, parent=None, cpos=0, rpos=0, **kwargs):
cspan = kwargs.pop('colspan', None)
rspan = kwargs.pop('rowspan', None)
if (type == 'combo'):
widget = Combobox(parent, textvariable=kwargs.pop('textvariable', None))
if ('bind' in kwargs):
widget.bind('<<ComboboxSelecte... |
class PathMatcher(object):
def __init__(self, include_patterns, omit_patterns):
self.include_patterns = include_patterns
self.omit_patterns = omit_patterns
def omit(self, path):
path = os.path.realpath(path)
return (any((fnmatch.fnmatch(path, p) for p in self.omit_patterns)) or (... |
def llvm_build_bin_dir(tool):
build_dir = llvm_build_dir(tool)
if (WINDOWS and ('Visual Studio' in CMAKE_GENERATOR)):
old_llvm_bin_dir = os.path.join(build_dir, 'bin', decide_cmake_build_type(tool))
new_llvm_bin_dir = None
default_cmake_build_type = decide_cmake_build_type(tool)
... |
class CollapseCodeExtension(BlocksExtension):
def __init__(self, *args, **kwargs):
self.config = {'expand_text': ['Expand', 'Set the text for the expand button.'], 'collapse_text': ['Collapse', 'Set the text for the collapse button.'], 'expand_title': ['expand', 'Set the text for the expand title.'], 'colla... |
class CommonSegCode(CommonSegGroup):
def __init__(self, rom_start: Optional[int], rom_end: Optional[int], type: str, name: str, vram_start: Optional[int], args: list, yaml):
self.bss_size: int = (yaml.get('bss_size', 0) if isinstance(yaml, dict) else 0)
super().__init__(rom_start, rom_end, type, nam... |
def create_organisations(random):
for regtm_ix in range(5):
regtm = RegionalTeam.objects.create(code='Y0{}'.format(regtm_ix), name='Region {}'.format(regtm_ix))
for stp_ix in range(5):
stp = STP.objects.create(code='E{}{}'.format(regtm_ix, stp_ix), name='STP {}/{}'.format(regtm_ix, stp_i... |
class TestComposerThread__determine_tag_actions(ComposerThreadBaseTestCase):
('bodhi.server.models.buildsys.get_session')
def test_from_tag_not_found(self, get_session):
tags = ['some', 'unknown', 'tags']
get_session.return_value.listTags.return_value = [{'name': n} for n in tags]
task =... |
def test_mask_arguments_null_list():
configuration = AesEncryptionMaskingConfiguration()
masker = AesEncryptionMaskingStrategy(configuration)
expected = [None]
cache_secrets()
masked = masker.mask([None], request_id)
assert (expected == masked)
clear_cache_secrets(request_id) |
class pool2d_base(Operator):
def __init__(self, stride, pad, kernel_size, reduce_func) -> None:
super().__init__()
self._attrs['op'] = 'pool2d'
self._attrs['stride'] = stride
self._attrs['pad'] = pad
self._attrs['reduce_func'] = reduce_func
self._attrs['kernel_size'] ... |
class CatalogTable(object):
def __init__(self, data, columns):
self.data = data
self.columns = columns
def as_list_of_dicts(self):
R = []
for r in self.data:
d = {}
for (i, c) in enumerate(self.columns):
d[c] = r[i]
R += [d]
... |
def run_all(joblist):
run_id = 'run_all'
context = SubstitutionList.from_dict({'DEFINE': [['<RUNPATH>', './']]})
data = ErtConfig(forward_model_list=set_up_forward_model(joblist), substitution_list=context).forward_model_data_to_json(run_id)
verify_json_dump(joblist, data, range(len(joblist)), run_id) |
def olar(nome: str=Argument(..., help='Seu primeiro nome', callback=lower), email: str=Argument(..., metavar='<email>'), senha: str=Option(..., prompt=True, hide_input=True, confirmation_prompt=True, help='A senha sera perguntada no prompt!'), version: bool=Option(False, '--version', '-v', '--versao', callback=version,... |
def lines(geom, **kwargs):
if (geom['type'] == 'LineString'):
return linestring(geom['coordinates'], **kwargs)
if (geom['type'] == 'MultiLineString'):
return multilinestring(geom['coordinates'], **kwargs)
raise SvgisError(('Unexpected geometry type. Expected LineString or MultiLineString, bu... |
('pyscf')
def test_geometry_get_restart_info():
geom = geom_loader('lib:benzene.xyz')
calc = PySCF(method='scf', basis='def2svp')
geom.set_calculator(calc)
restart = geom.get_restart_info()
atoms = restart['atoms']
coords = restart['cart_coords']
assert (atoms == geom.atoms)
assert (len(... |
class ShardedFileComponents():
def __init__(self, filepattern) -> None:
(self.directory, root) = os.path.split(filepattern)
m = re.match('([^]+)([^.]+)(\\.[^.]*)?$', root)
if (not m):
raise ValueError('Not a sharded file: {}'.format(filepattern))
self.extension: str = (m.... |
class TestPrismaticSerialize(util.ColorAssertsPyTest):
COLORS = [('color(--prismatic 0 0.3 0.75 0.5 / 0.5)', {}, 'color(--prismatic 0 0.3 0.75 0.5 / 0.5)'), ('color(--prismatic 0 0.3 0.75 0.5)', {'alpha': True}, 'color(--prismatic 0 0.3 0.75 0.5 / 1)'), ('color(--prismatic 0 0.3 0.75 0.5 / 0.5)', {'alpha': False}, ... |
def test_filter_by_nonexistent_identity_reference():
identity_data: Dict[(str, Any)] = {'phone_number': '123-1234-1235'}
config = FilterPostProcessorConfiguration(field='email_contact', value={'identity': 'email'})
data = [{'id': , 'email_contact': '', 'name': 'Somebody Awesome'}, {'id': , 'email_contact': ... |
class AbstractFieldMonitor(Monitor, ABC):
fields: Tuple[(EMField, ...)] = pydantic.Field(['Ex', 'Ey', 'Ez', 'Hx', 'Hy', 'Hz'], title='Field Components', description='Collection of field components to store in the monitor.')
interval_space: Tuple[(pydantic.PositiveInt, pydantic.PositiveInt, pydantic.PositiveInt)... |
def test_ref_task_more_2():
_task(project='flytesnacks', domain='development', name='recipes.aaa.simple.join_strings', version='553018f39e519bdb2597b652639c30ce16b99c79')
def ref_t1(a: typing.List[str]) -> str:
...
_task(project='flytesnacks', domain='development', name='recipes.aaa.simple.join_stri... |
class EntityExtractor(BaseEstimator, TransformerMixin):
def __init__(self, labels=GOODLABELS, **kwargs):
self.labels = labels
def get_entities(self, document):
entities = []
for paragraph in document:
for sentence in paragraph:
trees = ne_chunk(sentence)
... |
def test_form_args_embeddeddoc():
(app, db, admin) = setup()
class Info(db.EmbeddedDocument):
name = db.StringField()
age = db.StringField()
class Model(db.Document):
info = db.EmbeddedDocumentField('Info')
timestamp = db.DateTimeField()
view = CustomModelView(Model, form... |
def fetch_exchange(zone_key1, zone_key2, session=None, target_datetime=None, logger=None) -> dict:
exchange_data = get_data(exchange_url, target_datetime)
exchange_dataframe = create_exchange_df(exchange_data)
if ('->'.join(sorted([zone_key1, zone_key2])) == 'GB->GB-NIR'):
moyle = moyle_processor(ex... |
def launch(main_func, num_gpus_per_machine, num_machines=1, machine_rank=0, dist_url=None, args=(), timeout=DEFAULT_TIMEOUT):
world_size = (num_machines * num_gpus_per_machine)
args[0].distributed = (world_size > 1)
if args[0].distributed:
if (dist_url == 'auto'):
assert (num_machines ==... |
class Fixed(Raw):
def __init__(self, decimals=5, **kwargs):
super(Fixed, self).__init__(**kwargs)
self.precision = MyDecimal((('0.' + ('0' * (decimals - 1))) + '1'))
def format(self, value):
dvalue = MyDecimal(value)
if ((not dvalue.is_normal()) and (dvalue != ZERO)):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.