code
stringlengths
281
23.7M
('/api/custom_graph/<graph_id>/<start_date>/<end_date>') def custom_graph(graph_id, start_date, end_date): post_to_back_if_telemetry_enabled(**{'name': f'custom_graph{graph_id}'}) start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d') end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d') ...
class SwitchTable(GivElm): total = 0 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.offset = kwargs['offset'] self.locs = kwargs['locs'] self.access = kwargs['access'] def __repr__(self): return '(SwitchTable {})'.format(format(self.offset...
class RoleRuleBook(bre.BaseRuleBook): def __init__(self, rule_defs=None): super(RoleRuleBook, self).__init__() self._rules_sema = threading.BoundedSemaphore(value=1) self.rules_map = {} if (not rule_defs): self.rule_defs = {} else: self.rule_defs = rul...
def extend(reference: str, module_path, version: str, cdnjs_url: str=CDNJS_REPO, required: Optional[list]=None): for (module, path) in module_path: config = (JS_IMPORTS if module.endswith('.js') else CSS_IMPORTS) if (reference not in config): config[reference] = {'modules': []} ...
class VoteApi(Api): _id(Article, Post, Comment) def votes(self, help_centre_object): url = self._build_url(self.endpoint.votes(id=help_centre_object, cursor_pagination=True)) return self._get(url) _id(Article, Post, Comment) def vote_up(self, help_centre_object): url = self._buil...
class TestTicketsPagination(PaginationTestCase): __test__ = True ZenpyType = Ticket api_name = 'tickets' expected_single_result_type = TicketAudit object_kwargs = dict(subject='test', description='test') pagination_limit = 10 def create_objects(self): job_status = self.create_multipl...
class TestESP8266V12SectionHeaderNotAtEnd(BaseTestCase): ELF = 'esp8266-nonossdkv12-example.elf' BIN_LOAD = (ELF + '-0x00000.bin') BIN_IROM = (ELF + '-0x40000.bin') def teardown_class(self): try_delete(self.BIN_LOAD) try_delete(self.BIN_IROM) def test_elf_section_header_not_at_end(se...
def test_collect_child_tags_no_tags(backend_db, common_db): (fo, fw) = create_fw_with_child_fo() fo.processed_analysis['software_components'] = generate_analysis_entry(tags={}) backend_db.insert_multiple_objects(fw, fo) assert (common_db._collect_analysis_tags_from_children(fw.uid) == {})
.parametrize('input_vars', [['Name', 'City', 'Age', 'Marks', 'dob'], ['Name', 'City', 'Age', 'Marks'], 'Name', ['Age']]) def test_check_all_variables_returns_all_variables(df_vartypes, input_vars): if isinstance(input_vars, list): assert (check_all_variables(df_vartypes, input_vars) == input_vars) else:...
.parametrize('degree', range(1, 4)) def test_convergence(degree): res = [(2 ** i) for i in range(4, 7)] error = [solve_helmholtz(degree, r)[1] for r in res] convergence_rate = np.array([(np.log((error[i] / error[(i + 1)])) / np.log((res[(i + 1)] / res[i]))) for i in range((len(res) - 1))]) print(('Achie...
def test_doubles_set_to_zero_on_windows(): ' schema = {'doc': 'A weather reading.', 'name': 'Weather', 'namespace': 'test', 'type': 'record', 'fields': [{'name': 'station', 'type': 'string'}, {'name': 'time', 'type': 'long'}, {'name': 'temp', 'type': 'int'}, {'name': 'test_float', 'type': 'double'}]} record...
def order_histogram(items, path=''): sorted_list = [] indent = (PathHash.get_indent(path) + 1) order = sorted([(key, value) for (key, value) in items if ((key[0][:len(path)] == path) and (PathHash.get_indent(key[0]) == indent))], key=(lambda row: row[0][1])) for (key, value) in order: sorted_lis...
class DbtGenericTest(DbtTest): column: Optional[str] = field(init=False) def __repr__(self): attrs = ['name', '_status', 'model_ids', 'source_ids', 'column'] props = ', '.join([f'{item}={repr(getattr(self, item))}' for item in attrs]) return f'DbtGenericTest({props})' def __post_init...
def casb_profile(data, fos): vdom = data['vdom'] state = data['state'] casb_profile_data = data['casb_profile'] casb_profile_data = flatten_multilists_attributes(casb_profile_data) filtered_data = underscore_to_hyphen(filter_casb_profile_data(casb_profile_data)) if ((state == 'present') or (stat...
def deployments(testproject): path = testproject._path.joinpath('build/deployments/ropsten') path.mkdir(exist_ok=True) with path.joinpath('0xBcd0a9167015Ee213Ba01dAff79d60CD221B0cAC.json').open('w') as fp: json.dump(testproject.BrownieTester._build, fp) path = testproject._path.joinpath('build/d...
class Solution(): def longestCommonSubsequence(self, text1: str, text2: str) -> int: if ((not text1) or (not text2)): return 0 dp = [([0] * len(text2)) for _ in text1] for (i, c1) in enumerate(text1): for (j, c2) in enumerate(text2): if (c1 == c2): ...
class worker(): def __init__(self, command): self.command = command self.wd = os.path.abspath('.') def output(self): return subprocess.getoutput(' '.join(self.command)) def pipe(self): return subprocess.Popen(self.command, stdout=subprocess.PIPE, universal_newlines=True, cwd=...
def bc_chromosome_draw_label(self, cur_drawing, label_name): x_position = (0.5 * (self.start_x_position + self.end_x_position)) y_position = (self.start_y_position + (0.1 * inch)) label_string = BC.String(x_position, y_position, label_name) label_string.fontName = 'Times-BoldItalic' label_string.fon...
def pair_thread_with_doubles(metafunc, tp): d = metafunc.config.option.double ds = (lambda dv: ('dp' if dv else 'sp')) vals = [] ids = [] if (d == 'supported'): for dv in [False, True]: if ((not dv) or tp.device_params.supports_dtype(numpy.float64)): vals.append((...
def test_find_TADs_fdr(): matrix = (ROOT + 'small_test_matrix.h5') tad_folder = mkdtemp(prefix='test_case_find_tads_fdr') args = '--matrix {} --minDepth 60000 --maxDepth 180000 --numberOfProcessors 2 --step 20000 --outPrefix {}/test_multiFDR --minBoundaryDistance 20000 --correctForMultipleTesting fd...
('response_bar_chart', 'Histogram, suitable for comparative analysis of multiple target values', '"df":"<data frame>"') def response_bar_chart(df: DataFrame) -> str: logger.info(f'response_bar_chart') if (df.size <= 0): raise ValueError('No Data!') font_names = ['Heiti TC', 'Songti SC', 'STHeiti Lig...
def _can_run(factory): if (_WIN32 and (factory == _daphne_factory)): pytest.skip('daphne does not support windows') if (factory == _daphne_factory): try: import daphne except Exception: pytest.skip('daphne not installed') elif (factory == _hypercorn_factory): ...
('/circle') def circle_view(): circle = {'stroke_color': '#FF00FF', 'stroke_opacity': 1.0, 'stroke_weight': 7, 'fill_color': '#FFFFFF', 'fill_opacity': 0.8, 'center': {'lat': 33.685, 'lng': (- 116.251)}, 'radius': 2000} circlemap = Map(identifier='circlemap', varname='circlemap', lat=33.678, lng=(- 116.243), ci...
def _prepare_batch_inputs(non_batch_inputs, has_bias=False): inputs = [[] for i in range(len(non_batch_inputs))] for (i, non_batch_input) in enumerate(non_batch_inputs): n = (3 if has_bias else 2) to_be_stacked = [[] for j in range(n)] for (j, inp) in enumerate(non_batch_input): ...
class DECMC(DeltaE): NAME = 'cmc' def __init__(self, l: float=2, c: float=1): self.l = l self.c = c def distance(self, color: 'Color', sample: 'Color', l: Optional[float]=None, c: Optional[float]=None, **kwargs: Any) -> float: if (l is None): l = self.l if (c is N...
def _download_coco_captions_json(cache_dir: str): zip_path = os.path.join(cache_dir, 'annotations.zip') if (not os.path.exists(zip_path)): print('Downloading COCO Captions annotations.') wget.download(COCO_ANNOTATIONS_URL, zip_path) with ZipFile(zip_path, mode='r') as zip: if (not os...
def _kill_srv(pidfile): logSys.debug('cleanup: %r', (pidfile, isdir(pidfile))) if isdir(pidfile): piddir = pidfile pidfile = pjoin(piddir, 'f2b.pid') if (not isfile(pidfile)): pidfile = pjoin(piddir, 'fail2ban.pid') if (unittest.F2B.log_level < logging.DEBUG): log...
def pack_nodes(n2i): max_r = max_x = min_x = max_y = min_y = 0.0 for node in sorted(n2i, key=(lambda x: n2i[x].radius)): item = n2i[node] if (node.is_leaf and item.extra_branch_line and (item.extra_branch_line.line().dx() > 0)): itemBoundingPoly = item.content.mapToScene(item.nodeReg...
.asyncio .workspace_host class TestGetTenant(): async def test_unauthorized(self, unauthorized_dashboard_assertions: HTTPXResponseAssertion, test_client_dashboard: test_data: TestData): response = (await test_client_dashboard.get(f"/tenants/{test_data['tenants']['default'].id}")) unauthorized_dashb...
def get_list_marker_type(node: RenderTreeNode) -> str: if (node.type == 'bullet_list'): mode = 'bullet' primary_marker = '-' secondary_marker = '*' else: mode = 'ordered' primary_marker = '.' secondary_marker = ')' consecutive_lists_count = 1 current = nod...
def create_node(entity: Union[(PythonTask, LaunchPlan, WorkflowBase, RemoteEntity)], *args, **kwargs) -> Union[(Node, VoidPromise)]: from flytekit.remote.remote_callable import RemoteEntity if (len(args) > 0): raise _user_exceptions.FlyteAssertion(f'Only keyword args are supported to pass inputs to work...
class oyBallisticRuler(OpenMayaMPx.MPxNode): aInput = OpenMaya.MObject() aStartPos = OpenMaya.MObject() aStartPosX = OpenMaya.MObject() aStartPosY = OpenMaya.MObject() aStartPosZ = OpenMaya.MObject() aEndPos = OpenMaya.MObject() aEndPosX = OpenMaya.MObject() aEndPosY = OpenMaya.MObject()...
def _option_initpath(*suboptions): grid = get_xyzgrid() def _log(msg): print(msg) grid.log = _log xymaps = grid.all_maps() nmaps = len(xymaps) for (inum, xymap) in enumerate(xymaps): print(f'(Re)building pathfinding matrix for xymap Z={xymap.Z} ({(inum + 1)}/{nmaps}) ...') ...
def get_rule_target_or_error(db: Session, policy_key: FidesKey, rule_key: FidesKey, rule_target_key: FidesKey) -> RuleTarget: logger.info("Finding rule target with key '{}'", rule_target_key) rule: Rule = get_rule_or_error(db, policy_key, rule_key) rule_target = RuleTarget.filter(db=db, conditions=((RuleTar...
() ('tag', [nox.param('prod', id='prod'), nox.param('dev', id='dev'), nox.param('rc', id='rc'), nox.param('prerelease', id='prerelease')]) ('app', [nox.param('fides', id='fides'), nox.param('privacy_center', id='privacy_center'), nox.param('sample_app', id='sample_app')]) def push(session: nox.Session, tag: str, app: s...
class NameDataGenerator(ContextAwareLayoutTokenModelDataGenerator): def iter_model_data_for_context_layout_token_features(self, token_features: ContextAwareLayoutTokenFeatures) -> Iterable[LayoutModelData]: (yield token_features.get_layout_model_data([token_features.token_text, token_features.get_lower_toke...
def test_matching_on_tas(client, basic_agency): resp = _call_and_expect_200(client, (base_query + '?depth=2&filter=00001')) assert (resp.json() == {'results': [{'id': '001', 'ancestors': [], 'description': 'Agency 001 (001)', 'count': 1, 'children': [{'id': '0001', 'ancestors': ['001'], 'description': 'Fed Acco...
def test_generate_ass_repr_for_building_yapi_model(create_test_data, store_local_session, create_pymel, create_maya_env): data = create_test_data pm = create_pymel maya_env = create_maya_env gen = RepresentationGenerator(version=data['building1_yapi_model_main_v001']) gen.generate_ass() repr_ = ...
def qstat(user=None): if (user is None): user = os.getlogin() cmd = ['qstat', '-u', user] try: p = subprocess.Popen(cmd, stdout=subprocess.PIPE) except Exception as ex: logging.error(('Exception when running qstat: %s' % ex)) return [] (stdout, stderr) = p.communicate...
def check_padded_entry(batch): seq_len = sum(batch['attention_mask'][0]) assert (seq_len < len(batch['attention_mask'][0])) assert (batch['labels'][0][0] == (- 100)) assert (batch['labels'][0][(seq_len - 1)] == 2) assert (batch['labels'][0][(- 1)] == (- 100)) assert (batch['input_ids'][0][0] == ...
def _delete_summary_for_block_range(db_session, after_block_number: int, before_block_number: int) -> None: db_session.execute('\n DELETE FROM mev_summary\n WHERE\n block_number >= :after_block_number AND\n block_number < :before_block_number\n ', params={'after_block_numb...
class TestVersion(unittest.TestCase): def test_version_output(self): assert (Version(1, 0, 0, 'final')._get_canonical() == '1.0') assert (Version(1, 2, 0, 'final')._get_canonical() == '1.2') assert (Version(1, 2, 3, 'final')._get_canonical() == '1.2.3') assert (Version(1, 2, 0, 'alph...
def fetch_production(zone_key='US-BPA', session=None, target_datetime=None, logger=logging.getLogger(__name__)) -> list: if target_datetime: raise NotImplementedError('This parser is not yet able to parse past dates') raw_data = get_data(GENERATION_URL, session=session) processed_data = data_process...
class ColorHelperCommand(_ColorMixin, sublime_plugin.TextCommand): html_parser = HTMLParser() def unescape(self, value): return self.html_parser.unescape(value) def on_navigate(self, href): if href.startswith('__insert__'): parts = href.split(':', 3) if (len(parts) ==...
class ResultCache(object): def __init__(self, cache_dir: str): self.cache_str = cache_dir def cache_file(self): if (self.cache_str is None): return None return os.path.join(self.cache_str, f'_result_cache_.{comm.get_rank()}.pkl') def has_cache(self): return PathMa...
def test_from_conversation(basic_conversation): new_conversation = OnceConversation(chat_mode='chat_advanced', user_name='user2') basic_conversation.from_conversation(new_conversation) assert (basic_conversation.chat_mode == 'chat_advanced') assert (basic_conversation.user_name == 'user2')
.parametrize('app,expectation', [(app, pytest.raises(MultiPartException)), (Starlette(routes=[Mount('/', app=app)]), does_not_raise())]) def test_too_many_fields_raise(app, expectation, test_client_factory): client = test_client_factory(app) fields = [] for i in range(1001): fields.append(f'''--B Co...
def join(uri, path): if (not path.startswith('grpc://')): if (not uri.startswith('grpc://')): if (path.startswith(os.path.sep) or (not path)): return ('%s%s' % (nmduri(uri), path)) return ('%s%s%s' % (nmduri(uri), os.path.sep, path)) elif (path.startswith(os.p...
class OptionSeriesOrganizationSonificationContexttracksMappingFrequency(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): ...
class OptionPlotoptionsTreegraphSonificationTracksMappingNoteduration(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
def extract_ct_body_valid_source(): return [('/foo?ct&dns=aW1wYXJhbGxlbGVk', (constants.DOH_MEDIA_TYPE, b'imparalleled')), ('/foo?ct=&dns=aW1wYXJhbGxlbGVk', (constants.DOH_MEDIA_TYPE, b'imparalleled')), ('/foo?ct=bar&dns=aW1wYXJhbGxlbGVk', (constants.DOH_MEDIA_TYPE, b'imparalleled')), ('/foo?dns=aW1wYXJhbGxlbGVk', ...
class TestGoEthereumAsyncAdminModuleTest(GoEthereumAsyncAdminModuleTest): .asyncio .xfail(reason="running geth with the --nodiscover flag doesn't allow peer addition") async def test_admin_peers(self, async_w3: 'AsyncWeb3') -> None: (await super().test_admin_peers(async_w3)) .asyncio async d...
class KvTree(Tree): def get(self, name): for match in self.get_list(name): return match def get_list(self, name): return [child for child in self.children if ((isinstance(child, Token) and (child.type == name)) or (isinstance(child, KvTree) and (child.data == name)))] def __conta...
class TestGenericModule(TestCase): def test(self): self.main() def do(self): script = self.script from mayavi.filters.optional import Optional from mayavi.filters.warp_scalar import WarpScalar from mayavi.filters.cut_plane import CutPlane from mayavi.components.po...
class Test_MetadataCacher(): TIMEOUT = 2000 MAX_ENTRIES = 2 def setup_method(self): self.mc: track._MetadataCacher[(str, str)] = track._MetadataCacher(self.TIMEOUT, self.MAX_ENTRIES) def test_add(self): with patch('gi.repository.GLib.timeout_add_seconds') as timeout_add_seconds: ...
class UF_FLAG_Codes(Enum): UF_SCRIPT = 1 UF_ACCOUNTDISABLE = 2 UF_HOMEDIR_REQUIRED = 8 UF_LOCKOUT = 16 UF_PASSWD_NOTREQD = 32 UF_PASSWD_CANT_CHANGE = 64 UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 128 UF_TEMP_DUPLICATE_ACCOUNT = 256 UF_NORMAL_ACCOUNT = 512 UF_INTERDOMAIN_TRUST_ACCOUNT =...
_api.route((api_url + 'department_categories/'), methods=['GET']) _auth.login_required def get_department_categories(): department_category = request.args.get('department_category') department_id = request.args.get('department_id') department = request.args.get('department') department_categories = Flic...
.parametrize('form_data, expected_msg', [({}, b'Ran command with option: option_value argument 10'), ({'1.1.argument.int.1.number.an-argument': 321}, b'Ran command with option: option_value argument 321'), ({'0.0.flag.bool_flag.1.checkbox.--debug': '--debug', '1.0.option.text.1.text.--an-option': 'ABC', '1.1.argument.i...
class StorageService(abc.ABC): def read(self, filename: str) -> str: pass def write(self, filename: str, data: str) -> None: pass def copy(self, source: str, destination: str) -> None: pass def file_exists(self, filename: str) -> bool: pass def path_type(filename: str...
class DvmDescConverter(): def __init__(self, desc): self.dvm_desc = desc def to_java(self): result = str(self.dvm_desc) result = result.strip() dim = 0 while result.startswith('['): result = result[1:] dim += 1 if (result.startswith('L') an...
def test_list_saml_provider_configs(saml_provider): page = auth.list_saml_provider_configs() result = None for provider_config in page.iterate_all(): if (provider_config.provider_id == saml_provider.provider_id): result = provider_config break assert (result is not None)
def start_command_interface(wb): cmd_list = '\nCommands list:\n 0 --> Write memory\n 1 --> Read memory\n 2 --> Write/Read memory\n 3 --> Print commands list\n 4 --> Exit\n' print(cmd_list) while True: print('\nWaiting for command: ', end='') cmd = int(input()) if (cmd ...
_renderer(wrap_type=ColumnCategoryMetric) class ColumnCategoryMetricRenderer(MetricRenderer): def _get_count_info(self, stat: CategoryStat): percents = round((stat.category_ratio * 100), 3) return f'{stat.category_num} out of {stat.all_num} ({percents}%)' def render_html(self, obj: ColumnCategor...
def test_only_one_occurrence_of_each_case(task): var_0 = Variable('var_0', Integer(32, True), None, True, Variable('var_10', Integer(32, True), 0, True, None)) var_1 = Variable('var_1', Pointer(Integer(32, True), 32), None, False, Variable('var_28', Pointer(Integer(32, True), 32), 1, False, None)) arg1 = Va...
class OptionPlotoptionsSunburstSonificationDefaultinstrumentoptionsMappingNoteduration(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(sel...
class FlowShowingPolicy(GObject.Object): def __init__(self, flow_view): super(FlowShowingPolicy, self).__init__() self._flow_view = flow_view self.counter = 0 self._has_initialised = False def initialise(self, album_manager): if self._has_initialised: return ...
class TestOutput(unittest.TestCase): def test_dict_optional_fields_unused(self): output = paymentrequest.Output(P2PKH_SCRIPT) data = output.to_dict() self.assertTrue(('amount' not in data)) self.assertTrue(('description' not in data)) def test_dict_optional_fields_used(self): ...
def crawl_from_commoncrawl(callback_on_article_extracted, callback_on_warc_completed=None, valid_hosts=None, start_date=None, end_date=None, warc_files_start_date=None, warc_files_end_date=None, strict_date=True, reuse_previously_downloaded_files=True, local_download_dir_warc=None, continue_after_error=True, show_downl...
class ConfigStore(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): return {'name': (str,)} _property de...
class OptionPlotoptionsVariwideSonificationDefaultinstrumentoptionsMappingTremoloDepth(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(sel...
class _Monitor(QtCore.QObject): def __init__(self, layout): QtCore.QObject.__init__(self, layout.window.control) self._layout = layout def eventFilter(self, obj, e): if isinstance(e, QtGui.QCloseEvent): for editor in self._layout.window.editors: if (editor.con...
def test_cli_known_first_party(poetry_venv_factory: PoetryVenvFactory) -> None: with poetry_venv_factory('example_project') as virtual_env: issue_report = f'{uuid.uuid4()}.json' result = virtual_env.run(f'deptry . --known-first-party white -o {issue_report}') assert (result.returncode == 1) ...
def _find_path_in_sources(source_path, *sources): for source in sources: try: return path_get(source, source_path) except (KeyError, IndexError): try: return path_get(source, source_path.lower()) except (KeyError, IndexError): try: ...
def on_message(client, userdata, msg): print(((msg.topic + ' ') + str(msg.payload))) dbus_msg = json.loads(msg.payload) portalId = dbus_msg.get('portalId') deviceId = dbus_msg.get('deviceInstance').get('t1') for key in temp_data: topic = 'W/{}/temperature/{}/{}'.format(portalId, deviceId, ke...
(base=RequestContextTask, name='export.speakers.pdf', bind=True) def export_speakers_pdf_task(self, event_id): speakers = db.session.query(Speaker).filter_by(event_id=event_id) try: speakers_pdf_url = create_save_pdf(render_template('pdf/speakers_pdf.html', speakers=speakers), UPLOAD_PATHS['exports-temp...
def test_end_serialization(): msg = FipaMessage(message_id=1, dialogue_reference=(str(0), ''), target=0, performative=FipaMessage.Performative.END) msg.to = 'receiver' envelope = Envelope(to=msg.to, sender='sender', message=msg) envelope_bytes = envelope.encode() actual_envelope = Envelope.decode(en...
def extractAcquiescetranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('stolen love', 'Stolen Love', 'translated'), ('PRC', 'PRC', 'translated'), ('Loitero...
class TimeAlignment(unittest.TestCase): make_plots_blocking = False n_samples = 100.0 q1_initial = Quaternion(0, 0, 0, 1) q1_final = Quaternion((np.sqrt(2.0) / 2.0), 0, 0, (np.sqrt(2.0) / 2.0)) ts = np.linspace(0, ((n_samples + 1) / n_samples), n_samples) t1s = ts q2_initial = Quaternion((np...
class MessageAPI(v1.MessageAPI): _version = rfc1901.version.clone(1) def setDefaults(self, msg): msg.setComponentByPosition(0, self._version, verifyConstraints=False, matchTags=False, matchConstraints=False) msg.setComponentByPosition(1, self._community, verifyConstraints=False, matchTags=False,...
def get_maintenance_response_context(request): context = {} if settings.MAINTENANCE_MODE_GET_CONTEXT: try: get_request_context_func = import_string(settings.MAINTENANCE_MODE_GET_CONTEXT) except ImportError as error: raise ImproperlyConfigured('settings.MAINTENANCE_MODE_GE...
class TreeItem(HasTraits): allows_children = Bool(True) children = List(Instance('TreeItem')) data = Any() has_children = Property(Bool) parent = Instance('TreeItem') def __str__(self): if (self.data is None): s = '' else: s = str(self.data) return...
.network .parametrize('version, missing, present', [(1, 'LC08_L2SP_218074___02_T1-cropped.tar.gz', 'cropped-before.tar.gz'), (2, 'cropped-before.tar.gz', 'LC08_L2SP_218074___02_T1-cropped.tar.gz')]) def test_figshare_data_repository_versions(version, missing, present): doi = f'10.6084/m9.figshare..v{version}' u...
def test_required_confirmations_transact(accounts, BrownieTester, block_time_network, web3): block = web3.eth.block_number brownieTester = BrownieTester.deploy(True, {'from': accounts[0], 'required_confs': 2}) assert ((web3.eth.block_number - block) >= 2) block = web3.eth.block_number tx = brownieTe...
.parametrize('schema', ['\n version: 2\n models:\n - name: model_with_scripts\n meta:\n fal:\n post-hook:\n - fal_scripts/test.py\n ', '\n version: 2\n models:\n - name: model_with_scripts\n meta:\n ...
class IpywidgetToolBar(HBox, ToolBar): def __init__(self, plot): ToolBar.__init__(self, plot) self._auto_scale_button = Button(value=False, disabled=False, icon='expand-arrows-alt', layout=Layout(width='auto'), tooltip='auto-scale scene') self._center_scene_button = Button(value=False, disab...
class SimpleSwitchLacp13(simple_switch_13.SimpleSwitch13): OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION] _CONTEXTS = {'lacplib': lacplib.LacpLib} def __init__(self, *args, **kwargs): super(SimpleSwitchLacp13, self).__init__(*args, **kwargs) self.mac_to_port = {} self._lacp = kwargs['lacp...
def test_create() -> None: bad = [((- 1), 0, 0), (256, 0, 0), (0, (- 1), 0), (0, 256, 0), (0, 0, (- 1)), (0, 0, 256), (0, 0, 0, (- 1)), (0, 0, 0, 256)] for rgb in bad: with pytest.raises(ValueError): staticmaps.Color(*rgb) staticmaps.Color(1, 2, 3) staticmaps.Color(1, 2, 3, 4)
class OrderTicket(db.Model): __tablename__ = 'orders_tickets' order_id = db.Column(db.Integer, db.ForeignKey('orders.id', ondelete='CASCADE'), primary_key=True) ticket_id = db.Column(db.Integer, db.ForeignKey('tickets.id', ondelete='CASCADE'), primary_key=True) quantity = db.Column(db.Integer) price...
def extractJinyutranslationsWordpressCom(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, ...
def test_ensemble_state_tracker_handles(): state_machine = _EnsembleStateTracker() expected_sates = [state.ENSEMBLE_STATE_UNKNOWN, state.ENSEMBLE_STATE_STARTED, state.ENSEMBLE_STATE_FAILED, state.ENSEMBLE_STATE_STOPPED, state.ENSEMBLE_STATE_CANCELLED] handled_states = list(state_machine._handles.keys()) ...
def lazy_import(): from fastly.model.timestamps import Timestamps from fastly.model.tls_bulk_certificate_response_attributes_all_of import TlsBulkCertificateResponseAttributesAllOf globals()['Timestamps'] = Timestamps globals()['TlsBulkCertificateResponseAttributesAllOf'] = TlsBulkCertificateResponseAtt...
def test_json_Message_Sticker(): json_string = '{"message_id": 21552, "from": {"id": , "is_bot": false, "first_name": " r ", "username": "Purya", "language_code": "en"}, "chat": {"id": -, "title": "123", "type": "supergroup"}, "date": , "sticker": {"type": "regular", "width": 368, "height": 368, "emoji": "", "set_n...
_bp.route((app.config['FLICKET'] + 'history/topic/<int:topic_id>/'), methods=['GET', 'POST']) _required def flicket_history_topic(topic_id): history = FlicketHistory.query.filter_by(topic_id=topic_id).all() ticket = FlicketTicket.query.filter_by(id=topic_id).one() title = gettext('History') return rende...
_config(context=HTTPForbidden, accept='application/json') _config(context=Exception, accept='application/json') def exception_json_view(exc, request): errors = getattr(request, 'errors', []) status = getattr(exc, 'status_code', 500) if (status not in (404, 403)): log.exception('Error caught. Handli...
def verify_dir_outputs(job_return: JobReturn, overrides: Optional[List[str]]=None) -> None: assert isinstance(job_return, JobReturn) assert (job_return.working_dir is not None) assert (job_return.task_name is not None) assert (job_return.hydra_cfg is not None) assert os.path.exists(os.path.join(job_...
(custom_vjp, nondiff_argnums=tuple(range(1, 6))) def run_async(simulations: Tuple[(JaxSimulation, ...)], folder_name: str='default', path_dir: str=DEFAULT_DATA_DIR, callback_url: str=None, verbose: bool=True, num_workers: int=None) -> Tuple[(JaxSimulationData, ...)]: task_names = [str(_task_name_orig(i)) for i in r...
class MatrixMultiplicationCost(object): def find_min_cost(self, matrices): if (matrices is None): raise TypeError('matrices cannot be None') if (not matrices): return 0 size = len(matrices) T = [([0] * size) for _ in range(size)] for offset in range(1,...
_chunk_type class chunk_init_ack(chunk_init_base): _RECOGNIZED_PARAMS = {} def register_param_type(*args): def _register_param_type(cls): chunk_init_ack._RECOGNIZED_PARAMS[cls.param_type()] = cls return cls return _register_param_type(args[0]) def chunk_type(cls): ...
class TestMMR(unittest.TestCase): def setUp(self): txo1 = ((Field(1) * G) + (Field(11) * H)) txo2 = ((Field(2) * G) + (Field(12) * H)) txo3 = ((Field(3) * G) + (Field(13) * H)) txo4 = ((Field(4) * G) + (Field(14) * H)) txo5 = ((Field(5) * G) + (Field(15) * H)) txo6 = ...
.integration_test .parametrize('config_str, expected', [('GEN_KW KW_NAME prior.txt\nRANDOM_SEED 1234', (- 0.881423))]) def test_gen_kw_optional_template(storage, tmpdir, config_str, expected): with tmpdir.as_cwd(): config = dedent('\n JOBNAME my_name%d\n NUM_REALIZATIONS 1\n ') ...