code
stringlengths
281
23.7M
def match_row(manager, system_id, table, fn): def _match_row(tables): return next((r for r in tables[table].rows.values() if fn(r)), None) request_to_get_tables = ovsdb_event.EventReadRequest(system_id, _match_row) reply_to_get_tables = manager.send_request(request_to_get_tables) return reply_to...
def get_color_image_size(config, imshow=True): if imshow: cv2.namedWindow('k4a') k4a = PyK4A(config) k4a.start() count = 0 while (count < 60): capture = k4a.get_capture() if np.any(capture.color): count += 1 if imshow: cv2.imshow('k4a',...
class Binary(Field): name = 'binary' _coerce = True def clean(self, data): return data def _deserialize(self, data): return base64.b64decode(data) def _serialize(self, data): if (data is None): return None return base64.b64encode(data).decode()
class Deck(): def __init__(self, name: str, html: Optional[str]=''): self._name = name self._html = html FlyteContextManager.current_context().user_space_params.decks.append(self) def append(self, html: str) -> 'Deck': assert isinstance(html, str) self._html = ((self._htm...
class MACAddress(FancyValidator): strip = True valid_characters = 'abcdefABCDEF' add_colons = False messages = dict(badLength=_('A MAC address must contain 12 digits and A-F; the value you gave has %(length)s characters'), badCharacter=_('MAC addresses may only contain 0-9 and A-F (and optionally :), no...
class TestTags(BaseEvenniaTest): def test_has_tag_key_only(self): self.obj1.tags.add('tagC') self.assertTrue(self.obj1.tags.has('tagC')) def test_has_tag_key_with_category(self): self.obj1.tags.add('tagC', 'categoryC') self.assertTrue(self.obj1.tags.has('tagC', 'categoryC')) ...
class OptionPlotoptionsCylinderSonification(Options): def contextTracks(self) -> 'OptionPlotoptionsCylinderSonificationContexttracks': return self._config_sub_data('contextTracks', OptionPlotoptionsCylinderSonificationContexttracks) def defaultInstrumentOptions(self) -> 'OptionPlotoptionsCylinderSonific...
def get_section_label_and_title_from_layout_block(layout_block: LayoutBlock) -> Tuple[(Optional[LayoutBlock], LayoutBlock)]: if (not layout_block): return (None, layout_block) layout_tokens_text = LayoutTokensText(layout_block) text = str(layout_tokens_text) m = re.match(HEADER_LABEL_REGEX, text...
def extractSkimtranslation15BlogspotCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if (item['tags'] == []): try: nums = item['title'].split(' ')[0] num...
def test_contract_get_logs_argument_filter(w3, emitter, wait_for_transaction, emitter_contract_event_ids): contract = emitter txn_hashes = [] event_id = emitter_contract_event_ids.LogTripleWithIndex txn_hashes.append(emitter.functions.logTriple(event_id, 1, 4, 1).transact()) txn_hashes.append(emitte...
def create_site_pin_to_wire_maps(tile_name, nodes): tile_prefix = (tile_name + '/') site_pin_to_wires = {} for node in nodes: if (len(node['site_pins']) == 0): continue wire_names = [wire for wire in node['wires'] if wire.startswith(tile_prefix)] assert (len(wire_names) =...
def make_sudoku_CSP(): rows = range(9) cols = range(9) vars = cross(rows, cols) domains = defaultdict((lambda : range(1, 10))) triples = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] unitlist = (([cross(rows, [c]) for c in cols] + [cross([r], cols) for r in rows]) + [cross(rs, cs) for rs in triples for cs i...
def find_bonds(atoms, coords3d, covalent_radii=None, bond_factor=BOND_FACTOR, min_dist=0.1): atoms = [atom.lower() for atom in atoms] c3d = coords3d.reshape((- 1), 3) if (covalent_radii is None): covalent_radii = [CR[atom] for atom in atoms] cr = np.array(covalent_radii) max_bond_dists = get...
class RMTTestRDepSolvedBy(object): def rmttest_neg_empty_solved_by(self): mstderr = StringIO() init_logger(mstderr) config = TestConfig() reqset = RequirementSet(config) req1 = Requirement('Name: A\nType: master requirement', 'A', None, None, None) reqset.add_requirem...
class clone_test_case(unittest.TestCase): def test_clone(self): i = {'a': {'b': {'c': 1}}} o = _clone(i) self.assertEqual(type(i), type(o)) self.assertEqual(i, o) self.assertFalse((i is o)) o['a']['b']['c'] = 2 self.assertEqual(i['a']['b']['c'], 1) sel...
class LiteEthARPTX(LiteXModule): def __init__(self, mac_address, ip_address, dw=8): self.sink = sink = stream.Endpoint(_arp_table_layout) self.source = source = stream.Endpoint(eth_mac_description(dw)) packet_length = max(arp_header.length, arp_min_length) packet_words = (packet_leng...
def vtk_version_changed(zipfile): result = True if os.path.exists(zipfile): import vtk vtk_version = vtk.vtkVersion().GetVTKVersion()[:3] sys.path.append(zipfile) try: from tvtk_classes.vtk_version import vtk_build_version except ImportError: resul...
class RoughVizPie(RoughVizBar): def fillStyle(self): return self._config_get() def fillStyle(self, text): self._config(text) def legend(self): return self._config_get(True) def legend(self, flag): self._config(flag) def legendPosition(self): return self._confi...
_overwritable() def _populate_registries(): logger.info('Populating registries ...') from d2go import optimizer from d2go.data import dataset_mappers from d2go.modeling.backbone import fbnet_v2 logger.info(f'populated registries for following modules: {optimizer} {dataset_mappers} {fbnet_v2}')
def plan_graph(graph: nx.DiGraph, execution_plan: ExecutionPlan, enable_chunking: bool=True) -> nx.DiGraph: origin_graph = OriginGraph(graph) filtered_graph = FilteredGraph.from_execution_plan(origin_graph, execution_plan=execution_plan) connected_graph = ScriptConnectedGraph.from_filtered_graph(filtered_gr...
class ActionManagerItem(HasTraits): id = Str() parent = Instance('pyface.action.group.Group') enabled = Bool(True) visible = Bool(True) def add_to_menu(self, parent, menu, controller): raise NotImplementedError() def add_to_toolbar(self, parent, tool_bar, image_cache, controller): ...
class NotebookEditor(Editor): close_button = Any() _pagewidgets = Dict() _action_dict = Dict() scrollable = True selected = Any() def init(self, parent): self._uis = [] self.control = QtGui.QTabWidget() self.control.currentChanged.connect(self._tab_activated) if (...
class Stations(): def __init__(self, root): leaf = root.find('Stations') self.file = Projection.leaf_to_string(leaf, 'File') self.visible = Projection.leaf_to_bool(leaf, 'Visible', False) self.markstyle = Projection.leaf_to_list(leaf, 'MarkStyle', ['o', 'full']) self.color = ...
def test_unwrap_to_list(): config = UnwrapPostProcessorConfiguration(data_path='exact_matches.members') data = {'exact_matches': {'contacts': {'slenderman': 321}, 'members': [{'howdy': 123}, {'meow': 841}]}} processor = UnwrapPostProcessorStrategy(configuration=config) result = processor.process(data) ...
class ChefRemoteDirectory(Processor): description = 'Produces a remote_directory Chef block. See input_variables = {'resource_name': {'required': True, 'description': 'Name for the resource. This can be a single string or an array of strings. If an array is provided, the first item in the array will be the res...
(CISAudit, 'audit_package_is_installed', mock_result_pass) (CISAudit, 'audit_service_is_masked', mock_result_pass) def test_audit_package_not_installed_or_service_is_masked_pass_masked(): state = test.audit_package_not_installed_or_service_is_masked(package='pytest', service='pytestd') assert (state == 0)
def verify_proof(username, salt, balance, index, user_table_size, root, proof): leaf = userdata_to_leaf(username, salt, balance) branch_length = (log2(get_next_power_of_2(user_table_size)) - 1) for i in range(branch_length): if (index & (2 ** i)): leaf = combine_tree_nodes(proof[i], leaf...
class NsInfo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) nsInstanceName = models.TextField(null=True, blank=True) nsInstanceDescription = models.TextField(null=True, blank=True) nsdId = models.UUIDField(null=True, blank=True) nsdInfoId = models.UUIDField(null=True, bla...
class TestXYZProperties(util.ColorAsserts, unittest.TestCase): def test_x(self): c = Color('color(xyz-d50 0.1 0.2 0.3 / 1)') self.assertEqual(c['x'], 0.1) c['x'] = 0.2 self.assertEqual(c['x'], 0.2) def test_y(self): c = Color('color(xyz-d50 0.1 0.2 0.3 / 1)') self...
def justify(text, width=None, align='l', indent=0, fillchar=' '): global _ANSISTRING if (not _ANSISTRING): from evennia.utils.ansi import ANSIString as _ANSISTRING is_ansi = isinstance(text, _ANSISTRING) lb = (_ANSISTRING('\n') if is_ansi else '\n') def _process_line(line): line_rest...
class OptionSeriesTilemapSonificationDefaultinstrumentoptionsMappingFrequency(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: ...
def render_ebook_reader(fpath): ext = os.path.splitext(fpath)[(- 1)] furl = urllib.parse.urljoin('/epub-content/', urllib.parse.quote(os.path.relpath(fpath, settings.EBOOK_STORAGE_DIR))) if (ext == '.pdf'): return redirect(('/static/ext/pdfjs/web/viewer.html?file=%s' % urllib.parse.quote(furl))) ...
class RoutingRule(): __slots__ = ['router'] def __init__(self, router, *args, **kwargs): self.router = router def app(self): return self.router.app def build_name(self, f): filename = os.path.realpath(f.__code__.co_filename) short = filename[(1 + len(self.app.root_path)):...
def load_model(name: str, device: Optional[Union[(str, torch.device)]]=None, download_root: str=None, in_memory: bool=False) -> Whisper: if (device is None): device = ('cuda' if torch.cuda.is_available() else 'cpu') if (download_root is None): download_root = os.getenv('XDG_CACHE_HOME', os.path....
class TestOkLChSerialize(util.ColorAssertsPyTest): COLORS = [('oklch(0.75 0.3 50)', {}, 'oklch(0.75 0.3 50)'), ('oklch(0.75 0.3 50 / 0.5)', {}, 'oklch(0.75 0.3 50 / 0.5)'), ('oklch(0.75 0.3 50)', {'alpha': True}, 'oklch(0.75 0.3 50 / 1)'), ('oklch(0.75 0.3 50 / 0.5)', {'alpha': False}, 'oklch(0.75 0.3 50)'), ('oklc...
def convertToLayer(viewOrLayer): if fb.evaluateBooleanExpression(('[(id)%s isKindOfClass:(Class)[CALayer class]]' % viewOrLayer)): return viewOrLayer elif fb.evaluateBooleanExpression(('[(id)%s respondsToSelector:(SEL)(layer)]' % viewOrLayer)): return fb.evaluateExpression(('(CALayer *)[%s layer...
def es_version(es_client: Elasticsearch) -> Tuple[(int, int, int)]: eland_es_version: Tuple[(int, int, int)] if (not hasattr(es_client, '_eland_es_version')): version_info = es_client.info()['version']['number'] eland_es_version = parse_es_version(version_info) es_client._eland_es_versio...
def _getTensorInfoFromPyTorchETEntry(tensor_container: List, container_type: str) -> Tuple[(int, int, str)]: list_count = container_type.count('GenericList') tensors = [] if (list_count == 2): tensors = tensor_container[0][0] dtype = container_type.replace('GenericList[', '').split(',', 1)[0...
def retry_decorator(number_of_retries: int, error_message: str, delay: float=0, logger_method: str='error') -> Callable: def decorator(fn: Callable) -> Callable: (fn) def wrapper(*args: Any, **kwargs: Any) -> Callable: log = get_logger_method(fn, logger_method) for retry in r...
def extractHellobiewtranslationWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('offered into marriage', 'offered into marriage', 'translated'), ('the bell and the d...
class wxListCtrl(wx.ListCtrl, TextEditMixin): def __init__(self, parent, ID, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, can_edit=False, edit_labels=False): wx.ListCtrl.__init__(self, parent, ID, pos, size, style) if can_edit: TextEditMixin.__init__(self, edit_labels) def m...
def usage(): print(("%s version %s\nusage: %s [-46DeFhqTvX] [-i interval] [-s server] [-p port] [-P port] [-S address] [-c count] [-t type] [-w wait] hostname\n\n -h --help Show this help\n -q --quiet Quiet\n -v --verbose Print actual dns response\n -s --server DNS server to use (defau...
(autouse=True) def check_postgresql_min_version(request, postgresql_version): postgresql_min_version_mark = request.node.get_closest_marker('postgresql_min_version') if postgresql_min_version_mark: min_version = postgresql_min_version_mark.args[0] if (postgresql_version < min_version): ...
class FortranObj(): def __init__(self): self.vis: int = 0 self.def_vis: int = 0 self.doc_str: str = None self.parent = None self.eline: int = (- 1) self.implicit_vars = None def set_default_vis(self, new_vis: int): self.def_vis = new_vis def set_visibi...
class OpUtil(object): def package_install(cls) -> None: OpUtil.log_operation_info('Installing packages') t0 = time.time() requirements_file = cls.determine_elyra_requirements() elyra_packages = cls.package_list_to_dict(requirements_file) current_packages = cls.package_list_to...
class C(): n = 0 now = 0 elapsed = 0 def start(self): self.n += 1 if (time is not None): self.now = time.time() def end(self): if (time is not None): self.elapsed += (time.time() - self.now) def __repr__(self): m = (self.n if self.n else 1)...
def _column_not_present_in_list(column: Optional[str], columns: Collection[str], handle_error: str, message: str) -> Optional[str]: if (column is None): return None if (column not in columns): return column if (handle_error == 'error'): raise ValueError(message.format(column=column))...
class abusechScan(Module): load_dotenv() ABUSECH_API_KEY = os.getenv('ABUSECH_API_KEY') bazaar = Bazaar(ABUSECH_API_KEY) config = Config({Option('HASH', 'Provide hash', True): str('f670080b1f42d1b70a37adda924976e6d7bd62bf77c35263aff97e')}) def run(self): hash = self.config.option('HASH').val...
def upgrade(): session = sa.orm.sessionmaker(bind=op.get_bind())() rows = session.query(CounterStat).filter(CounterStat.name.like('%\\%40%')).all() for stat in rows: name = stat.name.replace(':hset::%40', ':hset::', 1) existing = session.query(CounterStat).filter((CounterStat.name == name))....
def test_await_condition_met(): factory = WorkerFactory('localhost', 7933, DOMAIN) worker = factory.new_worker(TASK_LIST) worker.register_workflow_implementation_type(TestAwaitTimeoutWorkflowImpl) factory.start() client = WorkflowClient.new_client(domain=DOMAIN) workflow: TestAwaitTimeoutWorkflo...
class CustomDatasetDataLoader(): def __init__(self, opt): self.opt = opt dataset_class = find_dataset_using_name(opt.dataset_mode) self.dataset = dataset_class(opt) print(('dataset [%s] was created' % type(self.dataset).__name__)) loader = torch.utils.data.DataLoader ...
def parse_ns_lookup_output(lines): server = None prog = re.compile('Address:\\s*({})\\s*'.format(RE_IPV4_ADDRESS)) for line in lines: matches = prog.match(line) if (not matches): continue server = matches.group(1) break if (server is None): raise XVEx(...
class ValveTestIPV4StackedRoutingPathNoVLANS(ValveTestBases.ValveTestStackedRouting): VLAN100_FAUCET_VIPS = '10.0.1.254' VLAN100_FAUCET_VIP_SPACE = '10.0.1.254/24' VLAN200_FAUCET_VIPS = '10.0.2.254' VLAN200_FAUCET_VIP_SPACE = '10.0.2.254/24' V100_HOSTS = [1] V200_HOSTS = [3] def create_confi...
class VlanPCP(MatchTest): def runTest(self): match = ofp.match([ofp.oxm.vlan_vid((ofp.OFPVID_PRESENT | 2)), ofp.oxm.vlan_pcp(3)]) matching = {'vid=2 pcp=3': simple_tcp_packet(dl_vlan_enable=True, vlan_vid=2, vlan_pcp=3)} nonmatching = {'vid=2 pcp=4': simple_tcp_packet(dl_vlan_enable=True, vl...
def parse_incoming_chat_message(data: (str | dict)): result = IncomingChatMessage() try: if isinstance(data, dict): obj = data else: obj = json.loads(data) result.user_id = obj['user']['id'] result.chat_id = obj['chat']['id'] result.message_type = ...
class VengeOfTsukumogamiAction(FatetellAction): def __init__(self, source, target, card): self.source = source self.target = target self.card = card self.fatetell_target = source def fatetell_action(self, ft): if ft.succeeded: self.game.process_action(Damage(s...
.parametrize('query_template, expected_query', [('\nselect *\nfrom tracks\nlimit {{.inputs.limit}}', 'select * from tracks limit {{.inputs.limit}}'), (' select * from tracks limit {{.inputs.limit}}', 'select * from tracks limit {{.inputs.limit}}'), ('select * from abc', 'select * from abc')]) def test_query_sanitizatio...
class OptionPlotoptionsSolidgaugeSonificationContexttracksMappingHighpassResonance(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...
class LayoutHumanOGs(TreeLayout): def __init__(self, name='Human OGs', human_orth_prop='human_orth', column=5, color='#6b92d6'): super().__init__(name) self.aligned_faces = True self.human_orth_prop = human_orth_prop self.column = column self.color = color def set_node_st...
def naturalize_bspline_controls(coordinates: list[Vector]) -> None: n = (len(coordinates) - 2) if (n == 1): coordinates[1] = [(((a * 6) - (b + c)) / 4) for (a, b, c) in zip(coordinates[1], coordinates[0], coordinates[2])] elif (n > 1): m = _matrix_141(n) c = [] for r in range...
def pql_inspect_sql(obj: T.object): if (not isinstance(obj, objects.Instance)): raise Signal.make(T.TypeError, None, f'inspect_sql() expects a concrete object. Instead got: {obj.type}') s = get_db().compile_sql(obj.code, obj.subqueries) return objects.ValueInstance.make(sql.make_value(s), T.text, []...
def test_context_managed_transport_and_mount(): class Transport( def __init__(self, name: str) -> None: self.name: str = name self.events: typing.List[str] = [] def close(self): self.events.append(f'{self.name}.close') def __enter__(self): supe...
def check_autocomplete(route, client, fields, value, expected): for match_objs in (0, 1): resp = client.post('/api/v1/{}/autocomplete/'.format(route), content_type='application/json', data=json.dumps({'fields': fields, 'value': value, 'matched_objects': match_objs})) assert (resp.status_code == stat...
class _XTGeoFile(): def __init__(self, filelike: (((str | pathlib.Path) | io.BytesIO) | io.StringIO), mode: Literal[('rb', 'wb')]='rb', obj: XTGeoObject=None) -> None: logger.debug('Init ran for _XTGeoFile') if (not isinstance(filelike, (str, pathlib.Path, io.BytesIO, io.StringIO))): rai...
class CmdFlyAndDive(COMMAND_DEFAULT_CLASS): key = 'fly or dive' aliases = ('fly', 'dive') def func(self): caller = self.caller action = self.cmdname try: xyz_start = caller.location.xyz except AttributeError: caller.msg(f'You cannot {action} here.') ...
class OptionSeriesOrganizationStatesHoverHalo(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def opacity(self): return self._config_get(0.25) def opacity(self, num: float): self._config(nu...
def _conversation_from_dict(once: dict) -> OnceConversation: conversation = OnceConversation(once.get('chat_mode'), once.get('user_name'), once.get('sys_code')) conversation.cost = once.get('cost', 0) conversation.chat_mode = once.get('chat_mode', 'chat_normal') conversation.tokens = once.get('tokens', ...
def test_multi_merkle_tree(): leaves = [i.to_bytes(32, 'big') for i in range(16)] tree = merkle_tree(leaves) for i in range(65536): indices = [j for j in range(16) if (((i >> j) % 2) == 1)] proof = mk_multi_proof(tree, indices) assert verify_multi_proof(tree[1], indices, [leaves[i] f...
class B11R(): def __init__(self, options: argparse.Namespace) -> None: self.options = options if ('stdin' in (options.input_header, options.input_ommers, options.input_txs)): stdin = json.load(sys.stdin) else: stdin = None self.body: Body = Body(options, stdin...
def main(): import argparse parser = argparse.ArgumentParser(description='Check int_loop completion. Exits 0 on done, 1 if more loops are needed') parser.add_argument('--verbose', action='store_true', help='') parser.add_argument('--todo-dir', default='build/todo', help='') parser.add_argument('--mi...
class Instance(Type): def __init__(self, _class): self._class = _class def __contains__(self, value): return isinstance(value, self._class) def __repr__(self): return ('Instance(%s)' % self._class.__name__) __pnmltype__ = 'instance' def __pnmldump__(self): return Tree...
def parse_arguments(args=None): parser = argparse.ArgumentParser(add_help=False, formatter_class=argparse.RawDescriptionHelpFormatter, description='\nComputes per input matrix all viewpoints which are defined in the reference points file.\n\n') parserRequired = parser.add_argument_group('Required arguments') ...
class WebhookHandler(Resource): isLeaf = True def render_POST(self, request: Request): request_body_dict = json.load(request.content) update = telebot.types.Update.de_json(request_body_dict) reactor.callInThread((lambda : bot.process_new_updates([update]))) return b''
class _GroupPanel(object): def __init__(self, group, ui, suppress_label=False): content = group.get_content() self.group = group self.ui = ui if (group.orientation == 'horizontal'): self.direction = QtGui.QBoxLayout.Direction.LeftToRight else: self.dir...
def gen_function_call(func_attrs, backend_spec, indent=' '): p2 = func_attrs['inputs'][0] p3 = func_attrs['inputs'][1] p4 = func_attrs['inputs'][2] p5 = func_attrs['inputs'][3] rois = func_attrs['inputs'][4] xshape = p2._attrs['shape'] y = func_attrs['outputs'][0] yshape = y._attrs['sha...
def gen_test_cases(base_dir, get_conn, is_rocksdb=False, test_to_run=None, database='test', socket='/var/lib/mysql/mysql.sock'): try: dbh = get_conn(socket=socket, dbname=database) dbh.close() except Exception as e: raise RuntimeError(('Failed to connect to MySQL: %s' % str(e))) def ...
class SubscribableSchema(WebSocketEndpoint, WithMetaSubSchema): async def on_connect(self, websocket): (await websocket.accept(subprotocol='graphql-ws')) socket = StarletteSocket(websocket) try: (await self.execute(socket)) finally: (await websocket.close())
class OptionSeriesArcdiagramSonificationTracksPointgrouping(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, flag: bool): s...
class OptionPlotoptionsScatterSonificationTracksMappingRate(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...
class AutocompleteResponseMixin(object): def build_response(self, request, *args, **kwargs): queryset = kwargs.get('queryset') serializer = kwargs.get('serializer') params = request.query_params.copy() params.update(request.data.copy()) return AutoCompleteHandler.handle(query...
def test_flatten_is_working_properly_with_only_one_level_of_multiple_references_to_the_same_file(create_test_data, trash_bin, create_pymel, create_maya_env): data = create_test_data maya_env = create_maya_env pm = create_pymel maya_env.open(data['asset2_model_main_v001'], force=True) maya_env.refere...
def doit(reading): global rate_short, rate_long global ema_short, ema_long, trend for attribute in list(reading): if (not ema_long): ema_long = ema_short = reading[attribute] else: ema_long = ((reading[attribute] * rate_long) + (ema_long * (1 - rate_long))) ...
def dsn(): return 'postgres://{user}:{password}{host}:{port}/{database}'.format(**{'database': os.environ.get('POSTGRES_DB', 'elasticapm_test'), 'user': os.environ.get('POSTGRES_USER', 'postgres'), 'password': os.environ.get('POSTGRES_PASSWORD', 'postgres'), 'host': os.environ.get('POSTGRES_HOST', 'localhost'), 'po...
class BuilderTest(unittest.TestCase): TEST_FEATURE_FILES = '\n Attach cid_range enum markClass language_required\n GlyphClassDef LigatureCaretByIndex LigatureCaretByPos\n lookup lookupflag feature_aalt ignore_pos\n GPOS_1 GPOS_1_zero GPOS_2 GPOS_2b GPOS_3 GPOS_4 GPOS_5 GPOS_6 GPOS_8\n ...
def extractPcptranslationsCom(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...
def test_step_three_create_column(app): db = Database(app, auto_migrate=False) db.define_models(StepThreeThingOne) ops = _make_ops(db) db2 = Database(app, auto_migrate=False) db2.define_models(StepThreeThingTwo) ops2 = _make_ops(db2, ops) op = ops2.ops[0] sql = _make_sql(db, op) asse...
class GetBlockHeaders(BaseCommand[GetBlockHeadersPayload]): protocol_command_id = 2 serialization_codec = RLPCodec(sedes=GET_BLOCK_HEADERS_STRUCTURE, process_inbound_payload_fn=compose((lambda args: GetBlockHeadersPayload(*args)), apply_formatter_at_index((lambda args: BlockHeadersQuery(*args)), 1)))
class OptionPlotoptionsDependencywheelSonificationTracksMappingHighpassFrequency(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, tex...
def get_buffer_size(): for i in range(1, 100): payload = ('A' * i) buf_size = len(payload) try: io = get_io() io.send(payload) io.recv() io.close() log.info(('bad: %d' % buf_size)) except EOFError as e: io.close(...
class TestFS(object): def test_copy(self, tdenv): src = fs.pathify(tdenv.templateDir, 'TradeDangerous.sql') dst = fs.pathify(tdenv.tmpDir, src.name) fs.copy(src, dst) assert (dst.exists() and dst.is_file()) def test_ensureflag(self, tdenv): self.result = False fla...
.parametrize('codes', [['TEST'], ['TEST', 'UNAUTHORIZED']]) def test_raises_error_codes_missing(codes): errors = [Error(code=code, message='bam') for code in codes] with pytest.raises(pytest.raises.Exception): with raises_error_codes(['AUTH_MISSING']): raise Client.CallActionError(actions=[A...
def test_phi_function_in_head2(): u1 = Variable('u', Integer.int32_t(), 1) u2 = Variable('u', Integer.int32_t(), 2) v0 = Variable('v', Integer.int32_t(), 0) v1 = Variable('v', Integer.int32_t(), 1) node = BasicBlock(0, [Phi(u1, [v0, u2]), Phi(v1, [v0, u1]), Assignment(u2, BinaryOperation(OperationTy...
def parseinsfile(insfilename): insfile = open(insfilename, 'r', encoding='utf-8') content = insfile.read() insfile.close() insarray = re.findall('{name:(.*?),method_idx:(.*?),offset:(.*?),code_item_len:(.*?),ins:(.*?)}', content) for eachins in insarray: methodname = eachins[0].replace(' ', ...
class MsgStub(object): def __init__(self, channel): self.CreateValidator = channel.unary_unary('/cosmos.staking.v1beta1.Msg/CreateValidator', request_serializer=cosmos_dot_staking_dot_v1beta1_dot_tx__pb2.MsgCreateValidator.SerializeToString, response_deserializer=cosmos_dot_staking_dot_v1beta1_dot_tx__pb2.M...
class Namespace(): def __init__(self, *args): self.args = list(args) self.f_map = {} def __call__(self, var): all_args = (self.args + [var]) return variable(*all_args) def add(self, src, name=None): for key in self.f_map: if ((name is None) and (self.f_map...
class AbstractDataAccessor(ABCHasStrictTraits): title = Str() title_type = Instance(AbstractValueType, factory=TextValue) value_type = Instance(AbstractValueType) updated = Event def get_value(self, obj): raise NotImplementedError() def can_set_value(self, obj): return False ...
def extractDremingdemonWordpressCom(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_ty...
class OptionPlotoptionsScatter3dSonificationPointgrouping(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, flag: bool): sel...
def abstract(InterfaceClass: Type[ProviderInterface], method_prefix: str): class NewAbstractedClass(): pass for method_name in dir(InterfaceClass): if method_name.startswith(method_prefix): attr = getattr(InterfaceClass, method_name) wrapped = return_provider_method(attr)...
class Slider(ConstrainedControl): def __init__(self, ref: Optional[Ref]=None, key: Optional[str]=None, width: OptionalNumber=None, height: OptionalNumber=None, left: OptionalNumber=None, top: OptionalNumber=None, right: OptionalNumber=None, bottom: OptionalNumber=None, expand: Union[(None, bool, int)]=None, col: Op...