code
stringlengths
281
23.7M
class OptionSeriesFunnelSonificationTracksMappingTremoloDepth(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...
def _get_serializer_hierarchy(serializer): name = (serializer.field_name or '') parent = serializer.parent while parent: if parent.field_name: if name: name = '{0}__{1}'.format(parent.field_name, name) else: name = parent.field_name par...
_converter(torch.ops.aten.t.default) def aten_ops_transpose(target: Target, args: Tuple[(Argument, ...)], kwargs: Dict[(str, Argument)], name: str) -> ConverterOutput: input_val = args[0] permutation = [0, 2, 1] if (not isinstance(input_val, AITTensor)): raise ValueError(f'Unexpected input for {name...
class JsDomEvents(primitives.JsDataModel): def __init__(self, component: primitives.HtmlModel=None, js_code: str=None): self.component = component self._js = [] if (js_code is not None): self.varName = js_code else: self.varName = ("document.getElementById('%s...
class Admin(Eth1ChainRPCModule): def __init__(self, chain: AsyncChainAPI, event_bus: EndpointAPI, trinity_config: TrinityConfig) -> None: super().__init__(chain, event_bus) self.trinity_config = trinity_config async def addPeer(self, uri: str) -> None: validate_enode_uri(uri, require_ip=...
class OptionPlotoptionsScatter3dSonificationDefaultspeechoptionsPointgrouping(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: ...
class TestCollect(unittest.TestCase): def generate_random_sequence(self, length): sequence = '' for i in range(length): sequence += choice('ACGT') return sequence def generate_random_cigar_string(self, readlength): softclip_left = round(triangular(0, readlength, min(1...
def run_module(): module = AnsibleModule(argument_spec=dict(state=dict(default='present', choices=['present', 'absent']), resource1=dict(required=True), resource2=dict(required=True), resource1_action=dict(required=False, choices=['start', 'promote', 'demote', 'stop'], default='start'), resource2_action=dict(requir...
def test_save_privacy_request(db: Session, privacy_request: PrivacyRequest) -> None: EXTERNAL_ID = 'testing' privacy_request.external_id = EXTERNAL_ID privacy_request.save(db) from_db = PrivacyRequest.get(db=db, object_id=privacy_request.id) assert (from_db.external_id == EXTERNAL_ID)
.django_db def test_update_treasury_appropriation_account(disable_vacuuming): baker.make('accounts.TreasuryAppropriationAccount', agency_id='009') call_command('load_agencies', AGENCY_FILE) assert (TreasuryAppropriationAccount.objects.first().funding_toptier_agency_id == ToptierAgency.objects.get(toptier_co...
class ChimeraDetector(object): def __init__(self, breakpoint_graphs, run_stages, target_seqs): logger.info('Detecting chimeric adjacencies') self.bp_graphs = breakpoint_graphs self.run_stages = run_stages self.target_seqs = target_seqs self._make_hierarchical_breaks() def...
def test_sphere_mg(): R = 1.0 base = IcosahedralSphereMesh(radius=R, refinement_level=0) nref = 5 mh = MeshHierarchy(base, nref) for mesh in mh: x = SpatialCoordinate(mesh) mesh.init_cell_orientations(x) mesh = mh[(- 1)] (x, y, z) = SpatialCoordinate(mesh) V = FunctionSpa...
def get_facility_code(stock_entry, unicommerce_settings) -> str: target_warehouses = {d.t_warehouse for d in stock_entry.items} if (len(target_warehouses) > 1): frappe.throw(_('{} only supports one target warehouse (unicommerce facility)').format(GRN_STOCK_ENTRY_TYPE)) warehouse = list(target_wareho...
_event class PollVoted(ThreadEvent): poll = attr.ib(type='_models.Poll') added_ids = attr.ib(type=Sequence[str]) removed_ids = attr.ib(type=Sequence[str]) at = attr.ib(type=datetime.datetime) def _parse(cls, session, data): (author, thread, at) = cls._parse_metadata(session, data) po...
class OptionLangExportdata(Options): def annotationHeader(self): return self._config_get('Annotations') def annotationHeader(self, text: str): self._config(text, js_type=False) def categoryDatetimeHeader(self): return self._config_get('DateTime') def categoryDatetimeHeader(self, ...
def main(): module_spec = schema_to_module_spec(versioned_schema) mkeyname = None fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path': {...
def _test_method(self, method): for cnr in (self.tas_cnr,): (cns, raw_str) = segmentation.do_segmentation(cnr, method, processes=1, save_dataframe=True) self.assertGreater(len(cns), 0) self.assertGreater(len(raw_str), 0) (p_cns, p_raw_str) = segmentation.do_segmentation(cnr, method, ...
def sum_thermal_units(soup) -> float: thermal_h3 = soup.find('h3', string=re.compile('\\s*Termicas\\s*')) thermal_tables = thermal_h3.find_next_sibling().find_all('table', {'class': 'table table-hover table-striped table-sm sitr-gen-group'}) thermal_units = 0 for thermal_table in thermal_tables: ...
class UserManager(base_models.BaseUserManager): def create_user(self, email, password, **extra_fields): if (not email): raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password)...
def show_slice(*args, **kwargs): import matplotlib.pyplot as plt show_abs = kwargs.pop('abs', False) (a, extent, axes) = sample_slice(*args, **kwargs) if show_abs: a = np.abs(a) im = plt.imshow(a, extent=extent, origin='lower') plt.xlabel(axes[0]) plt.ylabel(axes[1]) plt.colorbar...
class StateUpdateDialogues(Model, BaseStateUpdateDialogues): def __init__(self, **kwargs: Any) -> None: Model.__init__(self, **kwargs) def role_from_first_message(message: Message, receiver_address: Address) -> BaseDialogue.Role: return BaseStateUpdateDialogue.Role.SKILL BaseStat...
class TestNoValue(TestCase): def setUp(self): self.model = Mock() def test_has_editor_value(self): value_type = NoValue() self.assertFalse(value_type.has_editor_value(self.model, [0], [0])) def test_has_text(self): value_type = NoValue() self.assertFalse(value_type.ha...
def pytest_cmdline_main(config): repo = config.option.track_repository if (not os.path.isdir(repo)): if (repo == TRACK_REPO_PATH): try: subprocess.run(shlex.split(f'git clone {REMOTE_TRACK_REPO} {repo}'), text=True, capture_output=True, check=True) except subproce...
def validate_item(doc, method=None): 'Validate Item:\n\n\t1. item_code should fulfill unicommerce SKU code requirements.\n\t2. Selected item group should have unicommerce product category.\n\n\tref: item = doc settings = frappe.get_cached_doc(SETTINGS_DOCTYPE) if ((not settings.is_enabled()) or (not i...
def SdkToolsPopen(commands, cwd=None, output=True): cmd = commands[0] if (cmd not in config): config[cmd] = find_sdk_tools_cmd(commands[0]) abscmd = config[cmd] if (abscmd is None): raise FDroidException(_("Could not find '{command}' on your system").format(command=cmd)) if (cmd == '...
def handle_s3(operation_name, service, instance, args, kwargs, context): span_type = 'storage' span_subtype = 's3' span_action = operation_name if (len(args) > 1): bucket = args[1].get('Bucket', '') key = args[1].get('Key', '') else: bucket = '' key = '' if (bucke...
.dev def test_create_petsc_ksp_obj(create_simple_petsc_matrix): def getSize(): return 3 petsc_options = PETSc.Options() petsc_options.clear() for k in petsc_options.getAll(): petsc_options.delValue(k) petsc_options.setValue('test_F_ksp_type', 'preonly') petsc_options.setValue('te...
def get_evennia_executable(): if OS_WINDOWS: batpath = os.path.join('bin', 'windows', 'evennia.bat') scriptpath = os.path.join(sys.prefix, 'Scripts', 'evennia_launcher.py') with open(batpath, 'w') as batfile: batfile.write(('"%s" "%s" %%*' % (sys.executable, scriptpath))) ...
class OptionPlotoptionsLineSonificationDefaultinstrumentoptionsMappingTremolo(Options): def depth(self) -> 'OptionPlotoptionsLineSonificationDefaultinstrumentoptionsMappingTremoloDepth': return self._config_sub_data('depth', OptionPlotoptionsLineSonificationDefaultinstrumentoptionsMappingTremoloDepth) d...
def itersubclasses(cls, _seen=None): if (not isinstance(cls, type)): raise TypeError(('itersubclasses must be called with new-style classes, not %.100r' % cls)) if (_seen is None): _seen = set() try: subclasses = cls.__subclasses__() except TypeError: subclasses = cls.__s...
def get_slot_names(save_stats: dict[(str, Any)]) -> list[str]: total_slots = len(save_stats['slots']) if (save_stats['game_version']['Value'] >= 110600): total_slots = next_int(1) names: list[str] = [] for _ in range(total_slots): names.append(get_utf8_string()) return names
def metadata_find_signing_files(appid, vercode): ret = [] sigdir = metadata_get_sigdir(appid, vercode) signature_block_files = ((glob.glob(os.path.join(sigdir, '*.DSA')) + glob.glob(os.path.join(sigdir, '*.EC'))) + glob.glob(os.path.join(sigdir, '*.RSA'))) signature_block_pat = re.compile('(\\.DSA|\\.EC...
class OptionSeriesVariablepieDataDragdrop(Options): def draggableX(self): return self._config_get(None) def draggableX(self, flag: bool): self._config(flag, js_type=False) def draggableY(self): return self._config_get(None) def draggableY(self, flag: bool): self._config(f...
('cuda.conv2d_bias_add_identity.gen_function') def conv2d_bias_add_identity_gen_function(func_attrs, exec_cond_template, shape_eval_template, shape_save_template): return cbaa.gen_function(func_attrs=func_attrs, exec_cond_template=exec_cond_template, shape_eval_template=shape_eval_template, shape_save_template=shap...
class ProductItemLocalInfoLatLongShape(AbstractObject): def __init__(self, api=None): super(ProductItemLocalInfoLatLongShape, self).__init__() self._isProductItemLocalInfoLatLongShape = True self._api = api class Field(AbstractObject.Field): latitude = 'latitude' longitud...
class encrypt(tunnel.builder): __key = b'' __iv = b'' __const_fill = b'' __real_size = 0 __body_size = 0 def __init__(self): if ((tunnel.MIN_FIXED_HEADER_SIZE % 16) != 0): self.__const_fill = (b'f' * (16 - (tunnel.MIN_FIXED_HEADER_SIZE % 16))) super(encrypt, self).__i...
((SKIP_REASON is not None), SKIP_REASON) class TestEnamlTaskPane(GuiTestAssistant, unittest.TestCase): def setUp(self): GuiTestAssistant.setUp(self) self.task_pane = DummyTaskPane() with self.event_loop(): self.task_pane.create(None) def tearDown(self): if (self.task_...
def compare_resources(module, res1, res2): (n1_file_fd, n1_tmp_path) = tempfile.mkstemp() (n2_file_fd, n2_tmp_path) = tempfile.mkstemp() n1_file = open(n1_tmp_path, 'w') n2_file = open(n2_tmp_path, 'w') sys.stdout = n1_file ET.dump(res1) sys.stdout = n2_file ET.dump(res2) sys.stdout ...
def train_model(model, optimizer, n_iter, batch_size): ((train_X, train_y), (dev_X, dev_y)) = ml_datasets.ud_ancora_pos_tags() model.initialize(X=train_X[:5], Y=train_y[:5]) for n in range(n_iter): loss = 0.0 batches = model.ops.multibatch(batch_size, train_X, train_y, shuffle=True) ...
def get_video_frame(video_path: str, frame_number: int=0) -> Optional[Frame]: if video_path: video_capture = cv2.VideoCapture(video_path) if video_capture.isOpened(): frame_total = video_capture.get(cv2.CAP_PROP_FRAME_COUNT) video_capture.set(cv2.CAP_PROP_POS_FRAMES, min(fram...
class LiteEthIP(LiteXModule): def __init__(self, mac, mac_address, ip_address, arp_table, with_broadcast=True, dw=8): self.tx = tx = LiteEthIPTX(mac_address, ip_address, arp_table, dw=dw) self.rx = rx = LiteEthIPRX(mac_address, ip_address, with_broadcast, dw=dw) mac_port = mac.crossbar.get_p...
class LondonTransactionExecutor(BerlinTransactionExecutor): def build_evm_message(self, transaction: SignedTransactionAPI) -> MessageAPI: gas_fee = (transaction.gas * self.vm_state.get_gas_price(transaction)) self.vm_state.delta_balance(transaction.sender, ((- 1) * gas_fee)) self.vm_state.in...
def to_gpu_supported_dtype(array): if isinstance(array, np.ndarray): if (array.dtype not in supported_dtypes): if np.issubdtype(array.dtype, np.integer): warn(f'converting {array.dtype} array to int32') return array.astype(np.int32) elif np.issubdtype(...
class port_stats_request(stats_request): version = 5 type = 18 stats_type = 4 def __init__(self, xid=None, flags=None, port_no=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): self.flags = flags else: ...
def test_minTRL(): assert_daily = 2. assert_weekly = 2. assert_monthly = 27. stats1 = (pbo.minTRL(sharpe=(2 / np.sqrt(250)), skew=0, kurtosis=3, target_sharpe=(1 / np.sqrt(250)), prob=0.95) / 250) stats2 = (pbo.minTRL(sharpe=(2 / np.sqrt(52)), skew=0, kurtosis=3, target_sharpe=(1 / np.sqrt(52)), pro...
class IndexStructType(str, Enum): NODE = 'node' TREE = 'tree' LIST = 'list' KEYWORD_TABLE = 'keyword_table' DICT = 'dict' SIMPLE_DICT = 'simple_dict' KG = 'kg' SIMPLE_KG = 'simple_kg' NEBULAGRAPH = 'nebulagraph' FALKORDB = 'falkordb' EMPTY = 'empty' COMPOSITE = 'composite...
def get_data_bike(use_model: bool) -> Tuple[(pd.DataFrame, pd.DataFrame)]: content = requests.get(BIKE_DATA_SOURCE_URL).content with zipfile.ZipFile(io.BytesIO(content)) as arc: with arc.open('day.csv') as datafile: raw_data = pd.read_csv(datafile, header=0, sep=',', parse_dates=['dteday']) ...
def test_remove_empty_nodes_empty_graph(): asgraph = AbstractSyntaxInterface() code_node_1 = asgraph._add_code_node([]) code_node_1.reaching_condition = LogicCondition.initialize_symbol('a', asgraph.factory.logic_context) code_node_2 = asgraph._add_code_node([]) seq_node = asgraph.factory.create_seq...
def _test_names_default(): scene = td.Scene(size=(2.0, 2.0, 2.0), structures=[td.Structure(geometry=td.Box(size=(1, 1, 1), center=((- 1), 0, 0)), medium=td.Medium(permittivity=2.0)), td.Structure(geometry=td.Box(size=(1, 1, 1), center=(0, 0, 0)), medium=td.Medium(permittivity=2.0)), td.Structure(geometry=td.Sphere(...
def _wrap_non_coroutine_unsafe(func: Optional[Callable[(..., Any)]]) -> Union[(Callable[(..., Awaitable[Any])], Callable[(..., Any)], None)]: if (func is None): return func if (not _should_wrap_non_coroutines()): return func if inspect.iscoroutinefunction(func): return func retur...
class Metrics(IFLBatchMetrics): def __init__(self, num_examples, loss): self._num_examples = num_examples self._loss = loss def loss(self) -> torch.Tensor: return self._loss def num_examples(self) -> int: return self._num_examples def predictions(self): pass d...
def test_field_parameter_size(tmpdir, storage: StorageAccessor): with tmpdir.as_cwd(): shape = Shape(8, 10, 2) grid = xtgeo.create_box_grid(dimension=(shape.nx, shape.ny, shape.nz)) grid.to_file('MY_EGRID.EGRID', 'egrid') config = Field.from_config_list('MY_EGRID.EGRID', shape, ['PAR...
def test_arbitrage_real_block(): block = load_test_block() expected_sandwiches = load_test_sandwiches() trace_classifier = TraceClassifier() classified_traces = trace_classifier.classify(block.traces) swaps = get_swaps(classified_traces) assert (len(swaps) == 21) sandwiches = get_sandwiches(...
class OptionPlotoptionsPackedbubbleSonificationContexttracksMappingRate(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 base_h_content(out): out.write('\n/*\n * Base OpenFlow definitions. These depend only on standard C headers\n */\n#include <string.h>\n#include <stdint.h>\n\n/* g++ requires this to pick up PRI, etc.\n * See */\n#if !defined(__STDC_FORMAT_MACROS)\n#define __STDC_FORMAT_MACROS\n#endif\n#include <inttypes.h>\n...
class TestHSIPoperties(util.ColorAsserts, unittest.TestCase): def test_names(self): self.assertEqual(Color('color(--hsi 60 1 0.66667)')._space.names(), ('h', 's', 'i')) def test_h(self): c = Color('color(--hsi 60 1 0.66667)') self.assertEqual(c['h'], 60) c['h'] = 0.2 self...
def get_max_socket_path_length(): if ('UNIX_PATH_MAX' in os.environ): return int(os.environ['UNIX_PATH_MAX']) if sys.platform.startswith('darwin'): return 104 elif sys.platform.startswith('linux'): return 108 elif sys.platform.startswith('win'): return 260
def test_2d_args(): mesh = UnitSquareMesh(1, 1) f = mesh.coordinates assert np.allclose([0.2, 0.4], f.at(0.2, 0.4)) assert np.allclose([0.2, 0.4], f.at((0.2, 0.4))) assert np.allclose([0.2, 0.4], f.at([0.2, 0.4])) assert np.allclose([0.2, 0.4], f.at(np.array([0.2, 0.4]))) assert np.allclose(...
def test_return_record_name_with_named_type_and_null_in_union2(): ' schema = {'type': 'record', 'name': 'my_record', 'fields': [{'name': 'foo', 'type': {'type': 'record', 'name': 'Foo', 'fields': [{'name': 'subfoo', 'type': 'string'}]}}, {'name': 'my_union', 'type': ['null', 'Foo', {'name': 'bar', 'type': 'reco...
class AbstractSyntaxInterface(ABC): def __init__(self, context=None): self._ast = DiGraph() self._code_node_reachability_graph: ReachabilityGraph = ReachabilityGraph() context = (LogicCondition.generate_new_context() if (context is None) else context) self.factory = ASTNodeFactory(co...
class OptionPlotoptionsVariwideAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def descriptionFormat(self): return self._config_get(None) def descriptionFormat(self, text: str): ...
def initialize_app(param: WebServerParameters=None, args: List[str]=None): if (not param): param = _get_webserver_params(args) from dbgpt.model.cluster import initialize_worker_manager_in_client if (not param.log_level): param.log_level = _get_logging_level() setup_logging('dbgpt', loggi...
def test_voice_from_id(): from elevenlabs import Voice, VoiceSettings voice_id = '21m00Tcm4TlvDq8ikWAM' voice = Voice.from_id(voice_id) assert isinstance(voice, Voice) assert (voice.voice_id == voice_id) assert (voice.name == 'Rachel') assert (voice.category == 'premade') assert isinstan...
def hydrate_registration_parameters(resource_type: int, project: str, domain: str, version: str, entity: Union[(LaunchPlan, WorkflowSpec, TaskSpec)]) -> Tuple[(_identifier_pb2.Identifier, Union[(LaunchPlan, WorkflowSpec, TaskSpec)])]: if (resource_type == _identifier_pb2.LAUNCH_PLAN): identifier = _hydrate_...
def filter_endpoint_control_registered_forticlient_data(json): option_list = ['flag', 'ip', 'mac', 'reg_fortigate', 'status', 'uid', 'vdom'] json = remove_invalid_fields(json) dictionary = {} for attribute in option_list: if ((attribute in json) and (json[attribute] is not None)): di...
class AdAccountTargetingUnified(AbstractCrudObject): def __init__(self, fbid=None, parent_id=None, api=None): self._isAdAccountTargetingUnified = True super(AdAccountTargetingUnified, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): audience_size_lower_bound = 'aud...
class MarkDown(): def __init__(self, page: primitives.PageModel): self.page = page def translate(cls, data: str): convert_data = data (count, map_objs) = (0, {}) for (r, interface) in RULES.items(): m = re.findall(r, data, re.MULTILINE) if (m is not None):...
class DBValidator(Validator): def __init__(self, db, tablename, fieldname='id', dbset=None, message=None): super().__init__(message=message) self.db = db self.tablename = tablename self.fieldname = fieldname self._dbset = dbset def __call__(self, value): raise Not...
class BillingTotal(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() ...
def extractMysakuratranslationsCom(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...
def main(): parser = argparse.ArgumentParser(description='Download F3RM datasets.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('type', type=str, help="Type of dataset to download. Use 'all' to download all datasets.", nargs='?', choices=(['all'] + list(_name_to_dataset.keys())),...
class flow_mod(message): subtypes = {} version = 2 type = 14 def __init__(self, xid=None, cookie=None, cookie_mask=None, table_id=None, _command=None, idle_timeout=None, hard_timeout=None, priority=None, buffer_id=None, out_port=None, out_group=None, flags=None, match=None, instructions=None): i...
def fetch_production(zone_key: str='GB-ORK', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> dict: if target_datetime: raise NotImplementedError('This parser is not yet able to parse past dates') raw_data = get_json_data() raw_data.pop(...
class OptionSeriesCylinderSonificationContexttracksMappingVolume(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): ...
.parametrize('guesses, labels, names', [([guesses1], [['A', '!A', '', '!C']], ['A', 'B', 'C'])]) def test_sequence_categorical_missing_negative(guesses, labels, names): d_scores = SequenceCategoricalCrossentropy(normalize=False, names=names, neg_prefix='!', missing_value='').get_grad(guesses, labels) d_scores0 ...
class ETHPeerPool(BaseChainPeerPool): peer_factory_class = ETHPeerFactory wit_enabled_metrics_name = 'trinity.p2p/wit_peers.counter' non_wit_enabled_metrics_name = 'trinity.p2p/non_wit_peers.counter' def record_metrics_for_added_peer(self, peer: BasePeer) -> None: if hasattr(peer, 'wit_api'): ...
class KnapsackTopDown(object): def fill_knapsack(self, items, total_weight): if ((items is None) or (total_weight is None)): raise TypeError('input_items or total_weight cannot be None') if ((not items) or (not total_weight)): return 0 memo = {} result = self....
class GoogleMaps(object): def __init__(self, app=None, **kwargs): self.key = kwargs.get('key') if app: self.init_app(app) def init_app(self, app): if self.key: app.config['GOOGLEMAPS_KEY'] = self.key self.register_blueprint(app) app.add_template_fi...
def login_fields(auth): model = auth.models['user'] rv = {'email': Field(validation={'is': 'email', 'presence': True}, label=model.email.label), 'password': Field('password', validation=model.password._requires, label=model.password.label)} if auth.ext.config.remember_option: rv['remember'] = Field(...
class DataViewTreeView(QTreeView): _widget = None def dragEnterEvent(self, event): drop_handler = self._get_drop_handler(event) if (drop_handler is not None): event.acceptProposedAction() else: super().dragEnterEvent(event) def dragMoveEvent(self, event): ...
class _MultiCallable(): def __init__(self, channel, method_full_rpc_name): self._handler = channel.server._find_method_handler(method_full_rpc_name) def with_call(self, *args, **kwargs): raise NotImplementedError def future(self, *args, **kwargs): raise NotImplementedError
.parametrize('max_age', [0, 300]) def test_csv_loader_without_cache(tmpdir, mocker, csv_string, expected_from_loader, max_age): mock_resp = mocker.Mock() mock_resp.status_code = 400 mock_resp.text = csv_string mock_get = mocker.patch('requests.Session.get', return_value=mock_resp) mock_mal = mocker....
def local_install(): exe = (os.getenv('LOCALAPPDATA') + '/Programs/Music Caster/Music Caster.exe') cmd = [str((DIST_DIR / 'Music Caster Setup.exe')), '/FORCECLOSEAPPLICATIONS', '/VERYSILENT', '/MERGETASKS="!desktopicon"'] cmd.extend(('&&', exe)) if (not player_state.get('gui_open', False)): cmd....
def extractChinaLightNovel(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None tagmap = [('Twin Sword', 'Twin Sword', 'translated'), ("Devil's Examination", "Devil's Examination", 'tra...
class Position(NamedTuple): path: str line: int start: int end: int def default() -> 'Position': return Position(UNKNOWN_PATH, UNKNOWN_LINE, 0, 0) def from_json(position: Dict[(str, Any)], method: Optional[Method]) -> 'Position': path = position.get('path', UNKNOWN_PATH) ...
class ExtremeIntelligenceHandler(THBEventHandler): interested = ['action_after', 'game_begin'] def handle(self, evt_type, act): if ((evt_type == 'action_after') and isinstance(act, InstantSpellCardAction)): if isinstance(act, Reject): return act g = self.game ...
class DF_writer(object): def __init__(self, columns): self.df = pd.DataFrame(columns=columns) self.columns = columns def append(self, **row_data): if (set(self.columns) == set(row_data)): s = pd.Series(row_data) self.df = self.df.append(s, ignore_index=True)
def test_copy_doc_func_to_method(tdocstring): def tfunc(): pass tfunc.__doc__ = tdocstring class tObj(): _doc_func_to_method(tfunc) def tmethod(): pass assert tObj.tmethod.__doc__ assert ('first' not in tObj.tmethod.__doc__) assert ('second' in tObj.tmethod.__...
def create_cmp_j_instructions(mode, expr, val, target, kind): cmp_inst = instruction_x86('CMP', mode, [expr, val]) cmp_inst.additional_info = additional_info() cmp_inst.additional_info.g1.value = 0 jz_inst = instruction_x86(kind, mode, [target]) jz_inst.additional_info = additional_info() jz_ins...
(name='sample_grid_upward') def fixture_sample_grid_upward(region): (easting, northing, upward) = grid_coordinates(region, spacing=500, extra_coords=100) data = (np.sin((easting / 1000.0)) + np.cos((northing / 1000.0))) return make_xarray_grid((easting, northing, upward), data, data_names='sample', extra_co...
.WebInterfaceUnitTestConfig(database_mock_class=DbMock) class TestAppAddComment(): def test_app_add_comment_get_not_in_db(self, test_client): rv = test_client.get('/comment/abc_123') assert (b'Error: UID not found in database' in rv.data) def test_app_add_comment_get_valid_uid(self, test_client)...
class Context(threading.local): def __init__(self): self._ctx = [{}] def __getattr__(self, name): for scope in reversed(self._ctx): if (name in scope): return scope[name] raise AttributeError(name) def get(self, name, default=None): try: ...
class PerfectFreezeHandler(THBEventHandler): interested = ['action_before'] execute_after = ['RepentanceStickHandler', 'AyaRoundfanHandler'] def handle(self, evt_type, act): if ((evt_type == 'action_before') and isinstance(act, Damage)): if act.cancelled: return act ...
def backupTVPlanerHTML(): if (config.plugins.serienRec.tvplaner.value and config.plugins.serienRec.tvplaner_backupHTML.value and config.plugins.serienRec.longLogFileName.value): lt = time.localtime() backup_filepath = os.path.join(config.plugins.serienRec.LogFilePath.value, SERIENRECORDER_TVPLANER_H...
def verify_hub_empty(): def format_listener(listener): return ('Listener %r for greenlet %r with run callback %r' % (listener, listener.greenlet, getattr(listener.greenlet, 'run', None))) from eventlet import hubs hub = hubs.get_hub() readers = hub.get_readers() writers = hub.get_writers() ...
def test_get_repacked_binary_and_file_name(binary_service): (tar, file_name) = binary_service.get_repacked_binary_and_file_name(TEST_FW.uid) assert (file_name == f'{TEST_FW.file_name}.tar.gz'), 'file_name not correct' file_type = magic.from_buffer(tar, mime=False) assert ('gzip compressed data' in file_...
def test_more_statistics(constant_map_surfaces): res = constant_map_surfaces.statistics() sum2 = 0.0 for inum in range(101): sum2 += ((float(inum) - 50.0) ** 2) stdev = math.sqrt((sum2 / 100.0)) assert (res['mean'].values.mean() == pytest.approx(50.0, abs=0.0001)) assert (res['std'].valu...
class PDMDependencyGetter(PEP621DependencyGetter): def get(self) -> DependenciesExtract: pep_621_dependencies_extract = super().get() dev_dependencies = self._get_pdm_dev_dependencies() self._log_dependencies(dev_dependencies, is_dev=True) return DependenciesExtract(pep_621_dependenc...
def main(rounds=10000): st = time.time() d = do_test_serialize(mk_block(), rounds) elapsed = (time.time() - st) print(('Block serializations / sec: %.2f' % (rounds / elapsed))) st = time.time() d = do_test_deserialize(d, rounds) elapsed = (time.time() - st) print(('Block deserializations...
class TestLinalgConverter(AITTestCase): ([param('l2_norm_dim_3', input_shape=[1, 100, 40, 40], ord=2, dim=3, keepdims=False), param('l2_norm_dim_2', input_shape=[1, 100, 40, 40], ord=2, dim=2, keepdims=False), param('l2_norm_dim_1', input_shape=[1, 100, 40, 40], ord=2, dim=1, keepdims=True), param('vector_norm_dim_...