code stringlengths 281 23.7M |
|---|
class GradientNormClipping(Callback['Trainer[BaseConfig, Any]']):
def on_backward_end(self, trainer: 'Trainer[BaseConfig, Any]') -> None:
clip_norm = trainer.config.training.clip_grad_norm
if (clip_norm is not None):
clip_gradient_norm(parameters=trainer.learnable_parameters, total_norm=... |
class PyWinAutoLoader(Loader):
def __init__(self):
self._original_coinit_flags_defined = False
self._original_coinit_flags = None
def set_sys_coinit_flags(self):
self._original_coinit_flags_defined = hasattr(sys, 'coinit_flags')
self._original_coinit_flags = getattr(sys, 'coinit_... |
class GridItemCardDirective(SphinxDirective):
has_content = True
required_arguments = 0
optional_arguments = 1
final_argument_whitespace = True
option_spec = {'columns': item_columns_option, 'margin': margin_option, 'padding': padding_option, 'class-item': directives.class_option, 'width': make_choi... |
class Submission(DB.Model):
__tablename__ = 'submissions'
id = DB.Column(DB.Integer, primary_key=True)
submitted_at = DB.Column(DB.DateTime)
form_id = DB.Column(DB.Integer, DB.ForeignKey('forms.id'), nullable=False)
data = DB.Column(MutableDict.as_mutable(JSON))
def __init__(self, form_id):
... |
class TestInitialRun():
def initial_run(s3_data_bucket, load_source_tables=True, load_other_raw_tables=None, initial_copy=True):
_load_tables_to_delta(s3_data_bucket, load_source_tables, load_other_raw_tables)
call_params = ['load_transactions_in_delta', '--etl-level', 'initial_run', '--spark-s3-buc... |
def record(oid, tag, value, **context):
if ('started' not in moduleContext):
moduleContext['started'] = time.time()
if ('iterations' not in moduleContext):
moduleContext['iterations'] = min(1, moduleContext['settings'].get('iterations', 0))
iterations = moduleContext['settings'].get('iterati... |
def _rule_match(analysis_plugin, filename, expected_rule_name, expected_number_of_rules=1):
path = os.path.join(TEST_DATA_DIR, filename)
test_file = FileObject(file_path=path)
analysis_plugin.process_object(test_file)
number_of_rules = (len(test_file.processed_analysis[analysis_plugin.NAME]) - 1)
as... |
def test_parse_schema_includes_hint_with_list():
'
schema = [{'type': 'record', 'name': 'test_parse_schema_includes_hint_with_list_1', 'doc': 'blah', 'fields': [{'name': 'field1', 'type': 'string', 'default': ''}]}, {'type': 'record', 'name': 'test_parse_schema_includes_hint_with_list_2', 'doc': 'blah', 'fields... |
class RateLimiter():
EXPIRE_AFTER_PERIOD_SECONDS: int = 500
def build_redis_key(self, current_seconds: int, request: RateLimiterRequest) -> str:
fixed_time_filter = (int((current_seconds / request.period.factor)) * request.period.factor)
redis_key = f'{request.key}:{request.period.label}:{fixed_... |
class FipaSerializer(Serializer):
def encode(msg: Message) -> bytes:
msg = cast(FipaMessage, msg)
message_pb = ProtobufMessage()
dialogue_message_pb = DialogueMessage()
fipa_msg = fipa_pb2.FipaMessage()
dialogue_message_pb.message_id = msg.message_id
dialogue_referenc... |
def setUpModule():
Practice.objects.create(code='N84014', name='AINSDALE VILLAGE SURGERY')
Practice.objects.create(code='P84034', name='BARLOW MEDICAL CENTRE')
Practice.objects.create(code='Y02229', name='ADDACTION NUNEATON')
ImportLog.objects.create(current_at='2039-12-01', category='patient_list_size'... |
def flatten_groups(*geometries: GeometryType, flatten_nonunion_type: bool=False) -> GeometryType:
for geometry in geometries:
if isinstance(geometry, base.GeometryGroup):
(yield from flatten_groups(*geometry.geometries, flatten_nonunion_type=flatten_nonunion_type))
elif (isinstance(geome... |
class TestMergePipeline():
.parametrize('data', datas)
def test_fit_execute_simple(self, data):
columns = ['revenue', 'netinc', 'ncf', 'ebitda', 'debt', 'fcf']
f1 = QuarterlyFeatures(data_key='quarterly', columns=columns, quarter_counts=[2, 10], max_back_quarter=1)
target1 = QuarterlyTar... |
class TestUSSPP(unittest.TestCase):
def test_fetch_production(self):
filename = 'parsers/test/mocks/US_SPP_Gen_Mix.pkl'
fake_data = read_pickle(filename)
with LogCapture() as log:
with patch('parsers.US_SPP.get_data') as gd:
gd.return_value = fake_data
... |
.parametrize('bytecode,link_refs,attr_dict,expected', ((bytearray(60), [{'length': 20, 'name': 'SafeSendLib', 'offsets': [1]}], {'SafeSendLib': SAFE_SEND_CANON}, ((b'\x00' + SAFE_SEND_CANON) + bytearray(39))), (bytearray(60), [{'length': 20, 'name': 'SafeSendLib', 'offsets': [1, 31]}], {'SafeSendLib': SAFE_SEND_CANON},... |
class ChatDestinationCache():
def __init__(self, mode: str, size: int=CHAT_DEST_CACHE_SIZE):
self.enabled = (mode in ('enabled', 'warn'))
if self.enabled:
self.weak: 'WeakValueDictionary[str, ChatDestination]' = WeakValueDictionary()
self.strong: Deque[ChatDestination] = dequ... |
class JsonFormatter(logging.Formatter):
def format(self, record):
log_entry = {'level': record.levelname, 'timestamp': datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')}
if isinstance(record.msg, dict):
log_entry.update(record.msg)
return json.dumps(log_entry) |
class ServicePlanTestCaseTestFunction(Function):
def __init__(self, parent, fixture_test_case_data):
cls = parent.parent.obj
test_name = 'plan__{fixture}__{test}'.format(fixture=fixture_test_case_data.fixture_name, test=fixture_test_case_data.name)
if hasattr(cls, test_name):
rai... |
class TaskID(str):
def __new__(cls, value, request=None):
obj = str.__new__(cls, value)
if request:
obj.__dict__.update(request.__dict__)
return obj
def __repr__(self):
return ('<%s: %s>' % (self.__class__.__name__, self))
def prefix(self):
return task_pre... |
def test_invert():
ar = Compose([AffineAutoregressive(params.DenseAutoregressive()), AffineAutoregressive(params.DenseAutoregressive())])
shape = torch.Size([16])
bij = ar(shape=shape)
inv_bij = bijectors.Invert(ar)(shape=shape)
inv_bij.load_state_dict(bij.state_dict(prefix='bijector.'))
x = tor... |
class Contrast(Filter):
NAME = 'contrast'
ALLOWED_SPACES = ('srgb-linear', 'srgb')
def filter(self, color: 'Color', amount: Optional[float], **kwargs: Any) -> None:
amount = alg.clamp((1 if (amount is None) else amount), 0)
for (e, c) in enumerate(color[:(- 1)]):
color[e] = linea... |
class OptionPlotoptionsWindbarbSonificationTracksMappingHighpassResonance(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 extractWentaoxuelinBlogspotCom(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_typ... |
class TestMinHeap(unittest.TestCase):
def test_min_heap(self):
heap = MinHeap()
self.assertEqual(heap.peek_min(), None)
self.assertEqual(heap.extract_min(), None)
heap.insert(20)
self.assertEqual(heap.array[0], 20)
heap.insert(5)
self.assertEqual(heap.array[0]... |
.django_db
def test_tas_balances_total(account_models, client):
response_tas_sums = {'XYZ': '10.00', 'ZZZ': '5.00'}
resp = client.post('/api/v1/tas/balances/total/', content_type='application/json', data=json.dumps({'field': 'budget_authority_unobligated_balance_brought_forward_fyb', 'group': 'treasury_account_... |
class RayLauncher(Launcher):
def __init__(self, ray: DictConfig) -> None:
self.ray_cfg = ray
self.hydra_context: Optional[HydraContext] = None
self.task_function: Optional[TaskFunction] = None
self.config: Optional[DictConfig] = None
def setup(self, *, hydra_context: HydraContext... |
class OptionPlotoptionsOrganizationSonificationDefaultspeechoptionsMappingVolume(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, tex... |
class Model(object):
def __init__(self, input_shape, output_labels_size):
model = keras.Sequential()
model.add(layers.Convolution2D(16, (3, 3), padding='same', input_shape=input_shape, activation='relu'))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
model.add(layers.Convolution2D... |
('foremast.elb.format_listeners.get_template')
def test_elb_cert_name_v1(rendered_template):
rendered_template.return_value = SAMPLE_TLSCERT_V1_JSON
iam_cert = 'arn:aws:iam:::server-certificate/wildcard.example.com-2020-07-15'
assert (iam_cert == format_cert_name(env='prod', account='', region='us-east-1', ... |
def pull_process_and_push_data(device, device_attendance_logs=None):
attendance_success_log_file = '_'.join(['attendance_success_log', device['device_id']])
attendance_failed_log_file = '_'.join(['attendance_failed_log', device['device_id']])
attendance_success_logger = setup_logger(attendance_success_log_f... |
_stats_reply_type(ofproto.OFPST_GROUP_DESC)
class OFPGroupDescStats(StringifyMixin):
def __init__(self, type_, group_id, buckets, length=None):
self.type = type_
self.group_id = group_id
self.buckets = buckets
def parser(cls, buf, offset):
(length, type_, group_id) = struct.unpac... |
def check_metric(mh, cfg, loc, metric, metrics, justifications):
if (not cfg.metric_enabled(metric)):
return
elif cfg.metric_check(metric):
measure = metrics[metric]['measure']
if (measure is None):
return
limit = cfg.metric_upper_limit(metric)
metrics[metric]... |
class controller_status(message):
version = 6
type = 35
def __init__(self, xid=None, entry=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (entry != None):
self.entry = entry
else:
self.entry = loxi.unimplemente... |
def read_solutions_table(readme_fp):
def parse_line(line):
elems = [el for el in line.strip().split('|') if el]
question_elem = elems[1]
match = re.search('\\[(.+?)\\]\\((.+)\\)', question_elem)
if (not match):
raise ValueError('{} is not a valid link'.format(question_ele... |
def fix_and_dump_pe(process_controller: ProcessController, pe_file_path: str, image_base: int, oep: int, text_section_range: MemoryRange) -> None:
section_virtual_addr = (image_base + text_section_range.base)
text_section_range = MemoryRange(section_virtual_addr, text_section_range.size, 'r-x', process_controll... |
def check_valid_call():
if ('-s' not in sys.argv):
msg = 'You must use the `-s` flag when running integration tests.'
print(msg)
return False
if (sum(((platform in ' '.join(sys.argv)) for platform in ['platform_sh', 'fly_io', 'heroku'])) == 1):
return True
else:
msg =... |
class LiteSATAMirroring(Module):
def __init__(self, controllers):
n = len(controllers)
dw = len(controllers[0].sink.data)
self.ports = [LiteSATAUserPort(dw) for i in range(n)]
self.submodules.ctrl = LiteSATAMirroringCtrl(n)
self.submodules.tx = LiteSATAMirroringTX(n, dw, self... |
def build_head(config):
from .det_db_head import DBHead
from .det_east_head import EASTHead
from .det_sast_head import SASTHead
from .det_pse_head import PSEHead
from .e2e_pg_head import PGHead
from .rec_ctc_head import CTCHead
from .rec_att_head import AttentionHead
from .rec_srn_head i... |
def download_file(url, dstpath, download_even_if_exists=False, filename_prefix='', silent=False):
debug_print((((('download_file(url=' + url) + ', dstpath=') + dstpath) + ')'))
file_name = get_download_target(url, dstpath, filename_prefix)
if (os.path.exists(file_name) and (not download_even_if_exists)):
... |
class TestSSEClient():
test_url = '
def init_sse(self, payload, recorder=None):
if (recorder is None):
recorder = []
adapter = MockSSEClientAdapter(payload, recorder)
session = requests.Session()
session.mount(self.test_url, adapter)
return _sseclient.SSEClien... |
def request(method: str, url: URLTypes, *, params: typing.Optional[QueryParamTypes]=None, content: typing.Optional[RequestContent]=None, data: typing.Optional[RequestData]=None, files: typing.Optional[RequestFiles]=None, json: typing.Optional[typing.Any]=None, headers: typing.Optional[HeaderTypes]=None, cookies: typing... |
def test_changing_case(qtbot, notifier, storage):
ensemble_a = storage.create_experiment().create_ensemble(name='default_a', ensemble_size=1)
ensemble_b = storage.create_experiment().create_ensemble(name='default_b', ensemble_size=1)
notifier.set_storage(storage)
notifier.set_current_case(ensemble_a)
... |
class Lab(base.CIELab):
def to_string(self, parent: Color, *, alpha: (bool | None)=None, precision: (int | None)=None, fit: ((bool | str) | dict[(str, Any)])=True, none: bool=False, color: bool=False, percent: (bool | Sequence[bool])=False, **kwargs: Any) -> str:
return serialize.serialize_css(parent, func=... |
class OptionPlotoptionsBarStates(Options):
def hover(self) -> 'OptionPlotoptionsBarStatesHover':
return self._config_sub_data('hover', OptionPlotoptionsBarStatesHover)
def inactive(self) -> 'OptionPlotoptionsBarStatesInactive':
return self._config_sub_data('inactive', OptionPlotoptionsBarStatesI... |
.order((- 1))
.parametrize(('username', 'path', 'slug', 'status'), (('tessdoe', 'tess-title-blog-3', 'tell-title-blog-3', 204), ('tessdoe', 'tell-title-blog-10000', 'tell-title-blog-3', 404), ('leodoe', 'tess-title-blog-2', 'tell-title-blog-2', 403)))
def test_delete_post(username, path, slug, status):
headers = {}... |
def extractFirsttrytranslationsWordpressCom(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, nam... |
def test_summary_collector(monkeypatch, snake_oil_case_storage, snake_oil_default_storage, snapshot):
monkeypatch.setenv('TZ', 'CET')
data = snake_oil_default_storage.load_all_summary_data()
snapshot.assert_match(data.iloc[:4].round(4).to_csv(), 'summary_collector_1.csv')
assert (data.shape == (1000, 44... |
def test_dualperm_fractured_soil_property(dual_poro_dual_perm_run):
soil = dual_poro_dual_perm_run.get_property_from_restart('SOIL', date=, fracture=True)
assert (soil.values[(3, 0, 0)] == pytest.approx(0.0))
assert (soil.values[(0, 1, 0)] == pytest.approx(0.))
assert (soil.values[(3, 2, 0)] == pytest.a... |
class port_status(message):
version = 4
type = 12
def __init__(self, xid=None, reason=None, desc=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (reason != None):
self.reason = reason
else:
self.reason = 0
... |
class AttachableTests(unittest.TestCase):
def test_unicode(self):
attachable = Attachable()
attachable.FileName = 'test'
self.assertEqual(str(attachable), 'test')
def test_to_ref(self):
attachable = Attachable()
attachable.FileName = 'test'
attachable.Id = 12
... |
_renderer(wrap_type=TestCategoryCount)
_renderer(wrap_type=TestCategoryShare)
class TestCategoryRenderer(TestRenderer):
def _get_number_and_percents(s: pd.Series, num: int) -> pd.DataFrame:
return (((s.astype(str) + ' (') + ((s / num) * 100).round(2).astype(str)) + '%)')
def get_value_counts_table_with_... |
()
def make_sales_invoice(reference_name, patient, company, therapy_plan_template):
from erpnext.stock.get_item_details import get_item_details
si = frappe.new_doc('Sales Invoice')
si.company = company
si.patient = patient
si.customer = frappe.db.get_value('Patient', patient, 'customer')
item = ... |
def dump_github() -> str:
self = CTX
r = self.github.graphql('\n query {\n repository(name: "pytorch", owner: "pytorch") {\n pullRequests {\n nodes {\n number\n baseRefName\n headRefName\n title\n body\n ... |
class ExpressionPropagationBase(PipelineStage, ABC):
name = 'expression-propagation-base'
def __init__(self):
self._use_map: UseMap
self._def_map: DefMap
self._pointers_info: Optional[Pointers] = None
self._blocks_map: Optional[DefaultDict[(str, Set)]] = None
self._cfg: O... |
def prepServers(dut_list, args, profile):
for dut in dut_list:
if (not dut.inLocalMode()):
startAoeServer(dut)
if (args.tunneling == 'y'):
startSshTunnel(dut)
fio_json_parser.tunnel2host[dut.sshTunnelPort] = dut.serverName
if dut.capacity:
dut.... |
class OptionPlotoptionsErrorbarSonificationTracksMappingGapbetweennotes(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):
... |
.usefixtures('use_tmpdir')
def test_that_config_path_is_the_directory_of_the_main_ert_config():
os.mkdir('jobdir')
with open('jobdir/job_file', 'w', encoding='utf-8') as fout:
fout.write(dedent('\n EXECUTABLE echo\n ARGLIST <CONFIG_PATH>\n '))
with open('config_file.... |
def test_cast(base):
with pytest.raises(EtypeCastError):
cast(base.id, [], Etype.Image)
with pytest.raises(EtypeCastError):
cast(base.id, [base.txt1], Etype.Image)
t1 = cast(base.id, [base.im1], to=Etype.Image)
assert (len(t1.paths) == 1)
assert (t1.et == Etype.Image)
with pytest... |
class TestMostCommonValueShare(BaseFeatureDataQualityMetricsTest):
name: ClassVar = 'Share of the Most Common Value'
def get_stat(self, current: NumericCharacteristics):
return current.most_common_percentage
def get_condition_from_reference(self, reference: Optional[ColumnCharacteristics]) -> TestVa... |
def deny_unsafe_hosts(host: str) -> str:
if CONFIG.dev_mode:
return host
try:
host_ip: Union[(IPv4Address, IPv6Address)] = ip_address(socket.gethostbyname(host))
except socket.gaierror:
raise ValueError(f'Failed to resolve hostname: {host}')
if (host_ip.is_link_local or host_ip.i... |
class TableEditorToolbar(HasPrivateTraits):
no_sort = Instance(Action, {'name': 'No Sorting', 'tooltip': 'Do not sort columns', 'action': 'on_no_sort', 'enabled': False, 'image': ImageResource('table_no_sort.png')})
move_up = Instance(Action, {'name': 'Move Up', 'tooltip': 'Move current item up one row', 'actio... |
def add_types_to_namespaces(files, pkg, pkg_module):
for file in files:
add_after_namespaces = []
for child in file['children']:
simple_name = child['name'].split('::')[0]
if (child['kind'] == 'namespace'):
entity = getattr(cppyy.gbl, simple_name)
... |
class OptionPlotoptionsPolygonSonificationTracksMappingLowpassResonance(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 VectorEnv(BaseEnv, ABC):
def __init__(self, n_envs: int):
self.n_envs = n_envs
def step(self, actions: ActionType) -> Tuple[(ObservationType, np.ndarray, np.ndarray, Iterable[Dict[(Any, Any)]])]:
def reset(self):
def seed(self, seeds: List[Any]) -> None:
def _get_indices(self, indices)... |
def CreateTable(connection, table_name):
create_table_statement = 'CREATE TABLE IF NOT EXISTS {}(id INTEGER NOT NULL AUTO_INCREMENT,category VARCHAR(50) NOT NULL,time_of_entry DATETIME,runid VARCHAR(50),envoy_hash VARCHAR(40),total_time INTEGER UNSIGNED,time_for_1st_byte_max INTEGER UNSIGNED,time_for_1st_byte_min ... |
('slanted_triangular.v1')
def slanted_triangular(max_rate: float, num_steps: int, *, cut_frac: float=0.1, ratio: int=32, decay: float=1.0, t: float=0.0) -> Iterable[float]:
cut = int((num_steps * cut_frac))
while True:
t += 1
if (t < cut):
p = (t / cut)
else:
p = ... |
(scope='function')
def policy_drp_action_erasure(db: Session, oauth_client: ClientDetail) -> Generator:
erasure_request_policy = Policy.create(db=db, data={'name': 'example erasure request policy drp', 'key': 'example_erasure_request_policy_drp', 'drp_action': 'deletion', 'client_id': oauth_client.id})
erasure_... |
class OptionSeriesTreegraphSonificationDefaultinstrumentoptionsMappingLowpassResonance(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(sel... |
class Primitive(metaclass=abc.ABCMeta):
def __init__(self, indices, periodic=False, calc_kwargs=None, cache=False):
self.indices = list(indices)
self.periodic = periodic
if (calc_kwargs is None):
calc_kwargs = ()
self.calc_kwargs = calc_kwargs
self.cache = cache
... |
def clipper(bbox):
(minx, miny, maxx, maxy) = bbox
bounds = {'type': 'Polygon', 'coordinates': [[(minx, miny), (minx, maxy), (maxx, maxy), (maxx, miny), (minx, miny)]]}
try:
bbox_shape = shape(bounds)
def func(geometry):
try:
clipped = bbox_shape.intersection(shap... |
def leak():
global free_hook_addr
global system_addr
for i in range(9):
build(('A' * 7))
for i in range(7):
destroy(i)
destroy(7)
blow_up()
for i in range(8):
build(('A' * 7))
visit()
leak = u64(io.recvuntil('Type[7]', drop=True)[(- 6):].ljust(8, '\x00'))
... |
def klippa_receipt_parser(original_response: dict) -> ReceiptParserDataClass:
data_response = original_response['data']
customer_information = CustomerInformation(customer_name=data_response['customer_name'])
merchant_information = MerchantInformation(merchant_name=data_response['merchant_name'], merchant_a... |
class SelectorFilter():
def __init__(self, config: Config, tracking: Optional[Tracking], selector: Optional[str]=None) -> None:
self.tracking = tracking
self.selector = selector
user_dbt_runner = self._create_user_dbt_runner(config)
self.selector_fetcher = (SelectorFetcher(user_dbt_r... |
.parametrize('service', BACKEND_SERVICES)
.usefixtures('frappe_site')
def test_frappe_connections_in_backends(service: str, python_path: str, compose: Compose):
filename = '_ping_frappe_connections.py'
compose('cp', f'tests/{filename}', f'{service}:/tmp/')
compose.exec('-w', '/home/frappe/frappe-bench/sites... |
def store_stats_fdroid_signing_key_fingerprints(appids, indent=None):
if (not os.path.exists('stats')):
os.makedirs('stats')
data = OrderedDict()
fps = read_fingerprints_from_keystore()
for appid in sorted(appids):
alias = key_alias(appid)
if (alias in fps):
data[appi... |
class GraphSlice():
def __init__(self, t_cfg: TransitionCFG, source: TransitionBlock, sink: TransitionBlock):
assert t_cfg.is_acyclic(), 'The given transition cfg is not a directed acyclic graph, therefore we can not compute the graph slice!'
self._t_cfg: TransitionCFG = t_cfg
self._source: ... |
class SettingNamePrefixFilter(admin.SimpleListFilter):
title = _('Name Prefix')
parameter_name = 'name_prefix'
def lookups(self, request, model_admin):
sep = '_'
names = list(set(Setting.objects.all().values_list('name', flat=True)))
names_count = len(names)
names_parts = [na... |
def test_compare(tmp_path, capsys):
__main__._parse_and_main([*helpers.setup_temp_env(tmp_path), 'compare', 'cpython-3.12.0a0-c20186c397-fc_linux-b2cf916db80e-pyperformance', 'cpython-3.10.4-9d38120e33-fc_linux-b2cf916db80e-pyperformance'], __file__)
expected_start = '\n| Benchmark | cpython-3.12.... |
def test_1():
clf1 = mord.OrdinalRidge(alpha=0.0)
clf1.fit(X, y)
clf2 = mord.LogisticAT(alpha=0.0)
clf2.fit(X, y)
clf3 = mord.LogisticSE(alpha=0.0)
clf3.fit(X, y)
pred3 = clf3.predict(X)
pred2 = clf2.predict(X)
assert (np.abs((pred2 - y)).mean() <= np.abs((pred3 - y)).mean())
X_s... |
class OptionSeriesTreegraphDataEvents(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)
... |
class AMIClientTest(unittest.TestCase):
client = None
event = None
def setUp(self):
self.client = ami.AMIClient(**connection)
def build_event(self, event='SomeEvent', **kwargs):
return ami.Event(event, kwargs)
def test_add_event_listener(self):
def event_listener(event, **kwa... |
def test_powerline_decoration(manager_nospawn, minimal_conf_noscreen):
config = minimal_conf_noscreen
config.screens = [libqtile.config.Screen(top=libqtile.bar.Bar([widget.Spacer(length=50, name='one', background='ff0000', decorations=[PowerLineDecoration(size=10, path='arrow_left')]), widget.Spacer(length=50, ... |
def test_calculate_fades():
fader = TrackFader(None, None, None)
calcs = [(0, 4, 0, 0, 10, 0, 0, 6, 10), (None, 4, 0, 0, 10, 0, 0, 6, 10), (4, 0, 0, 0, 10, 0, 4, 10, 10), (4, None, 0, 0, 10, 0, 4, 10, 10), (4, 4, 0, 0, 10, 0, 4, 6, 10), (0, 0, 0, 0, 10, 0, 0, 10, 10), (None, None, 0, 0, 10, 0, 0, 10, 10), (0, 4... |
def output(title, collection, plotter):
print()
print((title[0].upper() + title[1:]))
print(('-' * len(title)))
print()
path = os.path
for p in collection:
print()
print(p)
print(('^' * len(p)))
image = ('_static/gallery/%s/%s.svg' % (title, p))
path = os.... |
def test_set_container_security_context():
config = ''
r = helm_template(config)
c = r['statefulset'][name]['spec']['template']['spec']['containers'][0]
assert (c['securityContext']['capabilities']['drop'] == ['ALL'])
assert (c['securityContext']['runAsNonRoot'] == True)
assert (c['securityConte... |
class PlaybackAdapter():
def __init__(self, player):
self.__player = player
self.__events = ('playback_track_start', 'playback_track_end', 'playback_player_end', 'playback_toggle_pause', 'playback_error')
for e in self.__events:
event.add_callback(getattr(self, ('on_%s' % e)), e,... |
class OptionSeriesArearangeDataDatalabelsTextpath(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def enabled(self):
return self._config_get(False)
def enabled(self, flag: bool):
self._conf... |
def iter_commits(until=None, headers=None):
page = 1
uri = f'{FALCON_REPOSITORY_API}/commits'
resp = requests.get(uri, headers=headers)
resp.raise_for_status()
while (commits := resp.json()):
for commit in commits:
if (until and commit['sha'].startswith(until)):
r... |
class User():
__slots__ = ['uid', 'username', 'password', 'is_admin']
def __init__(self, uid, username, password, is_admin=False):
self.uid = uid
self.username = username
self.password = password
self.is_admin = is_admin
def __repr__(self):
template = 'User id={s.uid}... |
class Test_ofctl_v1_3(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_to_actions_pop_mpls(self):
dp = ofproto_protocol.ProtocolDesc(version=ofproto_v1_3.OFP_VERSION)
acts = [{'type': 'POP_MPLS', 'ethertype': 2048}]
result = ofctl_v1_3.to_ac... |
class TestContract(BaseTestContract, FaucetMixIn):
COIN = COIN
GAS_LIMIT = GAS_LIMIT
PREFIX = PREFIX
def get_ledger(self):
return LedgerClient(NET_CONFIG)
def get_wallet(self):
wallet = LocalWallet.generate(prefix=PREFIX)
self.ask_funds(wallet, self.get_ledger(), )
re... |
def get_concatenated_alg(alg_filenames, models=None, sp_field=0, sp_delimiter='_', kill_thr=0.0, keep_species=None):
if (keep_species is None):
keep_species = set()
concat = SeqGroup()
concat.id2partition = {}
if (not models):
models = (['None'] * len(alg_filenames))
elif (len(models... |
class ModelSerializer(ABC):
def __init__(self, feature_names: Sequence[str], target_type: Optional[str]=None, classification_labels: Optional[Sequence[str]]=None):
self._target_type = target_type
self._feature_names = feature_names
self._classification_labels = classification_labels
def ... |
def open(filename, mode='r', iline=189, xline=193, strict=True, ignore_geometry=False, endian='big'):
if ('w' in mode):
problem = 'w in mode would truncate the file'
solution = 'use r+ to open in read-write'
raise ValueError(', '.join((problem, solution)))
endians = {'little': 256, 'lsb'... |
class OptionPlotoptionsGaugeSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionPlotoptionsGaugeSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionPlotoptionsGaugeSonificationDefaultinstrumentoptionsMappingTremoloDepth)
... |
_identity
_basic_type_str
def abi_bytes_to_hex(abi_type: BasicType, type_str: TypeStr, data: Any) -> Optional[Tuple[(TypeStr, HexStr)]]:
if ((abi_type.base != 'bytes') or abi_type.is_array):
return None
bytes_data = hexstr_if_str(to_bytes, data)
if (abi_type.sub is None):
return (type_str, t... |
def calc_adaptation_matrices(w1: Tuple[(float, float)], w2: Tuple[(float, float)], m: Matrix) -> Tuple[(Matrix, Matrix)]:
first = alg.dot(m, util.xy_to_xyz(w1), dims=alg.D2_D1)
second = alg.dot(m, util.xy_to_xyz(w2), dims=alg.D2_D1)
m2 = alg.diag(alg.divide(first, second, dims=alg.D1))
adapt = cast(Matr... |
def test_state_manipulation():
state = State()
old_dict = state.full_dict = {'a': 1}
old_key = state.key = 'a'
new_dict = {'b': 2}
class MyValidator(Validator):
check_key = None
pre_validator = False
post_validator = False
__unpackargs__ = ('check_key',)
def t... |
def filter_extension_controller_dataplan_data(json):
option_list = ['apn', 'auth_type', 'billing_date', 'capacity', 'carrier', 'iccid', 'modem_id', 'monthly_fee', 'name', 'overage', 'password', 'pdn', 'preferred_subnet', 'private_network', 'signal_period', 'signal_threshold', 'slot', 'type', 'username']
json = ... |
class TrackDB():
def __init__(self, name: str='', location: str='', pickle_attrs: List[str]=[], loadfirst: bool=False):
if (loadfirst and (Track._get_track_count() != 0)):
raise RuntimeError((('Internal error! %d tracks already loaded, ' + 'TrackDB must be loaded first!') % Track._get_track_coun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.