code
stringlengths
281
23.7M
def string_token_to_bytes(token: Token) -> Union[(Token, bytes)]: if (isinstance(token, Token) and (token.type == 'STRING')): bstring = token.value[1:(- 1)] buffer = [] it = StringIterator(bstring) for c in it: if ((c == '\\') and it.has_next()): next2 = next(it) if (next2 == 'u'): if (not it.has_next(4)): raise ValueError('not enough remaining chars for \\uXXXX') _ = it.next(2) hexstr = ''.join(it.next(2)) buffer.append(int(hexstr, 16)) elif (next2 == 'x'): if (not it.has_next(2)): raise ValueError('not enough remaining chars for \\xXX') hexstr = ''.join(it.next(2)) buffer.append(int(hexstr, 16)) elif (next2 == 'n'): buffer.append(ord('\n')) elif (next2 == 'r'): buffer.append(ord('\r')) elif (next2 == 't'): buffer.append(ord('\t')) elif (next2 == '\\'): buffer.append(ord('\\')) elif (next2 == '"'): buffer.append(ord('"')) elif (next2 == "'"): buffer.append(ord("'")) else: buffer.append(ord(c)) return bytes(buffer) return token
.parametrize('django_elasticapm_client', [{'capture_body': 'errors'}, {'capture_body': 'transactions'}, {'capture_body': 'all'}, {'capture_body': 'off'}], indirect=True) def test_capture_empty_body(client, django_elasticapm_client): with pytest.raises(MyException): client.post(reverse('elasticapm-raise-exc'), data={}) error = django_elasticapm_client.events[ERROR][0] if (django_elasticapm_client.config.capture_body not in ('error', 'all')): assert (error['context']['request']['body'] == '[REDACTED]') else: assert (error['context']['request']['body'] == {})
class AbstractIndexManager(ABCHasStrictTraits): def create_index(self, parent, row): raise NotImplementedError() def get_parent_and_row(self, index): raise NotImplementedError() def from_sequence(self, indices): index = Root for row in indices: index = self.create_index(index, row) return index def to_sequence(self, index): result = () while (index != Root): (index, row) = self.get_parent_and_row(index) result = ((row,) + result) return result def from_id(self, id): raise NotImplementedError() def id(self, index): raise NotImplementedError() def reset(self): resettable_traits = self.trait_names(can_reset=True) self.reset_traits(resettable_traits)
def first(predicate=None, defaultValue=None): if (defaultValue is None): if (predicate is not None): return JsUtils.jsWrap(('%sfirst(%s)' % (LIB_REF, predicate))) return JsUtils.jsWrap(('%sfirst()' % LIB_REF)) defaultValue = JsUtils.jsConvertData(defaultValue, None) return JsUtils.jsWrap(('%sfirst(%s, %s)' % (LIB_REF, predicate, defaultValue)))
class OptionPlotoptionsVenn(Options): def accessibility(self) -> 'OptionPlotoptionsVennAccessibility': return self._config_sub_data('accessibility', OptionPlotoptionsVennAccessibility) def allowPointSelect(self): return self._config_get(False) def allowPointSelect(self, flag: bool): self._config(flag, js_type=False) def animation(self): return self._config_get(True) def animation(self, flag: bool): self._config(flag, js_type=False) def animationLimit(self): return self._config_get(None) def animationLimit(self, num: float): self._config(num, js_type=False) def borderDashStyle(self): return self._config_get('solid') def borderDashStyle(self, text: str): self._config(text, js_type=False) def brighten(self): return self._config_get(0) def brighten(self, num: float): self._config(num, js_type=False) def className(self): return self._config_get(None) def className(self, text: str): self._config(text, js_type=False) def clip(self): return self._config_get(False) def clip(self, flag: bool): self._config(flag, js_type=False) def cluster(self) -> 'OptionPlotoptionsVennCluster': return self._config_sub_data('cluster', OptionPlotoptionsVennCluster) def color(self): return self._config_get(None) def color(self, text: str): self._config(text, js_type=False) def colorAxis(self): return self._config_get(0) def colorAxis(self, num: float): self._config(num, js_type=False) def colorByPoint(self): return self._config_get(True) def colorByPoint(self, flag: bool): self._config(flag, js_type=False) def colorIndex(self): return self._config_get(None) def colorIndex(self, num: float): self._config(num, js_type=False) def colorKey(self): return self._config_get('y') def colorKey(self, text: str): self._config(text, js_type=False) def crisp(self): return self._config_get(True) def crisp(self, flag: bool): self._config(flag, js_type=False) def cursor(self): return self._config_get(None) def cursor(self, text: str): self._config(text, js_type=False) def custom(self): return self._config_get(None) def custom(self, value: Any): self._config(value, js_type=False) def dashStyle(self): return self._config_get('Solid') def dashStyle(self, text: str): self._config(text, js_type=False) def dataLabels(self) -> 'OptionPlotoptionsVennDatalabels': return self._config_sub_data('dataLabels', OptionPlotoptionsVennDatalabels) def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def enableMouseTracking(self): return self._config_get(True) def enableMouseTracking(self, flag: bool): self._config(flag, js_type=False) def events(self) -> 'OptionPlotoptionsVennEvents': return self._config_sub_data('events', OptionPlotoptionsVennEvents) def inactiveOtherPoints(self): return self._config_get(True) def inactiveOtherPoints(self, flag: bool): self._config(flag, js_type=False) def includeInDataExport(self): return self._config_get(None) def includeInDataExport(self, flag: bool): self._config(flag, js_type=False) def keys(self): return self._config_get(None) def keys(self, value: Any): self._config(value, js_type=False) def legendSymbol(self): return self._config_get('rectangle') def legendSymbol(self, text: str): self._config(text, js_type=False) def onPoint(self) -> 'OptionPlotoptionsVennOnpoint': return self._config_sub_data('onPoint', OptionPlotoptionsVennOnpoint) def opacity(self): return self._config_get(0.75) def opacity(self, num: float): self._config(num, js_type=False) def point(self) -> 'OptionPlotoptionsVennPoint': return self._config_sub_data('point', OptionPlotoptionsVennPoint) def pointDescriptionFormat(self): return self._config_get(None) def pointDescriptionFormat(self, value: Any): self._config(value, js_type=False) def pointDescriptionFormatter(self): return self._config_get(None) def pointDescriptionFormatter(self, value: Any): self._config(value, js_type=False) def relativeXValue(self): return self._config_get(False) def relativeXValue(self, flag: bool): self._config(flag, js_type=False) def selected(self): return self._config_get(False) def selected(self, flag: bool): self._config(flag, js_type=False) def showCheckbox(self): return self._config_get(False) def showCheckbox(self, flag: bool): self._config(flag, js_type=False) def showInLegend(self): return self._config_get(False) def showInLegend(self, flag: bool): self._config(flag, js_type=False) def skipKeyboardNavigation(self): return self._config_get(None) def skipKeyboardNavigation(self, flag: bool): self._config(flag, js_type=False) def sonification(self) -> 'OptionPlotoptionsVennSonification': return self._config_sub_data('sonification', OptionPlotoptionsVennSonification) def states(self) -> 'OptionPlotoptionsVennStates': return self._config_sub_data('states', OptionPlotoptionsVennStates) def step(self): return self._config_get(None) def step(self, value: Any): self._config(value, js_type=False) def stickyTracking(self): return self._config_get(False) def stickyTracking(self, flag: bool): self._config(flag, js_type=False) def tooltip(self) -> 'OptionPlotoptionsVennTooltip': return self._config_sub_data('tooltip', OptionPlotoptionsVennTooltip) def turboThreshold(self): return self._config_get(1000) def turboThreshold(self, num: float): self._config(num, js_type=False) def visible(self): return self._config_get(True) def visible(self, flag: bool): self._config(flag, js_type=False)
class RequestDispatcher(Dispatcher): __slots__ = ['response_builder'] def __init__(self, route, rule, response_builder): super().__init__(route) self.response_builder = response_builder async def dispatch(self, reqargs, response): return self.response_builder((await self.f(**reqargs)), response)
class OptionSeriesPieSonificationTracksMappingTremolo(Options): def depth(self) -> 'OptionSeriesPieSonificationTracksMappingTremoloDepth': return self._config_sub_data('depth', OptionSeriesPieSonificationTracksMappingTremoloDepth) def speed(self) -> 'OptionSeriesPieSonificationTracksMappingTremoloSpeed': return self._config_sub_data('speed', OptionSeriesPieSonificationTracksMappingTremoloSpeed)
def test_DataclassTransformer_to_python_value(): class MyDataClassMashumaro(DataClassJsonMixin): x: int _json class MyDataClass(): x: int de = DataclassTransformer() json_str = '{ "x" : 5 }' mock_literal = Literal(scalar=Scalar(generic=_json_format.Parse(json_str, _struct.Struct()))) result = de.to_python_value(FlyteContext.current_context(), mock_literal, MyDataClass) assert isinstance(result, MyDataClass) assert (result.x == 5) result = de.to_python_value(FlyteContext.current_context(), mock_literal, MyDataClassMashumaro) assert isinstance(result, MyDataClassMashumaro) assert (result.x == 5)
class OptionSeriesVariablepieSonificationTracksMappingVolume(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._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
class ChartJsOptTicks(DataAttrs): def beginAtZero(self, flag: Union[(bool, primitives.JsDataModel)]): self._attrs['beginAtZero'] = JsUtils.jsConvertData(flag, None) return self def display(self, flag: Union[(bool, primitives.JsDataModel)]): self._attrs['display'] = JsUtils.jsConvertData(flag, None) return self
class Solution(): def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def construct(preorder, idx, inorder, start, end): if (start > end): return None node = TreeNode(preorder[idx]) i = (inorder[start:(end + 1)].index(preorder[idx]) + start) left = construct(preorder, (idx + 1), inorder, start, (i - 1)) right = construct(preorder, (((idx + 1) + i) - start), inorder, (i + 1), end) node.left = left node.right = right return node return construct(preorder, 0, inorder, 0, (len(inorder) - 1))
class UIWrapper(): def __init__(self, target, *, registries, delay=0, auto_process_events=True): self._target = target self._registries = registries self._auto_process_events = auto_process_events self.delay = delay def help(self): interaction_to_doc = dict() location_to_doc = dict() for registry in self._registries[::(- 1)]: for type_ in registry._get_interactions(self._target): interaction_to_doc[type_] = registry._get_interaction_doc(target=self._target, interaction_class=type_) for type_ in registry._get_locations(self._target): location_to_doc[type_] = registry._get_location_doc(target=self._target, locator_class=type_) print('Interactions') print('') for interaction_type in sorted(interaction_to_doc, key=repr): print(repr(interaction_type)) print(textwrap.indent(interaction_to_doc[interaction_type], prefix=' ')) print() if (not interaction_to_doc): print('No interactions are supported.') print() print('Locations') print('') for locator_type in sorted(location_to_doc, key=repr): print(repr(locator_type)) print(textwrap.indent(location_to_doc[locator_type], prefix=' ')) print() if (not location_to_doc): print('No locations are supported.') print() def locate(self, location): return UIWrapper(target=self._get_next_target(location), registries=self._registries, delay=self.delay, auto_process_events=self._auto_process_events) def find_by_name(self, name): return self.locate(locator.TargetByName(name=name)) def find_by_id(self, id): return self.locate(locator.TargetById(id=id)) def perform(self, interaction): self._perform_or_inspect(interaction) def inspect(self, interaction): return self._perform_or_inspect(interaction) def _perform_or_inspect(self, interaction): supported = [] for registry in self._registries: try: handler = registry._get_handler(target=self._target, interaction=interaction) except InteractionNotSupported as e: supported.extend(e.supported) continue else: context = (_event_processed if self._auto_process_events else _nullcontext) with context(): return handler(self, interaction) raise InteractionNotSupported(target_class=self._target.__class__, interaction_class=interaction.__class__, supported=supported) def _get_next_target(self, location): supported = set() for registry in self._registries: try: handler = registry._get_solver(target=self._target, location=location) except LocationNotSupported as e: supported |= set(e.supported) else: if self._auto_process_events: with _reraise_exceptions(): _process_cascade_events() return handler(self, location) raise LocationNotSupported(target_class=self._target.__class__, locator_class=location.__class__, supported=list(supported))
class TestBackend(ErrBot): def change_presence(self, status: str=ONLINE, message: str='') -> None: pass def __init__(self, config): config.BOT_LOG_LEVEL = logging.DEBUG config.CHATROOM_PRESENCE = ('testroom',) config.BOT_IDENTITY = {'username': 'err'} self.bot_identifier = self.build_identifier('Err') super().__init__(config) self.incoming_stanza_queue = Queue() self.outgoing_message_queue = Queue() self.sender = self.build_identifier(config.BOT_ADMINS[0]) self.reset_rooms() self.md = text() def send_message(self, msg: Message) -> None: log.info('\n\n\nMESSAGE:\n%s\n\n\n', msg.body) super().send_message(msg) self.outgoing_message_queue.put(self.md.convert(msg.body)) def send_stream_request(self, user: Identifier, fsource: Optional[BinaryIO], name: Optional[str], size: Optional[int], stream_type: Optional[str]) -> None: self.outgoing_message_queue.put(fsource.read()) def serve_forever(self) -> None: self.connect_callback() try: while True: log.debug('waiting on queue') (stanza_type, entry, extras) = self.incoming_stanza_queue.get() log.debug('message received') if (entry == QUIT_MESSAGE): log.info('Stop magic message received, quitting...') break if (stanza_type is STZ_MSG): msg = Message(entry, extras=extras) msg.frm = self.sender msg.to = self.bot_identifier self.callback_message(msg) mentioned = [self.build_identifier(word[1:]) for word in entry.split() if word.startswith('')] if mentioned: self.callback_mention(msg, mentioned) elif (stanza_type is STZ_PRE): log.info('Presence stanza received.') self.callback_presence(entry) elif (stanza_type is STZ_IQ): log.info('IQ stanza received.') else: log.error('Unknown stanza type.') except EOFError: pass except KeyboardInterrupt: pass finally: log.debug('Trigger disconnect callback') self.disconnect_callback() log.debug('Trigger shutdown') self.shutdown() def shutdown(self) -> None: if self.is_open_storage(): self.close_storage() self.plugin_manager.shutdown() self.repo_manager.shutdown() def connect(self) -> None: return def build_identifier(self, text_representation) -> TestPerson: return TestPerson(text_representation) def build_reply(self, msg: Message, text=None, private: bool=False, threaded: bool=False) -> Message: msg = self.build_message(text) msg.frm = self.bot_identifier msg.to = msg.frm return msg def mode(self) -> str: return 'test' def rooms(self) -> List[TestRoom]: return [r for r in self._rooms if r.joined] def query_room(self, room: TestRoom) -> TestRoom: try: return [r for r in self._rooms if (str(r) == str(room))][0] except IndexError: r = TestRoom(room, bot=self) return r def prefix_groupchat_reply(self, message: Message, identifier: Identifier): super().prefix_groupchat_reply(message, identifier) message.body = f'{identifier.nick} {message.body}' def pop_message(self, timeout: int=5, block: bool=True): return self.outgoing_message_queue.get(timeout=timeout, block=block) def push_message(self, msg: Message, extras=''): self.incoming_stanza_queue.put((STZ_MSG, msg, extras), timeout=5) def push_presence(self, presence): self.incoming_stanza_queue.put((STZ_PRE, presence), timeout=5) def zap_queues(self) -> None: while (not self.incoming_stanza_queue.empty()): msg = self.incoming_stanza_queue.get(block=False) log.error('Message left in the incoming queue during a test: %s.', msg) while (not self.outgoing_message_queue.empty()): msg = self.outgoing_message_queue.get(block=False) log.error('Message left in the outgoing queue during a test: %s.', msg) def reset_rooms(self) -> None: self._rooms = []
def clear_all_regions(): for window in sublime.windows(): for view in window.views(): for region_key in view.settings().get('bracket_highlighter.regions', []): view.erase_regions(region_key) view.settings().set('bracket_highlighter.locations', {'open': {}, 'close': {}, 'unmatched': {}, 'icon': {}})
def get_test_cls(cls): cls_instances = list(classes[cls]) ids = [('%s.%s::%s' % (mod, cls, i['tag'])) for (_, i, cls, mod) in cls_instances] .parametrize(('instance', 'i_data', 'cls', 'mod'), cls_instances, ids=ids) class TestWrap(BaseInstanceTest): pass name = ('Test%s' % cls) return type(str(name), (TestWrap,), {})
def prod_tile(p, i_tile=32, j_tile=32): p = inline(p, 'producer(_)') p = inline(p, 'consumer(_)') p = tile(p, 'g', 'i', 'j', ['io', 'ii'], ['jo', 'ji'], i_tile, j_tile, perfect=True) p = simplify(p) loop = p.find_loop('io') p = fuse_at(p, 'f', 'g', loop) loop = p.find_loop('jo') p = fuse_at(p, 'f', 'g', loop) p = rewrite_expr(p, 'n % 128', 0) p = rewrite_expr(p, 'm % 256', 0) p = simplify(p) p = store_at(p, 'f', 'g', p.find_loop('io')) p = store_at(p, 'f', 'g', p.find_loop('jo')) p = lift_alloc(p, 'f: _', n_lifts=2) p = simplify(p) return p
class HashEngine(object): def __init__(self, inputQueue, outputQueue, threads=2, pHash=True, integrity=True): self.log = logging.getLogger('Main.HashEngine') self.tlog = logging.getLogger('Main.HashEngineThread') self.hashWorkers = threads self.inQ = inputQueue self.outQ = outputQueue self.archIntegrity = integrity self.runStateMgr = multiprocessing.Manager() self.manNamespace = self.runStateMgr.Namespace() self.dbApi = self.getDbConnection() def getDbConnection(self): return dbApi.DbApi() def runThreads(self): self.manNamespace.stopOnEmpty = False self.manNamespace.run = True args = (self.inQ, self.outQ, self.manNamespace, self.archIntegrity) self.pool = multiprocessing.pool.Pool(processes=self.hashWorkers, initializer=createHashThread, initargs=args) def close(self): self.log.info('Closing threadpool') self.manNamespace.run = False self.pool.terminate() def haltEarly(self): self.manNamespace.run = False def gracefulShutdown(self): self.manNamespace.stopOnEmpty = True self.pool.close() self.pool.join() def cleanPathCache(self, fqPathBase): self.log.info('Querying for all files on specified path.') itemsCursor = self.dbApi.getUniqueOnBasePath(fqPathBase) items = [] retItems = 0 for item in tqdm.tqdm(itemsCursor): retItems += 1 items.append(item[0]) if (not scanner.runState.run): print('Breaking due to exit flag') return self.log.info('Looking for files in the DB that are not on disk anymore.') self.log.info('Recieved items = %d', retItems) self.log.info('total unique items = %s', len(items)) for itemPath in tqdm.tqdm(items, desc='Exist check'): if (not os.path.exists(itemPath)): self.log.info('Item %s does not exist. Should delete from DB', itemPath) self.dbApi.deleteBasePath(itemPath) try: if (not scanner.runState.run): print('Breaking due to exit flag') return except BrokenPipeError: self.log.error('Runstate thread exited? Halting') return self.outQ.put('clean')
def test_unit(rel_path='.'): try: import pytest except ImportError: sys.exit('Cannot do unit tests, pytest not installed') py2 = (sys.version_info[0] == 2) rel_path = (('flexx_legacy/' + rel_path) if py2 else ('flexx/' + rel_path)) test_path = os.path.join(ROOT_DIR, rel_path) if (py2 or (os.getenv('TEST_INSTALL', '').lower() in ('1', 'yes', 'true'))): if (ROOT_DIR in sys.path): sys.path.remove(ROOT_DIR) os.chdir(os.path.expanduser('~')) m = __import__(NAME) assert (ROOT_DIR not in os.path.abspath(m.__path__[0])) else: os.chdir(ROOT_DIR) m = __import__(NAME) assert (ROOT_DIR in os.path.abspath(m.__path__[0])) _enable_faulthandler() try: res = pytest.main(['--cov', NAME, '--cov-config=.coveragerc', '--cov-report=term', '--cov-report=html', test_path]) sys.exit(res) finally: m = __import__(NAME) print('Unit tests were performed on', str(m))
class TestUnit(unittest.TestCase): def test_record_soh(self): get_new_test_db() car = vehicule_list[0] soh_list = [99.0, 96.0, 90.2] for x in range(len(soh_list)): Database.record_battery_soh(car.vin, get_date(x), soh_list[x]) compare_dict(vars(BatterySoh(car.vin, [get_date(0), get_date(1), get_date(2)], soh_list)), vars(Database.get_soh_by_vin(car.vin))) self.assertEqual(soh_list[(- 1)], Database.get_last_soh_by_vin(car.vin)) def test_record_same_soh(self): get_new_test_db() car = vehicule_list[0] Database.record_battery_soh(car.vin, get_date(0), 99.0) self.assertRaises(IntegrityError, Database.record_battery_soh, car.vin, get_date(0), 99.0)
class CompositeRaceStore(): def __init__(self, es_store, file_store): self.es_store = es_store self.file_store = file_store def find_by_race_id(self, race_id): return self.es_store.find_by_race_id(race_id) def store_race(self, race): self.file_store.store_race(race) self.es_store.store_race(race) def delete_race(self): return self.es_store.delete_race() def delete_annotation(self): return self.es_store.delete_annotation() def list_annotations(self): return self.es_store.list_annotations() def add_annotation(self): return self.es_store.add_annotation() def list(self): return self.es_store.list()
def get_deleted_fpds_data_from_s3(date): ids_to_delete = [] regex_str = '.*_delete_records_(IDV|award).*' if (not date): return [] if settings.IS_LOCAL: for file in os.listdir(settings.CSV_LOCAL_PATH): if (re.search(regex_str, file) and (datetime.strptime(file[:file.find('_')], '%m-%d-%Y').date() >= date)): with open((settings.CSV_LOCAL_PATH + file), 'r') as current_file: reader = csv.reader(current_file.read().splitlines()) next(reader) unique_key_list = [rows[0] for rows in reader] ids_to_delete += unique_key_list else: aws_region = settings.USASPENDING_AWS_REGION DELETED_TRANSACTION_JOURNAL_FILES = settings.DELETED_TRANSACTION_JOURNAL_FILES if (not (aws_region and DELETED_TRANSACTION_JOURNAL_FILES)): raise Exception('Missing required environment variables: USASPENDING_AWS_REGION, DELETED_TRANSACTION_JOURNAL_FILES') s3client = boto3.client('s3', region_name=aws_region) s3resource = boto3.resource('s3', region_name=aws_region) s3_bucket = s3resource.Bucket(DELETED_TRANSACTION_JOURNAL_FILES) file_list = [item.key for item in s3_bucket.objects.all()] for item in file_list: if (re.search(regex_str, item) and ('/' not in item) and (datetime.strptime(item[:item.find('_')], '%m-%d-%Y').date() >= date)): s3_item = s3client.get_object(Bucket=DELETED_TRANSACTION_JOURNAL_FILES, Key=item) reader = csv.reader(s3_item['Body'].read().decode('utf-8').splitlines()) next(reader) unique_key_list = [rows[0] for rows in reader] ids_to_delete += unique_key_list logger.info(('Number of records to delete: %s' % str(len(ids_to_delete)))) return ids_to_delete
class TraitSheetApp(wx.App): def __init__(self, object): self.object = object wx.InitAllImageHandlers() wx.App.__init__(self, 1, 'debug.log') self.MainLoop() def OnInit(self): ui = self.object.edit_traits(kind='live') ui = self.object.edit_traits(kind='modal') ui = self.object.edit_traits(kind='nonmodal') ui = self.object.edit_traits(kind='wizard') self.SetTopWindow(ui.control) return True
class test(testing.TestCase): def test_torque(self): args = main(rotation=1.0, increment=1.0, elemsize=1.0, poisson=0.25) self.assertAlmostEqual64(args['u'], '\n eNoN0stLE3AcAHAC58Ieq9SDh8Z87ffcQrCQJBcVJFMKKUzaQSExeihKFzvEwsBU6GJlJCYpLCQKLXQY\n VjazmHWI7ff4/rYx3Tx4CSotw2lQff6Gz3jJZKzAVMe4aYFWYDCszyY+xNZQ2FlhAvgxroBWsru0FjlI\n CD9E/WQXfYPXSRbqJBuoEf8gfuwlXtqGM+YaycAQfCUdMK5P0pvwJ34ApbUHOlG7XlVjOEc3mE2cVt+h\n evmcEvBNW9RTZCGc2rG1aIqewNvAyoppgnmYpBmWYufZBvPx+3iOVxJBfvMBMkALXXFyCUJ8Qjv1Oq/X\n F5TDlauTyrBZydUvZpcBucpGhcV4cB4cK2womde30JAZ1JvIi/NJ49K9kiZy2wRMNznIz7AuGmRlrJeF\n 6TKt4VE27irHRfywe4ECf+e2cSZfuFIQF0fcZapYzLlXxCdxivWpGkmZX1apGJ0R2SYI+WTEcTXRRK4j\n H+omWygEefB2cSwxr2+YZjSoD/GXsk9NMS39co4iNSMUOx1NgZO/j5SpJK+KrAi3rIuW40XxMbJAiTga\n sfHP4rnsol75RfayCmVXNbzebGlOlyGTnKKv4S+2sjGUDWm1F0/vP6dceB+xqGKK5ayUdKe0Sx+zyVHx\n AHvEhI6THaJeP6KpaK6+AlWikrh0jhggl9VSNE6SqlR6GFdWmWJP5Hbp489KKp1rqCIWRgHcBGHcSuoS\n tc4CM+2UqAXuYoWHdVZpxKR1CPeYdm2jDZCjreiOzkAzztcdUEdeqf8TTI/eQCOwR/txUAdVG16LTxoH\n 8cBF009+quOwTv4BeBNCLA==') def test_stretch(self): args = main(rotation=0.0, elemsize=2.0, poisson=0.25, restol=1e-08, trim=0.0, stretch=1.1, degree=3) self.assertAlmostEqual64(args['u'], '\n eNodjy2OwlAURu8GipmgJ6gRff25jCGT1LOFBtd0AxVTMyEhIRgEVbgG2y3gCQmGdx+9ONSIUeOmG5j3\n YT7x5eQkp3MqP+71RvLimtuX3clJR3YinSP6TP1Pc278XvmkRB/TzkXpk2fwGwb/xxNpo7G8ucFc7EO2\n Zm33crjP7cL/RO88GKIVb/2e+XAnomkb/abgZwx+yeCPvJCyhydQeGqFpwjhKXt4AoWnVniKEJ6yhydQ\n eGqFpwjhyRN0fcfoqmJ0ZQZdeYIu//uuKkZXZtCVJ+jyP4NHV2bQ9Q9mTH+1')
def openflags_to_symbols(openflags): open_symbols = [] flags = OrderedDict([('O_WRONLY', 1), ('O_RDWR', 2), ('O_CREAT', 64), ('O_EXCL', 128), ('O_NOCTTY', 256), ('O_TRUNC', 512), ('O_APPEND', 1024), ('O_NONBLOCK', 2048), ('O_DSYNC', 4096), ('O_ASYNC', 8192), ('O_DIRECT', 16384), ('O_DIRECTORY', 65536), ('O_NOFOLLOW', 131072), ('O_NOATIME', 262144), ('O_CLOEXEC', 524288), ('O_SYNC', 1052672), ('O_PATH', 2097152), ('O_TMPFILE', 4259840)]) if ((openflags & (flags['O_WRONLY'] | flags['O_RDWR'])) == 0): open_symbols.append('O_RDONLY') for (symbol, flag) in flags.items(): if ((openflags & flag) == flag): open_symbols.append(symbol) return ' | '.join(open_symbols)
def gen_function_src(sorted_graph: List[Tensor], workdir: str, model_name: str='') -> List[Tuple[(str, str)]]: target = Target.current() file_pairs = [] exist_func = set() prefix = os.path.join(workdir, model_name) for node in sorted_graph: for func in node.src_ops(): fname = func._attrs['name'] if (fname not in exist_func): src_path = os.path.join(prefix, (fname + target.src_extension())) obj_path = os.path.join(prefix, (fname + '.obj')) file_pairs.append((src_path, obj_path)) with open(src_path, 'w') as fo: fo.write(func.gen_function()) exist_func.add(fname) _LOGGER.info(f'generated {len(file_pairs)} function srcs') return file_pairs
class PDFNum(PDFObject): def __init__(self, s): PDFObject.__init__(self) self.s = s def __str__(self): sign = '' if (random.randint(0, 100) > 50): if (self.s > 0): sign = '+' elif (self.s < 0): sign = '-' elif (random.randint(0, 100) > 50): sign = '-' else: sign = '+' obfuscated = '' obfuscated += sign obfuscated += putSome(['0']) obfuscated += ('%s' % self.s) if (type(self.s) == type(0)): if (random.randint(0, 100) > 60): obfuscated += ('.' + putSome(['0'])) elif (random.randint(0, 100) > 60): obfuscated += putSome(['0']) return obfuscated
class CouncilAgenda(Base): __tablename__ = 'council_agenda' agenda_id = Column(Integer, primary_key=True) country_id = Column(ForeignKey(Country.country_id), nullable=False, index=True) start_date = Column(Integer) launch_date = Column(Integer) cooldown_date = Column(Integer) is_resolved = Column(Boolean) name_id = Column(ForeignKey(SharedDescription.description_id), index=True) country = relationship(Country, foreign_keys=[country_id], back_populates='council_agendas') db_name = relationship(SharedDescription, foreign_keys=[name_id]) def rendered_name(self) -> str: return game_info.lookup_key((self.db_name.text + '_name'))
class Solution(): def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: def subtree_with_deepest(node): if (node is None): return (node, 0) (lt, ll) = subtree_with_deepest(node.left) (rt, rl) = subtree_with_deepest(node.right) if (ll == rl): return (node, (ll + 1)) elif (ll > rl): return (lt, (ll + 1)) else: return (rt, (rl + 1)) return subtree_with_deepest(root)[0]
def upgrade(): op.execute("ALTER TABLE image_sizes ALTER full_aspect TYPE boolean USING CASE full_aspect WHEN 'on' THEN TRUE ELSE FALSE END", execution_options=None) op.execute("ALTER TABLE image_sizes ALTER icon_aspect TYPE boolean USING CASE icon_aspect WHEN 'on' THEN TRUE ELSE FALSE END", execution_options=None) op.execute("ALTER TABLE image_sizes ALTER thumbnail_aspect TYPE boolean USING CASE thumbnail_aspect WHEN 'on' THEN TRUE ELSE FALSE END", execution_options=None)
def get_result_formatters(method_name: Union[(RPCEndpoint, Callable[(..., RPCEndpoint)])], module: 'Module') -> Dict[(str, Callable[(..., Any)])]: formatters = combine_formatters((PYTHONIC_RESULT_FORMATTERS,), method_name) formatters_requiring_module = combine_formatters((FILTER_RESULT_FORMATTERS,), method_name) partial_formatters = apply_module_to_formatters(formatters_requiring_module, module, method_name) return compose(*partial_formatters, *formatters)
.usefixtures('use_tmpdir') def test_move_file(shell): with open('file', 'w', encoding='utf-8') as f: f.write('Hei') shell.move_file('file', 'file2') assert os.path.isfile('file2') assert (not os.path.isfile('file')) assert (b'No such file or directory' in shell.move_file('file2', 'path/file2').stderr) shell.mkdir('path') shell.move_file('file2', 'path/file2') assert os.path.isfile('path/file2') assert (not os.path.isfile('file2')) assert (b'not an existing file' in shell.move_file('path', 'path2').stderr) assert (b'not an existing file' in shell.move_file('not_existing', 'target').stderr) with open('file2', 'w', encoding='utf-8') as f: f.write('123') shell.move_file('file2', 'path/file2') assert os.path.isfile('path/file2') assert (not os.path.isfile('file2')) shell.mkdir('rms/ipl') with open('global_variables.ipl', 'w', encoding='utf-8') as f: f.write('123') shell.move_file('global_variables.ipl', 'rms/ipl/global_variables.ipl')
def set_fast_pyparsing_reprs(): for obj in vars(_pyparsing).values(): try: if issubclass(obj, ParserElement): _old_pyparsing_reprs.append((obj, (obj.__repr__, obj.__str__))) obj.__repr__ = fast_repr obj.__str__ = fast_repr except TypeError: pass
class _Worker(Thread): def __init__(self, task_queue): Thread.__init__(self) self.tasks_queue = task_queue self.setDaemon(True) def run(self): while True: func = self.tasks_queue.get() try: try: func() except: from mu_repo.print_ import PrintError PrintError() finally: self.tasks_queue.task_done()
class getCounters_args(): thrift_spec = None thrift_field_annotations = None thrift_struct_annotations = None def isUnion(): return False def read(self, iprot): if ((isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocol) and (iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL))) and isinstance(iprot.trans, TTransport.CReadableTransport) and (self.thrift_spec is not None) and (fastproto is not None)): fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0) self.checkRequired() return if ((isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocol) and (iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL))) and isinstance(iprot.trans, TTransport.CReadableTransport) and (self.thrift_spec is not None) and (fastproto is not None)): fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2) self.checkRequired() return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if (ftype == TType.STOP): break else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() self.checkRequired() def checkRequired(self): return def write(self, oprot): if ((isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocol) and (oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL))) and (self.thrift_spec is not None) and (fastproto is not None)): oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)) return if ((isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocol) and (oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL))) and (self.thrift_spec is not None) and (fastproto is not None)): oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)) return oprot.writeStructBegin('getCounters_args') oprot.writeFieldStop() oprot.writeStructEnd() def __repr__(self): L = [] padding = (' ' * 4) return ('%s(\n%s)' % (self.__class__.__name__, ',\n'.join(L))) def __eq__(self, other): if (not isinstance(other, self.__class__)): return False return (self.__dict__ == other.__dict__) def __ne__(self, other): return (not (self == other)) if (not six.PY2): __hash__ = object.__hash__
def extractJackofalltastesconnoisseurofnoneWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('A Tale of Two Phoenixes', 'A Tale of Two Phoenixes', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in tagmap: if (tagname in item['tags']): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
class TestReentrancy(): def setup_class(cls): protocol_path = os.path.join(ROOT_DIR, 'packages', 'fetchai', 'protocols', 'oef_search') connection_path = os.path.join(ROOT_DIR, 'packages', 'fetchai', 'connections', 'soef') builder = AEABuilder() builder.set_name('aea1') builder.add_private_key(DEFAULT_LEDGER) builder.add_protocol(protocol_path) builder.add_contract(contract_path) builder.add_connection(connection_path) builder.add_skill(dummy_skill_path) cls.aea1 = builder.build() builder.set_name('aea2') cls.aea2 = builder.build() def are_components_different(components_a: Collection[Component], components_b: Collection[Component], is_including_config: bool=True) -> None: assert (len(components_a) == len(components_b)), 'Cannot compare, number of components is different.' assert ({c.component_id for c in components_a} == {c.component_id for c in components_b}), 'Cannot compare, component ids are different.' d1 = {c.component_id: c for c in components_a} d2 = {c.component_id: c for c in components_b} assert all(((d1[k] is not d2[k]) for k in d1.keys())) if is_including_config: c1 = {c.component_id: c.configuration for c in components_a} c2 = {c.component_id: c.configuration for c in components_b} assert all(((c1[k] is not c2[k]) for k in c1.keys())) def test_skills_instances_are_different(self): aea1_skills = self.aea1.resources.get_all_skills() aea2_skills = self.aea2.resources.get_all_skills() self.are_components_different(aea1_skills, aea2_skills) def test_protocols_instances_are_different(self): aea1_protocols = self.aea1.resources.get_all_protocols() aea2_protocols = self.aea2.resources.get_all_protocols() self.are_components_different(aea1_protocols, aea2_protocols) def test_contracts_instances_are_different(self): aea1_contracts = self.aea1.resources.get_all_contracts() aea2_contracts = self.aea2.resources.get_all_contracts() self.are_components_different(aea1_contracts, aea2_contracts, is_including_config=False) def test_connections_instances_are_different(self): aea1_connections = self.aea1.runtime.multiplexer.connections aea2_connections = self.aea2.runtime.multiplexer.connections self.are_components_different(aea1_connections, aea2_connections)
class FitterOptions(BaseModel): num_poles: Optional[int] = 1 num_tries: Optional[int] = 50 tolerance_rms: Optional[float] = 0.01 min_wvl: Optional[float] = None max_wvl: Optional[float] = None bound_amp: Optional[float] = None bound_eps_inf: Optional[float] = 1.0 bound_f: Optional[float] = None constraint: ConstraintEnum = ConstraintEnum.HARD nlopt_maxeval: int = 5000
class OptionSeriesOrganizationLevelsDatalabelsFilter(Options): def operator(self): return self._config_get(None) def operator(self, value: Any): self._config(value, js_type=False) def property(self): return self._config_get(None) def property(self, text: str): self._config(text, js_type=False)
def prepare_ndarray(data, schema): if hasattr(data, '__array_interface__'): array_interface = data.__array_interface__.copy() array_interface['data'] = data.tobytes() array_interface['shape'] = list(array_interface['shape']) return array_interface else: return data
class StorageManager(): def __init__(self, hass, config_manager: ConfigManager): self._hass = hass self._config_manager = config_manager def config_data(self) -> ConfigData: config_data = None if (self._config_manager is not None): config_data = self._config_manager.data return config_data def file_name(self): file_name = f'.{DOMAIN}.{slugify(self.config_data.name)}' return file_name async def async_load_from_store(self): store = Store(self._hass, STORAGE_VERSION, self.file_name, encoder=JSONEncoder) data = (await store.async_load()) return data async def async_save_to_store(self, data): store = Store(self._hass, STORAGE_VERSION, self.file_name, encoder=JSONEncoder) (await store.async_save(data))
class OptionSeriesVariwideDataDatalabelsFilter(Options): def operator(self): return self._config_get(None) def operator(self, value: Any): self._config(value, js_type=False) def property(self): return self._config_get(None) def property(self, text: str): self._config(text, js_type=False)
def main(args): parser = argparse.ArgumentParser(description='Generate ESPHome Home Assistant config.json') parser.add_argument('channels', nargs='+', type=Channel, choices=list(Channel)) args = parser.parse_args(args) root = Path(__file__).parent.parent templ = (root / 'template') with open((templ / 'addon_config.yaml'), 'r') as f: config = yaml.safe_load(f) copyf = config['copy_files'] for channel in args.channels: conf = config[f'esphome-{channel.value}'] base_image = conf.pop('base_image', None) dir_ = (root / conf.pop('directory')) path = (dir_ / 'config.yaml') with open(path, 'w') as f: yaml.dump(conf, f, indent=2, sort_keys=False, explicit_start=True) for file_ in copyf: os.makedirs((dir_ / Path(file_).parent), exist_ok=True) if Path.exists(((templ / channel.value) / file_)): copyfile(((templ / channel.value) / file_), (dir_ / file_)) else: copyfile((templ / file_), (dir_ / file_)) path = (dir_ / 'FILES ARE GENERATED DO NOT EDIT') with open(path, 'w') as f: f.write("Any edits should be made to the files in the 'template' directory") if (channel == Channel.dev): path = (dir_ / 'build.yaml') build_conf = {'build_from': {arch: base_image for arch in conf['arch']}} with open(path, 'w') as f: yaml.dump(build_conf, f, indent=2, sort_keys=True, explicit_start=True)
class OptionPlotoptionsBulletDragdrop(Options): def draggableTarget(self): return self._config_get(True) def draggableTarget(self, flag: bool): self._config(flag, js_type=False) 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(flag, js_type=False) def dragHandle(self) -> 'OptionPlotoptionsBulletDragdropDraghandle': return self._config_sub_data('dragHandle', OptionPlotoptionsBulletDragdropDraghandle) def dragMaxX(self): return self._config_get(None) def dragMaxX(self, num: float): self._config(num, js_type=False) def dragMaxY(self): return self._config_get(None) def dragMaxY(self, num: float): self._config(num, js_type=False) def dragMinX(self): return self._config_get(None) def dragMinX(self, num: float): self._config(num, js_type=False) def dragMinY(self): return self._config_get(None) def dragMinY(self, num: float): self._config(num, js_type=False) def dragPrecisionX(self): return self._config_get(0) def dragPrecisionX(self, num: float): self._config(num, js_type=False) def dragPrecisionY(self): return self._config_get(0) def dragPrecisionY(self, num: float): self._config(num, js_type=False) def dragSensitivity(self): return self._config_get(2) def dragSensitivity(self, num: float): self._config(num, js_type=False) def groupBy(self): return self._config_get(None) def groupBy(self, text: str): self._config(text, js_type=False) def guideBox(self) -> 'OptionPlotoptionsBulletDragdropGuidebox': return self._config_sub_data('guideBox', OptionPlotoptionsBulletDragdropGuidebox) def liveRedraw(self): return self._config_get(True) def liveRedraw(self, flag: bool): self._config(flag, js_type=False)
_settings(ROOT_URLCONF='tests.browsable_api.no_auth_urls') class NoDropdownWithoutAuthTests(TestCase): def setUp(self): self.client = APIClient(enforce_csrf_checks=True) self.username = 'john' self.email = '' self.password = 'password' self.user = User.objects.create_user(self.username, self.email, self.password) def tearDown(self): self.client.logout() def test_name_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get('/') content = response.content.decode() assert ('john' in content) def test_dropdown_not_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get('/') content = response.content.decode() assert ('<li class="dropdown">' not in content) def test_dropdown_not_shown_when_logged_out(self): response = self.client.get('/') content = response.content.decode() assert ('<li class="dropdown">' not in content)
class OptionPlotoptionsColumnSonificationContexttracksMappingRate(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._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
class TestAchromaticRoundTrip(TestRoundTrip): class Color(Base): Color.deregister('space:hpluv') Color.deregister('space:ryb') Color.deregister('space:ryb-biased') SPACES = {k: 6 for k in Color.CS_MAP.keys()} COLORS = [Color('darkgrey'), Color('lightgrey'), Color('gray'), Color('black'), Color('white')] .parametrize('space', SPACES) def test_round_trip(self, space): for c in self.COLORS: self.assert_round_trip(c, space)
def cfg_with_single_aliased_variable_4(x, z_aliased): cfg = ControlFlowGraph() (mem0, mem1, mem2, mem3) = generate_mem_phi_variables(4) n0 = BasicBlock(0, [Assignment(ListOperation([]), Call(function_symbol('func'), [UnaryOperation(OperationType.dereference, [z_aliased[1]])]))]) n1 = BasicBlock(1, [MemPhi(mem2, [mem1, mem3]), Assignment(x[1], BinaryOperation(OperationType.plus, [x[0], Constant(1)])), Branch(Condition(OperationType.less_or_equal, [z_aliased[2], x[1]]))]) n2 = BasicBlock(2, []) cfg.add_edges_from([UnconditionalEdge(n0, n1), UnconditionalEdge(n1, n1), UnconditionalEdge(n1, n2)]) expected_cfg = ControlFlowGraph() n1 = BasicBlock(1, [Phi(z_aliased[2], [z_aliased[1], z_aliased[3]]), Assignment(x[1], BinaryOperation(OperationType.plus, [x[0], Constant(1)])), Branch(Condition(OperationType.less_or_equal, [z_aliased[2], x[1]]))]) expected_cfg.add_edges_from([UnconditionalEdge(n0, n1), UnconditionalEdge(n1, n1), UnconditionalEdge(n1, n2)]) return (cfg, expected_cfg)
class InputSticker(Dictionaryable, JsonSerializable): def __init__(self, sticker: Union[(str, InputFile)], emoji_list: List[str], mask_position: Optional[MaskPosition]=None, keywords: Optional[List[str]]=None) -> None: self.sticker: Union[(str, InputFile)] = sticker self.emoji_list: List[str] = emoji_list self.mask_position: Optional[MaskPosition] = mask_position self.keywords: Optional[List[str]] = keywords if service_utils.is_string(self.sticker): self._sticker_name = '' self._sticker_dic = self.sticker else: self._sticker_name = service_utils.generate_random_token() self._sticker_dic = 'attach://{0}'.format(self._sticker_name) def to_dict(self) -> dict: json_dict = {'sticker': self._sticker_dic, 'emoji_list': self.emoji_list} if (self.mask_position is not None): json_dict['mask_position'] = self.mask_position.to_dict() if (self.keywords is not None): json_dict['keywords'] = self.keywords return json_dict def to_json(self) -> str: return json.dumps(self.to_dict()) def convert_input_sticker(self): if service_utils.is_string(self.sticker): return (self.to_json(), None) return (self.to_json(), {self._sticker_name: self.sticker})
def _prepare_input_tensors(m, nk_groups, dtype, start=0, has_bias=True, only_params=False): inputs = [] for (i, (n, k)) in enumerate(nk_groups): X = Tensor(shape=[m, k], dtype=dtype, name='x_{}'.format((i + start)), is_input=True) W = Tensor(shape=[n, k], dtype=dtype, name='w_{}'.format((i + start)), is_input=True) B = Tensor(shape=[n], dtype=dtype, name='b_{}'.format((i + start)), is_input=True) if has_bias: if only_params: inputs.append([W, B]) else: inputs.append([X, W, B]) elif only_params: inputs.append([W]) else: inputs.append([X, W]) return inputs
def test_math_operations(): c = 2.0 x = (0.25 - (1j * 14.5)) y = ((- 1.0) + (1j * 0.5)) x_fxp = Fxp(x, dtype='Q14.3') y_fxp = Fxp(y, dtype='Q14.3') z = (x + y) z_fxp = (x_fxp + y_fxp) assert (z_fxp() == z) z = (x + c) z_fxp = (x_fxp + c) assert (z_fxp() == z) z = (x - y) z_fxp = (x_fxp - y_fxp) assert (z_fxp() == z) z = (x - c) z_fxp = (x_fxp - c) assert (z_fxp() == z) z = (x * y) z_fxp = (x_fxp * y_fxp) assert (z_fxp() == z) z = (x * c) z_fxp = (x_fxp * c) assert (z_fxp() == z) z = (x / y) z_fxp = (x_fxp / y_fxp) assert (z_fxp() == z) z = (x / c) z_fxp = (x_fxp / c) assert (z_fxp() == z) x = np.asarray(x) y = np.asarray(y) z = (((x * y.conj()).real // (y * y.conj()).real) + (1j * ((x * y.conj()).imag // (y * y.conj()).real))) z_fxp = (x_fxp // y_fxp) assert (z_fxp() == z) c = np.asarray(c) z = (((x * c.conj()).real // (c * c.conj()).real) + (1j * ((x * c.conj()).imag // (c * c.conj()).real))) z_fxp = (x_fxp // c) assert (z_fxp() == z) x = ((- 3.0) + (1j * 4.0)) x_fxp = Fxp(x, dtype='Q16.16') assert (abs(x_fxp)() == 5.0)
def convert_traditional_views_to_materialized_views(transactional_db): with connection.cursor() as cursor: cursor.execute('; '.join((f'drop view if exists {v} cascade' for v in ALL_MATVIEWS))) generate_matviews(materialized_views_as_traditional_views=False) (yield) with connection.cursor() as cursor: cursor.execute('; '.join((f'drop materialized view if exists {v} cascade' for v in ALL_MATVIEWS))) generate_matviews(materialized_views_as_traditional_views=True)
class BadLen(BgpExc): CODE = BGP_ERROR_MESSAGE_HEADER_ERROR SUB_CODE = BGP_ERROR_SUB_BAD_MESSAGE_LENGTH def __init__(self, msg_type_code, message_length): super(BadLen, self).__init__() self.msg_type_code = msg_type_code self.length = message_length self.data = struct.pack('!H', self.length) def __str__(self): return ('<BadLen %d msgtype=%d>' % (self.length, self.msg_type_code))
class TestCoinChange(unittest.TestCase): def test_coin_change(self): coin_changer = CoinChanger() self.assertRaises(TypeError, coin_changer.make_change, None, None) self.assertEqual(coin_changer.make_change([], 0), 0) self.assertEqual(coin_changer.make_change([1, 2, 3], 5), 2) self.assertEqual(coin_changer.make_change([3, 2, 1], 5), 2) self.assertEqual(coin_changer.make_change([3, 2, 1], 8), 3) print('Success: test_coin_change')
def _cli_reverse_dns_lookup(ip_list, max_workers=600): socket.setdefaulttimeout(8) count_df = pd.Series(ip_list).value_counts().reset_index() count_df.columns = ['ip_address', 'count'] count_df['cum_count'] = count_df['count'].cumsum() count_df['perc'] = count_df['count'].div(count_df['count'].sum()) count_df['cum_perc'] = count_df['perc'].cumsum() hosts = [] with futures.ThreadPoolExecutor(max_workers=max_workers) as executor: for host in executor.map(_single_request, count_df['ip_address']): hosts.append(host) df = pd.DataFrame(hosts) columns = ['ip', 'hostname', 'aliaslist', 'ipaddrlist', 'errors'] if (df.shape[1] == 4): columns = columns[:(- 1)] df.columns = columns final_df = pd.merge(count_df, df, left_on='ip_address', right_on='ip', how='left').drop('ip', axis=1) return final_df
_counter _table _wkt _with_session def get_statistics(session, interval='day', wkt=None, distance=None, begin=None, end=None, limit=None, offset=None, tbl=None, **kwargs): query = emissionsapi.db.get_statistics(session, tbl, interval_length=interval) query = emissionsapi.db.filter_query(query, tbl, wkt=wkt, distance=distance, begin=begin, end=end) query = emissionsapi.db.limit_offset_query(query, limit=limit, offset=offset) return [{'value': {'count': count, 'average': avg, 'standard deviation': stddev, 'min': min_val, 'max': max_val}, 'time': {'min': min_time, 'max': max_time, 'interval_start': inter}} for (count, avg, stddev, min_val, max_val, min_time, max_time, inter) in query]
class RowLimitedContractDownloadViewSet(BaseDownloadViewSet): endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/download/contract.md' def post(self, request): request.data['constraint_type'] = 'row_count' return BaseDownloadViewSet.post(self, request, validator_type=ContractDownloadValidator)
class OptionPlotoptionsPieStates(Options): def hover(self) -> 'OptionPlotoptionsPieStatesHover': return self._config_sub_data('hover', OptionPlotoptionsPieStatesHover) def inactive(self) -> 'OptionPlotoptionsPieStatesInactive': return self._config_sub_data('inactive', OptionPlotoptionsPieStatesInactive) def normal(self) -> 'OptionPlotoptionsPieStatesNormal': return self._config_sub_data('normal', OptionPlotoptionsPieStatesNormal) def select(self) -> 'OptionPlotoptionsPieStatesSelect': return self._config_sub_data('select', OptionPlotoptionsPieStatesSelect)
(LOOK_DEV_TYPES) def check_only_supported_materials_are_used(progress_controller=None): if (progress_controller is None): progress_controller = ProgressControllerBase() non_arnold_materials = [] all_valid_materials = [] for renderer in VALID_MATERIALS.keys(): all_valid_materials.extend(VALID_MATERIALS[renderer]) all_materials = pm.ls(mat=1) progress_controller.maximum = len(all_materials) for material in all_materials: if (material.name() not in ['lambert1', 'particleCloud1', 'standardSurface1']): if (material.type() not in all_valid_materials): non_arnold_materials.append(material) progress_controller.increment() if len(non_arnold_materials): pm.select(non_arnold_materials) progress_controller.complete() raise PublishError(('There are non-Arnold materials in the scene:<br><br>%s<br><br>Please remove them!!!' % '<br>'.join(map((lambda x: x.name()), non_arnold_materials)))) progress_controller.complete()
class PageTest(FaunaTestCase): def test_page(self): self.assertEqual(Page.from_raw({'data': 1, 'before': 2, 'after': 3}), Page(1, 2, 3)) self.assertEqual(Page([1, 2, 3], 2, 3).map_data((lambda x: (x + 1))), Page([2, 3, 4], 2, 3)) def test_set_iterator(self): collection_ref = self.client.query(query.create_collection({'name': 'gadgets'}))['ref'] index_ref = self.client.query(query.create_index({'name': 'gadgets_by_n', 'active': True, 'source': collection_ref, 'terms': [{'field': ['data', 'n']}]}))['ref'] def create(n): q = query.create(collection_ref, {'data': {'n': n}}) return self.client.query(q)['ref'] a = create(0) create(1) b = create(0) gadgets_set = query.match(index_ref, 0) self.assertEqual(list(Page.set_iterator(self.client, gadgets_set, page_size=1)), [a, b]) query_mapper = (lambda a: query.select(['data', 'n'], query.get(a))) query_mapped_iter = Page.set_iterator(self.client, gadgets_set, map_lambda=query_mapper) self.assertEqual(list(query_mapped_iter), [0, 0]) mapped_iter = Page.set_iterator(self.client, gadgets_set, mapper=(lambda x: [x])) self.assertEqual(list(mapped_iter), [[a], [b]]) def test_repr(self): self.assertEqual(repr(Page([1, 2, 3], ['before'])), "Page(data=[1, 2, 3], before=['before'], after=None)")
def test_tas_b_defaults_success(client, download_test_data): download_generation.retrieve_db_string = Mock(return_value=get_database_dsn_string()) resp = client.post('/api/v2/download/accounts/', content_type='application/json', data=json.dumps({'account_level': 'treasury_account', 'filters': {'submission_types': ['object_class_program_activity'], 'fy': '2018', 'quarter': '1'}, 'file_format': 'csv'})) assert (resp.status_code == status.HTTP_200_OK) assert ('.zip' in resp.json()['file_url'])
def test_get_limited_markdown_msg(): slack_message_builder = SlackMessageBuilder() short_message = 'short message' long_message = (short_message * 3000) markdown_short_message = slack_message_builder.get_limited_markdown_msg(short_message) markdown_long_message = slack_message_builder.get_limited_markdown_msg(long_message) assert (markdown_short_message == short_message) assert (len(markdown_long_message) == SectionBlock.text_max_length) assert markdown_long_message.endswith('...age')
def test_should_guess_only_specific_actions_and_fix_upper_lowercase(): input_policy = PolicyDocument(Version='2012-10-17', Statement=[Statement(Effect='Allow', Action=[Action('ec2', 'DetachVolume')], Resource=['*'])]) expected_output = PolicyDocument(Version='2012-10-17', Statement=[Statement(Effect='Allow', Action=[Action('ec2', 'DetachVolume')], Resource=['*']), Statement(Effect='Allow', Action=[Action('ec2', 'AttachVolume'), Action('ec2', 'DescribeVolumes')], Resource=['*'])]) runner = CliRunner() result = runner.invoke(cli.root_group, args=['guess', '--only', 'Attach', '--only', 'describe'], input=input_policy.to_json()) assert (result.exit_code == 0) assert (parse_policy_document(result.output) == expected_output)
class OptionSeriesBarSonificationDefaultspeechoptionsMappingPlaydelay(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._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
class get_config_reply(message): version = 1 type = 8 def __init__(self, xid=None, flags=None, miss_send_len=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): self.flags = flags else: self.flags = 0 if (miss_send_len != None): self.miss_send_len = miss_send_len else: self.miss_send_len = 0 return def pack(self): packed = [] packed.append(struct.pack('!B', self.version)) packed.append(struct.pack('!B', self.type)) packed.append(struct.pack('!H', 0)) packed.append(struct.pack('!L', self.xid)) packed.append(struct.pack('!H', self.flags)) packed.append(struct.pack('!H', self.miss_send_len)) length = sum([len(x) for x in packed]) packed[2] = struct.pack('!H', length) return ''.join(packed) def unpack(reader): obj = get_config_reply() _version = reader.read('!B')[0] assert (_version == 1) _type = reader.read('!B')[0] assert (_type == 8) _length = reader.read('!H')[0] orig_reader = reader reader = orig_reader.slice(_length, 4) obj.xid = reader.read('!L')[0] obj.flags = reader.read('!H')[0] obj.miss_send_len = reader.read('!H')[0] return obj def __eq__(self, other): if (type(self) != type(other)): return False if (self.xid != other.xid): return False if (self.flags != other.flags): return False if (self.miss_send_len != other.miss_send_len): return False return True def pretty_print(self, q): q.text('get_config_reply {') with q.group(): with q.indent(2): q.breakable() q.text('xid = ') if (self.xid != None): q.text(('%#x' % self.xid)) else: q.text('None') q.text(',') q.breakable() q.text('flags = ') value_name_map = {0: 'OFPC_FRAG_NORMAL', 1: 'OFPC_FRAG_DROP', 2: 'OFPC_FRAG_REASM', 3: 'OFPC_FRAG_MASK'} q.text(util.pretty_flags(self.flags, value_name_map.values())) q.text(',') q.breakable() q.text('miss_send_len = ') q.text(('%#x' % self.miss_send_len)) q.breakable() q.text('}')
def get_chain_backend_class(backend_import_path=None): warnings.simplefilter('default') if (backend_import_path is None): if ('ETHEREUM_TESTER_CHAIN_BACKEND' in os.environ): backend_import_path = os.environ['ETHEREUM_TESTER_CHAIN_BACKEND'] elif is_supported_pyevm_version_available(): backend_import_path = get_import_path(PyEVMBackend) else: warnings.warn(UserWarning('Ethereum Tester: No backend was explicitly set, and no *full* backends were available. Falling back to the `MockBackend` which does not support all EVM functionality. Please refer to the `eth-tester` documentation for information on what backends are available and how to set them. Your py-evm package may need to be updated.'), stacklevel=2) backend_import_path = get_import_path(MockBackend) return import_string(backend_import_path)
class Solution(): def maximalSquare(self, matrix: List[List[str]]) -> int: dp = [([0] * len(matrix[0])) for _ in range(len(matrix))] ans = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if ((i == 0) or (j == 0)): dp[i][j] = int(matrix[i][j]) elif (matrix[i][j] == '1'): dp[i][j] = (min(dp[(i - 1)][j], dp[i][(j - 1)], dp[(i - 1)][(j - 1)]) + 1) ans = max(ans, dp[i][j]) return (ans * ans)
def eql_search(path, query_text, config=None): config = (config or {}) config.setdefault('flatten', True) engine = get_engine(query_text, config) event_stream = stream_file_events(path) rows = [result.data for result in engine(event_stream)] frame = DataFrame(rows) return frame.replace(numpy.nan, '', regex=True)
class OptionPlotoptionsSolidgaugeSonificationDefaultinstrumentoptionsMappingTremoloDepth(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._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
class MarkdownEmbedding(SourceEmbedding): def __init__(self, file_path, vector_store_config, source_reader: Optional=None, text_splitter: Optional[TextSplitter]=None): super().__init__(file_path, vector_store_config, source_reader=None, text_splitter=None) self.file_path = file_path self.vector_store_config = vector_store_config self.source_reader = (source_reader or None) self.text_splitter = (text_splitter or None) def read(self): if (self.source_reader is None): self.source_reader = EncodeTextLoader(self.file_path) if (self.text_splitter is None): try: self.text_splitter = SpacyTextSplitter(pipeline='zh_core_web_sm', chunk_size=100, chunk_overlap=100) except Exception: self.text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=50) return self.source_reader.load_and_split(self.text_splitter) def data_process(self, documents: List[Document]): i = 0 for d in documents: content = markdown.markdown(d.page_content) soup = BeautifulSoup(content, 'html.parser') for tag in soup(['!doctype', 'meta', 'i.fa']): tag.extract() documents[i].page_content = soup.get_text() documents[i].page_content = documents[i].page_content.replace('\n', ' ') i += 1 return documents
def apply_crd(): crd_spec = {'apiVersion': 'apiextensions.k8s.io/v1', 'kind': 'CustomResourceDefinition', 'metadata': {'name': f'{PLURAL}.{GROUP}'}, 'spec': {'group': GROUP, 'names': {'kind': 'MagicHappens', 'listKind': 'MagicHappensList', 'plural': PLURAL, 'singular': 'magichappens'}, 'scope': 'Namespaced', 'versions': [{'name': VERSION, 'schema': {'openAPIV3Schema': {'type': 'object', 'properties': {'spec': {'type': 'object', 'properties': {'description': {'type': 'string'}, 'expectedObjects': {'type': 'string'}, 'dryRun': {'type': 'boolean', 'default': True}}}, 'status': {'type': 'object', 'properties': {'createdObjects': {'type': 'array', 'items': {'type': 'object'}}, 'error': {'type': 'string'}, 'comments': {'type': 'array', 'items': {'type': 'string'}}, 'created': {'type': 'object'}, 'updated': {'type': 'object'}}}}}}, 'served': True, 'storage': True}]}} kubernetes.config.load_kube_config() api_instance = kubernetes.client.CustomObjectsApi() try: api_instance.create_cluster_custom_object(group='apiextensions.k8s.io', version='v1', plural='customresourcedefinitions', body=crd_spec) except: pass
def extractNovelhereWordpressCom(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: if (tagname in item['tags']): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
def test_check_inds(): assert (check_inds(1) == np.array([1])) assert array_equal(check_inds([0, 2]), np.array([0, 2])) assert array_equal(check_inds(range(0, 2)), np.array([0, 1])) assert array_equal(check_inds(np.array([1, 2, 3])), np.array([1, 2, 3])) assert array_equal(check_inds(np.array([True, False, True])), np.array([0, 2]))
('frontend.management.commands.generate_presentation_replacements.cleanup_empty_classes') ('frontend.management.commands.generate_presentation_replacements.create_bigquery_table') class CommandsTestCase(TestCase): def setUp(self): Section.objects.create(bnf_id='0000', name='Subsection 0.0', bnf_chapter=0, bnf_section=0, bnf_para=0) Section.objects.create(bnf_id='9999', name='Subsection 9.9', bnf_chapter=0, bnf_section=0, bnf_para=0) Section.objects.create(bnf_id='777777', name='Para 7.7.7', bnf_chapter=0, bnf_section=0, bnf_para=0) Section.objects.create(bnf_id='222222', name='Para 2.2.2', bnf_chapter=0, bnf_section=0, bnf_para=0) Chemical.objects.create(bnf_code='ZZZZZZZZZ', chem_name='Chemical Z') Chemical.objects.create(bnf_code='YYYYYYYYY', chem_name='Chemical Y') Chemical.objects.create(bnf_code='', chem_name='Chemical 1') Product.objects.create(bnf_code='', name='Product 3') Product.objects.create(bnf_code='', name='Product 4') Presentation.objects.create(bnf_code='MMMMMMMMMMMMMMM', name='Drug M') Presentation.objects.create(bnf_code='', name='Drug 9') Presentation.objects.create(bnf_code='ZZZZZZZZZZZZZZZ', name='Drug Z') fixtures_dir = 'frontend/tests/fixtures/commands/' self.args = [(fixtures_dir + 'presentation_replacements_2017.txt'), (fixtures_dir + 'presentation_replacements_2016.txt')] self.opts = {} def test_replacements(self, mock_cleanup_empty_classes, mock_create_bigquery_table): call_command('generate_presentation_replacements', *self.args, **self.opts) p = Presentation.objects.get(bnf_code='YYYYYYYYYYYYYYY') self.assertEqual(p.replaced_by.bnf_code, 'ZZZZZZZZZZZZZZZ') self.assertEqual(p.current_version.bnf_code, 'ZZZZZZZZZZZZZZZ') p = Presentation.objects.get(bnf_code='') self.assertEqual(p.current_version.bnf_code, '') p = Presentation.objects.get(bnf_code='MMMMMMMMMMMMMMM') self.assertEqual(p.current_version.bnf_code, 'MMMMMMMMMMMMMMM') def test_chemical_currency(self, mock_cleanup_empty_classes, mock_create_bigquery_table): call_command('generate_presentation_replacements', *self.args, **self.opts) self.assertEqual(Chemical.objects.get(pk='YYYYYYYYY').is_current, False) self.assertEqual(Chemical.objects.get(pk='ZZZZZZZZZ').is_current, True) self.assertEqual(Chemical.objects.get(pk='').is_current, True) self.assertEqual(Section.objects.get(pk='0000').is_current, False) self.assertEqual(Section.objects.get(pk='9999').is_current, True) self.assertEqual(Section.objects.get(pk='777777').is_current, False) self.assertEqual(Section.objects.get(pk='222222').is_current, True) self.assertEqual(Product.objects.get(pk='').is_current, False) self.assertEqual(Product.objects.get(pk='').is_current, True)
def identify_plant(file_names): params = {'images': [encode_file(img) for img in file_names], 'latitude': 49.1951239, 'longitude': 16.6077111, 'datetime': , 'modifiers': ['crops_fast', 'similar_images']} headers = {'Content-Type': 'application/json', 'Api-Key': API_KEY} response = requests.post(' json=params, headers=headers).json() return get_result(response['id'])
class ReduceStreamOperator(BaseOperator, Generic[(IN, OUT)]): def __init__(self, reduce_function=None, **kwargs): super().__init__(**kwargs) if (reduce_function and (not callable(reduce_function))): raise ValueError('reduce_function must be callable') self.reduce_function = reduce_function async def _do_run(self, dag_ctx: DAGContext) -> TaskOutput[OUT]: curr_task_ctx: TaskContext[OUT] = dag_ctx.current_task_context task_input = curr_task_ctx.task_input if (not task_input.check_stream()): raise ValueError('ReduceStreamOperator expects stream data') if (not task_input.check_single_parent()): raise ValueError('ReduceStreamOperator expects single parent') reduce_function = (self.reduce_function or self.reduce) input_ctx: InputContext = (await task_input.reduce(reduce_function)) reduce_output = input_ctx.parent_outputs[0].task_output curr_task_ctx.set_task_output(reduce_output) return reduce_output async def reduce(self, input_value: AsyncIterator[IN]) -> OUT: raise NotImplementedError
def test_mine_multiple_timedelta(devnetwork, chain): chain.mine(5, timedelta=123) timestamps = [i.timestamp for i in list(chain)[(- 5):]] assert ((chain.time() - timestamps[(- 1)]) < 3) for i in range(1, 5): assert (timestamps[i] > timestamps[(i - 1)]) assert ((timestamps[0] + 123) == timestamps[(- 1)])
def main(page: Page): N = 45 (x, y) = np.random.rand(2, N) c = np.random.randint(1, 5, size=N) s = np.random.randint(10, 220, size=N) (fig, ax) = plt.subplots() scatter = ax.scatter(x, y, c=c, s=s) legend1 = ax.legend(*scatter.legend_elements(), loc='lower left', title='Classes') ax.add_artist(legend1) (handles, labels) = scatter.legend_elements(prop='sizes', alpha=0.6) legend2 = ax.legend(handles, labels, loc='upper right', title='Sizes') page.add(MatplotlibChart(fig, expand=True))
def extractMusubinovelBlogspotCom(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: if (tagname in item['tags']): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
def get_os_name(metadata=None): if metadata: platform = metadata['platform'].lower() if ('linux' in platform): return 'linux' elif (('darwin' in platform) or ('macos' in platform) or ('osx' in platform)): return 'mac' elif ('win' in platform): return 'windows' else: raise NotImplementedError(platform) elif (sys.platform == 'win32'): return 'windows' elif (sys.paltform == 'linux'): return 'linux' elif (sys.platform == 'darwin'): return 'mac' else: raise NotImplementedError(sys.platform)
class SignInViaUsernameForm(SignIn): username = forms.CharField(label=_('Username')) def field_order(self): if settings.USE_REMEMBER_ME: return ['username', 'password', 'remember_me'] return ['username', 'password'] def clean_username(self): username = self.cleaned_data['username'] user = User.objects.filter(username=username).first() if (not user): raise ValidationError(_('You entered an invalid username.')) if (not user.is_active): raise ValidationError(_('This account is not active.')) self.user_cache = user return username
class Descritor(): def __init__(self, obj): self.obj = obj def __set__(self, obj, val): print('Estou setando algo') self.obj = val def __get__(self, obj, tipo=None): print('Estou pegango algo') return self.obj def __delete__(self, obj): print('Estou deletando algo') del self.obj def __repr__(self): return self.obj
class NoiselessDetector(Detector): def __init__(self, detector_grid, subsamping=1): Detector.__init__(self, detector_grid, subsamping) self.accumulated_charge = 0 def integrate(self, wavefront, dt, weight=1): if hasattr(wavefront, 'power'): power = wavefront.power else: power = wavefront self.accumulated_charge += ((power * dt) * weight) def read_out(self): output_field = self.accumulated_charge.copy() self.accumulated_charge = 0 return output_field
.parametrize('defines, expected', [pytest.param('\nNUM_REALIZATIONS 1\nDEFINE <A> <B><C>\nDEFINE <B> my\nDEFINE <C> name\nJOBNAME <A>%d', 'myname0', id='Testing of use before declaration works for defines'), pytest.param('\nNUM_REALIZATIONS 1\nDATA_KW <A> <B><C>\nDATA_KW <B> my\nDATA_KW <C> name\nJOBNAME <A>%d', 'myname0', id='Testing of use before declaration works for data_kw'), pytest.param('\nNUM_REALIZATIONS 1\nDEFINE <B> my\nDEFINE <C> name\nDEFINE <A> <B><C>\nJOBNAME <A>%d', 'myname0', id='Testing of declaration before use works for defines'), pytest.param('\nNUM_REALIZATIONS 1\nDATA_KW <B> my\nDATA_KW <C> name\nDATA_KW <A> <B><C>\nJOBNAME <A>%d', 'myname0', id='Testing of declaration before use works for data_kw')]) def test_that_user_defined_substitution_works_as_expected(defines, expected, tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) config_file = (tmp_path / 'config_file.ert') config_file.write_text(defines) assert (read_jobname(str(config_file)) == expected)
class InputMediaDocument(InputMedia): def __init__(self, media, thumbnail=None, caption=None, parse_mode=None, caption_entities=None, disable_content_type_detection=None): super(InputMediaDocument, self).__init__(type='document', media=media, caption=caption, parse_mode=parse_mode, caption_entities=caption_entities) self.thumbnail = thumbnail self.disable_content_type_detection = disable_content_type_detection def thumb(self): logger.warning('The parameter "thumb" is deprecated, use "thumbnail" instead') return self.thumbnail def to_dict(self): ret = super(InputMediaDocument, self).to_dict() if self.thumbnail: ret['thumbnail'] = self.thumbnail if (self.disable_content_type_detection is not None): ret['disable_content_type_detection'] = self.disable_content_type_detection return ret
.external .parametrize('config_name', ('fewshot.cfg', 'zeroshot.cfg')) def test_textcat_openai(config_name: str): path = (_USAGE_EXAMPLE_PATH / 'textcat_openai') textcat_openai.run_pipeline(text='text', config_path=(path / config_name), examples_path=(None if (config_name == 'zeroshot.cfg') else (path / 'examples.jsonl')), verbose=False)
class BulkCommandResponder(cmdrsp.BulkCommandResponder): def handleMgmtOperation(self, snmp_engine, state_reference, context_name, pdu, ac_info): try: cmdrsp.BulkCommandResponder.handleMgmtOperation(self, snmp_engine, state_reference, probe_hash_context(self, snmp_engine), pdu, (None, snmp_engine)) except NoDataNotification: self.releaseStateInformation(state_reference)
class TakeWhile(Op): __slots__ = ('_predicate',) def __init__(self, predicate=bool, source=None): Op.__init__(self, source) self._predicate = predicate def on_source(self, *args): if self._predicate(*args): self.emit(*args) else: self.set_done() self._disconnect_from(self._source)
class Cards(): def __init__(self, cards: List[Card], lowest_rank=2): self._sorted = sorted(cards, key=int, reverse=True) self._lowest_rank: int = lowest_rank def _group_by_ranks(self) -> Dict[(int, List[Card])]: ranks = collections.defaultdict(list) for card in self._sorted: ranks[card.rank].append(card) return ranks def _x_sorted_list(self, x) -> List[List[Card]]: return sorted((cards for cards in self._group_by_ranks().values() if (len(cards) == x)), key=(lambda cards: cards[0].rank), reverse=True) def _get_straight(self, sorted_cards): if (len(sorted_cards) < 5): return None straight = [sorted_cards[0]] for i in range(1, len(sorted_cards)): if (sorted_cards[i].rank == (sorted_cards[(i - 1)].rank - 1)): straight.append(sorted_cards[i]) if (len(straight) == 5): return straight elif (sorted_cards[i].rank != sorted_cards[(i - 1)].rank): straight = [sorted_cards[i]] if ((len(straight) == 4) and (sorted_cards[0].rank == 14) and (straight[(- 1)].rank == self._lowest_rank)): straight.append(sorted_cards[0]) return straight return None def _merge_with_cards(self, score_cards: List[Card]): return (score_cards + [card for card in self._sorted if (card not in score_cards)]) def quads(self): quads_list = self._x_sorted_list(4) try: return self._merge_with_cards(quads_list[0])[0:5] except IndexError: return None def full_house(self) -> Optional[List[Card]]: trips_list = self._x_sorted_list(3) pair_list = self._x_sorted_list(2) try: return self._merge_with_cards((trips_list[0] + pair_list[0]))[0:5] except IndexError: return None def trips(self) -> Optional[List[Card]]: trips_list = self._x_sorted_list(3) try: return self._merge_with_cards(trips_list[0])[0:5] except IndexError: return None def two_pair(self) -> Optional[List[Card]]: pair_list = self._x_sorted_list(2) try: return self._merge_with_cards((pair_list[0] + pair_list[1]))[0:5] except IndexError: return None def pair(self) -> Optional[List[Card]]: pair_list = self._x_sorted_list(2) try: return self._merge_with_cards(pair_list[0])[0:5] except IndexError: return None def straight(self) -> Optional[List[Card]]: return self._get_straight(self._sorted) def flush(self) -> Optional[List[Card]]: suits = collections.defaultdict(list) for card in self._sorted: suits[card.suit].append(card) if (len(suits[card.suit]) == 5): return suits[card.suit] return None def straight_flush(self) -> Optional[List[Card]]: suits = collections.defaultdict(list) for card in self._sorted: suits[card.suit].append(card) if (len(suits[card.suit]) >= 5): straight = self._get_straight(suits[card.suit]) if straight: return straight return None def no_pair(self) -> List[Card]: return self._sorted[0:5]
def get_example_tree(): t = Tree() t.populate(10) rs1 = faces.TextFace('branch-right\nmargins&borders', fsize=12, fgcolor='#009000') rs1.margin_top = 10 rs1.margin_bottom = 50 rs1.margin_left = 40 rs1.margin_right = 40 rs1.border.width = 1 rs1.background.color = 'lightgreen' rs1.inner_border.width = 0 rs1.inner_border.line_style = 1 rs1.inner_border.color = 'red' rs1.opacity = 0.6 rs1.hz_align = 2 rs1.vt_align = 1 br1 = faces.TextFace('branch-right1', fsize=12, fgcolor='#009000') br2 = faces.TextFace('branch-right3', fsize=12, fgcolor='#009000') bb = faces.TextFace('branch-bottom 1', fsize=8, fgcolor='#909000') bb2 = faces.TextFace('branch-bottom 2', fsize=8, fgcolor='#909000') bt = faces.TextFace('branch-top 1', fsize=6, fgcolor='#099000') t1 = faces.TextFace('Header Face', fsize=12, fgcolor='#aa0000') t2 = faces.TextFace('Footer Face', fsize=12, fgcolor='#0000aa') aligned = faces.AttrFace('name', fsize=12, fgcolor='RoyalBlue', text_prefix='Aligned (', text_suffix=')') aligned.hz_align = 1 aligned.vt_align = 1 style = NodeStyle() style['fgcolor'] = 'Gold' style['shape'] = 'square' style['size'] = 15 style['vt_line_color'] = '#ff0000' t.set_style(style) fixed = faces.TextFace('FIXED branch-right', fsize=11, fgcolor='blue') t.add_face(fixed, column=1, position='branch-right') ts = TreeStyle() ts.aligned_header.add_face(t1, column=0) ts.aligned_header.add_face(t1, 1) ts.aligned_header.add_face(t1, 2) ts.aligned_header.add_face(t1, 3) t1.hz_align = 1 t1.border.width = 1 ts.aligned_foot.add_face(t2, column=0) ts.aligned_foot.add_face(t2, 1) ts.aligned_foot.add_face(t2, 2) ts.aligned_foot.add_face(t2, 3) t2.hz_align = 1 ts.mode = 'r' ts.scale = 10 for node in t.traverse(): if node.is_leaf: node.add_face(aligned, column=0, position='aligned') node.add_face(aligned, column=1, position='aligned') node.add_face(aligned, column=3, position='aligned') else: node.add_face(bt, column=0, position='branch-top') node.add_face(bb, column=0, position='branch-bottom') node.add_face(bb2, column=0, position='branch-bottom') node.add_face(br1, column=0, position='branch-right') node.add_face(rs1, column=0, position='branch-right') node.add_face(br2, column=0, position='branch-right') return (t, ts)
def test_new_variable_names_correct_assignment(): tr = DatetimeSubtraction(variables='var1', reference='var2') assert (tr.new_variables_names is None) tr = DatetimeSubtraction(variables='var1', reference='var2', new_variables_names=['var1']) assert (tr.new_variables_names == ['var1']) tr = DatetimeSubtraction(variables='var1', reference='var2', new_variables_names=['var1', 'var2']) assert (tr.new_variables_names == ['var1', 'var2'])
def test_record_names_must_match(): ' writer_schema = {'type': 'record', 'name': 'test', 'fields': [{'name': 'test1', 'type': {'type': 'record', 'name': 'my_record', 'fields': [{'name': 'field1', 'type': 'string'}]}}, {'name': 'test2', 'type': 'my_record'}]} reader_schema = {'type': 'record', 'name': 'test', 'fields': [{'name': 'test2', 'type': {'type': 'record', 'name': 'different_name', 'fields': [{'name': 'field1', 'type': 'string'}]}}]} records = [{'test1': {'field1': 'foo'}, 'test2': {'field1': 'bar'}}] with pytest.raises(SchemaResolutionError): roundtrip(writer_schema, records, reader_schema=reader_schema)
def extractFinebymetranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Death Progress Bar', 'Death Progress Bar', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in tagmap: if (tagname in item['tags']): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
def validate_eth1_withdrawal_address(cts: click.Context, param: Any, address: str) -> HexAddress: if (address is None): return None if (not is_hex_address(address)): raise ValidationError(load_text(['err_invalid_ECDSA_hex_addr'])) if (not is_checksum_address(address)): raise ValidationError(load_text(['err_invalid_ECDSA_hex_addr_checksum'])) normalized_address = to_normalized_address(address) click.echo(('\n%s\n' % load_text(['msg_ECDSA_hex_addr_withdrawal']))) return normalized_address
class PhoneHolder(Boxes): ui_group = 'Misc' description = '\n This phone stand holds your phone between two tabs, with access to its\n bottom, in order to connect a charger, headphones, and also not to obstruct\n the mic.\n\n Default values are currently based on Galaxy S7.\n' def __init__(self) -> None: Boxes.__init__(self) self.argparser.add_argument('--phone_height', type=float, default=142, help='Height of the phone.') self.argparser.add_argument('--phone_width', type=float, default=73, help='Width of the phone.') self.argparser.add_argument('--phone_depth', type=float, default=11, help='Depth of the phone. Used by the bottom support holding the phone, and the side tabs depth as well. Should be at least your material thickness for assembly reasons.') self.argparser.add_argument('--angle', type=float, default=25, help='angle at which the phone stands, in degrees. 0\xa0is vertical.') self.argparser.add_argument('--bottom_margin', type=float, default=30, help='Height of the support below the phone') self.argparser.add_argument('--tab_size', type=float, default=76, help='Length of the tabs holding the phone') self.argparser.add_argument('--bottom_support_spacing', type=float, default=16, help='Spacing between the two bottom support. Choose a value big enough for the charging cable, without getting in the way of other ports.') self.addSettingsArgs(edges.FingerJointSettings) def render(self): self.h = (self.phone_height + self.bottom_margin) tab_start = self.bottom_margin tab_length = self.tab_size tab_depth = self.phone_depth support_depth = self.phone_depth support_spacing = self.bottom_support_spacing rad = math.radians(self.angle) self.stand_depth = (self.h * math.sin(rad)) self.stand_height = (self.h * math.cos(rad)) self.render_front_plate(tab_start, tab_length, support_spacing, move='right') self.render_back_plate(move='right') self.render_side_plate(tab_start, tab_length, tab_depth, move='right') for move in ['right mirror', 'right']: self.render_bottom_support(tab_start, support_depth, tab_length, move=move) def render_front_plate(self, tab_start, tab_length, support_spacing, support_fingers_length=None, move='right'): if (not support_fingers_length): support_fingers_length = tab_length be = BottomEdge(self, tab_start, support_spacing) se1 = SideEdge(self, tab_start, tab_length) se2 = SideEdge(self, tab_start, tab_length, reverse=True) self.rectangularWall(self.phone_width, self.h, [be, se1, 'e', se2], move=move, callback=[partial((lambda : self.front_plate_holes(tab_start, support_fingers_length, support_spacing)))]) def render_back_plate(self, move='right'): be = BottomEdge(self, 0, 0) self.rectangularWall(self.phone_width, self.stand_height, [be, 'F', 'e', 'F'], move=move) def front_plate_holes(self, support_start_height, support_fingers_length, support_spacing): margin = (((self.phone_width - support_spacing) - self.thickness) / 2) self.fingerHolesAt(margin, support_start_height, support_fingers_length) self.fingerHolesAt((self.phone_width - margin), support_start_height, support_fingers_length) def render_side_plate(self, tab_start, tab_length, tab_depth, move): te = TabbedEdge(self, tab_start, tab_length, tab_depth, reverse=True) self.rectangularTriangle(self.stand_depth, self.stand_height, ['e', 'f', te], move=move, num=2) def render_bottom_support(self, support_start_height, support_depth, support_fingers_length, move='right'): full_height = (support_start_height + support_fingers_length) rad = math.radians(self.angle) floor_length = (full_height * math.sin(rad)) angled_height = (full_height * math.cos(rad)) bottom_radius = min(support_start_height, ((3 * self.thickness) + support_depth)) smaller_radius = 0.5 support_hook_height = 5 full_width = (floor_length + ((support_depth + (3 * self.thickness)) * math.cos(rad))) if self.move(full_width, angled_height, move, True): return self.polyline(floor_length, self.angle, (((3 * self.thickness) + support_depth) - bottom_radius), (90, bottom_radius), ((support_hook_height + support_start_height) - bottom_radius), (180, self.thickness), (support_hook_height - smaller_radius), ((- 90), smaller_radius), ((self.thickness + support_depth) - smaller_radius), (- 90)) self.edges['f'](support_fingers_length) self.polyline(0, (180 - self.angle), angled_height, 90) self.move(full_width, angled_height, move)
def exp(computation: ComputationAPI, gas_per_byte: int) -> None: (base, exponent) = computation.stack_pop_ints(2) bit_size = exponent.bit_length() byte_size = (ceil8(bit_size) // 8) if (exponent == 0): result = 1 elif (base == 0): result = 0 else: result = pow(base, exponent, constants.UINT_256_CEILING) computation.consume_gas((gas_per_byte * byte_size), reason='EXP: exponent bytes') computation.stack_push_int(result)
class HTMLParser(markupbase.ParserBase): CDATA_CONTENT_ELEMENTS = ('script', 'style') def __init__(self): self.reset() def reset(self): self.rawdata = '' self.lasttag = '???' self.interesting = interesting_normal self.cdata_elem = None markupbase.ParserBase.reset(self) def feed(self, data): self.rawdata = (self.rawdata + data) self.goahead(0) def close(self): self.goahead(1) def error(self, message): raise HTMLParseError(message, self.getpos()) __starttag_text = None def get_starttag_text(self): return self.__starttag_text def set_cdata_mode(self, elem): self.cdata_elem = elem.lower() self.interesting = re.compile(('</\\s*%s\\s*>' % self.cdata_elem), re.I) def clear_cdata_mode(self): self.interesting = interesting_normal self.cdata_elem = None def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while (i < n): match = self.interesting.search(rawdata, i) if match: j = match.start() else: if self.cdata_elem: break j = n if (i < j): self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if (i == n): break startswith = rawdata.startswith if startswith('<', i): if starttagopen.match(rawdata, i): k = self.parse_starttag(i) elif startswith('</', i): k = self.parse_endtag(i) elif startswith('<!--', i): k = self.parse_comment(i) elif startswith('<?', i): k = self.parse_pi(i) elif startswith('<!', i): k = self.parse_html_declaration(i) elif ((i + 1) < n): self.handle_data('<') k = (i + 1) else: break if (k < 0): if (not end): break k = rawdata.find('>', (i + 1)) if (k < 0): k = rawdata.find('<', (i + 1)) if (k < 0): k = (i + 1) else: k += 1 self.handle_data(rawdata[i:k]) i = self.updatepos(i, k) elif startswith('&#', i): match = charref.match(rawdata, i) if match: name = match.group()[2:(- 1)] self.handle_charref(name) k = match.end() if (not startswith(';', (k - 1))): k = (k - 1) i = self.updatepos(i, k) continue else: if (';' in rawdata[i:]): self.handle_data(rawdata[i:(i + 2)]) i = self.updatepos(i, (i + 2)) break elif startswith('&', i): match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if (not startswith(';', (k - 1))): k = (k - 1) i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: if (end and (match.group() == rawdata[i:])): self.error('EOF in middle of entity or char ref') break elif ((i + 1) < n): self.handle_data('&') i = self.updatepos(i, (i + 1)) else: break else: assert 0, 'interesting.search() lied' if (end and (i < n) and (not self.cdata_elem)): self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:] def parse_html_declaration(self, i): rawdata = self.rawdata if (rawdata[i:(i + 2)] != '<!'): self.error('unexpected call to parse_html_declaration()') if (rawdata[i:(i + 4)] == '<!--'): return self.parse_comment(i) elif (rawdata[i:(i + 3)] == '<!['): return self.parse_marked_section(i) elif (rawdata[i:(i + 9)].lower() == '<!doctype'): gtpos = rawdata.find('>', (i + 9)) if (gtpos == (- 1)): return (- 1) self.handle_decl(rawdata[(i + 2):gtpos]) return (gtpos + 1) else: return self.parse_bogus_comment(i) def parse_bogus_comment(self, i, report=1): rawdata = self.rawdata if (rawdata[i:(i + 2)] not in ('<!', '</')): self.error('unexpected call to parse_comment()') pos = rawdata.find('>', (i + 2)) if (pos == (- 1)): return (- 1) if report: self.handle_comment(rawdata[(i + 2):pos]) return (pos + 1) def parse_pi(self, i): rawdata = self.rawdata assert (rawdata[i:(i + 2)] == '<?'), 'unexpected call to parse_pi()' match = piclose.search(rawdata, (i + 2)) if (not match): return (- 1) j = match.start() self.handle_pi(rawdata[(i + 2):j]) j = match.end() return j def parse_starttag(self, i): self.__starttag_text = None endpos = self.check_for_whole_start_tag(i) if (endpos < 0): return endpos rawdata = self.rawdata self.__starttag_text = rawdata[i:endpos] attrs = [] match = tagfind.match(rawdata, (i + 1)) assert match, 'unexpected call to parse_starttag()' k = match.end() self.lasttag = tag = match.group(1).lower() while (k < endpos): m = attrfind.match(rawdata, k) if (not m): break (attrname, rest, attrvalue) = m.group(1, 2, 3) if (not rest): attrvalue = None elif ((attrvalue[:1] == "'" == attrvalue[(- 1):]) or (attrvalue[:1] == '"' == attrvalue[(- 1):])): attrvalue = attrvalue[1:(- 1)] if attrvalue: attrvalue = self.unescape(attrvalue) attrs.append((attrname.lower(), attrvalue)) k = m.end() end = rawdata[k:endpos].strip() if (end not in ('>', '/>')): (lineno, offset) = self.getpos() if ('\n' in self.__starttag_text): lineno = (lineno + self.__starttag_text.count('\n')) offset = (len(self.__starttag_text) - self.__starttag_text.rfind('\n')) else: offset = (offset + len(self.__starttag_text)) self.handle_data(rawdata[i:endpos]) return endpos if end.endswith('/>'): self.handle_startendtag(tag, attrs) else: self.handle_starttag(tag, attrs) if (tag in self.CDATA_CONTENT_ELEMENTS): self.set_cdata_mode(tag) return endpos def check_for_whole_start_tag(self, i): rawdata = self.rawdata m = locatestarttagend.match(rawdata, i) if m: j = m.end() next = rawdata[j:(j + 1)] if (next == '>'): return (j + 1) if (next == '/'): if rawdata.startswith('/>', j): return (j + 2) if rawdata.startswith('/', j): return (- 1) self.updatepos(i, (j + 1)) self.error('malformed empty start tag') if (next == ''): return (- 1) if (next in 'abcdefghijklmnopqrstuvwxyz=/ABCDEFGHIJKLMNOPQRSTUVWXYZ'): return (- 1) if (j > i): return j else: return (i + 1) raise AssertionError('we should not get here!') def parse_endtag(self, i): rawdata = self.rawdata assert (rawdata[i:(i + 2)] == '</'), 'unexpected call to parse_endtag' match = endendtag.search(rawdata, (i + 1)) if (not match): return (- 1) gtpos = match.end() match = endtagfind.match(rawdata, i) if (not match): if (self.cdata_elem is not None): self.handle_data(rawdata[i:gtpos]) return gtpos namematch = tagfind.match(rawdata, (i + 2)) if (not namematch): if (rawdata[i:(i + 3)] == '</>'): return (i + 3) else: return self.parse_bogus_comment(i) tagname = namematch.group(1).lower() gtpos = rawdata.find('>', namematch.end()) self.handle_endtag(tagname) return (gtpos + 1) elem = match.group(1).lower() if (self.cdata_elem is not None): if (elem != self.cdata_elem): self.handle_data(rawdata[i:gtpos]) return gtpos self.handle_endtag(elem) self.clear_cdata_mode() return gtpos def handle_startendtag(self, tag, attrs): self.handle_starttag(tag, attrs) self.handle_endtag(tag) def handle_starttag(self, tag, attrs): pass def handle_endtag(self, tag): pass def handle_charref(self, name): pass def handle_entityref(self, name): pass def handle_data(self, data): pass def handle_comment(self, data): pass def handle_decl(self, decl): pass def handle_pi(self, data): pass def unknown_decl(self, data): pass entitydefs = None def unescape(self, s): if ('&' not in s): return s def replaceEntities(s): s = s.groups()[0] try: if (s[0] == '#'): s = s[1:] if (s[0] in ['x', 'X']): c = int(s[1:], 16) else: c = int(s) return unichr(c) except ValueError: return (('&#' + s) + ';') else: import htmlentitydefs if (HTMLParser.entitydefs is None): entitydefs = HTMLParser.entitydefs = {'apos': u"'"} for (k, v) in htmlentitydefs.name2codepoint.iteritems(): entitydefs[k] = unichr(v) try: return self.entitydefs[s] except KeyError: return (('&' + s) + ';') return re.sub('&(#?[xX]?(?:[0-9a-fA-F]+|\\w{1,8}));', replaceEntities, s)
def _plotDistribution(axes: 'Axes', plot_config: 'PlotConfig', data: pd.DataFrame, label: str, index, previous_data): data = (pd.Series(dtype='float64') if data.empty else data[0]) axes.set_xlabel(plot_config.xLabel()) axes.set_ylabel(plot_config.yLabel()) style = plot_config.distributionStyle() if (data.dtype == 'object'): try: data = pd.to_numeric(data, errors='coerce') except AttributeError: data = data.convert_objects(convert_numeric=True) if (data.dtype == 'object'): dots = [] else: dots = axes.plot(([index] * len(data)), data, color=style.color, alpha=style.alpha, marker=style.marker, linestyle=style.line_style, markersize=style.size) if (plot_config.isDistributionLineEnabled() and (previous_data is not None)): line_style = plot_config.distributionLineStyle() x = [(index - 1), index] y = [previous_data[0], data] axes.plot(x, y, color=line_style.color, alpha=line_style.alpha, linestyle=line_style.line_style, linewidth=line_style.width) if (len(dots) > 0): plot_config.addLegendItem(label, dots[0])
class MapError(RuntimeError): def __init__(self, error='', node_or_link=None): prefix = '' if node_or_link: prefix = f"{node_or_link.__class__.__name__} '{node_or_link.symbol}' at XYZ=({node_or_link.X:g},{node_or_link.Y:g},{node_or_link.Z}) " self.node_or_link = node_or_link self.message = f'{prefix}{error}' super().__init__(self.message)
class OptionPlotoptionsFunnel3dSonificationDefaultspeechoptionsMappingTime(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._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
class OptionSeriesWordcloudSonificationDefaultspeechoptionsMappingTime(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._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)