code stringlengths 281 23.7M |
|---|
class bezier(TestCase):
def test_line(self):
line = element.getsimplex(1)
for n in range(2, 8):
bezier = line.getpoints('bezier', n)
self.assertEqual(bezier.npoints, n)
self.assertEqual(len(bezier.tri), (n - 1))
self.assertEqual(len(bezier.hull), 2)
... |
class AsyncOpenAIAPI():
def __init__(self):
self.maximum_retries = 20
self.complete_api_call_queue = asyncio.PriorityQueue()
self.complete_api_worker = asyncio.create_task(self.api_complete_worker(self.complete_api_call_queue))
self.request_ctr = 0
self.request_ctr_offset =
... |
class MyBuddyBlueTooth(MyBuddyCommandGenerator):
_write = write
def __init__(self, bt_address=None, port=10):
super(MyBuddyBlueTooth).__init__()
self.ble = BluetoothConnection(bt_address, port)
self.sock = self.ble.connect_target_device()
def connect(self, serialport='/dev/ttyAMA0', ... |
.parametrize('value, test_value, expected_result', ((approx(1, relative=0.5), 1.3, True), (approx(1, relative=0.5), 0.5, True), (approx(1, relative=0.5), 1.51, False), (approx(1, relative=0.5), 0.49, False), (approx(10, absolute=0.5), 10.4, True), (approx(10, absolute=0.5), 10.5, True), (approx(10, absolute=0.5), 9.5, ... |
class FaucetStringOfDPLACPUntaggedTest(FaucetMultiDPTestBase):
NUM_DPS = 2
NUM_HOSTS = 2
SOFTWARE_ONLY = True
match_bcast = {'dl_vlan': 100, 'dl_dst': 'ff:ff:ff:ff:ff:ff'}
action_str = 'OUTPUT:%u'
def setUp(self):
super().set_up(stack=False, n_dps=self.NUM_DPS, n_untagged=self.NUM_HOSTS,... |
class PackInfo(models.Model):
class Meta():
verbose_name = 'Appliance Pack Information'
ampp = models.OneToOneField(db_column='appid', to='AMPP', on_delete=models.CASCADE, help_text='AMPP')
reimb_stat = models.ForeignKey(db_column='reimb_statcd', to='ReimbursementStatus', on_delete=models.CASCADE, h... |
class OptionSeriesBubbleSonificationContexttracksMappingFrequency(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 auto_compilation(on=True, args=None, use_cache_dir=None):
if (args is not None):
coconut_importer.set_args(args)
if (use_cache_dir is not None):
coconut_importer.use_cache_dir(use_cache_dir)
if on:
if (coconut_importer not in sys.meta_path):
sys.meta_path.insert(0, co... |
()
('path')
def extract(path):
(audio, sr) = librosa.load(path, sr=44100, mono=True)
audio = torch.from_numpy(audio).unsqueeze(0).to(device)
mel = get_mel_from_audio(audio, sr, f_min=f_min, f_max=f_max, n_mels=n_mels).cpu().numpy()
logger.info(f'Got mel spectrogram with shape {mel.shape}')
np.save((... |
class AdAssetFeedSpecBody(AbstractObject):
def __init__(self, api=None):
super(AdAssetFeedSpecBody, self).__init__()
self._isAdAssetFeedSpecBody = True
self._api = api
class Field(AbstractObject.Field):
adlabels = 'adlabels'
text = 'text'
url_tags = 'url_tags'
... |
def test_load_data(postgres_loader, monkeypatch):
mock_cursor = MagicMock()
monkeypatch.setattr(postgres_loader, 'cursor', mock_cursor)
query = 'SELECT * FROM table'
mock_cursor.fetchall.return_value = [(1, 'data1'), (2, 'data2')]
result = postgres_loader.load_data(query)
assert ('doc_id' in res... |
def _add_common_task_arguments_to_command_parser(command_parser):
command_parser.add_argument('-d', '--deadline', help='Deadline of the task, in the YYYY-MM-DD (ISO 8601) format, or as a delay in the <n>(s|m|h|d|w) format, where <n> is an integer and what follows represents respectively seconds, minutes, hours, day... |
def create_new_account(data_dir, password, **geth_kwargs):
if os.path.exists(password):
geth_kwargs['password'] = password
(command, proc) = spawn_geth(dict(data_dir=data_dir, suffix_args=['account', 'new'], **geth_kwargs))
if os.path.exists(password):
(stdoutdata, stderrdata) = proc.communi... |
class FakeASE():
def __init__(self, calc):
self.calc = calc
self.results = dict()
def get_atoms_coords(self, atoms):
return (atoms.get_chemical_symbols(), (atoms.get_positions().flatten() / BOHR2ANG))
def get_potential_energy(self, atoms=None):
(atoms, coords) = self.get_atom... |
class XVProcessException(XVEx):
def __init__(self, cmd, retcode, stdout, stderr):
self.cmd = cmd
self.retcode = retcode
self.stdout = (stdout if stdout else '<no output>')
self.stderr = (stderr if stderr else '<no output>')
super().__init__(self._msg())
def _msg(self):
... |
class IamPolicyScanner(base_scanner.BaseScanner):
SCANNER_OUTPUT_CSV_FMT = 'scanner_output_iam.{}.csv'
def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, rules):
super(IamPolicyScanner, self).__init__(global_configs, scanner_configs, service_config, model... |
_on_exception
class TestFullTextTeiTrainingDataGenerator():
def test_should_include_layout_document_text_in_tei_output(self):
training_data_generator = get_tei_training_data_generator()
layout_document = LayoutDocument.for_blocks([LayoutBlock.for_text(TEXT_1)])
xml_root = training_data_gener... |
def _get_metric_hover(metric: Metric, value: 'PanelValue'):
params = []
for (name, v) in metric.dict().items():
if (name in ['type']):
continue
if (v is None):
continue
params.append(f'{name}: {v}')
params_join = '<br>'.join(params)
hover = f'<b>Timestamp:... |
def generate_wiki_per_category(output_path, update_readme: bool=True):
repo_df = get_repo_list()
for category in repo_df['category'].unique():
category_df = repo_df[(repo_df['category'] == category)].copy()
url_md_list = []
for (idx, irow) in category_df[['name', 'url']].iterrows():
... |
class TestCustomWebhook(CoprsTestCase):
def custom_post(self, data, token, copr_id, package_name=None):
url = '/webhooks/custom/{copr_id}/{uuid}/'
url = url.format(uuid=token, copr_id=copr_id)
if package_name:
url = '{0}{1}/'.format(url, package_name)
return self.tc.post(... |
class Test(object):
def __init__(self, test_dict, ruleset_meta):
self.test_dict = test_dict
self.ruleset_meta = ruleset_meta
self.test_title = self.test_dict['test_title']
self.stages = self.build_stages()
self.enabled = True
if ('enabled' in self.test_dict):
... |
def fortios_firewall(data, fos):
fos.do_member_operation('firewall', 'auth-portal')
if data['firewall_auth_portal']:
resp = firewall_auth_portal(data, fos)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'firewall_auth_portal'))
return ((not is_successful_status(resp)), (is_su... |
def page_for_app_request(request, *, queryset=None):
if (queryset is None):
queryset = _APPS_MODEL._default_manager.active().with_tree_fields()
return queryset.get(language_code=request.resolver_match.namespaces[0][(len(_APPS_MODEL.LANGUAGE_CODES_NAMESPACE) + 1):], app_namespace=request.resolver_match.n... |
class OptionSeriesSankeyLevelsDatalabelsTextpath(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._confi... |
.parametrize('dfsr_filename', ['dfsr-depth-reprc-bad.lis.part', 'dfsr-depth-reprc-none.lis.part'])
def test_depth_mode_1_repcode_invalid(tmpdir, merge_lis_prs, dfsr_filename):
fpath = os.path.join(str(tmpdir), 'depth-reprc-invalid.lis')
content = ((headers + [('data/lis/records/curves/' + dfsr_filename)]) + tra... |
def test_get_vulnerability_stats(stats_updater, backend_db):
assert (stats_updater.get_known_vulnerabilities_stats() == {'known_vulnerabilities': []})
vuln_plugin_summaries = [['Heartbleed', 'WPA_Key_Hardcoded'], ['Heartbleed'], ['not available']]
_add_objects_with_summary('known_vulnerabilities', vuln_plug... |
class MSpinField(HasTraits):
value = Range(low='minimum', high='maximum')
bounds = Tuple(Int, Int)
minimum = Property(Int, observe='bounds')
maximum = Property(Int, observe='bounds')
wrap = Bool()
def __init__(self, **traits):
value = traits.pop('value', None)
if ('bounds' in tra... |
class TestUCS(util.ColorAssertsPyTest):
COLORS = [('red', 'color(--ucs 0.27493 0.21264 0.12243)'), ('orange', 'color(--ucs 0.36462 0.48173 0.48122)'), ('yellow', 'color(--ucs 0.51332 0.92781 1.076)'), ('green', 'color(--ucs 0.05146 0.15438 0.20584)'), ('blue', 'color(--ucs 0.12032 0.07219 0.49331)'), ('indigo', 'co... |
def extractLibratranslationsknWordpressCom(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 archive_version():
if ('$' in ARCHIVE_COMMIT_HASH):
raise ValueError('This does not appear to be an archive.')
version_template = (RELEASED_VERSION if IS_RELEASED else UNRELEASED_VERSION)
version = version_template.format(major=MAJOR, minor=MINOR, micro=MICRO, prerelease=PRERELEASE, dev='-unknow... |
def validate_production_diffs(datapoints: list[dict[(str, Any)]], max_diff: dict, logger: Logger):
if (len(datapoints) < 2):
return datapoints
datapoints = [x for x in datapoints if x]
datapoints = sorted(datapoints, key=(lambda x: x['datetime']))
ok_diff = pd.Series(np.ones_like(datapoints, dty... |
class BoxSelectTool(BaseTool):
event_state = Enum('normal', 'selecting')
def normal_left_down(self, event):
self.event_state = 'selecting'
self.selecting_mouse_move(event)
def selecting_left_up(self, event):
self.event_state = 'normal'
def selecting_mouse_move(self, event):
... |
class TestCheckLanguageFormat():
def test_valid_language_code(self):
assert (check_language_format('en') == True), '"en" should be a valid language'
def test_valid_language_code_with_region(self):
assert (check_language_format('en-US') == True), '"en-US" should be a valid language'
def test_... |
(scope='function')
def fullstory_erasure_data(fullstory_secrets, fullstory_test_client: FullstoryTestClient, fullstory_erasure_identity_id) -> Generator:
user_id = fullstory_erasure_identity_id
user_response = fullstory_test_client.get_user(user_id)
user = user_response.json()
user_data = {'displayName'... |
def test_db_reset_dev_mode_disabled(test_config: FidesConfig, test_config_dev_mode_disabled: FidesConfig, test_client: TestClient) -> None:
error_message = 'Resetting the application database outside of dev_mode is not supported.'
response = test_client.post(((test_config.cli.server_url + API_PREFIX) + '/admin/... |
def convert_mod():
scaling_factor = calculate_ratio()
if (not isinstance(scaling_factor, float)):
scaling_factor = float(scaling_factor)
x = float_to_hex(scaling_factor)
if (not blyt_folder):
status_label.config(text='Error: Please select the BLYT folder.')
return
if (not num... |
def clean_after(func: Callable) -> Callable:
def wrapper(context: Union[(Context, click.core.Context)], *args: Any, **kwargs: Any) -> Callable:
ctx = _cast_ctx(context)
try:
return func(context, *args, **kwargs)
except click.ClickException as e:
_rmdirs(*ctx.clean_pat... |
def extractNirellatranslationsTumblrCom(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, t... |
class OptionPlotoptionsDumbbellSonificationDefaultinstrumentoptionsPointgrouping(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, f... |
def build_acl_entry(acl_table, rule_conf, meters, acl_allow_inst, acl_force_port_vlan_inst, port_num=None, vlan_vid=None, tunnel_rules=None, source_id=None):
acl_inst = []
acl_act = []
acl_match_dict = {}
acl_ofmsgs = []
acl_cookie = None
allow_inst = acl_allow_inst
for (attrib, attrib_value... |
class Game(Model):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self._phase = Phase.PRE_GAME
self._registration = Registration()
self._conf = None
self._initialization = None
self._initial_agent_states = None
self._current_agent_states... |
def deprecated_version_later_than_added(version_deprecated: Optional[FidesVersion], values: Dict) -> Optional[FidesVersion]:
if (not version_deprecated):
return None
if (version_deprecated < values.get('version_added', Version('0'))):
raise FidesValidationError("Deprecated version number can't b... |
class OptionPlotoptionsPyramid3dSonificationContexttracksActivewhen(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, num: f... |
class VirtualPythonEnvironment(BaseEnvironment[Path], make_thread_safe=True):
requirements: List[str]
inherit_from_local: bool = False
def from_config(cls, config: Dict[(str, Any)]) -> VirtualPythonEnvironment:
requirements = config.get('requirements', [])
inherit_from_local = config.get('_i... |
class _ComputeInstanceGroupsRepository(repository_mixins.AggregatedListQueryMixin, repository_mixins.ListQueryMixin, _base_repository.GCPRepository):
def __init__(self, **kwargs):
super(_ComputeInstanceGroupsRepository, self).__init__(component='instanceGroups', **kwargs)
def list_instances(self, resour... |
class Solution():
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
dic = collections.defaultdict(set)
neigh = collections.defaultdict(set)
for (i, j) in prerequisites:
dic[i].add(j)
neigh[j].add(i)
stack = [i for i in range(nu... |
def get_dynamic_dims(*shapes: List[List[IntVar]]) -> List[IntVar]:
res = {}
for shape in shapes:
for dim in shape:
if (not isinstance(dim, IntImm)):
res[dim._attrs['name']] = dim
if isinstance(dim, JaggedIntVar):
batch_dim = dim.batch_dim()... |
class ResourceMixin(BaseModel):
__possible_permissions__ = ()
_attr
def __tablename__(self):
return 'resources'
_attr
def resource_id(self):
return sa.Column(sa.Integer(), primary_key=True, nullable=False, autoincrement=True)
_attr
def parent_id(self):
return sa.Colum... |
class OptionSeriesLollipopSonificationTracksMappingRate(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
self._co... |
class Servo():
def __init__(self, pin: str, pwm_generator: PWMGenerator=None, min_angle_pulse: int=500, max_angle_pulse: int=2500, angle_range: int=180, frequency: float=50):
self._pwm = (PWMGenerator() if (pwm_generator is None) else pwm_generator)
self._pin = pin
self._angle = None
... |
class OptionSeriesOrganizationSonificationTracksActivewhen(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, num: float):
... |
class Rec2100PQ(sRGB):
BASE = 'rec2020-linear'
NAME = 'rec2100pq'
SERIALIZE = ('--rec2100pq',)
WHITE = WHITES['2deg']['D65']
def to_base(self, coords: Vector) -> Vector:
return alg.divide(util.pq_st2084_eotf(coords), util.YW, dims=alg.D1_SC)
def from_base(self, coords: Vector) -> Vector:... |
class MergeSlashesDisabled(AmbassadorTest):
target: ServiceType
def init(self):
self.target = HTTPBin()
def config(self) -> Generator[(Union[(str, Tuple[(Node, str)])], None, None)]:
(yield (self, self.format('\n---\napiVersion: getambassador.io/v3alpha1\nkind: Mapping\nname: {self.name}\nh... |
class OptionPlotoptionsTreemapSonificationDefaultspeechoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('last')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bo... |
def main(sc, spark):
corpus = load_corpus(sc, spark)
pipeline = Pipeline(stages=[Tokenizer(inputCol='text', outputCol='tokens'), Word2Vec(vectorSize=7, minCount=0, inputCol='tokens', outputCol='vecs'), BisectingKMeans(k=10, featuresCol='vecs', maxIter=10)])
model = pipeline.fit(corpus)
corpus = model.tr... |
class SpacesTrajectoryRecord(TrajectoryRecord[StructuredSpacesRecord]):
def stack(self) -> StructuredSpacesRecord:
return StructuredSpacesRecord.stack_records(self.step_records)
def stack_trajectories(cls, trajectories: List['SpacesTrajectoryRecord']) -> 'SpacesTrajectoryRecord':
assert (len(set... |
class OptionSeriesArearangeSonificationDefaultspeechoptionsMappingPlaydelay(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: st... |
class SioClientConnection(SioConnection):
_sio: socketio.AsyncClient = None
def __init__(self, sio: socketio.AsyncClient):
self._sio = sio
async def emit(self, msg_type: str, msg: str, user_id: str, session_id: str, message_id: str):
data = assemble_json_message(msg_type, msg, user_id, sessi... |
class TestPytorchModel():
.parametrize('model_id,task,text_input,value', TEXT_PREDICTION_MODELS)
def test_text_prediction(self, model_id, task, text_input, value, quantize):
with tempfile.TemporaryDirectory() as tmp_dir:
ptm = download_model_and_start_deployment(tmp_dir, quantize, model_id, ... |
def test_regular_polygon_aperture():
pupil_diameter = 1
for num_sides in [6, 5]:
for angle in [0, 15]:
name = 'polygon/pupil'
name += ('_rotated' if (angle != 0) else '')
name += ('_hex' if (num_sides == 6) else '_pent')
check_aperture(make_regular_polygon... |
.django_db
def test_query_search(client, disaster_account_data, elasticsearch_account_index, monkeypatch, helpers):
helpers.patch_datetime_now(monkeypatch, 2022, 12, 31)
setup_elasticsearch_test(monkeypatch, elasticsearch_account_index)
resp = helpers.post_for_spending_endpoint(client, url, query='Agency 00... |
class Envy(TreatAs, Skill):
treat_as = DemolitionCard
skill_category = ['character', 'active']
def check(self):
cards = self.associated_cards
if (len(cards) != 1):
return False
c = cards[0]
if (c.resides_in is None):
return False
if (c.resides_... |
def train_model(train_file, eval_file, scale, output_dir):
train_dataset = TrainAugmentDataset(train_file, scale=scale)
val_dataset = EvalDataset(eval_file)
training_args = TrainingArguments(output_dir=output_dir, num_train_epochs=1000)
config = DdbpnConfig(scale=scale)
model = DdbpnModel(config)
... |
class table_O_S_2f_2(DefaultTable.DefaultTable):
dependencies = ['head']
def decompile(self, data, ttFont):
(dummy, data) = sstruct.unpack2(OS2_format_0, data, self)
if (self.version == 1):
(dummy, data) = sstruct.unpack2(OS2_format_1_addition, data, self)
elif (self.version ... |
class TestDataFrameKeys(TestData):
def test_ecommerce_keys(self):
pd_ecommerce = self.pd_ecommerce()
ed_ecommerce = self.ed_ecommerce()
pd_keys = pd_ecommerce.keys()
ed_keys = ed_ecommerce.keys()
assert_index_equal(pd_keys, ed_keys)
def test_flights_keys(self):
pd... |
class OptionSeriesColumnpyramidSonificationContexttracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesColumnpyramidSonificationContexttracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesColumnpyramidSonificationContexttracksMappingTremoloDepth)
def speed(self) -> 'Op... |
def test__fillLimitOrder_swap(trace_classifier: TraceClassifier):
transaction_hash = '0x9255addffa2dbeb9560c5e20e78a78c949488d2054c70b2155c39f9e28394cbf'
block_number =
swap = Swap(abi_name='INativeOrdersFeature', transaction_hash=transaction_hash, transaction_position=8, block_number=block_number, trace_a... |
class PermissionConfig():
permissions = [{'codename': 'can_see_forum', 'label': _('Can see forum'), 'scope': 'forum'}, {'codename': 'can_read_forum', 'label': _('Can read forum'), 'scope': 'forum'}, {'codename': 'can_start_new_topics', 'label': _('Can start new topics'), 'scope': 'conversation'}, {'codename': 'can_... |
.parametrize('test_file_nonce', ['ttNonce/TransactionWithHighNonce32.json', 'ttNonce/TransactionWithHighNonce64Minus2.json'])
def test_nonce(test_file_nonce: str) -> None:
test = load_byzantium_transaction(test_dir, test_file_nonce)
tx = rlp.decode_to(Transaction, test['tx_rlp'])
result_intrinsic_gas_cost =... |
class Solution():
def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:
if (d == 1):
node = TreeNode(val=v, left=root)
return node
cl = 1
level = [root]
while level:
next_level = []
left = {}
right = {}
... |
class OrderAmountInputSchema(Schema):
tickets = fields.Nested(TicketSchema, many=True)
discount_code = fields.Integer(load_from='discount-code')
access_code = fields.Integer(load_from='access-code')
amount = fields.Float(allow_none=True)
discount_verify = fields.Boolean(required=False, default=True,... |
def checkVersion(tool):
cmd = None
if (tool == 'fio'):
minVersion = '2.20'
cmd = 'fio -v | sed s/fio-//'
if (cmd is not None):
min_version = LooseVersion(minVersion)
v3_version = LooseVersion('3.0')
version = cmdline(cmd).rstrip()
fio_version = LooseVersion(ve... |
class Top(Expr):
__slots__ = ()
__hash__ = Expr.__hash__
_coconut_tco
def __eq__(self, other):
return _coconut_tail_call(isinstance, other, Top)
def __repr__(self):
return 'top'
def __str__(self):
return top_sym
def __bool__(self):
return True |
def test_task_template_k8s_pod_target():
int_type = types.LiteralType(types.SimpleType.INTEGER)
obj = task.TaskTemplate(identifier.Identifier(identifier.ResourceType.TASK, 'project', 'domain', 'name', 'version'), 'python', task.TaskMetadata(False, task.RuntimeMetadata(1, 'v', 'f'), timedelta(days=1), literal_mo... |
def assert_waited_condition(condition, timeout=2.0):
import time
initial = time.time()
while True:
c = condition()
if isinstance(c, bool):
if c:
return
elif isinstance(c, basestring):
if (not c):
return
else:
... |
.parametrize('command_type,payload', ((StatusV1, StatusPayloadFactory(version=1)), (StatusV1, StatusPayloadFactory(version=1, tx_relay=True)), (StatusV1, StatusPayloadFactory(version=1, serve_headers=True)), (Announce, AnnouncePayloadFactory()), (GetBlockHeaders, GetBlockHeadersPayloadFactory()), (GetBlockHeaders, GetB... |
def str2yamlfile(fname):
ext = os.path.splitext(fname)[1][1:]
if (ext not in 'yaml'):
ArgumentTypeError('The file you specify to run mtriage must be a YAML file')
if (not os.path.exists(fname)):
ArgumentTypeError('Cannot find a file at {}.'.format(fname))
return fname |
class FileResponse(Response):
chunk_size = (64 * 1024)
def __init__(self, path: typing.Union[(str, 'os.PathLike[str]')], status_code: int=200, headers: typing.Optional[typing.Mapping[(str, str)]]=None, media_type: typing.Optional[str]=None, background: typing.Optional[BackgroundTask]=None, filename: typing.Opti... |
def test_substrings_case():
text = 'A, a, B, b, a,b,c,d'
substrings = ['a,']
res = _find_substrings(text, substrings, single_match=False, case_sensitive=True)
assert (res == [(3, 5), (12, 14)])
res = _find_substrings(text, substrings, single_match=False, case_sensitive=False)
assert (res == [(0,... |
def run_docker_compose_up(test_command):
env_variables = os.environ.copy()
env_variables['TEST_COMMAND'] = test_command
env_variables['RALLY_VERSION'] = version.__version__
return process.run_subprocess_with_logging(f'docker-compose -f {it.ROOT_DIR}/docker/docker-compose-tests.yml up --abort-on-containe... |
class OptionPlotoptionsGaugeSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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, ... |
()
('--bucket', required=True, help='The S3 bucket that contains cloud-trail logs')
('--prefix', default='', help='Prefix in the S3 bucket (including trailing slash)')
('--org-id', multiple=True, default=[], help='ID of the organisation we want to look at. Defaults to empty for non-organisational trails')
('--account-i... |
def bulk_wrapper(fn):
(fn)
def wrapped(self, *args, **kwargs):
arg_names = list(fn.func_code.co_varnames)
arg_names.remove('self')
kwargs.update(dict(zip(arg_names, args)))
wait = kwargs.get('wait', True)
query = dict([(k, v) for (k, v) in kwargs.iteritems() if (v is not ... |
def main():
import argparse
parser = argparse.ArgumentParser(description='Parse a db repository, checking for consistency')
util.db_root_arg(parser)
util.part_arg(parser)
parser.add_argument('--verbose', action='store_true', help='')
args = parser.parse_args()
run(args.db_root, args.part, ve... |
def validate_module(phase: str, module: str, cfg: dict):
try:
mod = get_module(phase, module)
except ModuleNotFoundError as e:
raise InvalidYamlError(f"No {phase} module named '{module}'")
sfolder = os.path.dirname(inspect.getfile(mod))
info = (Path(sfolder) / 'info.yaml')
with open(... |
class BitFieldByte():
def __init__(self, name, val=0, loval=(['Undef'] * 8)):
self.name = name
self._val = val
self.loval = loval
def encode(self):
val = pack('>B', self._val)
return val
def decode(self, data):
self._val = unpack('>B', data[:1])[0]
ret... |
class OptionSeriesXrangeDragdropDraghandle(Options):
def className(self):
return self._config_get('highcharts-drag-handle')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#fff')
def color(self, text: str):
self.... |
def test_migrate_summary(data, forecast, time_map, tmp_path):
group = '/REAL_0/SUMMARY'
with open_storage((tmp_path / 'storage'), mode='w') as storage:
experiment = storage.create_experiment(responses=[SummaryConfig(name='summary', input_file='some_file', keys=['some_key'])])
ensemble = experime... |
class OptionSeriesNetworkgraphStatesHoverMarker(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.... |
def test_get_root_uid(frontend_db, backend_db):
(child_fo, parent_fw) = create_fw_with_child_fo()
backend_db.insert_multiple_objects(parent_fw, child_fo)
assert (frontend_db.get_root_uid(child_fo.uid) == parent_fw.uid)
assert (frontend_db.get_root_uid(parent_fw.uid) == parent_fw.uid) |
class Solution(object):
def findTheDifference(self, s, t):
mapping = ([0] * 26)
for c in s:
mapping[(ord(c) - ord('a'))] += 1
for c in t:
mapping[(ord(c) - ord('a'))] -= 1
for (idx, num) in enumerate(mapping):
if (num < 0):
return s... |
.parametrize('weights_none', (False, True))
.parametrize('dtype', ('float64', 'float32', 'int32', 'int64'))
def test_cast_fit_input(weights_none, dtype):
region = ((- 7000.0), 4000.0, 10000.0, 25000.0)
coordinates = scatter_points(region=region, size=100, random_state=42)
data = np.arange(coordinates[0].siz... |
.parametrize(['enabled_devices', 'serverless_mode', 'serverless_operator', 'started', 'expected_msgs'], [(['optional-blocked'], False, False, {'default-public', 'default-internal', 'default-blocked', 'optional-blocked'}, []), ([], True, False, {'default-public'}, []), ([], True, True, {'default-public', 'default-intern... |
def setup_event_handlers(engine):
if (engine.dialect.name == 'sqlite'):
_for(engine, 'connect')
def set_sqlite_pragma(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute('PRAGMA foreign_keys=ON')
cursor.close() |
def test_add_metric_serialization():
msg = PrometheusMessage(message_id=1, dialogue_reference=(str(0), ''), target=0, performative=PrometheusMessage.Performative.ADD_METRIC, type='some_type', title='some_title', description='some_description', labels={'label_key': 'label_value'})
msg.to = 'receiver'
envelop... |
def generate_hr_zone_card():
rhr = pd.read_sql(sql=app.session.query(ouraSleepSummary.hr_lowest).statement, con=engine)
rhr = (int(rhr.loc[rhr.index.max()]['hr_lowest']) if (len(rhr) > 0) else 0)
athlete_info = app.session.query(athlete).filter((athlete.athlete_id == 1)).first()
birthday = athlete_info.... |
_os(*metadata.platforms)
def main():
masquerade = '/tmp/rmmod'
source = common.get_path('bin', 'linux.ditto_and_spawn')
common.copy_file(source, masquerade)
common.log('Launching fake commands to remove Kernel Module')
common.execute([masquerade], timeout=10, kill=True)
common.remove_file(masque... |
def filter_by_stoken(stoken: t.Optional[str], queryset: QuerySet, stoken_annotation: StokenAnnotation) -> t.Tuple[(QuerySet, t.Optional[Stoken])]:
stoken_rev = get_stoken_obj(stoken)
queryset = queryset.annotate(max_stoken=stoken_annotation).order_by('max_stoken')
if (stoken_rev is not None):
querys... |
def unpack_function(file_path, tmp_dir):
raw_binary = get_binary_from_file(file_path)
meta_data = dict()
for extractor in EXTRACTOR_LIST:
data_sections = extractor.extract_function(raw_binary, *extractor.optional_parameters)
dump_files(data_sections, tmp_dir, suffix=extractor.file_suffix)
... |
class CustomSqliteConnection(sqlite3.Connection):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.callbacks = []
def execute_callbacks(self):
for callback in self.callbacks:
callback()
def close(self):
if self.total_changes:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.