code stringlengths 281 23.7M |
|---|
class AnalysisModuleEdit(QWidget):
def __init__(self, analysis_module: AnalysisModule, ensemble_size: int):
self.analysis_module = analysis_module
self.ensemble_size = ensemble_size
QWidget.__init__(self)
layout = QHBoxLayout()
variables_popup_button = QToolButton()
v... |
class PsychoPyKeyboard(BaseKeyboard):
def __init__(self, keylist=settings.KEYLIST, timeout=settings.KEYTIMEOUT):
try:
copy_docstr(BaseKeyboard, PsychoPyKeyboard)
except:
pass
self.keymap = {'!': 'exclamation', '"': 'doublequote', '#': 'hash', '$': 'dollar', '&': 'ampe... |
def _process_bulk_chunk_error(error: ApiError, bulk_data: List[Union[(Tuple[_TYPE_BULK_ACTION_HEADER], Tuple[(_TYPE_BULK_ACTION_HEADER, _TYPE_BULK_ACTION_BODY)])]], ignore_status: Collection[int], raise_on_exception: bool=True, raise_on_error: bool=True) -> Iterable[Tuple[(bool, Dict[(str, Any)])]]:
if (raise_on_ex... |
class CaseInsensitiveDict(collections.abc.Mapping):
def __init__(self, d):
self._d = d
self._s = dict(((RB.search_fold(k), k) for k in d))
def __contains__(self, k):
return (RB.search_fold(k) in self._s)
def __len__(self):
return len(self._s)
def __iter__(self):
r... |
class OptionPlotoptionsPackedbubbleSonificationTracksMappingFrequency(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 test_move_file():
ali = Aligo()
move = ali.move_file(file_id=test_file, to_parent_file_id=dest_folder)
assert isinstance(move, MoveFileResponse)
assert (move.file_id == test_file)
time.sleep(1)
batch_move = ali.batch_move_files(file_id_list=[test_file], to_parent_file_id=origin_folder)
f... |
def test_not_force_defaults_password_value():
html = '<input type="password" name="password-1" class="my_password" value="i like this password" />'
expected_html = '<input type="password" name="password-1" class="my_password" value="this password is better" />'
rendered_html = htmlfill.render(html, defaults... |
def usage():
print(('\nusage: %s -d <domain> <options>' % sys.argv[0]))
print('options:')
print(' -h, --help Show this help message and exit.')
print(' -V, --version Output version information and exit.')
print(' -D, --debug Debug.')
print('... |
def extractAquaxenontetroxideWordpressCom(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,... |
def DummyTransformerModel(width: int, depth: int):
def _forward(model, tokens, is_train):
width = model.attrs['width']
depth = model.attrs['depth']
shape = (depth, tokens.input_ids.shape[0], tokens.input_ids.shape[1], width)
tensors = torch.zeros(*shape)
return (ModelOutput(l... |
class MistyMonitor(Monitor):
ocr = 'digit5-'
lock = asyncio.Lock()
name = 'Misty'
chat_name = 'FreeEmbyGroup'
chat_user = 'MistyNoiceBot'
chat_keyword = ': (?!0$)'
bot_username = 'EmbyMistyBot'
notify_create_name = True
async def init(self, initial=True):
async with self.lock... |
.parametrize('elasticapm_client', [{'transaction_max_spans': 5}], indirect=True)
def test_logging_filter_span(elasticapm_client):
transaction = elasticapm_client.begin_transaction('test')
with capture_span('test') as span:
f = LoggingFilter()
record = logging.LogRecord(__name__, logging.DEBUG, _... |
.parametrize('toc,msg', [('_toc_emptysections.yml', "entry not a mapping containing 'chapters' key '/parts/0/'"), ('_toc_url.yml', "'root' key not found"), ('_toc_wrongkey.yml', 'Unknown keys found')])
def test_corrupt_toc(build_resources, cli, toc, msg):
(books, tocs) = build_resources
with pytest.raises(Runt... |
class TestEmpty(util.TestCase):
def test_empty(self):
markup = '\n <body>\n <div id="div">\n <p id="0" class="somewordshere">Some text <span id="1"> in a paragraph</span>.</p>\n <a id="2" href=" <span id="3" class="herewords">Direct child</span>\n <pre id="pre" clas... |
class Advection_ASGS(SGE_base):
def __init__(self, coefficients, nd, stabFlag='1', lag=False):
SGE_base.__init__(self, coefficients, nd, lag)
self.stabilizationFlag = stabFlag
def initializeElementQuadrature(self, mesh, t, cq):
import copy
self.mesh = mesh
self.tau = []
... |
class TrioMetricsService(BaseMetricsService):
def session(self) -> Session:
url = self.reporter._get_post_url()
auth_header = self.reporter._generate_auth_header()
return Session(url, headers=auth_header)
async def async_post(self, data: str) -> None:
(await self.session.post(dat... |
class OptionPlotoptionsScatter3dDatasorting(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def matchByName(self):
return self._config_get(None)
def matchByName(self, flag: bool):
self._config(fla... |
class CallGraph():
stack_columns = ['parent', 'depth', 'height', 'first_kernel_start', 'last_kernel_end', 'num_kernels', 'kernel_dur_sum', 'kernel_span']
def __init__(self, trace: Trace, ranks: Optional[List[int]]=None) -> None:
self.trace_data: Trace = trace
_ranks: List[int] = self.trace_data.... |
.parametrize('input, output', [([], []), ([1], [DummyIntEnum.MY_VAL]), ([0, 1], [DummyIntEnum.DEFAULT, DummyIntEnum.MY_VAL]), ([(- 1)], []), ([0, (- 1)], [DummyIntEnum.DEFAULT]), ([DummyIntEnum.DEFAULT], [DummyIntEnum.DEFAULT])])
def test_api_int_enum_convert_list(input, output):
v = DummyIntEnum.convert_list(input... |
def _test_correct_response_for_pop_state(client):
resp = post(client, def_codes=['L', 'M'], geo_layer='state', geo_layer_filters=['WA'], spending_type='obligation', scope='place_of_performance')
expected_response = {'geo_layer': 'state', 'scope': 'place_of_performance', 'spending_type': 'obligation', 'results':... |
def test_pipeline_with_set_output_sklearn_last():
(X, y) = load_iris(return_X_y=True, as_frame=True)
pipeline = make_pipeline(YeoJohnsonTransformer(), StandardScaler(), LogisticRegression()).set_output(transform='default')
pipeline.fit(X, y)
X_t = pipeline[:(- 1)].transform(X)
assert isinstance(X_t,... |
class TestNpk(TestUnpackerBase):
def test_unpacker_selection_generic(self):
self.check_unpacker_selection('firmware/mikrotik-npk', 'MikroTik NPK files')
def test_extraction_bad_file():
file_path = str(Path(get_test_data_dir(), 'test_data_file.bin'))
with TemporaryDirectory() as tmp_dir:
... |
.skip
.django_db
def test_federal_account_spending_over_time(client, financial_spending_data):
resp = client.post('/api/v2/federal_accounts/1/spending_over_time', content_type='application/json', data=json.dumps(simple_payload))
assert (resp.status_code == status.HTTP_200_OK)
assert ('results' in resp.json(... |
class SegmentDataset(Dataset):
def __init__(self, where='train', seq=None):
self.img_list = glob.glob('processed/{}/*/img_*'.format(where))
self.mask_list = glob.glob('processed/{}/*/img_*')
self.seq = seq
def __len__(self):
return len(self.img_list)
def __getitem__(self, idx... |
class Conf():
mutable_attrs = frozenset()
defaults = {}
defaults_types = {}
dyn_finalized = False
dyn_hash = None
def __init__(self, _id, dp_id, conf=None):
self._id = _id
self.dp_id = dp_id
if (conf is None):
conf = {}
if ((self.defaults is not None) ... |
def civitdown2_convertimage(imagejpg_save_path, imagepng_save_path):
from PIL import Image
try:
img = Image.open(imagejpg_save_path)
img_resized = img.resize(((img.width // 2), (img.height // 2)))
img_resized.save(imagepng_save_path)
if os.path.exists(imagejpg_save_path):
... |
class PalindromeProductsTest(unittest.TestCase):
def test_find_the_smallest_palindrome_from_single_digit_factors(self):
(value, factors) = smallest(min_factor=1, max_factor=9)
self.assertEqual(value, 1)
self.assertFactorsEqual(factors, [[1, 1]])
def test_find_the_largest_palindrome_from_... |
class ProverbTest(unittest.TestCase):
def test_zero_pieces(self):
input_data = []
self.assertEqual(proverb(*input_data, qualifier=None), [])
def test_one_piece(self):
input_data = ['nail']
self.assertEqual(proverb(*input_data, qualifier=None), ['And all for the want of a nail.'])... |
def extractTruthiscreationBlogspotCom(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 start_notification(fledge_url, add_service, add_notification_instance, wait_time, retries):
add_service(fledge_url, 'notification', None, retries, installation_type='package', service_name=NOTIF_SERVICE_NAME)
time.sleep(wait_time)
verify_service_added(fledge_url, NOTIF_SERVICE_NAME)
rule_config = {'... |
def validate(typ, obj):
if hasattr(typ, 'fields'):
for (field, subtype) in typ.fields.items():
if (not hasattr(obj, field)):
raise Exception('Field {} not found'.format(field))
validate(subtype, getattr(obj, field))
elif isinstance(typ, list):
for element ... |
.parametrize('port_input,expected_range', [('10-20', range(10, 21)), ('0-65535', range(0, 65536)), ('1-1', range(1, 2))])
def test_argparse_valid_port_range(port_input, expected_range):
parsed = ert_parser(None, [ENSEMBLE_EXPERIMENT_MODE, '--port-range', port_input, 'path/to/config.ert'])
assert (parsed.port_ra... |
def test_get_ijk_from_points():
g1 = xtgeo.grid_from_file(REEKGRID)
pointset = [(456620.790918, 5935660.0, 1727.649124), (456620.80627, 5935660.0, 1744.557755), (467096.108653, 5930145.0, 1812.760864), (333333, 5555555, 1333), (459168., 5931614., 1715.), (464266., 5933844., 1742.)]
po = xtgeo.Points(pointse... |
def test():
assert ('from spacy.tokens import Doc' in __solution__), 'Doc?'
assert (len(spaces) == 5), ''
assert all((isinstance(s, bool) for s in spaces)), 'spaces'
assert ([int(s) for s in spaces] == [0, 1, 1, 0, 0]), 'spaces?'
assert (doc.text == 'Go, get started!'), 'Doc?'
__msg__.good('!') |
class CFFTableTest(unittest.TestCase):
def setUpClass(cls):
with open(CFF_BIN, 'rb') as f:
font = TTFont(file=CFF_BIN)
cffTable = font['CFF2']
cls.cff2Data = cffTable.compile(font)
with open(CFF_TTX, 'r') as f:
cff2XML = f.read()
cff2XML = ... |
def get_abi(contract_source: str, name: str) -> Dict:
input_json = {'language': 'Vyper', 'sources': {name: {'content': contract_source}}, 'settings': {'outputSelection': {'*': {'*': ['abi']}}}}
if (_active_version == Version(vyper.__version__)):
try:
compiled = vyper_json.compile_json(input_... |
.parametrize('num_encoder_layers', [1, 6])
.parametrize('num_decoder_layers', [1, 6])
.parametrize('dim_model', [2, 8])
.parametrize('num_heads', [1, 6])
.parametrize('dim_feedforward', [2, 8])
def test_init(num_encoder_layers: int, num_decoder_layers: int, dim_model: int, num_heads: int, dim_feedforward: int):
_ =... |
def _get_id_token(payload_overrides=None, header_overrides=None):
signer = crypt.RSASigner.from_string(MOCK_PRIVATE_KEY)
headers = {'kid': 'mock-key-id-1'}
payload = {'aud': MOCK_CREDENTIAL.project_id, 'iss': (' + MOCK_CREDENTIAL.project_id), 'iat': (int(time.time()) - 100), 'exp': (int(time.time()) + 3600)... |
def to_probs(model: Dict[(Any, Counter)]) -> Dict[(str, List[Tuple[(str, float)]])]:
probs = dict()
for (feature, counter) in model.items():
ts = counter.most_common()
total = sum([count for (_, count) in ts])
probs[feature] = [(label, (count / total)) for (label, count) in ts]
retur... |
class OptionPlotoptionsPictorialSonificationDefaultinstrumentoptionsMappingPlaydelay(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 RRDB(nn.Module):
def __init__(self, num_feat, num_grow_ch=32):
super().__init__()
self.rdb1 = ResidualDenseBlock(num_feat, num_grow_ch)
self.rdb2 = ResidualDenseBlock(num_feat, num_grow_ch)
self.rdb3 = ResidualDenseBlock(num_feat, num_grow_ch)
def forward(self, x):
... |
def pytest_generate_tests(metafunc):
test_yaml = []
paths = sorted(base_path.glob('**/*.yaml'))
idlist = []
for path in paths:
stem = path.stem
if stem.startswith('.#'):
continue
idlist.append(stem)
test_yaml.append([path])
metafunc.parametrize(['yaml'], t... |
class Test(testbase.ClassSetup):
def setUpClass(cls):
super().setUpClass()
cls.g_comp.load_formula_file('gf4d.frm')
cls.g_comp.load_formula_file('gf4d.cfrm')
cls.g_comp.load_formula_file('test.frm')
def setUp(self):
self.f = fractal.T(Test.g_comp)
self.f.render_ty... |
def main(self, context):
bm = bmesh.from_edit_mesh(bpy.context.active_object.data)
uv_layers = bm.loops.layers.uv.verify()
op_select_islands_outline.select_outline(self, context)
selection = {loop for face in bm.faces if face.select for loop in face.loops if loop[uv_layers].select_edge}
if selection... |
class OptionSeriesArcdiagramSonificationContexttracksMappingHighpass(Options):
def frequency(self) -> 'OptionSeriesArcdiagramSonificationContexttracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionSeriesArcdiagramSonificationContexttracksMappingHighpassFrequency)
def resonanc... |
_type(ofproto.OFPQDPT_MAX_RATE)
class OFPQueueDescPropMaxRate(OFPQueueDescProp):
def __init__(self, type_=None, length=None, rate=None):
self.type = type_
self.length = length
self.rate = rate
def parser(cls, buf):
maxrate = cls()
(maxrate.type, maxrate.length, maxrate.ra... |
class OptionSeriesDumbbellSonificationContexttracksMappingRate(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):
s... |
def convert_to_partial_project(project=None):
inner_tasks = aliased(Task.__table__)
subquery = DBSession.query(inner_tasks.c.id).filter((inner_tasks.c.project_id == Project.id))
return DBSession.query(Project.id, Project.name, Project.entity_type, Project.status_id, subquery.exists().label('has_children')).... |
class LoginTest(unittest.TestCase):
client = None
def setUp(self):
self.client = ami.AMIClient(**connection)
self.client.connect()
def tearDown(self):
future = self.client.logoff()
if (future is not None):
future.get_response()
self.client.disconnect()
... |
def test_success_with_all_filters(client, monkeypatch, elasticsearch_transaction_index, awards_and_transactions):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
resp = client.post('/api/v2/search/spending_by_category/county', content_type='application/json', data=json.dumps({'filters': n... |
def draw_multipolygon(path: Path) -> None:
grid: Grid = Grid()
outer_node: OSMNode = grid.add_node({}, 0, 0)
outer_nodes: list[OSMNode] = [outer_node, grid.add_node({}, 0, 3), grid.add_node({}, 3, 3), grid.add_node({}, 3, 0), outer_node]
inner_node: OSMNode = grid.add_node({}, 1, 1)
inner_nodes: lis... |
def setup_logging(name, verbose=False):
import subprocess
import datetime
hostname = str(subprocess.check_output('hostname').rstrip())
now = datetime.datetime.today().strftime('%Y-%m-%d-%H:%M')
log_name = '{name}-{hostname}-{now}'.format(name=name, hostname=hostname, now=now)
logging.basicConfig... |
class MultiUnitRenderer(DefaultRenderer):
def __init__(self, color='black', font='ARIAL', fontsize=8, suppress_warnings=False):
self.suppress_warnings = suppress_warnings
DefaultRenderer.__init__(self, color, font, fontsize)
def DrawForeground(self, grid, attr, dc, rect, row, col, isSelected):
... |
_ns.route('/github/<int:copr_id>/<uuid>/', methods=['POST'])
_ns.route('/github/<int:copr_id>/<uuid>/<string:pkg_name>/', methods=['POST'])
def webhooks_git_push(copr_id: int, uuid, pkg_name: Optional[str]=None):
if (flask.request.headers['X-GitHub-Event'] == 'ping'):
return ('OK', 200)
copr = ComplexLo... |
class Entity(_BaseLink):
_ADD_PRECEEDING_WS = False
_ADD_SUCEEDING_WS = False
_CLEAR_PRECEEDING_WS = False
_LABEL_OPERATOR = '+'
def __init__(self, variable=None, labels=None, **properties):
if (not isinstance(labels, Label)):
labels = Label(labels)
labels.operator = self... |
def load_cache():
if os.path.exists(STATIC_CACHE_FILE):
try:
with open(STATIC_CACHE_FILE, 'rb') as f:
r = zlib.decompress(f.read())
r = pickle.loads(r)
if (('v' in r) or (r['v'] == STATIC_CACHE_VERSION)):
return r
except... |
def run_on_file(target: Path, export: t.Optional[Path], list_ignored: bool, include_sym: t.List[str], include_nontop: bool, skip_sym: t.List[str], skip_stripped: bool, ignore_metrics: bool, score_weights: t.List[float]) -> None:
analyzer: t.TypeVar[AnalysisBackend]
extension = target.suffix
if (extension in... |
class ComponentLoader():
def __init__(self, root_path, component_entry_point, recurse=True):
self.root_path = root_path
self.component_entry_point = component_entry_point
self.recurse = recurse
self.logger = logging.getLogger(__name__)
def _modules(self, module_paths, component_n... |
def main(argv):
gui = GUI()
workbench = ExampleUndo(state_location=gui.state_location)
window = workbench.create_window(position=(300, 300), size=(400, 300))
window.open()
label = Label(text='Label')
label2 = Label(text='Label2')
window.edit(label)
window.edit(label2)
gui.start_event... |
class bsn_port_counter_stats_request(bsn_stats_request):
version = 6
type = 18
stats_type = 65535
experimenter = 6035143
subtype = 8
def __init__(self, xid=None, flags=None, port_no=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (... |
def create_item_from_template(doc):
disabled = doc.disabled
if (doc.is_billable and (not doc.disabled)):
disabled = 0
uom = (frappe.db.exists('UOM', 'Unit') or frappe.db.get_single_value('Stock Settings', 'stock_uom'))
item = frappe.get_doc({'doctype': 'Item', 'item_code': doc.template, 'item_na... |
('config_name, overrides, expected', [param('empty', [], DefaultsTreeNode(node=ConfigDefault(path='empty')), id='empty'), param('config_default', [], DefaultsTreeNode(node=ConfigDefault(path='config_default'), children=[ConfigDefault(path='empty'), ConfigDefault(path='_self_')]), id='config_default'), param('group_defa... |
class SNMPv1SecurityModel(SecurityModel[(PDU, Sequence)]):
def generate_request_message(self, message: PDU, security_engine_id: bytes, credentials: Credentials) -> Sequence:
if (not isinstance(credentials, V1)):
raise SnmpError('Credentials for the SNMPv1 security model must be V1 instances!')
... |
def _validate_write_steps(steps: list) -> tuple:
write_step_values = []
macro_step_values = []
for k in steps:
for (k1, v1) in k.items():
if (k1 == 'write'):
for (k2, v2) in v1['values'].items():
if (v2.startswith('$') and v2.endswith('$')):
... |
def test_missing_envs_required(config, ini_config_file_3):
with open(ini_config_file_3, 'w') as file:
file.write('[section]\nundefined=${UNDEFINED}\n')
config.set_ini_files([ini_config_file_3])
with raises(ValueError, match='Missing required environment variable "UNDEFINED"'):
config.load(en... |
def writeBoard(save):
for i in range(8):
for j in range(8):
save.write(str(board.Grid(i, j).pieceStatus))
save.write(',')
save.write(str(board.Grid(i, j).color))
save.write(',')
save.write(str(board.Grid(i, j).row))
save.write(',')
... |
.django_db
def test_adding_rows(disable_vacuuming, remove_csv_file):
assert (ObjectClass.objects.count() == 0)
mock_data(GOOD_SAMPLE)
call_command('load_object_classes', object_class_file=str(OBJECT_CLASS_FILE))
assert (ObjectClass.objects.count() == 6)
mock_data(ADDITIONAL_SAMPLE)
call_command(... |
(scope='module')
def fontfile():
class Glyph(object):
def __init__(self, empty=False, **kwargs):
if (not empty):
self.draw = partial(self.drawRect, **kwargs)
else:
self.draw = (lambda pen: None)
def drawRect(pen, xMin, xMax):
pen.mo... |
def rangestring_to_list(rangestring: str) -> List[int]:
result = set()
if (rangestring == ''):
return []
for _range in rangestring.split(','):
if ('-' in _range):
if (len(_range.strip().split('-')) != 2):
raise ValueError(f'Wrong range syntax {_range}')
... |
class CellRendererParams(Options):
def checkbox(self):
return self._config_get()
def checkbox(self, flag: bool):
self._config(flag)
def suppressCount(self):
return self._config_get()
def suppressCount(self, flag: bool):
self._config(flag)
def innerRenderer(self, js_fu... |
class ShHvac():
def __init__(self, tydom_attributes, tydom_client=None, mqtt=None):
self.config_topic = None
self.topic_to_func = None
self.config = None
self.device = None
self.attributes = tydom_attributes
self.device_id = self.attributes['device_id']
self.e... |
def parse_arguments(args=None):
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False, description='\nNormalizes given matrices either to the smallest given read number of all matrices or to 0 - 1 range. However, it does NOT compute the contact probability.\n\nWe reco... |
class QueryCounter(object):
def __init__(self):
self.count = 0
def __enter__(self):
self._start = len(connection.queries)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.count = (len(connection.queries) - self._start)
self.queries = connection.queries[... |
class TestMain(BaseTaskTestCase):
('bodhi.server.models.mail')
def test_autokarma_update_meeting_time_requirements_gets_one_comment(self, mail):
update = self.db.query(models.Update).all()[0]
update.autokarma = True
update.autotime = False
update.request = None
update.sta... |
def _get_trainer_callbacks(cfg: CfgNode) -> List[Callback]:
callbacks: List[Callback] = [TQDMProgressBar(refresh_rate=10), LearningRateMonitor(logging_interval='step'), ModelCheckpoint(dirpath=cfg.OUTPUT_DIR, save_last=True)]
if cfg.QUANTIZATION.QAT.ENABLED:
callbacks.append(QuantizationAwareTraining.fr... |
def test_sparseFactorPrepare_1(simple_nonsingular_sparse_mat):
A = simple_nonsingular_sparse_mat
sparseFactor = superluWrappers.SparseFactor(A.nr)
superluWrappers.sparseFactorPrepare(A, sparseFactor)
x = np.ones(A.nr)
superluWrappers.sparseFactorSolve(sparseFactor, x)
assert np.array_equal(x, np... |
class JvmStatsSummary(InternalTelemetryDevice):
serverless_status = serverless.Status.Internal
def __init__(self, client, metrics_store):
super().__init__()
self.metrics_store = metrics_store
self.client = client
self.jvm_stats_per_node = {}
def on_benchmark_start(self):
... |
class OptionSeriesBubbleSonificationTracksMappingTremoloDepth(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):
se... |
class InstanceChoiceItem(ABCHasStrictTraits):
name = Str()
view = AView
is_factory = Bool(False)
def get_name(self, object=None):
return self.name
def get_view(self):
return self.view
def get_object(self):
pass
def is_compatible(self, object):
pass
def is_... |
class TopicModel(QStandardItemModel):
header = [('Name', 300), ('Publisher', 50), ('Subscriber', 50), ('Type', (- 1))]
def __init__(self):
QStandardItemModel.__init__(self)
self.setColumnCount(len(TopicModel.header))
self.setHorizontalHeaderLabels([label for (label, _) in TopicModel.head... |
def mappings_test(download_type, sublevel):
download_mapping = VALUE_MAPPINGS[download_type]
table_name = download_mapping['table_name']
table = download_mapping['table']
annotations_function = download_mapping.get('annotations_function')
try:
if (annotations_function is not None):
... |
def create_resource_from_json(resource_type, parent, json_string):
if (resource_type not in _RESOURCE_TYPE_MAP):
return None
resource_type = _RESOURCE_TYPE_MAP[resource_type]
if (not resource_type.get('can_create_resource')):
return None
return resource_type.get('class').from_json(parent... |
class Chain(metaclass=_Singleton):
def __init__(self) -> None:
self._time_offset: int = 0
self._snapshot_id: Optional[int] = None
self._reset_id: Optional[int] = None
self._current_id: Optional[int] = None
self._undo_lock = threading.Lock()
self._undo_buffer: List = [... |
def test_outputs_formats():
values = [[1, 2, 3], [(- 1), 0, 1]]
w = Fxp(values, True, 16, 8)
like_ref = Fxp(None, True, 24, 12)
out_ref = Fxp(None, True, 24, 8)
if (version.parse(np.__version__) >= version.parse('1.21')):
from fxpmath.functions import add
z = add(w, 2, out_like=like_... |
class BusinessOwnedObjectOnBehalfOfRequest(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isBusinessOwnedObjectOnBehalfOfRequest = True
super(BusinessOwnedObjectOnBehalfOfRequest, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
... |
class TodoApp(ft.UserControl):
def build(self):
self.new_task = ft.TextField(hint_text='What needs to be done?', on_submit=self.add_clicked, expand=True)
self.tasks = ft.Column()
self.filter = ft.Tabs(selected_index=0, on_change=self.tabs_changed, tabs=[ft.Tab(text='all'), ft.Tab(text='activ... |
class Message():
__slots__ = ['msg_id', 'cmd_id', 'data_len', 'data', 'peer_id']
def __init__(self):
self.msg_id = 0
self.cmd_id = ServerCmdEnum.CmdNone
self.data_len = 0
self.peer_id = 0
self.data = bytearray()
def __str__(self):
return f'msg_id:{self.msg_id}... |
class ProtocolAnalysis(dict, metaclass=MadType):
classification: Classification
top_keywords: Keywords
language_score: LanguageScore
sentiment: Sentiment
embedding: Embedding
gender: Gender
source_type: SourceType
text_type: TextType
emotion: Emotion
irony: Irony
age: Age |
class SchemaspaceInstall(SchemaspaceBase):
replace_flag = Flag('--replace', name='replace', description='Replace an existing instance', default_value=False)
name_option = CliOption('--name', name='name', description='The name of the metadata instance to install')
file_option = FileOption('--file', name='fil... |
def line_transformation_suggestor(line_transformation, line_filter=None):
def suggestor(lines):
for (line_number, line) in enumerate(lines):
if (line_filter and (not line_filter(line))):
continue
candidate = line_transformation(line)
if (candidate is None)... |
def test_create_backfiller_parallel():
daily_lp = LaunchPlan.get_or_create(workflow=example_wf, name='daily', fixed_inputs={'v': 10}, schedule=CronSchedule(schedule='0 8 * * *', kickoff_time_input_arg='t'))
start_date = datetime(2022, 12, 1, 8)
end_date = (start_date + timedelta(days=10))
(wf, start, en... |
class Solution():
def diffWaysToCompute(self, input: str) -> List[int]:
def calc(num1, num2, op):
if (op == '+'):
return (num1 + num2)
elif (op == '-'):
return (num1 - num2)
elif (op == '*'):
return (num1 * num2)
def... |
class RelationshipMemberServiceInvitation(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():
... |
class AllTagsDialog(Gtk.Window):
def __init__(self, exaile, callback):
Gtk.Window.__init__(self)
self.set_title(_('Get all tags from collection'))
self.set_resizable(True)
self.set_size_request(150, 400)
self.add(Gtk.Frame())
vbox = Gtk.Box(orientation=Gtk.Orientation... |
def _unpack_map(code, read_fn):
if ((ord(code) & 240) == 128):
length = (ord(code) & (~ 240))
elif (code == b'\xde'):
length = _struct_unpack('>H', read_fn(2))[0]
elif (code == b'\xdf'):
length = _struct_unpack('>I', read_fn(4))[0]
else:
raise Exception(('logic error, not... |
def test_global_config_equal_config_defaults() -> None:
config1 = RichHelpConfiguration()
config2 = RichHelpConfiguration.load_from_globals(rc)
for k in {*config1.__dict__.keys(), *config2.__dict__.keys()}:
if (k == 'highlighter'):
continue
v1 = config1.__dict__[k]
v2 = c... |
()
('hash_', metavar='hash', type=str, required=True)
('target_dir', type=click.Path(dir_okay=True, file_okay=False, resolve_path=True), required=False)
_context
def download(click_context: click.Context, hash_: str, target_dir: Optional[str]) -> None:
target_dir = (target_dir or os.getcwd())
ipfs_tool = click_... |
def check_branch_out_of_sync(proj_dir, branch):
check_exists_with_error()
out_of_sync = False
remote_branches = get_branches(proj_dir)
local_rev = get_local_rev(proj_dir, branch)
if (branch in remote_branches):
remote_rev = get_remote_rev(proj_dir, remote_branches[branch])
out_of_syn... |
def compare_events(x: Event, y: Event) -> int:
result = (x.time - y.time)
if (result == 0):
if (x.type == y.type):
if (x.type == EVENT_START):
if (x.dur == y.dur):
result = ((- 1) if (x.idx < y.idx) else (1 if (x.idx > y.idx) else 0))
else:... |
def test_predict_proba_nonnegative():
def check_for_negative_prob(proba):
for p in np.ravel(proba):
assert (np.round(p, 7) >= 0)
clf = mord.LogisticAT(alpha=0.0)
clf.fit(X, y)
check_for_negative_prob(clf.predict_proba(X))
clf2 = mord.LogisticIT(alpha=0.0)
clf2.fit(X, y)
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.