code
stringlengths
281
23.7M
def cache_web_image(name, url): img_name = ''.join(name.split()).lower().encode('punycode').decode() img_name = (img_name[:(- 1)] if (img_name[(- 1)] == '-') else img_name) with urlopen(url) as response: filetype = response.getheader('Content-Type') ext = filetype.split('/')[1] if (e...
def gf_mult(x, y): assert (len(x) == BLOCK_SIZE) assert (len(y) == BLOCK_SIZE) z = encode_int(0, BLOCK_SIZE) v = copy_buf(x) for i in range(0, 128): if get_bit(y, i): z = xor_block(z, v) if (not get_bit(v, 127)): v = shift_right_block(v) else: ...
def lazy_import(): from fastly.model.billing import Billing from fastly.model.billing_response_item_items_data import BillingResponseItemItemsData from fastly.model.billing_response_line_items import BillingResponseLineItems from fastly.model.billing_status import BillingStatus from fastly.model.bil...
class OdysseyError(CommandLineError): def __init__(self, value): super().__init__("Invalid --odyssey '{}': Use a combination of one or more from 'Y' for Yes, 'N' for No or '?' for unknown, e.g. 'YN?' matches any station while 'Y?' matches yes or unknown, or 'N' matches only non-odyssey stations.".format(val...
def test_initialize_ctx_with_absolute_dir(hydra_restore_singletons: Any, tmpdir: Any) -> None: with raises(HydraException, match=re.escape('config_path in initialize() must be relative')): with initialize(version_base=None, config_path=str(tmpdir)): compose(overrides=['+test_group=test'])
(((detect_target().name() == 'cuda') and (int(detect_target()._arch) < 80)), 'Not supported by CUDA < SM80.') class TestCastConverter(AITTestCase): ([('half_to_float', torch.half, torch.float), ('float_to_half', torch.float, torch.half), ('half_to_bf16', torch.half, torch.bfloat16), ('bool_to_half', torch.bool, tor...
def filter_impulse_response(sos_or_fir_coef: np.ndarray, N: int=2048, fs: float=None, sos: bool=True) -> Tuple[(np.ndarray, Optional[np.ndarray])]: if sos: response = sosfilt(sos_or_fir_coef, unit_impulse(N)) else: response = lfilter(b=sos_or_fir_coef, a=1, x=unit_impulse(N)) if (fs is not N...
class TestGreenIoLong(tests.LimitedTestCase): TEST_TIMEOUT = 10 def test_multiple_readers(self): debug.hub_prevent_multiple_readers(False) recvsize = (2 * min_buf_size()) sendsize = (10 * recvsize) def reader(sock, results): while True: data = sock.rec...
class EntryStatsFragmented(BaseGenTableTest): def runTest(self): for i in range(0, 4095): self.do_add(vlan_vid=i, ipv4=, mac=(0, 1, 2, 3, 4, 5)) do_barrier(self.controller) verify_no_errors(self.controller) entries = self.do_entry_stats() seen = set() for ...
class MakingTheGradeTest(unittest.TestCase): .task(taskno=1) def test_round_scores(self): test_data = [tuple(), (0.5,), (1.5,), (90.33, 40.5, 55.44, 70.05, 30.55, 25.45, 80.45, 95.3, 38.7, 40.3), (50, 36.03, 76.92, 40.7, 43, 78.29, 63.58, 91, 28.6, 88.0)] result_data = [[], [0], [2], [90, 40, 55...
def test_export_airflow_format_option(airflow_runtime_instance): runner = CliRunner() with runner.isolated_filesystem(): cwd = Path.cwd().resolve() resource_dir = ((Path(__file__).parent / 'resources') / 'pipelines') copy_to_work_dir(str(cwd), [(resource_dir / 'airflow.pipeline'), (resou...
class TestPrototypeStorage(BaseEvenniaTest): def setUp(self): super().setUp() self.maxDiff = None self.prot1 = spawner.prototype_from_object(self.obj1) self.prot1['prototype_key'] = 'testprototype1' self.prot1['prototype_desc'] = 'testdesc1' self.prot1['prototype_tags...
class TestFocusVisible(util.TestCase): MARKUP = '\n <form id="form">\n <input type="text">\n </form>\n ' def test_focus_visible(self): self.assert_selector(self.MARKUP, 'form:focus-visible', [], flags=util.HTML) def test_not_focus_visible(self): self.assert_selector(self.MARKUP...
def ajax_staff_required(view_func): (view_func) def wrapper(request, *args, **kwargs): if request.user.is_staff: return view_func(request, *args, **kwargs) resp = json.dumps({'not_authenticated': True}) return HttpResponse(resp, content_type='application/json', status=401) ...
def validate_custom_claims(custom_claims, required=False): if ((custom_claims is None) and (not required)): return None claims_str = str(custom_claims) if (len(claims_str) > MAX_CLAIMS_PAYLOAD_SIZE): raise ValueError('Custom claims payload must not exceed {0} characters.'.format(MAX_CLAIMS_P...
class FBDelay(fb.FBCommand): def name(self): return 'zzz' def description(self): return 'Executes specified lldb command after delay.' def args(self): return [fb.FBCommandArgument(arg='delay in seconds', type='float', help='time to wait before executing specified command'), fb.FBComm...
def deposit(validation_addr: address, withdrawal_addr: address): assert (self.current_epoch == (block.number / self.epoch_length)) assert (extract32(raw_call(self.purity_checker, concat('\x90>', as_bytes32(validation_addr)), gas=500000, outsize=32), 0) != as_bytes32(0)) self.validators[self.nextValidatorInd...
class HagerZhang(LineSearch): def __init__(self, *args, alpha_prev=None, f_prev=None, dphi0_prev=None, quad_step=False, eps=1e-06, theta=0.5, gamma=0.5, rho=5, psi_0=0.01, psi_1=0.1, psi_2=2.0, psi_low=0.1, psi_hi=10, Delta=0.7, omega=0.001, max_bisects=10, **kwargs): kwargs['cond'] = 'wolfe' super(...
def msolc(monkeypatch): installed = [Version('0.5.8'), Version('0.5.7'), Version('0.4.23'), Version('0.4.22'), Version('0.4.6')] monkeypatch.setattr('solcx.get_installed_solc_versions', (lambda : installed)) monkeypatch.setattr('solcx.install_solc', (lambda k, **z: installed.append(k))) monkeypatch.seta...
class ErrorCode(Enum): UNSUCCESSFUL_MESSAGE_SIGNING = 0 UNSUCCESSFUL_TRANSACTION_SIGNING = 1 def encode(error_code_protobuf_object: Any, error_code_object: 'ErrorCode') -> None: error_code_protobuf_object.error_code = error_code_object.value def decode(cls, error_code_protobuf_object: Any) -> 'E...
class InlineResponse2005(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_import() ...
class Plain(AmbassadorTest): single_namespace = True namespace = 'plain-namespace' def variants(cls) -> Generator[(Node, None, None)]: (yield cls(variants(MappingTest))) def manifests(self) -> str: m = ((namespace_manifest('plain-namespace') + namespace_manifest('evil-namespace')) + '\n-...
(max_examples=250) (value=st.one_of(st.integers(), st.decimals(), st.none()), value_bit_size=st.integers(min_value=1, max_value=32).map((lambda v: (v * 8))), frac_places=st.integers(min_value=1, max_value=80), data_byte_size=st.integers(min_value=0, max_value=32)) def test_encode_signed_fixed(value, value_bit_size, fra...
class ThermalMonitor(): def __init__(self, log_handle: List[str], adb: ADB, thermal_monitor_config: Dict[(str, str)], pattern: str, delay: float=10.0, lead_in_delay: float=15.0): self.log_handle = log_handle self.thermal_monitor_config = thermal_monitor_config self.adb = adb self.ini...
class HttpSerializer(Serializer): def encode(msg: Message) -> bytes: msg = cast(HttpMessage, msg) message_pb = ProtobufMessage() dialogue_message_pb = DialogueMessage() = dialogue_message_pb.message_id = msg.message_id dialogue_reference = msg.dialogue_reference ...
def test_multipart_rewinds_files(): with tempfile.TemporaryFile() as upload: upload.write(b'Hello, world!') transport = client = files = {'file': upload} response = client.post(' files=files) assert (response.status_code == 200) assert (b'\r\nHello, world!\r...
def _transform_1x1_conv_gemm_rcr(sorted_graph: List[Tensor]) -> List[Tensor]: conv_to_gemm = {'conv2d': ops.gemm_rcr, 'conv2d_bias': ops.gemm_rcr_bias, 'conv2d_bias_relu': ops.gemm_rcr_bias_relu, 'conv2d_bias_sigmoid': ops.gemm_rcr_bias_sigmoid, 'conv2d_bias_hardswish': ops.gemm_rcr_bias_hardswish, 'conv2d_bias_add...
def test_warning_if_transform_df_contains_categories_not_present_in_fit_df(df_enc, df_enc_rare): msg = 'During the encoding, NaN values were introduced in the feature(s) var_A.' with pytest.warns(UserWarning) as record: encoder = MeanEncoder(unseen='ignore') encoder.fit(df_enc[['var_A', 'var_B']...
class OptionPlotoptionsStreamgraphSonificationTracksMappingHighpassResonance(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: s...
class KeyattrDict(BaseDict): _keyattr_enabled = None _keyattr_dynamic = None def __init__(self, *args, **kwargs): self._keyattr_enabled = kwargs.pop('keyattr_enabled', True) self._keyattr_dynamic = kwargs.pop('keyattr_dynamic', False) super().__init__(*args, **kwargs) def keyattr...
def exposed_process_nu_pages(transmit=True): wg = WebRequest.WebGetRobust() with db.session_context() as sess: if (transmit == True): print('Transmitting processed results') rm = common.RunManager.Crawler(1, 1) message_q = rm.start_aggregator() else: ...
class BstBalance(Bst): def _check_balance(self, node): if (node is None): return 0 left_height = self._check_balance(node.left) if (left_height == (- 1)): return (- 1) right_height = self._check_balance(node.right) if (right_height == (- 1)): ...
class TwoConv(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(8, 8, 2, 2) self.conv2 = nn.Conv2d(8, 8, 2, 2) def forward(self, x): x = self.conv1(x) x = self.conv2(x) return x def fill_all(self, value): def fill(layer): ...
def _decorator_factory(level: LogStatsLevel, reduce_function: Callable, input_name: Optional[str], output_name: Optional[str], group_by: Optional[str], cumulative: bool=False) -> Callable: def decorator(func_obj) -> Callable: input_to_reducers = getattr(func_obj, level.name, None) if (not input_to_r...
class RawTrace(Trace): def __init__(self, *args): super(RawTrace, self).__init__(*args) def __getitem__(self, i): try: i = self.wrapindex(i) buf = np.zeros(self.shape, dtype=self.dtype) return self.filehandle.gettr(buf, i, 1, 1, 0, self.shape, 1, self.shape) ...
class Data(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) qos = models.IntegerField(choices=PROTO_MQTT_QoS, default=0) payload = models.TextField(blank=True, null=True) retain = models.BooleanField(default=False)...
def check_sequence_name___fix(): shots = pm.ls(type='shot') shot = None for s in shots: if (s.referenceFile() is None): shot = s break sequencers = shot.outputs(type='sequencer') if (not sequencers): raise PublishError('There are no sequencers in the scene!') ...
class TestCreateIndexRunner(): ('elasticsearch.Elasticsearch') .asyncio async def test_creates_multiple_indices(self, es): es.indices.create = mock.AsyncMock() r = runner.CreateIndex() request_params = {'wait_for_active_shards': 'true'} params = {'indices': [('indexA', {'sett...
class OptionPlotoptionsWaterfallSonificationContexttracksMappingHighpassFrequency(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, te...
def test_is_valid_ip_address(): result_localhost = is_valid_ip_address('127.0.0.1') assert (result_localhost is True) result_unknown = is_valid_ip_address('unknown') assert (result_unknown is False) result_ipv4_valid = is_valid_ip_address('::ffff:192.168.0.1') assert (result_ipv4_valid is True) ...
class OptionSeriesArcdiagramDataAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(fl...
class _GridTableBase(GridTableBase): def __init__(self, model): GridTableBase.__init__(self) self.model = model return def GetNumberRows(self): return self.model.GetNumberRows() def GetNumberCols(self): return self.model.GetNumberCols() def IsEmptyCell(self, row, ...
class OptionPlotoptionsBarSonificationContexttracksMappingPitch(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('y') def mapTo(self, text: str): s...
class OptionSeriesWindbarbSonificationDefaultinstrumentoptionsMappingTremolo(Options): def depth(self) -> 'OptionSeriesWindbarbSonificationDefaultinstrumentoptionsMappingTremoloDepth': return self._config_sub_data('depth', OptionSeriesWindbarbSonificationDefaultinstrumentoptionsMappingTremoloDepth) def ...
class RedisOps(object): def __init__(self): self.host = _setting('REDIS_HOST', 'localhost') self.port = _setting('REDIS_PORT', 6379) self.db = _setting('REDIS_DB', 0) self.prefix = _setting('WHINBOX_REDIS_PREFIX', 'wi-') self.item_max = _setting('WHINBOX_ITEM_MAX', 100) ...
def check_xss_impact(res_headers): if res_headers['Content-Type']: if ((res_headers['Content-Type'].find('application/json') != (- 1)) or (res_headers['Content-Type'].find('text/plain') != (- 1))): impact = 'Low' else: impact = 'High' else: impact = 'Low' retu...
class DrawTestCase(unittest.TestCase): properties = {'cat': u'meow', 'dog': 'woof'} classes = [u'foo', 'cat'] lis1 = [[(- 110.6), 35.3], [(- 110.7), 35.5], [(- 110.3), 35.5], [(- 110.2), 35.1], [(- 110.2), 35.8], [(- 110.3), 35.2], [(- 110.1), 35.8], [(- 110.8), 35.5], [(- 110.7), 35.7], [(- 110.1), 35.4], ...
class GenericAgent(): source_type = None target_type = None def __init__(self, args: Optional[Namespace]=None) -> None: if (args is not None): self.args = args assert self.source_type assert self.target_type self.device = 'cpu' self.states = self.build_sta...
class SmartPlaylistManager(PlaylistManager): def __init__(self, playlist_dir, playlist_class=SmartPlaylist, collection=None): self.collection = collection PlaylistManager.__init__(self, playlist_dir=playlist_dir, playlist_class=playlist_class) def _create_playlist(self, name): return sel...
def inspect(mt, device, baudrate): def config_fmt(config): return ('[%s]' % ', '.join((('(0x%04X, %d)' % (mode, freq)) for (mode, freq) in config))) def hex_fmt(size=4): fmt = ('0x%%0%dX' % (2 * size)) def f(value): return (fmt % value) return f def sync_fmt(setti...
def _transpose(pitch_motif: PitchLine, scale: List[Pitch], step: int, error: bool=True) -> PitchLine: try: pitches = _extract(pitch_motif) pitches = [_move(pitch, scale, step, error) for pitch in pitches] motif = _replace(pitch_motif, pitches) except: motif = [] return motif
def extractBoxnovelCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in tagmap...
class UserEmailSchema(SoftDeletionSchema): class Meta(): type_ = 'user-email' self_view = 'v1.user_emails_detail' self_view_kwargs = {'id': '<id>'} inflect = dasherize id = fields.Str(dump_only=True) email_address = TrimmedEmail(allow_none=False) type = fields.Str(allow_n...
def normalize_prim_input(prim_inp): if (prim_inp is None): return [] (prim_type, *indices) = prim_inp indices = list(map(int, indices)) if isinstance(prim_type, PrimTypes): return [prim_inp] try: return [tuple(([PrimTypes(int(prim_type))] + indices))] except ValueError: ...
class OptionSeriesPieMarkerStatesHover(Options): def animation(self) -> 'OptionSeriesPieMarkerStatesHoverAnimation': return self._config_sub_data('animation', OptionSeriesPieMarkerStatesHoverAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): se...
.parametrize('input_', [pytest.param('\x0b'), pytest.param('\t##'), pytest.param('a\n\n\xa0\n\nb'), pytest.param('\xa0\n\n# heading'), pytest.param('```\na\n```\n\u2003\n# A\n', marks=pytest.mark.xfail())]) def test_output_is_equal(input_): output = mdformat.text(input_) assert is_md_equal(input_, output)
('foremast.utils.credentials.gate_request') ('foremast.utils.templates.TEMPLATES_PATH', None) def test_iam_construct_policy(gate_request, get_base_settings): settings = get_base_settings policy_json = construct_policy(pipeline_settings=settings) assert (policy_json is None) settings.update({'services': ...
def test_post_three_images(client, png_image): for _ in range(3): client.simulate_post('/images', body=png_image) resp = client.simulate_get('/images') images = [(item['image'], item['size']) for item in resp.json] assert (images == [('/images/-48e5-4a61-be67-e426b11821ed.jpeg', [640, 360]), ('/...
.parametrize('compiled', [True, False]) def test_flag_read(compiled): d = '\n flag Test16 : uint16 {\n A = 0x1,\n B = 0x2\n };\n\n flag Test24 : uint24 {\n A = 0x1,\n B = 0x2\n };\n\n flag Test32 : uint32 {\n A = 0x1,\n B = 0x2\n };\n\n struct test {\n ...
def test_init_terms_strict_negative(): ledger_id = DEFAULT_LEDGER sender_addr = 'SenderAddress' counterparty_addr = 'CounterpartyAddress' amount_by_currency_id = {'FET': 10} quantities_by_good_id = {'good_1': 20} is_sender_payable_tx_fee = True nonce = 'somestring' with pytest.raises(AEA...
class _Dispatch(object): def __init__(self, comobj): self.__dict__['_comobj'] = comobj self.__dict__['_ids'] = {} self.__dict__['_methods'] = set() def __enum(self): e = self._comobj.Invoke((- 4)) return e.QueryInterface(comtypes.automation.IEnumVARIANT) def __cmp__(s...
def test_mark_entities_mesh_mark_entities_1d(): label_name = 'test_label' label_value = 999 mesh = UnitIntervalMesh(2) (x,) = SpatialCoordinate(mesh) V = FunctionSpace(mesh, 'P', 1) f = Function(V).interpolate(conditional((x < 0.25), 1.0, 0.0)) mesh.mark_entities(f, label_value, label_name=l...
class SSHNetconf(SSHCommandSession): TERM_TYPE: typing.Optional[str] = None DELIM: bytes = b']]>]]>' PROMPT: re.Pattern = re.compile(DELIM) HELLO_MESSAGE: bytes = b'<?xml version="1.0" encoding="UTF-8" ?>\n<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">\n <capabilities>\n <capability>urn:iet...
def convert_vertex_colors(self, context): obj = bpy.context.active_object for i in range(len(obj.material_slots)): slot = obj.material_slots[i] if slot.material: bpy.ops.object.mode_set(mode='EDIT') bpy.ops.mesh.select_all(action='DESELECT') bm = bmesh.from_ed...
class GithubRest(requests.Session): GET = 'GET' POST = 'POST' PUT = 'PUT' DELETE = 'DELETE' base_url = ' repos_url = (base_url + '/repos') def __init__(self, token: str, wait_til_limits: bool=True): super().__init__() self.token = token self.limits = RequestsLimit(Non...
def init_myst_file(path, kernel, verbose=True): try: from jupytext.cli import jupytext except ImportError: raise ImportError('In order to use myst markdown features, please install jupytext first.') if (not Path(path).exists()): raise FileNotFoundError(f'Markdown file not found: {pat...
class LinkedFaceAreaCache(Cache): def __init__(self, angle=0.0, *args, **kwargs): super().__init__(angle, *args, **kwargs) self._angle = angle def _calc(self, face, *args, **kwargs): linked_faces = utils.get_linked_faces(face, self._angle) linked_face_area = sum((f.calc_area() fo...
class OptionPlotoptionsTreegraphSonificationTracksMappingPitch(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('y') def mapTo(self, text: str): se...
class OptionSeriesOrganizationTooltip(Options): def clusterFormat(self): return self._config_get('Clustered points: {point.clusterPointsAmount}') def clusterFormat(self, text: str): self._config(text, js_type=False) def dateTimeLabelFormats(self) -> 'OptionSeriesOrganizationTooltipDatetimela...
class TaskTimingInfoWidget(QtWidgets.QWidget): def __init__(self, task=None, parent=None, **kwargs): self._task = None self.parent = parent super(TaskTimingInfoWidget, self).__init__(parent=parent) self.vertical_layout = None self.title_label = None self.form_layout =...
class _FaunaJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, _Expr): return obj.to_fauna_json() elif isinstance(obj, datetime): return FaunaTime(obj).to_fauna_json() elif isinstance(obj, date): return {'': obj.isoformat()} elif ...
def render_target(jinja2_env, target_dir, project_name, target, target_cfg): target_cfg_items = gen_target_cfg_items(target_cfg) if (not target_cfg_items): logger.error('[%s] Invalid type for target config: %s', project_name, type(target_cfg)) return for (target_env, target_env_cfg) in gen_t...
class TestTupleLenFlip(): def test_tuple_len_set(self, monkeypatch): with monkeypatch.context() as m: with pytest.raises(_SpockInstantiationError): m.setattr(sys, 'argv', ['']) config = ConfigArgBuilder(TupleFailFlip, desc='Test Builder') config.ge...
class DcNodeSerializer(s.InstanceSerializer): _model_ = DcNode _update_fields_ = ('strategy', 'cpu', 'ram', 'disk', 'priority') _default_fields_ = ('cpu', 'ram', 'disk') hostname = s.Field(source='node.hostname') strategy = s.IntegerChoiceField(choices=DcNode.STRATEGY, default=DcNode.SHARED) pri...
class TestOFPTableStatsRequest(unittest.TestCase): class Datapath(object): ofproto = ofproto ofproto_parser = ofproto_v1_0_parser flags = {'buf': b'\x00\x00', 'val': 0} c = OFPTableStatsRequest(Datapath, flags['val']) def setUp(self): pass def tearDown(self): pass ...
(scope='session') def univariate_data() -> UnivariateData: x = np.linspace((- 5.0), 5.0, 25) y = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) xi = np.linspace((- 5.0), 5.0, 100) yi = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0...
.EventDecorator() def restrict(fine_dual, coarse_dual): check_arguments(coarse_dual, fine_dual, needs_dual=True) Vf = fine_dual.function_space() Vc = coarse_dual.function_space() if (len(Vc) > 1): if (len(Vc) != len(Vf)): raise ValueError('Mixed spaces have different lengths') ...
def kernel_name(op): from cutlass_lib import library threadblock = op.tile_description.procedural_name() extended_name = op.extended_name() opcode_class_name = library.OpcodeClassNames[op.tile_description.math_instruction.opcode_class] layout = op.layout_name() align_ab = op.A.alignment alig...
def eq_anr(record, value): def fmap(f, obj): if isinstance(obj, dict): return any((fmap(f, sub) for sub in obj.values())) elif isinstance(obj, list): return any((fmap(f, k) for k in obj)) elif isinstance(obj, str): return f(obj) else: r...
def test_generate_volume_config_with_test_dir(): output_dir = '/tmp/random_dir_on_disk' test_dir = '/home/user/test_directory' volume_map = docker_volume.generate_volume_config(output_dir, test_dir) assert volume_map verify_required_paths(volume_map, output_dir) assert (test_dir in volume_map) ...
def _transform_function(f: Callable) -> Tuple[(Optional[List[ast.stmt]], str, str)]: if (f.__name__ == '<lambda>'): return _transform_lambda(f) (source, original_ast) = _get_lines_ast(f) assert (len(original_ast.body) == 1) if (not isinstance(original_ast.body[0], ast.FunctionDef)): retu...
def to_decimal(value: Any) -> Fixed: d: Fixed = Fixed(value) if ((d < (- (2 ** 127))) or (d >= (2 ** 127))): raise OverflowError(f'{value} is outside allowable range for decimal') if (d.quantize(Decimal('1.')) != d): raise ValueError('Maximum of 10 decimal points allowed') return d
def run_bpftrace(prompt: str, verbose: bool=False) -> CommandResult: messages = [{'role': 'user', 'content': prompt}] response = openai.ChatCompletion.create(model='gpt-3.5-turbo', messages=messages, functions=functions, function_call='auto') response_message = response['choices'][0]['message'] if verbo...
class OptionPlotoptionsPyramidTooltipDatetimelabelformats(Options): def day(self): return self._config_get('%A, %e %b %Y') def day(self, text: str): self._config(text, js_type=False) def hour(self): return self._config_get('%A, %e %b, %H:%M') def hour(self, text: str): se...
def get_target_line(col_names, job_targets): target_list = [] target_dict = {} col_names_filtered = col_names for name in col_names: target_dict[name] = 'na' if isinstance(job_targets, dict): for (metric, subdict1) in job_targets.items(): for (iotype, subdict2) in subdict...
.django_db def test_agency_endpoint(client, create_agency_data): resp = client.get('/api/v2/references/agency/1/') assert (resp.status_code == status.HTTP_200_OK) assert (resp.data['results']['outlay_amount'] == '2.00') assert (resp.data['results']['obligated_amount'] == '2.00') assert (resp.data['r...
class Testglob(_TestGlob): cases = [[('a',), [('a',)]], [('a', 'D'), [('a', 'D')]], [('aab',), [('aab',)]], [('zymurgy',), []], Options(absolute=True), [['*'], None], [[os.curdir, '*'], None], Options(absolute=False), [('a*',), [('a',), ('aab',), ('aaa',)]], [('*a',), [('a',), ('aaa',)]], [('.*',), [('.',), ('..',)...
class OptionPlotoptionsAreaSonificationDefaultinstrumentoptionsMappingNoteduration(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, t...
def generate_engine_id_mac(pen: int, mac_address: str) -> bytes: buffer = bytearray(pen.to_bytes(4, 'big')) buffer[0] = (16 * 8) if ('-' in mac_address): octets = [int(oct, 16) for oct in mac_address.split('-')] else: octets = [int(oct, 16) for oct in mac_address.split(':')] buffer.a...
class OptionPlotoptionsPackedbubbleSonificationDefaultinstrumentoptionsMappingPan(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, te...
def extractJinzeffectWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Eternal Reverence', 'Eternal Reverence', 'translated'), ("i'm an olympic superstar", "i'm an o...
def main(): parser = argparse.ArgumentParser() parser.add_argument('folder') args = parser.parse_args() folder = Path(args.folder) if (not folder.exists()): print(f'Cloning google/oss-fuzz into: {folder}') folder.mkdir(parents=True) subprocess.check_call(['git', 'clone', '--s...
def test_init_check(): cur_list = rq.registry.StartedJobRegistry(queue=q).get_job_ids() if (len(cur_list) > 0): try: job_id = cur_list[0] logger.info('Deleting job: {:s}'.format(job_id)) job = q.fetch_job(job_id) job.meta['CrackQ State'] = 'Stop' ...
def main(): log_level = os.getenv('LOGGING_LEVEL') logger.remove() logger.add(sys.stderr, level=log_level) logger.info('Read config file') parser = argparse.ArgumentParser(description='Listener process') parser.add_argument('--config', type=str, help='Config path', default='/etc/inferoxy/bridges...
class TestGetSystemFromFidesKey(): def test_get_system_from_fides_key(self, db, system): resp = _get_system_from_fides_key(system.fides_key, db) assert (resp.system == system) assert (resp.original_data == system.fides_key) def test_get_system_from_fides_key_not_found(self, db): ...
class Formatter(): encoding_internal = None def __init__(self, indent=DEFAULT_INDENT, preserve=[], compress=DEFAULT_COMPRESS, indent_char=DEFAULT_INDENT_CHAR, encoding_input=DEFAULT_ENCODING_INPUT, encoding_output=DEFAULT_ENCODING_OUTPUT, inline=DEFAULT_INLINE, correct=DEFAULT_CORRECT, noemptytag=DEFAULT_NOEMPT...
def authenticate_user(): users = db.fetch_all_users() usernames = [user['key'] for user in users] names = [user['name'] for user in users] hashed_passwords = [user['password'] for user in users] authenticator = LoginSignup(names, usernames, hashed_passwords, 'query_aichat', 'abcdef', cookie_expiry_d...
class ExchangeJsonTestcase(unittest.TestCase): def test_all_zones_in_zones_json(self): zone_keys = ZONES_CONFIG.keys() for (zone_key, values) in EXCHANGES_CONFIG.items(): self.assertIn('->', zone_key) for zone in zone_key.split('->'): if (zone == 'US'): ...
def extractSakuratlWordpressCom(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) ...
def test_staticfiles_304_with_etag_match(tmpdir, test_client_factory): path = os.path.join(tmpdir, 'example.txt') with open(path, 'w') as file: file.write('<file content>') app = StaticFiles(directory=tmpdir) client = test_client_factory(app) first_resp = client.get('/example.txt') asser...