code
stringlengths
281
23.7M
def test_custom_lorentz(): eps_inf = td.SpatialDataArray((np.random.random((Nx, Ny, Nz)) + 1), coords=dict(x=X, y=Y, z=Z)) de1 = td.SpatialDataArray(np.random.random((Nx, Ny, Nz)), coords=dict(x=X, y=Y, z=Z)) f1 = td.SpatialDataArray((1 + np.random.random((Nx, Ny, Nz))), coords=dict(x=X, y=Y, z=Z)) delt...
class EventCopyrightFactory(BaseFactory): class Meta(): model = EventCopyright event = factory.RelatedFactory(EventFactoryBasic) holder = common.string_ holder_url = common.url_ licence = common.string_ licence_url = common.url_ year = 2007 logo = common.url_ event_id = 1
def print_strategy(strategy: Dict[(str, Dict[(str, int)])]): for (info_set, action_to_probabilities) in sorted(strategy.items()): norm = sum(list(action_to_probabilities.values())) log.info(f'{info_set}') for (action, probability) in action_to_probabilities.items(): log.info(f' ...
class FieldInteger(Field): name = 'Field Integer' def __init__(self, page: primitives.PageModel, value, label, placeholder, icon, width, height, html_code, helper, options, profile): html_input = page.ui.inputs.d_int(page.inputs.get(html_code, value), width=(None, '%'), placeholder=placeholder, options=...
def check_node_names_with_bad_characters(progress_controller=None): if (progress_controller is None): progress_controller = ProgressControllerBase() nodes_to_check = mc.ls() progress_controller.maximum = len(nodes_to_check) nodes_with_bad_name = [] for node_name in nodes_to_check: if...
class SlaveNoPacketIn(base_tests.SimpleDataPlane): def runTest(self): delete_all_flows(self.controller) (ingress_port,) = openflow_ports(1) pkt = str(simple_tcp_packet()) logging.info('Inserting table-miss flow sending all packets to controller') request = ofp.message.flow_ad...
(scope='function') def connection_config_mysql(db: Session) -> Generator: connection_config = ConnectionConfig.create(db=db, data={'name': str(uuid4()), 'key': 'my_mysql_db_1', 'connection_type': ConnectionType.mysql, 'access': AccessLevel.write, 'secrets': integration_secrets['mysql_example']}) (yield connecti...
class TestManagementFetcher(FetcherClient): def __init__(self, dbt_runner: BaseDbtRunner): super().__init__(dbt_runner) def get_models(self, exclude_elementary: bool=True, columns: Optional[DefaultDict[(str, List[ResourceColumnModel])]]=None) -> List[ResourceModel]: run_operation_response = self...
def urllist(arg: URIListArg, *, default_scheme: Optional[str]=None) -> List[URL]: if (not arg): raise ValueError('URL argument cannot be falsy') if isinstance(arg, URL): arg = [arg] elif isinstance(arg, str): urls = arg.replace(',', ';').split(';') default_scheme = _find_firs...
class TestSuperFencesCustomArithmatex(util.MdCase): extension = ['pymdownx.superfences'] extension_configs = {'pymdownx.superfences': {'custom_fences': [{'name': 'math', 'class': 'arithmatex', 'format': arithmatex.arithmatex_fenced_format(mode='mathjax')}]}} def test_arithmatex(self): self.check_mar...
def test_raises_warning_when_nan_introduced(): input_df = pd.DataFrame({'words': ['dog', 'dig', 'bird']}) output_df = pd.DataFrame({'words': [1, 0.66, np.nan]}) enc = MockClass(unseen='ignore') msg = 'During the encoding, NaN values were introduced in the feature(s) words.' with pytest.warns(UserWar...
class stats_reqs_cnt(StdOutputParams, ExecutorTopicContinuum, CreateMakeDependencies): def __init__(self, oconfig): tracer.debug('Called.') StdOutputParams.__init__(self, oconfig) CreateMakeDependencies.__init__(self) self.__ofile = None tracer.debug('Finished.') def topi...
class BlockHeaderFactory(factory.Factory): class Meta(): model = BlockHeader parent_hash = GENESIS_PARENT_HASH uncles_hash = EMPTY_UNCLE_HASH coinbase = GENESIS_COINBASE state_root = BLANK_ROOT_HASH transaction_root = BLANK_ROOT_HASH receipt_root = BLANK_ROOT_HASH bloom = 0 d...
def get_item_group_records(): return [{'doctype': 'Item Group', 'item_group_name': _('Laboratory'), 'name': _('Laboratory'), 'is_group': 0, 'parent_item_group': _('All Item Groups')}, {'doctype': 'Item Group', 'item_group_name': _('Drug'), 'name': _('Drug'), 'is_group': 0, 'parent_item_group': _('All Item Groups')}...
def run(f, *, argv=None): import treelog, bottombar from . import _util as util, matrix, parallel, cache, warnings decorators = (util.trap_sigint(), bottombar.add(util.timer(), label='runtime', right=True, refresh=1), bottombar.add(util.memory(), label='memory', right=True, refresh=1), util.in_context(cache...
def downgrade(): op.execute('COMMIT') try: op.execute('SHOW bdr.permit_ddl_locking') op.execute('SET LOCAL bdr.permit_ddl_locking = true') except exc.ProgrammingError: pass op.execute("UPDATE releases SET state = 'pending' WHERE state = 'frozen'") op.execute('ALTER TYPE ck_re...
class TestSearchBehaviour(ERC1155ClientTestCase): def test_setup(self): self.search_behaviour.setup() self.assert_quantity_in_outbox(1) (has_attributes, error_str) = self.message_has_attributes(actual_message=self.get_message_from_outbox(), message_type=LedgerApiMessage, performative=LedgerA...
def test_red_quantum(): q = ((2 ** QUANTUM_DEPTH) - 1) assert (Color('black').red_quantum == 0) assert (Color('red').red_quantum == q) assert (Color('white').red_quantum == q) assert ((0.49 * q) < Color('rgba(128, 0, 0, 1)').red_quantum < (0.51 * q)) c = Color('none') c.red_quantum = q a...
class Registry(Generic[ItemType]): def __init__(self) -> None: self.specs = {} def supported_ids(self) -> Set[str]: return {str(id_) for id_ in self.specs.keys()} def register(self, id_: Union[(ItemId, str)], entry_point: Union[(EntryPoint[ItemType], str)], class_kwargs: Optional[Dict[(str, ...
def create_start_workflow_request(workflow_client: WorkflowClient, wm: WorkflowMethod, args: List) -> StartWorkflowExecutionRequest: start_request = StartWorkflowExecutionRequest() start_request.domain = workflow_client.domain start_request.workflow_id = (wm._workflow_id if wm._workflow_id else str(uuid4())...
def test_write_to_model_more_than_once_top_level(): program = cleandoc("\n df = ref('model')\n write_to_model(df)\n\n df = ref('model')\n write_to_model(df, mode='append')\n ") module = ast.parse(program) try: write_to_model_check(module) except AssertionError:...
class SnmpUDPAddress(TextualConvention, OctetString): status = 'current' displayHint = '1d.1d.1d.1d/2d' subtypeSpec = OctetString.subtypeSpec subtypeSpec += ConstraintsUnion(ValueSizeConstraint(6, 6)) if mibBuilder.loadTexts: description = 'Represents a UDP over IPv4 address: octets contents...
def extractWebkingsgaUs(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 tagma...
class GuessTheNumberMachine(StateMachine): start = State(initial=True) low = State() high = State() won = State(final=True) lose = State(final=True) guess = (((lose.from_(low, high, cond='max_guesses_reached') | won.from_(low, high, cond='guess_is_equal')) | low.from_(low, high, start, cond='gue...
def namedtuple(cls): assert (cls.__base__ is object), 'Supports only simple classes with no inheritance' fields = [name for (name, _type) in cls.__annotations__.items()] ntuple_cls = collections.namedtuple(cls.__name__, fields) new_cls = type(cls.__name__, (ntuple_cls, object), cls.__dict__.copy()) ...
class OptionSeriesDependencywheelSonification(Options): def contextTracks(self) -> 'OptionSeriesDependencywheelSonificationContexttracks': return self._config_sub_data('contextTracks', OptionSeriesDependencywheelSonificationContexttracks) def defaultInstrumentOptions(self) -> 'OptionSeriesDependencywhee...
def get_resoure_path(filename): dest = os.path.abspath(os.path.join(__file__, '..', '..', 'resources')) if (not os.path.isdir(dest)): raise ValueError(('Resource dest dir %r is not a directory.' % dest)) path = os.path.join(dest, filename) url = '' if (filename in RESOURCES): (url, t...
def model_list(): ml_model_1 = ml.Model(display_name=_random_identifier('TestModel123_list1_')) model_1 = ml.create_model(model=ml_model_1) ml_model_2 = ml.Model(display_name=_random_identifier('TestModel123_list2_'), tags=['test_tag123']) model_2 = ml.create_model(model=ml_model_2) (yield [model_1,...
class jnitraceForm(QDialog, Ui_JniTraceDialog): def __init__(self, parent=None): super(jnitraceForm, self).__init__(parent) self.setupUi(self) self.setWindowOpacity(0.93) self.btnSubmit.clicked.connect(self.submit) self.moduleName = '' self.methodName = '' sel...
class FaceLandmarks(BaseModel): left_eye: Sequence[float] = Field(default_factory=list) left_eye_top: Sequence[float] = Field(default_factory=list) left_eye_right: Sequence[float] = Field(default_factory=list) left_eye_bottom: Sequence[float] = Field(default_factory=list) left_eye_left: Sequence[flo...
class EventType(SoftDeletionModel): __tablename__ = 'event_types' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String, nullable=False) slug = db.Column(db.String, unique=True, nullable=False) events = db.relationship('Event', backref='event-type') def __in...
class RegularBox(BayonetBox): description = "For short side walls that don't fit a connecting finger reduce *surroundingspaces* and *finger* in the Finger Joint Settings.\n\nThe lids needs to be glued. For the bayonet lid all outside rings attach to the bottom, all inside rings to the top.\n" ui_group = 'Box' ...
class cfm(packet_base.PacketBase): _PACK_STR = '!B' _MIN_LEN = struct.calcsize(_PACK_STR) _CFM_OPCODE = {} _TYPE = {'ascii': ['ltm_orig_addr', 'ltm_targ_addr']} def register_cfm_opcode(type_): def _register_cfm_opcode(cls): cfm._CFM_OPCODE[type_] = cls return cls ...
def test_schema_type(): obj = _types.SchemaType([_types.SchemaType.SchemaColumn('a', _types.SchemaType.SchemaColumn.SchemaColumnType.INTEGER), _types.SchemaType.SchemaColumn('b', _types.SchemaType.SchemaColumn.SchemaColumnType.FLOAT), _types.SchemaType.SchemaColumn('c', _types.SchemaType.SchemaColumn.SchemaColumnTy...
class AllowChunkedLengthTestTrue(AmbassadorTest): target: ServiceType def init(self): self.target = HTTP(name='target') def config(self) -> Generator[(Union[(str, Tuple[(Node, str)])], None, None)]: (yield (self, self.format('\n---\napiVersion: ambassador\nkind: Module\nname: ambassador\nc...
(scope='module', params=[0, 1, 2]) def solver_params(request): if (request.param == 0): return {'mat_type': 'matfree', 'snes_type': 'fas', 'snes_fas_cycles': 1, 'snes_fas_type': 'full', 'snes_fas_galerkin': False, 'snes_fas_smoothup': 1, 'snes_fas_smoothdown': 1, 'snes_monitor': None, 'snes_max_it': 20, 'fa...
def twist(pt: Point2D[FQP]) -> Point2D[FQ12]: if (pt is None): return None (_x, _y) = pt xcoeffs = [(_x.coeffs[0] - (_x.coeffs[1] * 9)), _x.coeffs[1]] ycoeffs = [(_y.coeffs[0] - (_y.coeffs[1] * 9)), _y.coeffs[1]] nx = FQ12(((([int(xcoeffs[0])] + ([0] * 5)) + [int(xcoeffs[1])]) + ([0] * 5))) ...
class ExtensionPointListenerLifetimeTestCase(unittest.TestCase): def setUp(self): registry = Application(extension_registry=ExtensionRegistry()) extension_point = ExtensionPoint(id='my.ep', trait_type=List()) registry.add_extension_point(extension_point) self.registry = registry ...
class OptionPlotoptionsBarSonificationTracksMappingTremoloDepth(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 determine_file_format(file_format: FileFormat, file_name: str) -> FileFormat: if (file_format != FileFormat.GUESS): return file_format extension = os.path.splitext(file_name)[1] if (extension == '.png'): return FileFormat.PNG if (extension == '.svg'): return FileFormat.SVG ...
def test_delivery_receipt_group(session): data = {'actorFbId': '1234', 'deliveredWatermarkTimestampMs': '', 'irisSeqId': '1111111', 'irisTags': ['DeltaDeliveryReceipt'], 'messageIds': ['mid.$XYZ', 'mid.$ABC'], 'requestContext': {'apiArgs': {}}, 'threadKey': {'threadFbId': '4321'}, 'class': 'DeliveryReceipt'} th...
def test_basic_functions(testblock: BasicBlock): assert (testblock.address == testblock.name == 1337) assert (len(testblock) == 5 == len(testblock.instructions)) assert (testblock.variables == {i[0], i[1], i[2], b[0], b[1], x}) assert (testblock.definitions == {i[1], i[2], b[0], b[1]}) assert (testb...
class WeakreffableInt(object): def __init__(self, value): self.value = value def __hash__(self): return hash(self.value) def __eq__(self, other): if isinstance(other, int): return (self.value == other) else: return (self.value == other.value) def _...
def extractElentiyalaeWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('legendoffei', 'Legend of Fei', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Lo...
class MTDevice(object): def __init__(self, port, baudrate=115200, timeout=0.002, autoconf=True, config_mode=False, verbose=False, initial_wait=0.1): self.verbose = verbose try: self.device = serial.Serial(port, baudrate, timeout=timeout, writeTimeout=timeout) except IOError: ...
class TOMLParser(Parser): def parse_string(s): import toml try: return toml.loads(f'val = {s}')['val'] except toml.decoder.TomlDecodeError: return s def load_config(stream): import toml return toml.load(stream) def save_config(d, stream=None, *...
class OptionPlotoptionsDumbbellSonificationTracksMappingNoteduration(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): ...
('value, expected', [param('shuffle(1,2,3)', ChoiceSweep(simple_form=True, list=[1, 2, 3], tags=set(), shuffle=True), id='shuffle:choice:simple'), param('shuffle(choice(1,2,3))', ChoiceSweep(list=[1, 2, 3], tags=set(), shuffle=True), id='shuffle:choice'), param('shuffle(tag(a,b,choice(1,2,3)))', ChoiceSweep(list=[1, 2,...
class OptionSeriesParetoStatesInactive(Options): def animation(self) -> 'OptionSeriesParetoStatesInactiveAnimation': return self._config_sub_data('animation', OptionSeriesParetoStatesInactiveAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): se...
def getAllGeneratorModules() -> dict[(str, ModuleType)]: generators = {} for (importer, modname, ispkg) in pkgutil.walk_packages(path=__path__, prefix=(__name__ + '.'), onerror=(lambda x: None)): module = importlib.import_module(modname) generators[modname.split('.')[(- 1)]] = module return ...
def conv2d_transpose(x, input_filters, output_filters, kernel_size, strides): shape = [kernel_size, kernel_size, output_filters, input_filters] weight = tf.Variable(tf.truncated_normal(shape, stddev=WEIGHT_INIT_STDDEV), name='weight') batch_size = tf.shape(x)[0] height = (tf.shape(x)[1] * strides) w...
def test_poll_for_query_completion_timeout(mocker, requests_mock: Mocker): mocker.patch('time.sleep') requests_mock.get(url=ANY, status_code=200, json={'queryId': '26f444dc-822d-4be7-9c8f-3be52779bea5', 'status': {'running': {}, 'type': 'running'}}) client = FoundryRestClient() with pytest.raises(Foundr...
class TestQueuePrivacyRequestToPropagateConsentHelper(): ('fides.api.api.v1.endpoints.consent_request_endpoints.create_privacy_request_func') def test_queue_privacy_request_to_propagate_consent(self, mock_create_privacy_request, db, consent_policy): mock_create_privacy_request.return_value = BulkPostPri...
class OptionPlotoptionsBellcurveSonificationDefaultinstrumentoptionsMappingHighpassResonance(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 map...
def extractPurplepetalsblossomsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, nam...
def test_span_finder_suggester(): nlp = Language() docs = [nlp('This is an example.'), nlp('This is the second example.')] docs[0].spans[TRAINING_KEY] = [docs[0][3:4]] docs[1].spans[TRAINING_KEY] = [docs[1][3:5]] span_finder = nlp.add_pipe('experimental_span_finder', config={'training_key': TRAINING...
class TestApiV3Permissions(CoprsTestCase): def auth_get(self, path, user): base = '/api_3/project/permissions' return self.get_api3_with_auth((base + path), user) def auth_post(self, path, data, user): base = '/api_3/project/permissions' return self.post_api3_with_auth((base + pa...
class OptionSeriesLineSonificationContexttracksMappingNoteduration(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 job_evt_listener(event): if (hasattr(event, 'exception') and event.exception): log.info('Job crashed: %s', event.job_id) log.info('Traceback: %s', event.traceback) else: log.info('Job event code: %s, job: %s', JOB_MAP[event.code], event.job_id) if (event.code == apscheduler.event...
class md_generator(): def __init__(self): self.output = '' def h1(self, text: str, end: str='<br>\n'): self.output += f'# {text}{end}' def h2(self, text: str, end: str='<br>\n'): self.output += f'## {text}{end}' def h3(self, text: str, end: str='<br>\n'): self.output += f...
def _state_agg_key(location_type, record: dict) -> Optional[str]: if (record[f'{location_type}_state_code'] is None): return None return json.dumps({'country_code': record[f'{location_type}_country_code'], 'state_code': record[f'{location_type}_state_code'], 'state_name': record[f'{location_type}_state_...
def sign_index(repodir, json_name): json_file = os.path.join(repodir, json_name) with open(json_file, encoding='utf-8') as fp: data = json.load(fp) if (json_name == 'entry.json'): index_file = os.path.join(repodir, data['index']['name'].lstrip('/')) sha256 = common.sha256...
class ArgumentParser(argparse.ArgumentParser): def __init__(self, *args, **kwargs) -> None: self.arguments: list[dict[(str, Any)]] = [] super().__init__(*args, **kwargs) def add_argument(self, *args, **kwargs) -> None: super().add_argument(*args, **kwargs) argument: dict[(str, An...
class OptionSeriesScatter3dDataDragdrop(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(fla...
.object(subprocess._subprocess, 'Popen') def test_check_call(mock_call): mock_call.return_value = _MockProcess() op = subprocess.check_call(['ls', '-l'], shell=True, env={'a': 'b'}, cwd='/tmp') assert (op == 0) mock_call.assert_called() assert (mock_call.call_args[0][0] == ['ls', '-l']) assert (...
class MinimalTableView(QtWidgets.QTableView): def __init__(self, model: QtCore.QAbstractTableModel) -> None: super().__init__() self.setShowGrid(False) self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.ResizeToContents) self.horizontalHeader().setVisible(F...
class CFFSpecializeProgramTest(unittest.TestCase): def __init__(self, methodName): unittest.TestCase.__init__(self, methodName) if (not hasattr(self, 'assertRaisesRegex')): self.assertRaisesRegex = self.assertRaisesRegexp def test_rmoveto_none(self): test_charstr = 'rmoveto' ...
def test_get_anchor_translation_multi_level(): anchor = (0.5, 0.5) trans1 = Jump.UP(1) pos1 = Pos(loc=trans1, relative_to=anchor) trans2 = Jump.LEFT(1) pos2 = Pos(loc=trans2, relative_to=pos1) trans3 = Jump.DOWN(1) ball_pos = BallPos(loc=trans3, relative_to=pos2, ids={'1'}) (anchor_resul...
def process_new_build(copr, form, create_new_build_factory, add_function, add_view, url_on_success, msg_on_success=True): if form.validate_on_submit(): build_options = {'enable_net': form.enable_net.data, 'timeout': form.timeout.data, 'bootstrap': form.bootstrap.data, 'isolation': form.isolation.data, 'with...
.parametrize('test_file_nonce', ['ttNonce/TransactionWithHighNonce32.json', 'ttNonce/TransactionWithHighNonce64Minus2.json']) def test_nonce(test_file_nonce: str) -> None: test = load_homestead_transaction(test_dir, test_file_nonce) tx = rlp.decode_to(Transaction, test['tx_rlp']) result_intrinsic_gas_cost =...
def extractSearchNiftyCom(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 tag...
class DictType(GenericType): def __init__(self, base: PythonType, item=(Any * Any)): super().__init__(base) if isinstance(item, tuple): assert (len(item) == 2) item = ProductType([type_caster.to_canon(x) for x in item]) self.item = item def validate_instance(self,...
def uniform_float(bijection, dtype, low=0, high=1): assert (low < high) ctype = dtypes.ctype(dtype) bitness = (64 if dtypes.is_double(dtype) else 32) raw_func = ('get_raw_uint' + str(bitness)) raw_max = dtypes.c_constant((2 ** bitness), dtype) size = dtypes.c_constant((high - low), dtype) lo...
def test_agent_configuration_loading_multipage_when_type_not_found(): file = Path(CUR_PATH, 'data', 'aea-config.example_multipage.yaml').open() jsons = list(yaml.safe_load_all(file)) jsons[1].pop('type') modified_file = io.StringIO() yaml.safe_dump_all(jsons, modified_file) modified_file.seek(0)...
class VecEnv(): def __init__(self): pass def reset(self, env_info: DictTensor=None): pass def step(self, policy_output: DictTensor) -> [[DictTensor, torch.Tensor], [DictTensor, torch.Tensor]]: raise NotImplementedError def close(self): raise NotImplementedError def n_...
class GroupTaggerView(Gtk.TreeView): __gsignals__ = {'category-changed': (GObject.SignalFlags.ACTION, None, (GObject.TYPE_PYOBJECT, GObject.TYPE_STRING)), 'category-edited': (GObject.SignalFlags.ACTION, None, (GObject.TYPE_STRING, GObject.TYPE_STRING)), 'group-changed': (GObject.SignalFlags.ACTION, None, (GObject.T...
def ttcollection_path(): font1 = TTFont() font1.importXML((TEST_DATA / 'TestTTF-Regular.ttx')) font2 = TTFont() font2.importXML((TEST_DATA / 'TestTTF-Regular.ttx')) coll = TTCollection() coll.fonts = [font1, font2] with tempfile.NamedTemporaryFile(suffix='.ttf', delete=False) as fp: ...
class PlotWidget(QWidget): customizationTriggered = Signal() def __init__(self, name, plotter, parent=None): QWidget.__init__(self, parent) self._name = name self._plotter = plotter self._figure = Figure() self._figure.set_layout_engine('tight') self._canvas = Fig...
def mock_dependencies(): with patch('tempfile.NamedTemporaryFile') as mock_tempfile, patch('usaspending_api.common.helpers.s3_helpers.download_s3_object'), patch('gzip.open') as mock_gzip_open, patch('builtins.open', mock_open(read_data='data')): mock_tempfile.return_value.__enter__.return_value.name = 'tem...
def add_SchedulerServiceServicer_to_server(servicer, server): rpc_method_handlers = {'addNamespace': grpc.unary_unary_rpc_method_handler(servicer.addNamespace, request_deserializer=message__pb2.NamespaceProto.FromString, response_serializer=message__pb2.Response.SerializeToString), 'getNamespace': grpc.unary_unary_...
class EmbedLinear(nn.Module): def __init__(self, nin, nhidden, nout, padding_idx=(- 1), sparse=False, lm=None): super(EmbedLinear, self).__init__() if (padding_idx == (- 1)): padding_idx = (nin - 1) if (lm is not None): self.embed = LMEmbed(nin, nhidden, lm, padding_i...
def extractShinTranslations(item): badwords = ['Status Update'] if any([(bad in item['tags']) for bad in badwords]): return None (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None ta...
def extractTheevilduketranslationsBlogspotCom(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, n...
class TestTouchFunction(unittest.TestCase): def setUp(self): self.test_dir = tempfile.mkdtemp() def tearDown(self): if os.path.exists(self.test_dir): shutil.rmtree(self.test_dir) def test_touch(self): filen = os.path.join(self.test_dir, 'touch.test') self.assertFa...
class Server(object): def __init__(self, core: Core): self.core = core self.server_name = 'Unknown' self.state = 'initial' self._ep: Optional[Endpoint] = None self._recv_gr: Optional[Greenlet] = None self._beater_gr: Optional[Greenlet] = None D = core.events.s...
def search_new_queries(additional_searches, history, sources_content): already_seen_results = history[history['query'].isin(additional_searches)] query_not_in_history = [value for value in additional_searches if (value not in history['query'].values)] sources_content = pd.concat([sources_content, already_se...
class BackendURL(): def __init__(self, fragment=None, host=None, opaque=None, path=None, query=None, rawQuery=None, scheme=None, username=None, password=None): self.fragment = fragment self.host = host self.opaque = opaque self.path = path self.query = query self.rawQ...
class Group(BaseEstimator): def __init__(self, indexer=None, learners=None, transformers=None, name=None, **kwargs): name = format_name(name, 'group', GLOBAL_GROUP_NAMES) super(Group, self).__init__(name=name, **kwargs) (learners, transformers) = mold_objects(learners, transformers) ...
def realtime_to_gametime(secs=0, mins=0, hrs=0, days=1, weeks=1, months=1, yrs=0, format=False): if ((days <= 0) or (weeks <= 0) or (months <= 0)): raise ValueError('realtime_to_gametime: days/weeks/months cannot be set <= 0, they start from 1.') (days, weeks, months) = ((days - 1), (weeks - 1), (months...
def message_from_worker_job(style, topic, job, who, ip, pid): if (style == 'v1'): content = {'user': job.submitter, 'copr': job.project_name, 'owner': job.project_owner, 'pkg': job.package_name, 'build': job.build_id, 'chroot': job.chroot, 'version': job.package_version, 'status': job.status} conten...
def test_mixer_one_input_node() -> None: sample_rate = 1 test_duration = 10 shape = (2,) amplitudes = np.array([5.0, 3.0]) frequencies = np.array([5, 10]) phase_shifts = np.array([1.0, 5.0]) midlines = np.array([3.0, (- 2.5)]) t_s = np.arange(0, test_duration, (1 / sample_rate)) angl...
def main(): if (sys.hexversion < ): raise InternalError('Benji only supports Python 3.6.5 or above.') enable_experimental = (os.getenv('BENJI_EXPERIMENTAL', default='0') == '1') parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, allow_abbrev=False) parser.ad...
def compile_vit(model_name, batch_size, class_token=False, global_pool='avg', use_fp16_acc=True): img_size = 224 patch_size = 16 embed_dim = 768 num_heads = 12 depth = 12 if (model_name == 'vit_base_patch16_224'): img_size = 224 patch_size = 16 embed_dim = 768 num...
class PermittivityMonitor(FreqMonitor): colocate: Literal[False] = pydantic.Field(False, title='Colocate Fields', description='Colocation turned off, since colocated permittivity values do not have a physical meaning - they do not correspond to the subpixel-averaged ones.') interval_space: Tuple[(pydantic.Posit...
class RssTriggerBase(UrlTrigger): pluginName = 'Rss Trigger' loggerPath = 'RssTrigger' def get_urls(self): self.rules = load_rules() feeds = [] for item in self.rules: feeds += item['feedurls'] return feeds def retriggerRssFeeds(self, feedurls): self.l...
def create_user_permissions(): (user_perm, _) = get_or_create(UserPermission, name='publish_event', description='Publish event (make event live)') user_perm.verified_user = True db.session.add(user_perm) (user_perm, _) = get_or_create(UserPermission, name='create_event', description='Create event') ...
def update(file: File) -> Tuple[(gradio.Image, gradio.Video)]: clear_reference_faces() clear_static_faces() if (file and is_image(file.name)): facefusion.globals.target_path = file.name return (gradio.Image(value=file.name, visible=True), gradio.Video(value=None, visible=False)) if (file...
def diff_bandwidth(): for k in range(10): delays_list = [] for j in range(1, 11, 1): env = UAVEnv() env.reset() env.B = (j * (10 ** 6)) costs = 0 i = 0 while (i < env.slot_num): (delay, is_terminal, step_redo) = ...
def test(): assert ('in doc.ents' in __solution__), 'Iterierst du uber die Entitaten?' assert (x_pro.text == 'X Pro'), 'Bist du dir sicher, dass x_pro die richtigen Tokens erfasst?' __msg__.good('Super! Naturlich musst du das hier nicht immer von Hand machen. In der nachsten Lektion lernst du spaCys regelba...
def to_serializable_case(entity_mapping: OrderedDict, settings: SerializationSettings, c: _core_wf.IfBlock, options: Optional[Options]=None) -> _core_wf.IfBlock: if (c is None): raise ValueError('Cannot convert none cases to registrable') then_node = get_serializable(entity_mapping, settings, c.then_nod...