code stringlengths 281 23.7M |
|---|
class Test_reply_egress_tlv(unittest.TestCase):
def setUp(self):
self._type = cfm.CFM_REPLY_EGRESS_TLV
self.length = 12
self.action = 2
self.mac_address = 'aa:bb:cc:56:34:12'
self.port_id_length = 3
self.port_id_subtype = 2
self.port_id = b'\x01\x04\t'
... |
class OptionSeriesItemPointEvents(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 PostConversationOperator(BaseConversationOperator, MapOperator[(ModelOutput, ModelOutput)]):
def __init__(self, **kwargs):
MapOperator.__init__(self, **kwargs)
async def map(self, input_value: ModelOutput) -> ModelOutput:
storage_conv: StorageConversation = (await self.get_storage_conversa... |
class AsyncioThriftClient(ServiceObj):
_TIMEOUT = 60
def __init__(self, client_class, host, port, service=None, timeout=None, open_timeout=None):
super().__init__(service)
self._client_class = client_class
self._host = host
self._port = port
self._connected = False
... |
class NodeFactory(factory.Factory):
class Meta():
model = Node.from_pubkey_and_addr
pubkey = factory.LazyFunction(PublicKeyFactory)
address = factory.SubFactory(AddressFactory)
def with_nodeid(cls, nodeid: int, *args: Any, **kwargs: Any) -> NodeAPI:
node = cls(*args, **kwargs)
no... |
class Report(BaseReport):
def __init__(self, date: datetime):
self.date = date
def full_name(self) -> str:
return self._get_name_with_date(self.date)
def url(self) -> str:
return DataLake().public.get_report_url(report_name=self.name, date=self.date)
def path(self) -> str:
... |
class IPView(ip.IPythonView):
__text_color = None
__background_color = None
__font = None
__css_provider = None
__text_color_str = None
__background_color_str = None
__font_str = None
__iptheme = None
def __init__(self, namespace):
ip.IPythonView.__init__(self)
event.... |
class TVTKClassChooser(HasTraits):
object = Property
class_name = Str('', desc='class name of TVTK class (case sensitive)')
search = Str('', desc='string to search in TVTK class documentation supports the "and" and "or" keywords. press <Enter> to start search. This is case insensitive.')
clear_search = ... |
class OptionPlotoptionsSeriesStatesInactive(Options):
def animation(self) -> 'OptionPlotoptionsSeriesStatesInactiveAnimation':
return self._config_sub_data('animation', OptionPlotoptionsSeriesStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bo... |
class TestCreateCustomToken():
valid_args = {'Basic': (MOCK_UID, {'one': 2, 'three': 'four'}), 'NoDevClaims': (MOCK_UID, None), 'EmptyDevClaims': (MOCK_UID, {})}
invalid_args = {'NoUid': (None, None, ValueError), 'EmptyUid': ('', None, ValueError), 'LongUid': (('x' * 129), None, ValueError), 'BoolUid': (True, N... |
.parametrize('SKs,messages', [(list(range(1, 6)), list(range(1, 6)))])
def test_core_aggregate_verify(SKs, messages):
PKs = [G2Basic.SkToPk(sk) for sk in SKs]
messages = [bytes(msg) for msg in messages]
signatures = [G2Basic._CoreSign(sk, msg, G2Basic.DST) for (sk, msg) in zip(SKs, messages)]
aggregate_... |
class Solution(object):
def decodeAtIndex(self, S, K):
(clens, clen) = ([], 0)
first_num_idx = (- 1)
for (idx, ch) in enumerate(S):
res = (ord(ch) - ord('0'))
if (0 <= res <= 10):
if (first_num_idx < 0):
first_num_idx = idx
... |
class EasyForm(Form):
name = TextField('name', validators=[wtforms.validators.DataRequired()], default=u'test')
email = TextField('email', validators=[wtforms.validators.Email(), wtforms.validators.DataRequired()])
message = TextAreaField('message', validators=[wtforms.validators.DataRequired()]) |
class Ban(BaseObject):
def __init__(self, api=None, ip_address=None, visitor=None, **kwargs):
self.api = api
self.ip_address = ip_address
self.visitor = visitor
for (key, value) in kwargs.items():
setattr(self, key, value)
for key in self.to_dict():
if... |
_defaults()
class BadgeFieldFormSchema(Schema):
class Meta():
type_ = 'badge-field-form'
self_view = 'v1.badge_field_form_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
badge_field_id = fields.Integer(dump_only=True)
badge_form = Relationship(self_view='v1.badg... |
class ApiToken(Base):
__tablename__ = 'tokens'
token = sa.Column(sa.String(40), default=_api_token_generator, primary_key=True)
created = sa.Column(sa.DateTime, default=datetime.datetime.utcnow, nullable=False)
user_id = sa.Column(GUID, sa.ForeignKey('users.id'), nullable=False)
user = sa.orm.relati... |
class OptionSeriesArcdiagramAccessibility(Options):
def description(self):
return self._config_get(None)
def description(self, text: str):
self._config(text, js_type=False)
def descriptionFormat(self):
return self._config_get(None)
def descriptionFormat(self, text: str):
... |
def vector_test_argsets():
argsets = [ReplaceTestArgs(TestFunction(Vv), {}, None), ReplaceTestArgs(TestFunction(V0), {}, ValueError), ReplaceTestArgs(TestFunction(Vv), {'new_idx': 0}, ValueError), ReplaceTestArgs(TestFunction(Wv), {'new_idx': 0}, None), ReplaceTestArgs(TestFunction(Wv), {'new_idx': 1}, ValueError),... |
class InvitationResponseAllOf(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
lazy_impor... |
class SnapshotClient(NamespacedClient):
_rewrite_parameters()
async def cleanup_repository(self, *, name: str, error_trace: t.Optional[bool]=None, filter_path: t.Optional[t.Union[(str, t.Sequence[str])]]=None, human: t.Optional[bool]=None, master_timeout: t.Optional[t.Union[('t.Literal[-1]', 't.Literal[0]', str... |
class SatisfactionRating(BaseObject):
def __init__(self, api=None, assignee_id=None, created_at=None, group_id=None, id=None, requester_id=None, score=None, ticket_id=None, updated_at=None, url=None, **kwargs):
self.api = api
self.assignee_id = assignee_id
self.created_at = created_at
... |
class ViewSetIntegrationTests(TestCase):
def setUp(self):
self.list = BasicViewSet.as_view({'get': 'list'})
self.create = BasicViewSet.as_view({'post': 'create'})
def test_get_succeeds(self):
request = factory.get('/')
response = self.list(request)
assert (response.status... |
def test_apply_transaction(chain, funded_address, funded_address_private_key, funded_address_initial_balance):
vm = chain.get_vm()
recipient = decode_hex('0xa94f5374fce5edbc8e2a8697ce6ebf0c')
amount = 100
from_ = funded_address
tx = new_transaction(vm, from_, recipient, amount, funded_address_privat... |
.xfail(raises=ImageComparisonFailure, reason='Matplotlib plots for reasons a different image size.')
def test_plot_single_point_two_matrices():
outfile = NamedTemporaryFile(suffix='.png', prefix='viewpoint1', delete=False)
matrix = ((((ROOT + 'Li_et_al_2015.h5') + ' ') + ROOT) + 'Li_et_al_2015_twice.h5')
ar... |
class Translator(PyTranslator):
ParseTree = ParseTree
parser = parser
ST = ast
def do_file_input(self, st, ctx):
return self.do(st[0])
def do_abcd_main(self, st, ctx):
expr = (len(st) - 1)
for (i, child) in enumerate(st):
if (child.symbol == 'abcd_expr'):
... |
(Output('api-connections', 'children'), [Input('submit-settings-button', 'n_clicks')])
def update_api_connection_status(n_clicks):
if (n_clicks and (n_clicks > 0)):
return html.Div(children=[html.Div(className='row ', children=[check_oura_connection()]), html.Div(className='row', children=[check_strava_conn... |
('aea.cli.registry.login.request_api', return_value={'key': 'key'})
class RegistryLoginTestCase(TestCase):
def test_registry_login_positive(self, request_api_mock):
result = registry_login('username', 'password')
expected_result = 'key'
self.assertEqual(result, expected_result)
reque... |
def extractIncaroseJealousyMTL(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
chp_prefixes = [('konyaku haki? yoroshi. naraba, fukushuda! chapter ', 'Konyaku haki? Yoroshi. Naraba... |
.slow
.skipif((not has_hf_transformers), reason='requires huggingface transformers')
.skipif((not has_torch_compile), reason='requires torch.compile')
.parametrize('torch_device', TORCH_DEVICES)
.parametrize('with_torch_sdp', [False, True])
def test_encoder_with_torch_compile(torch_device, with_torch_sdp):
assert_e... |
.unit_saas
class TestAuthenticatedClient():
.object(Session, 'send')
def test_client_returns_ok_response(self, send, test_authenticated_client, test_saas_request, test_config_dev_mode_disabled):
test_response = Response()
test_response.status_code = 200
send.return_value = test_response
... |
def send_closure(sock, hdrlen, fmts):
def send_msg(msg, fmt=None, packed=False):
if (not packed):
if (fmt == 'floats'):
msg = struct.pack(fmts[fmt], *msg)
elif (fmt is not None):
msg = struct.pack(fmts[fmt], msg)
else:
msg =... |
class ValveAddPortTrafficTestCase(ValveTestBases.ValveTestNetwork):
REQUIRE_TFM = False
CONFIG = '\ndps:\n s1:\n dp_id: 1\n hardware: Generic\n interfaces:\n p1:\n number: 1\n tagged_vlans: [0x100]\n p2:\n number: 2\n ... |
class SOEFException(Exception):
def warning(cls, msg: str, logger: logging.Logger=_default_logger) -> 'SOEFException':
logger.warning(msg)
return cls(msg)
def debug(cls, msg: str, logger: logging.Logger=_default_logger) -> 'SOEFException':
logger.debug(msg)
return cls(msg)
de... |
def extractPopularwebnovelBlogspotCom(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_... |
def extractNovelcvCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
return None
tagmap = []
for (tagname, name, tl_type) in tagmap:
if (tagname in item['tags']):
... |
class OptionSeriesLineStates(Options):
def hover(self) -> 'OptionSeriesLineStatesHover':
return self._config_sub_data('hover', OptionSeriesLineStatesHover)
def inactive(self) -> 'OptionSeriesLineStatesInactive':
return self._config_sub_data('inactive', OptionSeriesLineStatesInactive)
def nor... |
def group_elements(osm: OSMData):
elem2group = {'area': {}, 'way': {}, 'node': {}}
for node in filter(filter_node, osm.nodes.values()):
label = parse_node(node.tags)
if (label is None):
continue
group = match_to_group(label, Patterns.nodes)
if (group is None):
... |
class CraftNet(nn.Module):
def __init__(self, pretrained=False, freeze=False):
super(CraftNet, self).__init__()
self.basenet = vgg16_bn(pretrained, freeze)
self.upconv1 = double_conv(1024, 512, 256)
self.upconv2 = double_conv(512, 256, 128)
self.upconv3 = double_conv(256, 128... |
class SpectralNoiseFFT(SpectralNoise):
def __init__(self, factory, C):
self.factory = factory
self.C = C
self.coords = C.grid.separated_coords
def shift(self, shift):
S = [(shift[i] * self.coords[i]) for i in range(len(self.coords))]
S = np.add.reduce(np.ix_(*S))
... |
def create_annotation_table():
df_annotations = pd.read_sql(sql=app.session.query(annotations.athlete_id, annotations.date, annotations.annotation).filter((athlete.athlete_id == 1)).statement, con=engine).sort_index(ascending=False)
app.session.remove()
return dash_table.DataTable(id='annotation-table', col... |
_set_stats_type(ofproto.OFPMP_QUEUE_STATS, OFPQueueStats)
_set_msg_type(ofproto.OFPT_MULTIPART_REQUEST)
class OFPQueueStatsRequest(OFPMultipartRequest):
def __init__(self, datapath, flags=0, port_no=ofproto.OFPP_ANY, queue_id=ofproto.OFPQ_ALL, type_=None):
super(OFPQueueStatsRequest, self).__init__(datapath... |
def extractCafeno20WordpressCom(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) ... |
class OptionSeriesTreemapSonificationDefaultinstrumentoptionsMappingPlaydelay(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: ... |
class PackFile(object):
def __init__(self, path):
self.path = os.path.abspath(path)
def get_file(self):
return os.path.join(self.path, 'pack.py')
def needs_model(self):
file_name = self.get_file()
line = None
with open(file_name, 'r') as f:
for l in f:
... |
def gtest():
herder = VpsHerder(debug=True)
clientname = 'test-5'
(provider, kwargs) = herder.generate_gce_conf()
herder.log.info('Creating instance...')
herder.log.info("\tClient name: '%s'", clientname)
herder.log.info("\tusing provider: '%s'", provider)
herder.log.info("\tkwargs: '%s'", k... |
def test_prism_layer_no_regular_grid(dummy_layer):
((easting, northing), surface, reference, _) = dummy_layer
easting_invalid = easting.copy()
easting_invalid[3] = (- 22)
with pytest.raises(ValueError):
prism_layer((easting_invalid, northing), surface, reference)
northing_invalid = northing.... |
class OptionSeriesBulletSonificationDefaultinstrumentoptionsMappingLowpassFrequency(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, ... |
class RuntimeProcessorType(Enum):
LOCAL = 'Local'
KUBEFLOW_PIPELINES = 'Kubeflow Pipelines'
APACHE_AIRFLOW = 'Apache Airflow'
ARGO = 'Argo'
def get_instance_by_name(name: str) -> 'RuntimeProcessorType':
return RuntimeProcessorType.__members__[name.upper()]
def get_instance_by_value(value... |
def read_segbits(segbits_file):
segbits = []
with OpenSafeFile(segbits_file, 'r') as fp:
for line in fp.readlines():
line = line.split()
if (len(line) > 1):
fields = line[0].split('.')
segbit = '.'.join(fields[1:])
segbits.append(se... |
def is_meet_conditions(args, conditions, threshold=1e-08):
if (conditions is None):
return True
condition_names = list(conditions.keys())
condition_values = list(conditions.values())
assert (_is_same([len(values) for values in condition_values]) is True)
num_condition = len(condition_values)... |
(scope='function')
def privacy_preference_history_for_vendor_legitimate_interests(db, provided_identity_and_consent_request, privacy_experience_france_overlay, fides_user_provided_identity, served_notice_history_for_vendor_legitimate_interests):
preference_history_record = PrivacyPreferenceHistory.create(db=db, dat... |
('overrides, expected_files', [([], {'.hydra'}), (['hydra.output_subdir=foo'], {'foo'}), (['hydra.output_subdir=null'], set())])
('calling_file, calling_module', [('tests/test_apps/app_with_cfg/my_app.py', None), (None, 'tests.test_apps.app_with_cfg.my_app')])
def test_hydra_output_dir(hydra_restore_singletons: Any, hy... |
def test_param_iter():
step = Stepper(8, 12, 0.1)
osc = [step, 0.5, 0.5]
iter_1 = param_iter(osc)
for (ind, val) in enumerate(iter_1):
assert (val == [(8 + (0.1 * ind)), 0.5, 0.5])
step = Stepper(0.25, 3, 0.25)
ap_params = [0, step]
iter_1 = param_iter(ap_params)
for (ind, val) i... |
def test_inforec_encoding(tmpdir, merge_lis_prs):
fpath = os.path.join(str(tmpdir), 'encoded-inforec.dlis')
content = ['data/lis/records/RHLR-1.lis.part', 'data/lis/records/THLR-1.lis.part', 'data/lis/records/FHLR-1.lis.part', 'data/lis/records/inforec-encoded.lis.part', 'data/lis/records/FTLR-1.lis.part', 'dat... |
def test_get_file_tree_data(frontend_db, backend_db):
(fw, parent_fo, child_fo) = create_fw_with_parent_and_child()
fw.processed_analysis = {'file_type': generate_analysis_entry(analysis_result={'failed': 'some error'})}
parent_fo.processed_analysis = {'file_type': generate_analysis_entry(analysis_result={'... |
class OptionPlotoptionsGaugeSonificationContexttracks(Options):
def activeWhen(self) -> 'OptionPlotoptionsGaugeSonificationContexttracksActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsGaugeSonificationContexttracksActivewhen)
def instrument(self):
return self._config_get... |
def debatch_actor_ids(actor_ids: List[ActorID]) -> List[ActorID]:
for idx in range(len(actor_ids)):
actor_id_tmp = actor_ids[idx]
if (isinstance(actor_id_tmp.agent_id, torch.Tensor) and isinstance(actor_id_tmp.step_key, torch.Tensor)):
assert (len(set(actor_id_tmp.agent_id.tolist())) == ... |
class TSweepRunner(Protocol):
returns: List[List[JobReturn]]
def __call__(self, calling_file: Optional[str], calling_module: Optional[str], task_function: Optional[TaskFunction], config_path: Optional[str], config_name: Optional[str], overrides: Optional[List[str]], temp_dir: Optional[Path]=None) -> SweepTaskFu... |
class GitChangeEntry():
status: str
original_path: Path
new_path: Optional[Path] = None
def from_line(cls, text: str) -> 'GitChangeEntry':
columns = text.split('\t')
assert (2 <= len(columns) <= 3)
columns[1:] = [Path(c) for c in columns[1:]]
return cls(*columns)
def ... |
.parametrize('lineno,context,expected', [(10, 5, (['5', '6', '7', '8', '9'], '10', ['11', '12', '13', '14', '15'])), (1, 5, ([], '1', ['2', '3', '4', '5', '6'])), (2, 5, (['1'], '2', ['3', '4', '5', '6', '7'])), (20, 5, (['15', '16', '17', '18', '19'], '20', [])), (19, 5, (['14', '15', '16', '17', '18'], '19', ['20']))... |
class ChartTreeMap(Chart):
requirements = ('chart.js', 'chartjs-chart-treemap')
_chart__type = 'treemap'
_option_cls = OptChartJs.OptionsTreeMap
builder_name = 'ChartTreeMap'
def options(self) -> OptChartJs.OptionsTreeMap:
return super().options
def add_dataset(self, tree: List[dict], la... |
class OptionPlotoptionsAreaSonificationTracksPointgrouping(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):
se... |
def test_colors_whole_table_only_bg_colors(data, header, footer, bg_colors):
result = table(data, header=header, footer=footer, divider=True, bg_colors=bg_colors)
if SUPPORTS_ANSI:
assert (result == '\n\x1b[48;5;2mCOL A \x1b[0m \x1b[48;5;23mCOL B\x1b[0m COL 3 \n\x1b[48;5;2m\x1b[0m \x1b... |
def setNoZeroLSweakDirichletBCs(RDLSvt):
assert hasattr(RDLSvt, 'freezeLevelSet')
assert hasattr(RDLSvt, 'u_dof_last')
assert hasattr(RDLSvt, 'weakDirichletConditionFlags')
assert hasattr(RDLSvt.coefficients, 'epsFact')
assert hasattr(RDLSvt, 'dofFlag_element')
RDLSvt.freezeLevelSet = 0 |
class CompiledTask(_common.FlyteIdlEntity):
def __init__(self, template):
self._template = template
def template(self):
return self._template
def to_flyte_idl(self):
return _compiler_pb2.CompiledTask(template=self.template)
def from_flyte_idl(cls, p):
return cls(None) |
def inv_hue_quadrature(H: float) -> float:
Hp = (((H % 400) + 400) % 400)
i = math.floor((0.01 * Hp))
Hp = (Hp % 100)
(hi, hii) = HUE_QUADRATURE['h'][i:(i + 2)]
(ei, eii) = HUE_QUADRATURE['e'][i:(i + 2)]
return util.constrain_hue((((Hp * ((eii * hi) - (ei * hii))) - ((100 * hi) * eii)) / ((Hp * ... |
class HttpError(FaunaError):
def __init__(self, request_result):
self.errors = HttpError._get_errors(request_result)
super(HttpError, self).__init__(self._get_description(), request_result)
def _get_errors(request_result):
response = request_result.response_content
errors = _get_... |
class Colvar(metaclass=abc.ABCMeta):
def __init__(self, force_agrad=False):
try:
getattr(self, '_gradient')
except AttributeError:
force_agrad = True
if force_agrad:
grad_func = autograd.grad(self.value)
def wrapped(self, c3d):
... |
class LossMetrics(Metrics):
def __init__(self, window_size: int=100, device: torch.device=torch.device('cpu'), world_size: int=0):
super().__init__()
self._world_size = world_size
self._window_size = window_size
self._epoch = 0
self._iteration = 0
self._window_losses ... |
def testdir(a):
try:
names = [n for n in os.listdir(a) if n.endswith('.py')]
except OSError:
sys.stderr.write(('Directory not readable: %s\n' % a))
else:
for n in names:
fullname = os.path.join(a, n)
if os.path.isfile(fullname):
output = io.Str... |
class OptionPlotoptionsVennClusterLayoutalgorithm(Options):
def distance(self):
return self._config_get(40)
def distance(self, num: float):
self._config(num, js_type=False)
def gridSize(self):
return self._config_get(50)
def gridSize(self, num: float):
self._config(num, j... |
def get_ips(session, endpoint_id, limit=None):
query = session.query(Request.ip, func.count(Request.ip)).filter((Request.endpoint_id == endpoint_id)).group_by(Request.ip).order_by(desc(func.count(Request.ip)))
if limit:
query = query.limit(limit)
result = query.all()
session.expunge_all()
re... |
def test_adding_an_externalTrafficPolicy():
config = ''
r = helm_template(config)
assert ('externalTrafficPolicy' not in r['service'][uname]['spec'])
config = '\n service:\n externalTrafficPolicy: Local\n '
r = helm_template(config)
assert (r['service'][uname]['spec']['externalTraffic... |
_required
_required
def details(request, hostname):
dc1_settings = get_dc1_settings(request)
context = collect_view_data(request, 'node_list')
context['node'] = node = get_node(request, hostname, sr=('owner',))
context['nodes'] = Node.all()
context['node_dcs'] = node.dc.all().values_list('alias', fl... |
def convert_preprocessors():
subprocess.run(['curl', '-L', ' '-o', 'src/model.py'], check=True)
run_conversion_script('convert_informative_drawings.py', 'tests/weights/carolineec/informativedrawings/model2.pth', 'tests/weights/informative-drawings.safetensors', expected_hash='93dca207')
os.remove('src/model... |
def jzazbz_to_xyz_d65(jzazbz: Vector) -> Vector:
(jz, az, bz) = jzazbz
iz = ((jz + D0) / ((1 + D) - (D * (jz + D0))))
pqlms = alg.matmul(izazbz_to_lms_p_mi, [iz, az, bz], dims=alg.D2_D1)
lms = util.pq_st2084_eotf(pqlms, m2=M2)
(xm, ym, za) = alg.matmul(lms_to_xyz_mi, lms, dims=alg.D2_D1)
xa = ((... |
def gatherSplitTimeStepXDMFfilesOpt(size, filename, dataDir='.', addname='_all', nStepsOnly=None, stride=1):
xmlFile = open(((filename + str(0)) + '.xmf'), 'r')
tree = ElementTree(file=xmlFile)
xmlFile.close()
nSteps = len(tree.getroot()[(- 1)][(- 1)])
if (nStepsOnly != None):
nSteps = nStep... |
_models('spacy.Text-Babbage.v2')
def openai_text_babbage_v2(config: Dict[(Any, Any)]=SimpleFrozenDict(max_tokens=500, temperature=_DEFAULT_TEMPERATURE), name: Literal['text-babbage-001']='text-babbage-001', strict: bool=OpenAI.DEFAULT_STRICT, max_tries: int=OpenAI.DEFAULT_MAX_TRIES, interval: float=OpenAI.DEFAULT_INTER... |
def report_results(results, hw_config, report_json_filename):
if results:
tests_json = {}
report_title = 'test results'
print('\n')
print(report_title)
print(('=' * len(report_title)))
for result in results:
test_lists = [('ERROR', result.errors), ('FAIL',... |
class ModelWorker(ABC):
def worker_type(self) -> WorkerType:
return WorkerType.LLM
def model_param_class(self) -> Type:
return ModelParameters
def support_async(self) -> bool:
return False
def parse_parameters(self, command_args: List[str]=None) -> ModelParameters:
def load_w... |
class OptionSeriesArcdiagramLabelStyle(Options):
def fontSize(self):
return self._config_get('0.8em')
def fontSize(self, num: float):
self._config(num, js_type=False)
def fontWeight(self):
return self._config_get('bold')
def fontWeight(self, text: str):
self._config(text,... |
class Filter(object):
def __init__(self, **default_parameters):
self.func = None
self.filters = {}
self._default_parameters = default_parameters
self.set_parameters(default_parameters)
def __call__(self, func):
self.func = func
return self
def set_parameters(s... |
.parametrize('header', ['multipart/form-data; charset=utf-8', 'multipart/form-data; charset=utf-8; '])
def test_multipart_header_without_boundary(header: str) -> None:
client =
files = {'file': io.BytesIO(b'<file content>')}
headers = {'content-type': header}
response = client.post(' files=files, heade... |
def test_node_comparison():
node0 = MockNode({'name': 'test', 'type': 'none'})
node1 = MockNode({'name': 'test', 'type': 'none'})
node2 = MockNode({'name': 'test2', 'type': 'none'})
node3 = MockNode({'name': 'test', 'type': 'some'})
assert (node0 == node1)
assert (node1 != node2)
assert (nod... |
class GainLossSet(AbstractEntrySet):
def type_check(cls, name: str, instance: 'GainLossSet') -> 'GainLossSet':
Configuration.type_check_parameter_name(name)
if (not isinstance(instance, cls)):
raise RP2TypeError(f"Parameter '{name}' is not of type {cls.__name__}: {instance}")
ret... |
class BinaryServiceDbInterface(ReadOnlyDbInterface):
def get_file_name(self, uid: str) -> (str | None):
with self.get_read_only_session() as session:
entry: FileObjectEntry = session.get(FileObjectEntry, uid)
return (entry.file_name if (entry is not None) else None) |
class FFI(object):
def __init__(self, backend=None):
from . import cparser, model
if (backend is None):
import _cffi_backend as backend
from . import __version__
assert (backend.__version__ == __version__), ('version mismatch, %s != %s' % (backend.__version__, __v... |
('calling_file, calling_module, config_path, expected', [('foo.py', None, None, None), ('foo/bar.py', None, None, None), ('foo/bar.py', None, 'conf', realpath('foo/conf')), ('foo/bar.py', None, '../conf', realpath('conf')), ('foo/bar.py', None, realpath('conf'), realpath('conf')), ('c:/foo/bar.py', None, 'conf', realpa... |
def test_pole_coeffs():
num_poles = 10
coeffs = np.random.random((4 * num_poles))
poles = DispersionFitter._coeffs_to_poles(coeffs)
coeffs_ = DispersionFitter._poles_to_coeffs(poles)
poles_ = DispersionFitter._coeffs_to_poles(coeffs_)
assert np.allclose(coeffs, coeffs_)
assert np.allclose(po... |
def test_rectangular_dielectric_validations():
with pytest.raises(ValidationError, match='.* gaps .*'):
waveguide.RectangularDielectric(wavelength=1.55, core_width=(0.5, 0.5), core_thickness=0.22, core_medium=td.Medium(permittivity=(3.48 ** 2)), clad_medium=td.Medium(permittivity=(1.45 ** 2)), gap=(0.1, 0.1... |
def getosfullname():
try:
with open('/etc/os-release') as f:
for line in f:
line = line.strip()
if line.startswith('PRETTY_NAME'):
pname = line.split('"')
return pname[1]
except:
pass
return '' |
class TLSContextProtocolMaxVersion(AmbassadorTest):
def init(self):
self.target = HTTP()
if EDGE_STACK:
self.xfail = 'Not yet supported in Edge Stack'
self.xfail = 'FIXME: IHA'
def manifests(self) -> str:
return (f'''
---
apiVersion: v1
data:
tls.crt: {TLSCerts['tls... |
def test_tnr_test() -> None:
test_dataset = pd.DataFrame({'target': ['a', 'a', 'b', 'b'], 'prediction': ['a', 'b', 'b', 'b']})
column_mapping = ColumnMapping(pos_label='a')
suite = TestSuite(tests=[TestTNR(gt=0.8)])
suite.run(current_data=test_dataset, reference_data=None, column_mapping=column_mapping)... |
class OptionSeriesScatter3dDataMarkerStatesHover(Options):
def animation(self) -> 'OptionSeriesScatter3dDataMarkerStatesHoverAnimation':
return self._config_sub_data('animation', OptionSeriesScatter3dDataMarkerStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled... |
def test_estimate_semi_amplitude(seed=9502):
np.random.seed(seed)
t = np.sort(np.random.uniform(0, 10, 500))
period = 2.345
amp = 4.5
y = (amp * np.sin((((2 * np.pi) * t) / period)))
est = estimate_semi_amplitude(period, t, y)
assert np.allclose(est, amp)
est = estimate_semi_amplitude(pe... |
def render_info(totals, header):
(columns, _) = header
(yield 'totals:')
for (_, colname, _) in columns:
try:
value = totals[colname]
except KeyError:
continue
if isinstance(value, TinyTimeDelta):
value = value.render('us')
(yield f"{(colna... |
_installed
def test_flow(init_flow_config, source_root):
shutil.copy((source_root / 'test-data/eclipse/SPE1.DATA'), 'SPE1.DATA')
shutil.copy((source_root / 'test-data/eclipse/SPE1_ERROR.DATA'), 'SPE1_ERROR.DATA')
flow_config = ecl_config.FlowConfig()
sim = flow_config.sim()
flow_run = ecl_run.EclRun... |
def get_input(caller, prompt, callback, session=None, *args, **kwargs):
if (not callable(callback)):
raise RuntimeError('get_input: input callback is not callable.')
caller.ndb._getinput = _Prompt()
caller.ndb._getinput._callback = callback
caller.ndb._getinput._prompt = prompt
caller.ndb._g... |
def read_type_def(line: str):
type_match = FRegex.TYPE_DEF.match(line)
if (type_match is None):
return None
trailing_line = line[type_match.end(1):].split('!')[0]
trailing_line = trailing_line.strip()
keyword_match = FRegex.TATTR_LIST.match(trailing_line)
keywords: list[str] = []
par... |
def json_dumps(data: JSONInput, indent: Optional[int]=0, sort_keys: bool=False) -> str:
if sort_keys:
indent = (None if (indent == 0) else indent)
result = _builtin_json.dumps(data, indent=indent, separators=(',', ':'), sort_keys=sort_keys)
else:
result = ujson.dumps(data, indent=indent,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.