id
int64
0
300k
label
stringlengths
1
74
text
stringlengths
4k
8k
299,000
test subclass base fails no create method
# Copyright 2019, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unittest import mock from absl.testing import absltest from absl.testing import parameterized from tensorflow_federated.python.core.impl.executor_stacks import python_executor_stacks from tensorflow_federated.python.core.impl.executors import executor_base from tensorflow_federated.python.core.impl.executors import executor_factory from tensorflow_federated.python.core.impl.types import placements class ExecutorMock(mock.MagicMock, executor_base.Executor): async def create_value(self, *args): pass async def create_call(self, *args): pass async def create_selection(self, *args): pass async def create_struct(self, *args): pass async def close(self, *args): pass class ConcreteExecutorFactoryTest(parameterized.TestCase): def METHOD_NAME(self): class NotCallable(executor_factory.ExecutorFactory): def clean_up_executor(self, x): pass with self.assertRaisesRegex(TypeError, 'instantiate abstract class'): NotCallable() def test_subclass_base_fails_no_cleanup(self): class NoCleanup(executor_factory.ExecutorFactory): def create_executor(self, x): pass with self.assertRaisesRegex(TypeError, 'instantiate abstract class'): NoCleanup() def test_instantiation_succeeds_both_methods_specified(self): class Fine(executor_factory.ExecutorFactory): def create_executor(self, x): pass def clean_up_executor(self, x): pass Fine() @parameterized.named_parameters(( 'ResourceManagingExecutorFactory', python_executor_stacks.ResourceManagingExecutorFactory, )) def test_concrete_class_instantiates_stack_fn(self, ex_factory): def _stack_fn(x): del x # Unused return ExecutorMock() factory = ex_factory(_stack_fn) self.assertIsInstance(factory, ex_factory) @parameterized.named_parameters(( 'ResourceManagingExecutorFactory', python_executor_stacks.ResourceManagingExecutorFactory, )) def test_call_constructs_executor(self, ex_factory): def _stack_fn(x): del x # Unused return ExecutorMock() factory = ex_factory(_stack_fn) ex = factory.create_executor({}) self.assertIsInstance(ex, executor_base.Executor) @parameterized.named_parameters(( 'ResourceManagingExecutorFactory', python_executor_stacks.ResourceManagingExecutorFactory, )) def test_cleanup_succeeds_without_init(self, ex_factory): def _stack_fn(x): del x # Unused return ExecutorMock() factory = ex_factory(_stack_fn) factory.clean_up_executor({placements.CLIENTS: 1}) @parameterized.named_parameters(( 'ResourceManagingExecutorFactory', python_executor_stacks.ResourceManagingExecutorFactory, )) def test_cleanup_calls_close(self, ex_factory): ex = ExecutorMock() ex.close = mock.MagicMock() def _stack_fn(x): del x # Unused return ex factory = ex_factory(_stack_fn) factory.create_executor({}) factory.clean_up_executor({}) ex.close.assert_called_once() @parameterized.named_parameters(( 'ResourceManagingExecutorFactory', python_executor_stacks.ResourceManagingExecutorFactory, )) def test_construction_with_multiple_cardinalities_reuses_existing_stacks( self, ex_factory ): ex = ExecutorMock() ex.close = mock.MagicMock() num_times_invoked = 0 def _stack_fn(x): del x # Unused nonlocal num_times_invoked num_times_invoked += 1 return ex factory = ex_factory(_stack_fn) for _ in range(2): factory.create_executor({}) factory.create_executor({placements.SERVER: 1}) self.assertEqual(num_times_invoked, 2) def test_executors_persisted_is_capped(self): ex = ExecutorMock() factory = python_executor_stacks.ResourceManagingExecutorFactory( lambda _: ex ) for num_clients in range(100): factory.create_executor({placements.CLIENTS: num_clients}) self.assertLess(len(factory._executors), 20) if __name__ == '__main__': absltest.main()
299,001
get srcdir
## ## Copyright (C) by Argonne National Laboratory ## See COPYRIGHT in top-level directory ## import os import re import sys def METHOD_NAME(): m = re.match(r'(.*)\/maint\/local_python', __file__) if m: return m.group(1) elif re.match(r'maint\/local_python', __file__): return "." else: raise Exception("Can't determine srcdir from __file__") # RE class allows convenience of using regex capture in a condition class RE: m = None def match(pat, str, flags=0): RE.m = re.match(pat, str, flags) return RE.m def search(pat, str, flags=0): RE.m = re.search(pat, str, flags) return RE.m # Global data used across modules class MPI_API_Global: srcdir = METHOD_NAME() def get_srcdir_path(path): # assume path is a relative path from top srcdir return MPI_API_Global.srcdir + "/" + path def check_write_path(path): os.makedirs(os.path.dirname(path), exist_ok=True) # command line options and arguments # By default assumes sizes for LP64 model. # The F08 bindings use the sizes to detect duplicate large interfaces # The F90 bindings use the sizes to implement MPI_SIZEOF (although deprecated in MPI-4) opts = {'fint-size':4, 'aint-size':8, 'count-size':8, 'cint-size':4, 'f-logical-size':4} args = [] # output out = [] # api FUNCS = {} MAPS = {} default_descriptions = {} # misc globals used during code generation err_codes = {} mpi_sources = [] mpi_declares = [] impl_declares = [] mpi_errnames = [] mpix_symbols = {} status_fields = ["count_lo", "count_hi_and_cancelled", "MPI_SOURCE", "MPI_TAG", "MPI_ERROR"] handle_list = ["MPI_Comm", "MPI_Datatype", "MPI_Errhandler", "MPI_File", "MPI_Group", "MPI_Info", "MPI_Op", "MPI_Request", "MPI_Win", "MPI_Message", "MPI_Session", "MPIX_Stream"] handle_mpir_types = { 'COMMUNICATOR': "MPIR_Comm", 'GROUP': "MPIR_Group", 'DATATYPE': "MPIR_Datatype", 'ERRHANDLER': "MPIR_Errhandler", 'OPERATION': "MPIR_Op", 'INFO': "MPIR_Info", 'WINDOW': "MPIR_Win", 'KEYVAL': "MPII_Keyval", 'REQUEST': "MPIR_Request", 'MESSAGE': "MPIR_Request", 'SESSION': "MPIR_Session", 'GREQUEST_CLASS': "MPIR_Grequest_class", 'STREAM': "MPIR_Stream", } handle_error_codes = { 'COMMUNICATOR': "MPI_ERR_COMM", 'GROUP': "MPI_ERR_GROUP", 'DATATYPE': "MPI_ERR_TYPE", 'ERRHANDLER': "MPI_ERR_ARG", 'OPERATION': "MPI_ERR_OP", 'INFO': "MPI_ERR_INFO", 'WINDOW': "MPI_ERR_WIN", 'KEYVAL': "MPI_ERR_KEYVAL", 'REQUEST': "MPI_ERR_REQUEST", 'MESSAGE': "MPI_ERR_REQUEST", 'SESSION': "MPI_ERR_SESSION", 'GREQUEST_CLASS': "", 'STREAM': "MPIX_ERR_STREAM", } handle_out_do_ptrs = { 'COMMUNICATOR': 1, 'GROUP': 1, 'DATATYPE': 1, 'ERRHANDLER': 1, 'OPERATION': 1, 'INFO': 1, 'WINDOW': 1, # 'KEYVAL': 1, 'REQUEST': 1, 'MESSAGE': 1, 'SESSION': 1, 'GREQUEST_CLASS': 1, 'STREAM': 1, } handle_NULLs = { 'COMMUNICATOR': "MPI_COMM_NULL", 'GROUP': "MPI_GROUP_NULL", 'DATATYPE': "MPI_DATATYPE_NULL", 'ERRHANDLER': "MPI_ERRHANDLER_NULL", 'OPERATION': "MPI_OP_NULL", 'INFO': "MPI_INFO_NULL", 'WINDOW': "MPI_WIN_NULL", 'KEYVAL': "MPI_KEYVAL_INVALID", 'REQUEST': "MPI_REQUEST_NULL", 'MESSAGE': "MPI_MESSAGE_NULL", 'SESSION': "MPI_SESSION_NULL", # 'GREQUEST_CLASS': "", 'STREAM': "MPIX_STREAM_NULL", } copyright_c = [ "/*", " * Copyright (C) by Argonne National Laboratory", " * See COPYRIGHT in top-level directory", " */", "", "/* -- THIS FILE IS AUTO-GENERATED -- */", "" ] copyright_mk = [ "##", "## Copyright (C) by Argonne National Laboratory", "## See COPYRIGHT in top-level directory", "##", "", "# -- THIS FILE IS AUTO-GENERATED -- ", "" ] copyright_f90 = [ "!", "! Copyright (C) by Argonne National Laboratory", "! See COPYRIGHT in top-level directory", "!", "", "! -- THIS FILE IS AUTO-GENERATED -- ", "" ] def parse_cmdline(): print(" [", " ".join(sys.argv), "]") for a in sys.argv[1:]: if RE.match(r'--?([\w-]+)=(.*)', a): MPI_API_Global.opts[RE.m.group(1)] = RE.m.group(2) elif RE.match(r'--?([\w-].+)', a): MPI_API_Global.opts[RE.m.group(1)] = 1 else: MPI_API_Global.args.append(a)
299,002
test file size too large
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # import logging import os import tempfile import time from hashlib import sha256 from tests.unit import unittest from boto.compat import BytesIO, six, StringIO from boto.glacier.utils import minimum_part_size, chunk_hashes, tree_hash, \ bytes_to_hex, compute_hashes_from_fileobj class TestPartSizeCalculations(unittest.TestCase): def test_small_values_still_use_default_part_size(self): self.assertEqual(minimum_part_size(1), 4 * 1024 * 1024) def test_under_the_maximum_value(self): # If we're under the maximum, we can use 4MB part sizes. self.assertEqual(minimum_part_size(8 * 1024 * 1024), 4 * 1024 * 1024) def test_gigabyte_size(self): # If we're over the maximum default part size, we go up to the next # power of two until we find a part size that keeps us under 10,000 # parts. self.assertEqual(minimum_part_size(8 * 1024 * 1024 * 10000), 8 * 1024 * 1024) def test_terabyte_size(self): # For a 4 TB file we need at least a 512 MB part size. self.assertEqual(minimum_part_size(4 * 1024 * 1024 * 1024 * 1024), 512 * 1024 * 1024) def METHOD_NAME(self): with self.assertRaises(ValueError): minimum_part_size((40000 * 1024 * 1024 * 1024) + 1) def test_default_part_size_can_be_specified(self): default_part_size = 2 * 1024 * 1024 self.assertEqual(minimum_part_size(8 * 1024 * 1024, default_part_size), default_part_size) class TestChunking(unittest.TestCase): def test_chunk_hashes_exact(self): chunks = chunk_hashes(b'a' * (2 * 1024 * 1024)) self.assertEqual(len(chunks), 2) self.assertEqual(chunks[0], sha256(b'a' * 1024 * 1024).digest()) def test_chunks_with_leftovers(self): bytestring = b'a' * (2 * 1024 * 1024 + 20) chunks = chunk_hashes(bytestring) self.assertEqual(len(chunks), 3) self.assertEqual(chunks[0], sha256(b'a' * 1024 * 1024).digest()) self.assertEqual(chunks[1], sha256(b'a' * 1024 * 1024).digest()) self.assertEqual(chunks[2], sha256(b'a' * 20).digest()) def test_less_than_one_chunk(self): chunks = chunk_hashes(b'aaaa') self.assertEqual(len(chunks), 1) self.assertEqual(chunks[0], sha256(b'aaaa').digest()) class TestTreeHash(unittest.TestCase): # For these tests, a set of reference tree hashes were computed. # This will at least catch any regressions to the tree hash # calculations. def calculate_tree_hash(self, bytestring): start = time.time() calculated = bytes_to_hex(tree_hash(chunk_hashes(bytestring))) end = time.time() logging.debug("Tree hash calc time for length %s: %s", len(bytestring), end - start) return calculated def test_tree_hash_calculations(self): one_meg_bytestring = b'a' * (1 * 1024 * 1024) two_meg_bytestring = b'a' * (2 * 1024 * 1024) four_meg_bytestring = b'a' * (4 * 1024 * 1024) bigger_bytestring = four_meg_bytestring + b'a' * 20 self.assertEqual( self.calculate_tree_hash(one_meg_bytestring), b'9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360') self.assertEqual( self.calculate_tree_hash(two_meg_bytestring), b'560c2c9333c719cb00cfdffee3ba293db17f58743cdd1f7e4055373ae6300afa') self.assertEqual( self.calculate_tree_hash(four_meg_bytestring), b'9491cb2ed1d4e7cd53215f4017c23ec4ad21d7050a1e6bb636c4f67e8cddb844') self.assertEqual( self.calculate_tree_hash(bigger_bytestring), b'12f3cbd6101b981cde074039f6f728071da8879d6f632de8afc7cdf00661b08f') def test_empty_tree_hash(self): self.assertEqual( self.calculate_tree_hash(''), b'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855') class TestFileHash(unittest.TestCase): def _gen_data(self): # Generate some pseudo-random bytes of data. We include the # hard-coded blob as an example that fails to decode via UTF-8. return os.urandom(5000) + b'\xc2\x00' def test_compute_hash_tempfile(self): # Compute a hash from a file object. On Python 2 this uses a non- # binary mode. On Python 3, however, binary mode is required for # binary files. If not used, you will get UTF-8 code errors. if six.PY2: mode = "w+" else: mode = "wb+" with tempfile.TemporaryFile(mode=mode) as f: f.write(self._gen_data()) f.seek(0) compute_hashes_from_fileobj(f, chunk_size=512) @unittest.skipUnless(six.PY3, 'Python 3 requires reading binary!') def test_compute_hash_tempfile_py3(self): # Note the missing 'b' in the mode! with tempfile.TemporaryFile(mode='w+') as f: with self.assertRaises(ValueError): compute_hashes_from_fileobj(f, chunk_size=512) # What about file-like objects without a mode? If it has an # encoding we use it, otherwise attempt UTF-8 encoding to # bytes for hashing. f = StringIO('test data' * 500) compute_hashes_from_fileobj(f, chunk_size=512) @unittest.skipUnless(six.PY2, 'Python 3 requires reading binary!') def test_compute_hash_stringio(self): # Python 2 binary data in StringIO example f = StringIO(self._gen_data()) compute_hashes_from_fileobj(f, chunk_size=512) def test_compute_hash_bytesio(self): # Compute a hash from a file-like BytesIO object. f = BytesIO(self._gen_data()) compute_hashes_from_fileobj(f, chunk_size=512)
299,003
proc0
#!/usr/bin/env python3 """ "PYSTONE" Benchmark Program Version: Python/1.1 (corresponds to C/1.1 plus 2 Pystone fixes) Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013. Translated from ADA to C by Rick Richardson. Every method to preserve ADA-likeness has been used, at the expense of C-ness. Translated from C to Python by Guido van Rossum. Version History: Version 1.1 corrects two bugs in version 1.0: First, it leaked memory: in Proc1(), NextRecord ends up having a pointer to itself. I have corrected this by zapping NextRecord.PtrComp at the end of Proc1(). Second, Proc3() used the operator != to compare a record to None. This is rather inefficient and not true to the intention of the original benchmark (where a pointer comparison to None is intended; the != operator attempts to find a method __cmp__ to do value comparison of the record). Version 1.1 runs 5-10 percent faster than version 1.0, so benchmark figures of different versions can't be compared directly. """ from __future__ import print_function from time import clock LOOPS = 50000 __version__ = "1.1" [Ident1, Ident2, Ident3, Ident4, Ident5] = range(1, 6) class Record(object): def __init__(self, PtrComp = None, Discr = 0, EnumComp = 0, IntComp = 0, StringComp = 0): self.PtrComp = PtrComp self.Discr = Discr self.EnumComp = EnumComp self.IntComp = IntComp self.StringComp = StringComp def copy(self): return Record(self.PtrComp, self.Discr, self.EnumComp, self.IntComp, self.StringComp) TRUE = 1 FALSE = 0 def main(loops=LOOPS): benchtime, stones = pystones(loops) print("Pystone(%s) time for %d passes = %g" % \ (__version__, loops, benchtime)) print("This machine benchmarks at %g pystones/second" % stones) def pystones(loops=LOOPS): return METHOD_NAME(loops) IntGlob = 0 BoolGlob = FALSE Char1Glob = '\0' Char2Glob = '\0' Array1Glob = [0]*51 Array2Glob = [x[:] for x in [Array1Glob]*51] PtrGlb = None PtrGlbNext = None def METHOD_NAME(loops=LOOPS): global IntGlob global BoolGlob global Char1Glob global Char2Glob global Array1Glob global Array2Glob global PtrGlb global PtrGlbNext starttime = clock() for i in range(loops): pass nulltime = clock() - starttime PtrGlbNext = Record() PtrGlb = Record() PtrGlb.PtrComp = PtrGlbNext PtrGlb.Discr = Ident1 PtrGlb.EnumComp = Ident3 PtrGlb.IntComp = 40 PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING" String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING" Array2Glob[8][7] = 10 starttime = clock() for i in range(loops): Proc5() Proc4() IntLoc1 = 2 IntLoc2 = 3 String2Loc = "DHRYSTONE PROGRAM, 2'ND STRING" EnumLoc = Ident2 BoolGlob = not Func2(String1Loc, String2Loc) while IntLoc1 < IntLoc2: IntLoc3 = 5 * IntLoc1 - IntLoc2 IntLoc3 = Proc7(IntLoc1, IntLoc2) IntLoc1 = IntLoc1 + 1 Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3) PtrGlb = Proc1(PtrGlb) CharIndex = 'A' while CharIndex <= Char2Glob: if EnumLoc == Func1(CharIndex, 'C'): EnumLoc = Proc6(Ident1) CharIndex = chr(ord(CharIndex)+1) IntLoc3 = IntLoc2 * IntLoc1 IntLoc2 = IntLoc3 / IntLoc1 IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1 IntLoc1 = Proc2(IntLoc1) benchtime = clock() - starttime - nulltime if benchtime == 0.0: loopsPerBenchtime = 0.0 else: loopsPerBenchtime = (loops / benchtime) return benchtime, loopsPerBenchtime def Proc1(PtrParIn): PtrParIn.PtrComp = NextRecord = PtrGlb.copy() PtrParIn.IntComp = 5 NextRecord.IntComp = PtrParIn.IntComp NextRecord.PtrComp = PtrParIn.PtrComp NextRecord.PtrComp = Proc3(NextRecord.PtrComp) if NextRecord.Discr == Ident1: NextRecord.IntComp = 6 NextRecord.EnumComp = Proc6(PtrParIn.EnumComp) NextRecord.PtrComp = PtrGlb.PtrComp NextRecord.IntComp = Proc7(NextRecord.IntComp, 10) else: PtrParIn = NextRecord.copy() NextRecord.PtrComp = None return PtrParIn def Proc2(IntParIO): IntLoc = IntParIO + 10 while 1: if Char1Glob == 'A': IntLoc = IntLoc - 1 IntParIO = IntLoc - IntGlob EnumLoc = Ident1 if EnumLoc == Ident1: break return IntParIO def Proc3(PtrParOut): global IntGlob if PtrGlb is not None: PtrParOut = PtrGlb.PtrComp else: IntGlob = 100 PtrGlb.IntComp = Proc7(10, IntGlob) return PtrParOut def Proc4(): global Char2Glob BoolLoc = Char1Glob == 'A' BoolLoc = BoolLoc or BoolGlob Char2Glob = 'B' def Proc5(): global Char1Glob global BoolGlob Char1Glob = 'A' BoolGlob = FALSE def Proc6(EnumParIn): EnumParOut = EnumParIn if not Func3(EnumParIn): EnumParOut = Ident4 if EnumParIn == Ident1: EnumParOut = Ident1 elif EnumParIn == Ident2: if IntGlob > 100: EnumParOut = Ident1 else: EnumParOut = Ident4 elif EnumParIn == Ident3: EnumParOut = Ident2 elif EnumParIn == Ident4: pass elif EnumParIn == Ident5: EnumParOut = Ident3 return EnumParOut def Proc7(IntParI1, IntParI2): IntLoc = IntParI1 + 2 IntParOut = IntParI2 + IntLoc return IntParOut def Proc8(Array1Par, Array2Par, IntParI1, IntParI2): global IntGlob IntLoc = IntParI1 + 5 Array1Par[IntLoc] = IntParI2 Array1Par[IntLoc+1] = Array1Par[IntLoc] Array1Par[IntLoc+30] = IntLoc for IntIndex in range(IntLoc, IntLoc+2): Array2Par[IntLoc][IntIndex] = IntLoc Array2Par[IntLoc][IntLoc-1] = Array2Par[IntLoc][IntLoc-1] + 1 Array2Par[IntLoc+20][IntLoc] = Array1Par[IntLoc] IntGlob = 5 def Func1(CharPar1, CharPar2): CharLoc1 = CharPar1 CharLoc2 = CharLoc1 if CharLoc2 != CharPar2: return Ident1 else: return Ident2 def Func2(StrParI1, StrParI2): IntLoc = 1 while IntLoc <= 1: if Func1(StrParI1[IntLoc], StrParI2[IntLoc+1]) == Ident1: CharLoc = 'A' IntLoc = IntLoc + 1 if CharLoc >= 'W' and CharLoc <= 'Z': IntLoc = 7 if CharLoc == 'X': return TRUE else: if StrParI1 > StrParI2: IntLoc = IntLoc + 7 return TRUE else: return FALSE def Func3(EnumParIn): EnumLoc = EnumParIn if EnumLoc == Ident3: return TRUE return FALSE if __name__ == '__main__': import sys def error(msg): print(msg, end=' ', file=sys.stderr) print("usage: %s [number_of_loops]" % sys.argv[0], file=sys.stderr) sys.exit(100) nargs = len(sys.argv) - 1 if nargs > 1: error("%d arguments are too many;" % nargs) elif nargs == 1: try: loops = int(sys.argv[1]) except ValueError: error("Invalid argument %r;" % sys.argv[1]) else: loops = LOOPS main(loops)
299,004
debug
from __future__ import annotations import logging import os import warnings from dataclasses import dataclass from mitmproxy import hooks from mitmproxy import master from mitmproxy.contrib import click as miniclick from mitmproxy.utils import human ALERT = logging.INFO + 1 """ The ALERT logging level has the same urgency as info, but signals to interactive tools that the user's attention should be drawn to the output even if they're not currently looking at the event log. """ logging.addLevelName(ALERT, "ALERT") LogLevels = [ "error", "warn", "info", "alert", "debug", ] LOG_COLORS = {logging.ERROR: "red", logging.WARNING: "yellow", ALERT: "magenta"} class MitmFormatter(logging.Formatter): def __init__(self, colorize: bool): super().__init__() self.colorize = colorize time = "[%s]" client = "[%s]" if colorize: time = miniclick.style(time, fg="cyan", dim=True) client = miniclick.style(client, fg="yellow", dim=True) self.with_client = f"{time}{client} %s" self.without_client = f"{time} %s" default_time_format = "%H:%M:%S" default_msec_format = "%s.%03d" def format(self, record: logging.LogRecord) -> str: time = self.formatTime(record) message = record.getMessage() if record.exc_info: message = f"{message}\n{self.formatException(record.exc_info)}" if self.colorize: message = miniclick.style( message, fg=LOG_COLORS.get(record.levelno), # dim=(record.levelno <= logging.DEBUG) ) if client := getattr(record, "client", None): client = human.format_address(client) return self.with_client % (time, client, message) else: return self.without_client % (time, message) class MitmLogHandler(logging.Handler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._initiated_in_test = os.environ.get("PYTEST_CURRENT_TEST") def filter(self, record: logging.LogRecord) -> bool: # We can't remove stale handlers here because that would modify .handlers during iteration! return super().filter(record) and ( not self._initiated_in_test or self._initiated_in_test == os.environ.get("PYTEST_CURRENT_TEST") ) def install(self) -> None: if self._initiated_in_test: for h in list(logging.getLogger().handlers): if ( isinstance(h, MitmLogHandler) and h._initiated_in_test != self._initiated_in_test ): h.uninstall() logging.getLogger().addHandler(self) def uninstall(self) -> None: logging.getLogger().removeHandler(self) # everything below is deprecated! class LogEntry: def __init__(self, msg, level): # it's important that we serialize to string here already so that we don't pick up changes # happening after this log statement. self.msg = str(msg) self.level = level def __eq__(self, other): if isinstance(other, LogEntry): return self.__dict__ == other.__dict__ return False def __repr__(self): return f"LogEntry({self.msg}, {self.level})" class Log: """ The central logger, exposed to scripts as mitmproxy.ctx.log. Deprecated: Please use the standard Python logging module instead. """ def __init__(self, master): self.master = master def METHOD_NAME(self, txt): """ Log with level debug. """ warnings.warn( "mitmproxy's ctx.log.debug() is deprecated. Please use the standard Python logging module instead.", DeprecationWarning, stacklevel=2, ) logging.getLogger().METHOD_NAME(txt) def info(self, txt): """ Log with level info. """ warnings.warn( "mitmproxy's ctx.log.info() is deprecated. Please use the standard Python logging module instead.", DeprecationWarning, stacklevel=2, ) logging.getLogger().info(txt) def alert(self, txt): """ Log with level alert. Alerts have the same urgency as info, but signals to interactive tools that the user's attention should be drawn to the output even if they're not currently looking at the event log. """ warnings.warn( "mitmproxy's ctx.log.alert() is deprecated. Please use the standard Python logging module instead.", DeprecationWarning, stacklevel=2, ) logging.getLogger().log(ALERT, txt) def warn(self, txt): """ Log with level warn. """ warnings.warn( "mitmproxy's ctx.log.warn() is deprecated. Please use the standard Python logging module instead.", DeprecationWarning, stacklevel=2, ) logging.getLogger().warning(txt) def error(self, txt): """ Log with level error. """ warnings.warn( "mitmproxy's ctx.log.error() is deprecated. Please use the standard Python logging module instead.", DeprecationWarning, stacklevel=2, ) logging.getLogger().error(txt) def __call__(self, text, level="info"): warnings.warn( "mitmproxy's ctx.log() is deprecated. Please use the standard Python logging module instead.", DeprecationWarning, stacklevel=2, ) logging.getLogger().log(level=logging.getLevelName(level.upper()), msg=text) LOGGING_LEVELS_TO_LOGENTRY = { logging.ERROR: "error", logging.WARNING: "warn", logging.INFO: "info", ALERT: "alert", logging.DEBUG: "debug", } class LegacyLogEvents(MitmLogHandler): """Emit deprecated `add_log` events from stdlib logging.""" def __init__( self, master: master.Master, ): super().__init__() self.master = master self.formatter = MitmFormatter(colorize=False) def emit(self, record: logging.LogRecord) -> None: entry = LogEntry( msg=self.format(record), level=LOGGING_LEVELS_TO_LOGENTRY.get(record.levelno, "error"), ) self.master.event_loop.call_soon_threadsafe( self.master.addons.trigger, AddLogHook(entry), ) @dataclass class AddLogHook(hooks.Hook): """ **Deprecated:** Starting with mitmproxy 9, users should use the standard Python logging module instead, for example by calling `logging.getLogger().addHandler()`. Called whenever a new log entry is created through the mitmproxy context. Be careful not to log from this event, which will cause an infinite loop! """ entry: LogEntry def log_tier(level): """ Comparison method for "old" LogEntry log tiers. Ideally you should use the standard Python logging module instead. """ return dict(error=0, warn=1, info=2, alert=2, METHOD_NAME=3).get(level)
299,005
version details
"""Test for Satellite-maintain related Upgrade Scenario's :Requirement: UpgradedSatellite :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: ForemanMaintain :Team: Platform :TestType: Functional :CaseImportance: High :Upstream: No """ import pytest class TestSatelliteMaintain: """The test class contains pre-upgrade and post-upgrade scenarios to test satellite-maintain utility Test Steps: 1. Before Satellite upgrade, Perform test for "satellite-maintain upgrade list-versions" 2. Upgrade satellite/capsule. 3. Perform tests for satellite-maintain upgrade list-versions, after upgrade. 4. Check if tests passed. """ @staticmethod def satellite_upgradable_version_list(sat_obj): """ This function is used to collect the details of satellite version and upgradable version list. :return: satellite_version, upgradeable_version, major_version_change """ cmd = "rpm -q satellite > /dev/null && rpm -q satellite --queryformat=%{VERSION}" # leaving this section as-is for now but this could be refactored to use sat_obj.version satellite_version = sat_obj.execute(cmd) if satellite_version.status == 0: satellite_version = satellite_version.stdout else: return [], [], None, None satellite_maintain_version = sat_obj.execute( "satellite-maintain upgrade list-versions --disable-self-upgrade" ) upgradeable_version = [ version for version in satellite_maintain_version.stdout if version != '' ] version_change = 0 for version in upgradeable_version: version_change += int(version.split('.')[0]) if version_change % 2 == 0: major_version_change = False y_version = '' else: major_version_change = True y_version = list(set(satellite_maintain_version) - set(satellite_version))[0].split( '.' )[-1] return satellite_version, upgradeable_version, major_version_change, y_version @staticmethod def METHOD_NAME( satellite_version, major_version_change, y_version, upgrade_stage="pre-upgrade" ): """ This function is used to update the details of zstream upgrade and next version upgrade :param str satellite_version: satellite version would be like 6.5.0, 6.6.0, 6.7.0 :param bool major_version_change: For major version upgrade like 6.8 to 7.0, 7.0 to 8.0 etc, then major_version_change would be True. :param str y_version: y_version change depends on major_version_change :param str upgrade_stage: upgrade stage would be pre or post. :return: zstream_version, next_version """ major_version = satellite_version.split('.')[0:1] if major_version_change: major_version = [int(major_version[0]) + 1].append(y_version) else: y_version = int(satellite_version.split('.')[0:2][-1]) zstream_version = '' if upgrade_stage == "pre-upgrade": major_version.append(str(y_version + 1)) zstream_version = ".".join(satellite_version.split('.')[0:2]) + ".z" else: major_version.append(str(y_version)) major_version.append("z") next_version = ".".join(major_version) return zstream_version, next_version @pytest.mark.pre_upgrade def test_pre_satellite_maintain_upgrade_list_versions(self, target_sat): """Pre-upgrade sceanrio that tests list of satellite version which satellite can be upgraded. :id: preupgrade-fc2c54b2-2663-11ea-b47c-48f17f1fc2e1 :steps: 1. Run satellite-maintain upgrade list-versions :expectedresults: Versions should be current z-stream. """ ( satellite_version, upgradable_version, major_version_change, y_version, ) = self.satellite_upgradable_version_list(target_sat) if satellite_version: # In future If satellite-maintain packages update add before # pre-upgrade test case execution then next version kind of # stuff check we can add it here. zstream_version, next_version = self.METHOD_NAME( satellite_version[0], major_version_change, y_version ) else: zstream_version = -1 assert zstream_version in upgradable_version @pytest.mark.post_upgrade def test_post_satellite_maintain_upgrade_list_versions(self, target_sat): """Post-upgrade sceanrio that tests list of satellite version which satellite can be upgraded. :id: postupgrade-0bce689c-2664-11ea-b47c-48f17f1fc2e1 :steps: 1. Run satellite-maintain upgrade list-versions. :expectedresults: Versions should be next z-stream. """ ( satellite_version, upgradable_version, major_version_change, y_version, ) = self.satellite_upgradable_version_list(target_sat) if satellite_version: zstream_version, next_version = self.METHOD_NAME( satellite_version[0], major_version_change, y_version, upgrade_stage="post-upgrade" ) else: next_version = -1 assert next_version in upgradable_version
299,006
get info
#!/usr/bin/env python3 # pylint: disable=C0103 """ Resolve DLL Dependencies """ import argparse from collections import deque from enum import Enum import logging import os import os.path import shutil from typing import Deque, Dict, List, Optional import pefile class LibraryKind(Enum): INPUT = 1 SYSTEM = 2 THIRDPARTY = 3 class Library: """ Library information """ def __init__(self, name: str, path: str, kind: LibraryKind, deps: List[str]): self.name = name self.path = path self.kind = kind self.deps = deps class LibraryNotFoundError(RuntimeError): pass class LibraryResolver: """ Resolve library paths and dependencies recursively """ def __init__(self, libdirs: List[str], ignore_missing: bool = False): self.libdirs = libdirs self.ignore_missing = ignore_missing self.kind_paths = self._make_system_paths() self.queue: Deque[str] = deque() self.found: Dict[str, Library] = dict() @staticmethod def _make_system_paths() -> List[str]: system_root = os.getenv("SystemRoot") if system_root: system_paths = [ os.path.join(system_root, "system32"), system_root ] logging.info("Using system path: %s", ", ".join(system_paths)) return system_paths logging.warning("%%SystemRoot%% not set") return [] def process(self, files: List[str]) -> None: """ Process input files """ for f in files: self.process_file(f) while len(self.queue) > 0: file_name = self.queue.popleft() if file_name in self.found: continue try: lib_info = self.METHOD_NAME(file_name) self.record(lib_info) except LibraryNotFoundError: if self.ignore_missing: logging.info("Can't find %s, ignoring", file_name) else: raise def process_file(self, path: str) -> None: """ Process single input file """ base_name = os.path.basename(path) deps = self.scan_dependencies(path) info = Library(base_name, path, LibraryKind.INPUT, deps) self.record(info) def record(self, info: Library) -> None: """ Record resolved library path, and queue for scanning its dependencies """ for dep in info.deps: self.queue.append(dep) self.found[info.name] = info def print_files(self) -> None: """ Print full paths for library dependencies """ for fi in self.found.values(): if fi.kind == LibraryKind.THIRDPARTY: print(fi.path) def copy(self, dest: str, no_overwrite: bool) -> None: """ Copy found library paths to destination folder """ for fi in self.found.values(): if fi.kind == LibraryKind.THIRDPARTY: dest_path = os.path.join(dest, fi.name) if os.path.exists(dest_path) and no_overwrite: logging.info("%s already exists in %s", fi.name, dest) else: logging.info("Copying %s", fi.path) shutil.copy(fi.path, dest_path) def METHOD_NAME(self, file_name, kind: int = LibraryKind.THIRDPARTY) -> Library: """ Fetch information about given library. """ logging.debug("Processing %s", file_name) system_lib = self.find_lib(file_name, self.kind_paths) if system_lib: logging.debug(" Found system library: %s", system_lib) return Library(file_name, system_lib, LibraryKind.SYSTEM, []) path = self.find_lib(file_name, self.libdirs) if path: logging.debug(" Found: %s", path) deps = self.scan_dependencies(path) logging.debug(" Dependencies: %s", " ".join(deps)) return Library(file_name, path, kind, deps) raise LibraryNotFoundError("Cannot find DLL {0}".format(file_name)) @staticmethod def scan_dependencies(file_name: str) -> List[str]: """ Find libraries that given file depends on. """ pe = pefile.PE(file_name) return [entry.dll.decode("utf-8") for entry in pe.DIRECTORY_ENTRY_IMPORT] @staticmethod def find_lib(name: str, dirs: List[str]) -> Optional[str]: """ Find library file in one of provided directories. Return None if library cannot be found. """ for d in dirs: path = os.path.join(d, name) if os.path.exists(path): return path return None def main(): """ Application entry point """ parser = argparse.ArgumentParser(description="Copy all DLLs") parser.add_argument("files", type=str, nargs="+", help="Files to scan") parser.add_argument("-L", "--libdir", type=str, action="append", help="Source directory containing library files") parser.add_argument("-d", "--dest", type=str, help="Destination directory") parser.add_argument("-V", "--verbose", type=str, action="store", nargs="?", default="warning", const="info", help="Verbosity level") parser.add_argument("--dry-run", action='store_true', help="Do not copy anything; print files that would be copied") parser.add_argument("--no-overwrite", action='store_true', help="Do not overwrite files") parser.add_argument("--ignore-missing", action="store_true", help="Ignore missing libraries") args = parser.parse_args() logging.basicConfig(level=getattr(logging, args.verbose.upper(), None), format="%(levelname)s %(message)s") resolver = LibraryResolver(args.libdir or [], ignore_missing=args.ignore_missing) resolver.process(args.files) if args.dry_run: resolver.print_files() else: resolver.copy(args.dest, args.no_overwrite) if __name__ == "__main__": main()
299,007
prop descriptions
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Connector(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "waterfall" _path_str = "waterfall.connector" _valid_props = {"line", "mode", "visible"} # line # ---- @property def line(self): """ The 'line' property is an instance of Line that may be specified as: - An instance of :class:`plotly.graph_objs.waterfall.connector.Line` - A dict of string/value properties that will be passed to the Line constructor Supported dict properties: color Sets the line color. dash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). width Sets the line width (in px). Returns ------- plotly.graph_objs.waterfall.connector.Line """ return self["line"] @line.setter def line(self, val): self["line"] = val # mode # ---- @property def mode(self): """ Sets the shape of connector lines. The 'mode' property is an enumeration that may be specified as: - One of the following enumeration values: ['spanning', 'between'] Returns ------- Any """ return self["mode"] @mode.setter def mode(self, val): self["mode"] = val # visible # ------- @property def visible(self): """ Determines if connector lines are drawn. The 'visible' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["visible"] @visible.setter def visible(self, val): self["visible"] = val # Self properties description # --------------------------- @property def METHOD_NAME(self): return """\ line :class:`plotly.graph_objects.waterfall.connector.Line` instance or dict with compatible properties mode Sets the shape of connector lines. visible Determines if connector lines are drawn. """ def __init__(self, arg=None, line=None, mode=None, visible=None, **kwargs): """ Construct a new Connector object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.waterfall.Connector` line :class:`plotly.graph_objects.waterfall.connector.Line` instance or dict with compatible properties mode Sets the shape of connector lines. visible Determines if connector lines are drawn. Returns ------- Connector """ super(Connector, self).__init__("connector") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.waterfall.Connector constructor must be a dict or an instance of :class:`plotly.graph_objs.waterfall.Connector`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("line", None) _v = line if line is not None else _v if _v is not None: self["line"] = _v _v = arg.pop("mode", None) _v = mode if mode is not None else _v if _v is not None: self["mode"] = _v _v = arg.pop("visible", None) _v = visible if visible is not None else _v if _v is not None: self["visible"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
299,008
test solo
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.modules.chef import salt.states.chef as chef from tests.support.mock import MagicMock, create_autospec, patch @pytest.fixture def configure_loader_modules(): return {chef: {"__salt__": {}}} @pytest.fixture( params=[ ("chef.client", chef.client, create_autospec(salt.modules.chef.client)), ("chef.solo", chef.solo, create_autospec(salt.modules.chef.solo)), ] ) def chef_state_and_mock_mod(request): mod_name, state, mock_mod = request.param with patch.dict(chef.__salt__, {mod_name: mock_mod}): yield state, mock_mod @pytest.fixture def test_mode(): with patch.dict(chef.__opts__, {"test": True}): yield @pytest.fixture def not_test_mode(): with patch.dict(chef.__opts__, {"test": False}): yield @pytest.fixture( params=[ "Chef Client finished, 1", "Chef Infra Client finished, 1", "Infra Phase complete, 1", ] ) def changed_output(request): yield request.param @pytest.fixture( params=[ "Chef Client finished, 0", "Chef Infra Client finished, 0", "Infra Phase complete, 0", ] ) def unchanged_output(request): yield request.param @pytest.fixture def successful_changed_output(changed_output, chef_state_and_mock_mod): _, mock_mod = chef_state_and_mock_mod mock_mod.return_value = {"retcode": 0, "stderr": "", "stdout": changed_output} yield @pytest.fixture def successful_unchanged_output(unchanged_output, chef_state_and_mock_mod): _, mock_mod = chef_state_and_mock_mod mock_mod.return_value = {"retcode": 0, "stderr": "", "stdout": unchanged_output} yield @pytest.fixture def unsuccessful_output(chef_state_and_mock_mod): _, mock_mod = chef_state_and_mock_mod mock_mod.return_value = {"retcode": 1, "stderr": "", "stdout": ""} yield def test_client(): """ Test to run chef-client """ name = "my-chef-run" ret = {"name": name, "result": False, "changes": {}, "comment": ""} mock = MagicMock(return_value={"retcode": 1, "stdout": "", "stderr": "error"}) with patch.dict(chef.__salt__, {"chef.client": mock}): with patch.dict(chef.__opts__, {"test": True}): comt = "\nerror" ret.update({"comment": comt}) assert chef.client(name) == ret def METHOD_NAME(): """ Test to run chef-solo """ name = "my-chef-run" ret = {"name": name, "result": False, "changes": {}, "comment": ""} mock = MagicMock(return_value={"retcode": 1, "stdout": "", "stderr": "error"}) with patch.dict(chef.__salt__, {"chef.solo": mock}): with patch.dict(chef.__opts__, {"test": True}): comt = "\nerror" ret.update({"comment": comt}) assert chef.solo(name) == ret def test_when_testing_and_successful_changed_output_result_should_be_None( test_mode, successful_changed_output, chef_state_and_mock_mod ): state, _ = chef_state_and_mock_mod ret = state(name="fnord") assert ret["result"] is None def test_when_testing_and_successful_unchanged_output_result_should_be_True( test_mode, successful_unchanged_output, chef_state_and_mock_mod ): state, _ = chef_state_and_mock_mod ret = state(name="fnord") assert ret["result"] is True def test_when_not_testing_and_successful_changed_output_result_should_be_True( not_test_mode, successful_changed_output, chef_state_and_mock_mod ): state, _ = chef_state_and_mock_mod ret = state(name="fnord") assert ret["result"] is True def test_when_not_testing_and_successful_unchanged_output_result_should_be_True( not_test_mode, successful_unchanged_output, chef_state_and_mock_mod ): state, _ = chef_state_and_mock_mod ret = state(name="fnord") assert ret["result"] is True def test_when_not_testing_and_unsuccessful_output_result_should_be_False( not_test_mode, unsuccessful_output, chef_state_and_mock_mod ): state, _ = chef_state_and_mock_mod ret = state(name="fnord") assert ret["result"] is False
299,009
export ownertrust
# # This file is part of python-gnupg, a Python interface to GnuPG. # Copyright © 2013 Isis Lovecruft, <isis@leap.se> 0xA3ADB67A2CDB8B35 # © 2013 Andrej B. # © 2013 LEAP Encryption Access Project # © 2008-2012 Vinay Sajip # © 2005 Steve Traugott # © 2004 A.M. Kuchling # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the included LICENSE file for details. """Functions for handling trustdb and trust calculations. The functions within this module take an instance of :class:`gnupg.GPGBase` or a suitable subclass as their first argument. """ import os from . import _util from ._util import log def _create_trustdb(cls): # type: ignore[no-untyped-def] """Create the trustdb file in our homedir, if it doesn't exist.""" trustdb = os.path.join(cls.homedir, "trustdb.gpg") if not os.path.isfile(trustdb): log.info( "GnuPG complained that your trustdb file was missing. {}".format( "This is likely due to changing to a new homedir." ) ) log.info("Creating trustdb.gpg file in your GnuPG homedir.") cls.fix_trustdb(trustdb) def METHOD_NAME(cls, trustdb=None): # type: ignore[no-untyped-def] """Export ownertrust to a trustdb file. If there is already a file named :file:`trustdb.gpg` in the current GnuPG homedir, it will be renamed to :file:`trustdb.gpg.bak`. :param string trustdb: The path to the trustdb.gpg file. If not given, defaults to ``'trustdb.gpg'`` in the current GnuPG homedir. """ if trustdb is None: trustdb = os.path.join(cls.homedir, "trustdb.gpg") try: os.rename(trustdb, trustdb + ".bak") except OSError as err: log.debug(str(err)) export_proc = cls._open_subprocess(["--export-ownertrust"]) tdb = open(trustdb, "wb") _util._threaded_copy_data(export_proc.stdout, tdb) export_proc.wait() def import_ownertrust(cls, trustdb=None): # type: ignore[no-untyped-def] """Import ownertrust from a trustdb file. :param str trustdb: The path to the trustdb.gpg file. If not given, defaults to :file:`trustdb.gpg` in the current GnuPG homedir. """ if trustdb is None: trustdb = os.path.join(cls.homedir, "trustdb.gpg") import_proc = cls._open_subprocess(["--import-ownertrust"]) try: tdb = open(trustdb, "rb") except OSError: log.error("trustdb file %s does not exist!" % trustdb) _util._threaded_copy_data(tdb, import_proc.stdin) import_proc.wait() def fix_trustdb(cls, trustdb=None): # type: ignore[no-untyped-def] """Attempt to repair a broken trustdb.gpg file. GnuPG>=2.0.x has this magical-seeming flag: `--fix-trustdb`. You'd think it would fix the the trustdb. Hah! It doesn't. Here's what it does instead:: (gpg)~/code/python-gnupg $ gpg2 --fix-trustdb gpg: You may try to re-create the trustdb using the commands: gpg: cd ~/.gnupg gpg: gpg2 --export-ownertrust > otrust.tmp gpg: rm trustdb.gpg gpg: gpg2 --import-ownertrust < otrust.tmp gpg: If that does not work, please consult the manual Brilliant piece of software engineering right there. :param str trustdb: The path to the trustdb.gpg file. If not given, defaults to :file:`trustdb.gpg` in the current GnuPG homedir. """ if trustdb is None: trustdb = os.path.join(cls.homedir, "trustdb.gpg") export_proc = cls._open_subprocess(["--export-ownertrust"]) import_proc = cls._open_subprocess(["--import-ownertrust"]) _util._threaded_copy_data(export_proc.stdout, import_proc.stdin) export_proc.wait() import_proc.wait()
299,010
test operator cast
# Copyright (c) 2019-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import nvidia.dali.fn as fn import nvidia.dali.types as types from nose.tools import nottest from nvidia.dali import pipeline_def from test_utils import np_type_to_dali import itertools from nose2.tools import params def ref_cast(x, dtype): if np.issubdtype(dtype, np.integer): lo = np.iinfo(dtype).min hi = np.iinfo(dtype).max if np.issubdtype(x.dtype, np.floating): x = np.round(x) return x.clip(lo, hi).astype(dtype) else: return x.astype(dtype) def random_shape(rng, ndim: int, max_size: int): if ndim == 0: return [] max_size = int(max_size ** (1 / ndim)) return list(rng.integers(1, max_size, [ndim])) def replace_with_empty_volumes(rng, input, empty_volume_policy): """Replaces samples with 0-volumed ones if possible. Parameters ---------- rng : rng input : List of np.array Batch to process empty_volume_policy : str one of "left", "right, "middle", "mixed", "all", to indicate if the batch suffix, prefix, infix or all of them should be randomly replaced with 0-volumed samples Returns ------- List of np.array """ if empty_volume_policy is None: return input if len(input[0].shape) == 0: return input if empty_volume_policy == "mixed": left = replace_with_empty_volumes(rng, input, "left") left_and_mid = replace_with_empty_volumes(rng, left, "middle") return replace_with_empty_volumes(rng, left_and_mid, "right") if empty_volume_policy == "all": start = 0 end = len(input) elif empty_volume_policy == "left": start = 0 end = rng.integers(1, len(input) // 3) elif empty_volume_policy == "right": start = rng.integers(len(input) * 2 // 3, len(input) - 1) end = len(input) elif empty_volume_policy == "middle": start = rng.integers(1 + len(input) // 3, len(input) * 2 // 3) end = rng.integers(start + 1, len(input) - 1) for i in range(start, end): shape = list(input[i].shape) shape[0] = 0 input[i] = np.zeros(dtype=input[i].dtype, shape=shape) return input def generate(rng, ndim: int, batch_size: int, in_dtype: np.dtype, out_dtype: np.dtype, empty_volume_policy: str): lo, hi = -1000, 1000 if np.issubdtype(out_dtype, np.integer): lo = np.iinfo(out_dtype).min hi = np.iinfo(out_dtype).max if hi < np.iinfo(np.int64).max: r = hi - lo hi += r // 2 lo -= r // 2 if np.issubdtype(in_dtype, np.integer): lo = max(np.iinfo(in_dtype).min, lo) hi = min(np.iinfo(in_dtype).max, hi) else: lo = max(-np.finfo(in_dtype).max, lo) hi = min(np.finfo(in_dtype).max, hi) max_size = 100000 // batch_size out = [rng.uniform(lo, hi, size=random_shape(rng, ndim, max_size)).astype(in_dtype) for _ in range(batch_size)] out = replace_with_empty_volumes(rng, out, empty_volume_policy) if np.issubdtype(in_dtype, np.floating) and np.issubdtype(out_dtype, np.integer): for x in out: # avoid exactly halfway numbers - rounding is different for CPU and GPU halfway = x[x - np.floor(x) == 0.5] x[x - np.floor(x) == 0.5] = np.nextafter(halfway, np.Infinity) return out rng = np.random.default_rng(1234) @nottest def METHOD_NAME(ndim, batch_size, in_dtype, out_dtype, device, empty_volume_policy=None): def src(): return generate(rng, ndim, batch_size, in_dtype, out_dtype, empty_volume_policy) @pipeline_def(batch_size=batch_size, num_threads=4, device_id=types.CPU_ONLY_DEVICE_ID if device == 'cpu' else 0) def cast_pipe(): inp = fn.external_source(src) inp_dev = inp.gpu() if device == 'gpu' else inp return inp, fn.cast(inp_dev, dtype=np_type_to_dali(out_dtype)) pipe = cast_pipe() pipe.build() for _ in range(10): inp, out = pipe.run() if device == 'gpu': out = out.as_cpu() ref = [ref_cast(np.array(x), out_dtype) for x in inp] # work around a bug in numpy: when the argument is a scalar fp32 or fp16, nextafter # promotes it to fp64, resulting in insufficient epsilon - we want an epsilon of the # type specified in out_dtype eps = 0 if np.issubdtype(out_dtype, np.integer) else \ (np.nextafter(out_dtype([1]), 2) - 1.0)[0] for i in range(batch_size): if not np.allclose(out[i], ref[i], eps): matI = np.array(inp[i]) matO = np.array(out[i]) matR = ref[i] mask = np.logical_not(np.isclose(matO, matR, eps)) print(f"At sample {i}:\nI:\n{matI}\nO\n{matO}\nR\n{matR}") print(f"Differences at {mask}:\nI:\n{matI[mask]}\nO\n{matO[mask]}\nR\n{matR[mask]}") print(f"Result: {np.count_nonzero(mask)} wrong values out of {mask.size}.") assert np.array_equal(out[i], ref[i]) def test_operator_cast(): types = [np.uint8, np.int8, np.uint16, np.int16, np.uint32, np.int32, np.uint64, np.int64, np.float16, np.float32] for device in ['cpu', 'gpu']: for in_type in types: for out_type in types: ndim = rng.integers(0, 4) batch_size = rng.integers(1, 11) yield METHOD_NAME, ndim, batch_size, in_type, out_type, device def test_operator_cast_empty_volumes(): types = [np.uint8, np.int32, np.float32] for device in ['cpu', 'gpu']: for in_type in types: for out_type in types: ndim = rng.integers(0, 4) batch_size = rng.integers(12, 64) for empty_volume_policy in [ rng.choice(["left", "right", "middle", "mixed"]), "all" ]: yield (METHOD_NAME, ndim, batch_size, in_type, out_type, device, empty_volume_policy) @params(*itertools.product((('cpu', 'cpu'), ('gpu', 'cpu'), ('gpu', 'gpu')), (np.uint8, np.int32, np.float32), (np.uint8, np.int32, np.float32))) def test_cast_like(devices, dtype_in, dtype_out): @pipeline_def(batch_size=1, num_threads=4, device_id=0) def cast_pipe(): device_left, device_right = devices data0 = fn.random.uniform(range=[0, 255], dtype=np_type_to_dali(dtype_in), device=device_left) data1 = fn.random.uniform(range=[0, 255], dtype=np_type_to_dali(dtype_out), device=device_right) return fn.cast_like(data0, data1) p = cast_pipe() p.build() out, = p.run() expected_type = np_type_to_dali(dtype_out) assert out.dtype == expected_type, f"{out.dtype} != {expected_type}"
299,011
has strip suffix
# # Removes unused glyphs # from mojo.roboFont import version SC_ROMAN = [ "A.smcp", "B.smcp", "C.smcp", "D.smcp", "E.smcp", "F.smcp", "G.smcp", "H.smcp", "I.smcp", "J.smcp", "K.smcp", "L.smcp", "M.smcp", "N.smcp", "O.smcp", "P.smcp", "Q.smcp", "R.smcp", "S.smcp", "T.smcp", "U.smcp", "V.smcp", "W.smcp", "X.smcp", "Y.smcp", "Z.smcp", "AE.smcp", "AEacute.smcp", "Aacute.smcp", "Abreve.smcp", "Acircumflex.smcp", "Adieresis.smcp", "Agrave.smcp", "Alpha.smcp", "Alphatonos.smcp", "Amacron.smcp", "Aogonek.smcp", "Aogonek.smcp.NAV", "Aring.smcp", "Aringacute.smcp", "Atilde.smcp", "Beta.smcp", "Cacute.smcp", "Ccaron.smcp", "Ccedilla.smcp", "Ccircumflex.smcp", "Chi.smcp", "Dcaron.smcp", "Dcroat.smcp", "Delta.smcp", "Eacute.smcp", "Ebreve.smcp", "Ecaron.smcp", "Ecircumflex.smcp", "Edieresis.smcp", "Edotaccent.smcp", "Egrave.smcp", "Emacron.smcp", "Eng.smcp", "Eogonek.smcp", "Eogonek.smcp.NAV", "Epsilon.smcp", "Epsilontonos.smcp", "Eta.smcp", "Etatonos.smcp", "Eth.smcp", "Gamma.smcp", "Gbreve.smcp", "Gcircumflex.smcp", "Gcommaaccent.smcp", "Germandbls.smcp", "Hbar.smcp", "Hcircumflex.smcp", "IJ.smcp", "Iacute.smcp", "Ibreve.smcp", "Icircumflex.smcp", "Idieresis.smcp", "Igrave.smcp", "Imacron.smcp", "Iogonek.smcp", "Iota.smcp", "Iotadieresis.smcp", "Iotatonos.smcp", "Itilde.smcp", "Jcircumflex.smcp", "Kappa.smcp", "Kcommaaccent.smcp", "Lacute.smcp", "Lambda.smcp", "Lcaron.smcp", "Lcommaaccent.smcp", "Ldot.smcp", "Lslash.smcp", "Nacute.smcp", "Ncaron.smcp", "Ncommaaccent.smcp", "Ntilde.smcp", "Nu.smcp", "OE.smcp", "Oacute.smcp", "Obreve.smcp", "Ocircumflex.smcp", "Odieresis.smcp", "Ograve.smcp", "Ohungarumlaut.smcp", "Omacron.smcp", "Omega.smcp", "Omegatonos.smcp", "Omicron.smcp", "Omicrontonos.smcp", "Oogonek.smcp", "Oogonek.smcp.NAV", "Oslash.smcp", "Oslashacute.smcp", "Otilde.smcp", "Phi.smcp", "Pi.smcp", "Psi.smcp", "Racute.smcp", "Rcaron.smcp", "Rcommaaccent.smcp", "Rho.smcp", "Sacute.smcp", "Scaron.smcp", "Scedilla.smcp", "Scircumflex.smcp", "Sigma.smcp", "Tau.smcp", "Tbar.smcp", "Tcaron.smcp", "Theta.smcp", "Thorn.smcp", "Uacute.smcp", "Ubreve.smcp", "Ucircumflex.smcp", "Udieresis.smcp", "Ugrave.smcp", "Uhungarumlaut.smcp", "Umacron.smcp", "Uogonek.smcp", "Upsilon.smcp", "Upsilondieresis.smcp", "Upsilontonos.smcp", "Uring.smcp", "Utilde.smcp", "Wacute.smcp", "Wcircumflex.smcp", "Wdieresis.smcp", "Wgrave.smcp", "Xi.smcp", "Yacute.smcp", "Ycircumflex.smcp", "Ydieresis.smcp", "Ygrave.smcp", "Zacute.smcp", "Zcaron.smcp", "Zdotaccent.smcp", "Zeta.smcp", "ampersand.smcp", "uni010A.smcp", "uni0120.smcp", "uni0162.smcp", "Scommaaccent.smcp", "Tcommaaccent.smcp", "uni037F.smcp" ] SC_SET1 = [ "zero.smcp", "one.smcp", "two.smcp", "three.smcp", "four.smcp", "five.smcp", "six.smcp", "seven.smcp", "eight.smcp", "nine.smcp", "Euro.smcp", "Idotaccent.smcp", "Mu.smcp", "dollar.smcp", "lira.smcp", "sterling.smcp", "uni0401.smcp", "uni0402.smcp", "uni0403.smcp", "uni0404.smcp", "uni0405.smcp", "uni0406.smcp", "uni0407.smcp", "uni0408.smcp", "uni0409.smcp", "uni040A.smcp", "uni040B.smcp", "uni040C.smcp", "uni040E.smcp", "uni040F.smcp", "uni0410.smcp", "uni0411.smcp", "uni0412.smcp", "uni0413.smcp", "uni0414.smcp", "uni0415.smcp", "uni0416.smcp", "uni0417.smcp", "uni0418.smcp", "uni0419.smcp", "uni041A.smcp", "uni041B.smcp", "uni041C.smcp", "uni041D.smcp", "uni041E.smcp", "uni041F.smcp", "uni0420.smcp", "uni0421.smcp", "uni0422.smcp", "uni0423.smcp", "uni0424.smcp", "uni0425.smcp", "uni0426.smcp", "uni0427.smcp", "uni0428.smcp", "uni0429.smcp", "uni042A.smcp", "uni042B.smcp", "uni042C.smcp", "uni042D.smcp", "uni042E.smcp", "uni042F.smcp", "uni0490.smcp", "uni0492.smcp", "uni0496.smcp", "uni0498.smcp", "uni049A.smcp", "uni049C.smcp", "uni04A0.smcp", "uni04A2.smcp", "uni04A8.smcp", "uni04AA.smcp", "uni04AE.smcp", "uni04B0.smcp", "uni04B2.smcp", "uni04B4.smcp", "uni04B8.smcp", "uni04BA.smcp", "uni04BC.smcp", "uni04BE.smcp", "uni04D8.smcp", "uni04E0.smcp", "uni04E2.smcp", "uni04E8.smcp", "uni04EE.smcp", "uni20B4.smcp", "uni20B8.smcp", "uni20BD.smcp", "uni2116.smcp", "yen.smcp" ] SC_SET2 = [ "I.smcp", "Sigma.smcp", "Mu.smcp", "uni0410.smcp", "uni0411.smcp", "uni0412.smcp", "uni0413.smcp", "uni0414.smcp", "uni0415.smcp", "uni0416.smcp", "uni0417.smcp", "uni0418.smcp", "uni0419.smcp", "uni041A.smcp", "uni041B.smcp", "uni041C.smcp", "uni041D.smcp", "uni041E.smcp", "uni041F.smcp", "uni0420.smcp", "uni0421.smcp", "uni0422.smcp", "uni0423.smcp", "uni0424.smcp", "uni0425.smcp", "uni0426.smcp", "uni0427.smcp", "uni0428.smcp", "uni0429.smcp", "uni042A.smcp", "uni042B.smcp", "uni042C.smcp", "uni042D.smcp", "uni042E.smcp", "uni042F.smcp", "uni0401.smcp", "uni0402.smcp", "uni0403.smcp", "uni0404.smcp", "uni0405.smcp", "uni0406.smcp", "uni0407.smcp", "uni0408.smcp", "uni0409.smcp", "uni040A.smcp", "uni040B.smcp", "uni040C.smcp", "uni040E.smcp", "uni040F.smcp", "uni0490.smcp", "uni0492.smcp", "uni0496.smcp", "uni0498.smcp", "uni049A.smcp", "uni049C.smcp", "uni04A0.smcp", "uni04A2.smcp", "uni04A8.smcp", "uni04AA.smcp", "uni04AE.smcp", "uni04B0.smcp", "uni04B2.smcp", "uni04B4.smcp", "uni04B8.smcp", "uni04BA.smcp", "uni04BC.smcp", "uni04BE.smcp", "uni04D8.smcp", "uni04E0.smcp", "uni04E2.smcp", "uni04E8.smcp", "uni04EE.smcp" ] STRIP_NAME_SET = set(SC_ROMAN).union(SC_SET1).union(SC_SET2) STRIP_SUFFIXES = ( '.smcp', '.unic', '.alt', '.alt2', '.ss06', '.ss07', '.onum', '.pnum', '.tnum' ) def METHOD_NAME(g): name = g.name for suffix in STRIP_SUFFIXES: if str.endswith(name, suffix): return True return False if __name__ == "__main__": font = CurrentFont() if font is not None: for g in font: if g.name in STRIP_NAME_SET or METHOD_NAME(g): if g.unicode is not None: # glyph maps to a codepoint -- keep it continue print 'Removing "%s"' % g.name font.removeGlyph(g.name) font.update() else: print "No fonts open" print "Done"
299,012
test search community records
# -*- coding: utf-8 -*- # # Copyright (C) 2023 CERN. # # Invenio-RDM-Records is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """Test community records service.""" import pytest from invenio_records_resources.services.errors import PermissionDeniedError from marshmallow import ValidationError from invenio_rdm_records.proxies import ( current_community_records_service, current_rdm_records_service, ) from invenio_rdm_records.records import RDMRecord @pytest.fixture() def service(): """Get the current community records service.""" return current_community_records_service def test_remove_record_from_community_success( curator, community, record_community, service ): """Test removal of a record from a community.""" record = record_community.create_record() data = {"records": [{"id": record.pid.pid_value}]} errors = service.delete(curator.identity, str(community.id), data) assert errors == [] def test_remove_records_from_community_success( curator, community, record_community, service ): """Test removal of a multiple records from a community.""" record1 = record_community.create_record() record2 = record_community.create_record() record3 = record_community.create_record() data = { "records": [ {"id": record1.pid.pid_value}, {"id": record2.pid.pid_value}, {"id": record3.pid.pid_value}, ] } errors = service.delete(curator.identity, str(community.id), data) assert errors == [] def test_missing_permission(test_user, community, record_community, service): """Test missing permissions to delete.""" record = record_community.create_record() data = {"records": [{"id": record.pid.pid_value}]} with pytest.raises(PermissionDeniedError): service.delete(test_user.identity, str(community.id), data) def test_curator_permission(curator, community, record_community, service): """Test curator permissions to delete.""" record = record_community.create_record() data = {"records": [{"id": record.pid.pid_value}]} errors = service.delete(curator.identity, str(community.id), data) assert errors == [] def test_remove_non_existing_record(curator, community, service): """Test error on removing a non-existing record from a community.""" data = {"records": [{"id": "wrong-id"}]} errors = service.delete(curator.identity, str(community.id), data) assert len(errors) == 1 assert errors[0]["message"] == "The record does not exist." def test_remove_record_of_other_community( db, curator, community, community2, record_community, service ): """Test error on removing a record that belongs to another community.""" def add_to_community2(record): record.parent.communities.remove(community._record) record.parent.communities.add(community2._record, default=False) record.parent.commit() record.commit() db.session.commit() current_rdm_records_service.indexer.index(record) RDMRecord.index.refresh() return record record_comm2 = record_community.create_record() record_comm2 = add_to_community2(record_comm2) data = {"records": [{"id": record_comm2.pid.pid_value}]} errors = service.delete(curator.identity, str(community.id), data) assert len(errors) == 1 assert "not included in the community" in errors[0]["message"] def test_remove_records_from_communities_success_w_errors( curator, community, record_community, service ): """Test removal of records from communities with errors.""" record = record_community.create_record() correct_data = [{"id": record.pid.pid_value}] wrong_data = [{"id": "wrong-id"}, {"id": "wrong-id2"}] data = {"records": correct_data + wrong_data} errors = service.delete(curator.identity, str(community.id), data) assert len(errors) == 2 def test_remove_too_many_records(curator, community, record_community, service): """Test removal of too many records from a community.""" random_record = {"id": "random-id"} lots_of_records = [] while len(lots_of_records) <= service.config.max_number_of_removals: lots_of_records.append(random_record) data = {"records": lots_of_records} with pytest.raises(ValidationError): service.delete(curator.identity, str(community.id), data) def test_remove_w_empty_payload(curator, community, service): """Test removal of records from communities with empty payload.""" data = {"records": []} with pytest.raises(ValidationError): service.delete(curator.identity, str(community.id), data) def METHOD_NAME( community, record_community, service, anyuser_identity, uploader ): """Test search for records in a community.""" results = service.search( anyuser_identity, community_id=str(community.id), ) assert results.to_dict()["hits"]["total"] == 0 record_community.create_record() record_community.create_record() record_community.create_record() for identity in [anyuser_identity, uploader.identity]: results = service.search( identity, community_id=str(community.id), ) assert results.to_dict()["hits"]["total"] == 3
299,013
id
# coding=utf-8 # *** WARNING: this file was generated by pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs __all__ = [ 'GetScopeMapResult', 'AwaitableGetScopeMapResult', 'get_scope_map', 'get_scope_map_output', ] @pulumi.output_type class GetScopeMapResult: """ An object that represents a scope map for a container registry. """ def __init__(__self__, actions=None, creation_date=None, description=None, METHOD_NAME=None, name=None, provisioning_state=None, system_data=None, type=None): if actions and not isinstance(actions, list): raise TypeError("Expected argument 'actions' to be a list") pulumi.set(__self__, "actions", actions) if creation_date and not isinstance(creation_date, str): raise TypeError("Expected argument 'creation_date' to be a str") pulumi.set(__self__, "creation_date", creation_date) if description and not isinstance(description, str): raise TypeError("Expected argument 'description' to be a str") pulumi.set(__self__, "description", description) if METHOD_NAME and not isinstance(METHOD_NAME, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", METHOD_NAME) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if provisioning_state and not isinstance(provisioning_state, str): raise TypeError("Expected argument 'provisioning_state' to be a str") pulumi.set(__self__, "provisioning_state", provisioning_state) if system_data and not isinstance(system_data, dict): raise TypeError("Expected argument 'system_data' to be a dict") pulumi.set(__self__, "system_data", system_data) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) @property @pulumi.getter def actions(self) -> Sequence[str]: """ The list of scoped permissions for registry artifacts. E.g. repositories/repository-name/content/read, repositories/repository-name/metadata/write """ return pulumi.get(self, "actions") @property @pulumi.getter(name="creationDate") def creation_date(self) -> str: """ The creation date of scope map. """ return pulumi.get(self, "creation_date") @property @pulumi.getter def description(self) -> Optional[str]: """ The user friendly description of the scope map. """ return pulumi.get(self, "description") @property @pulumi.getter def METHOD_NAME(self) -> str: """ The resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> str: """ The name of the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ Provisioning state of the resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="systemData") def system_data(self) -> 'outputs.SystemDataResponse': """ Metadata pertaining to creation and last modification of the resource. """ return pulumi.get(self, "system_data") @property @pulumi.getter def type(self) -> str: """ The type of the resource. """ return pulumi.get(self, "type") class AwaitableGetScopeMapResult(GetScopeMapResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetScopeMapResult( actions=self.actions, creation_date=self.creation_date, description=self.description, METHOD_NAME=self.METHOD_NAME, name=self.name, provisioning_state=self.provisioning_state, system_data=self.system_data, type=self.type) def get_scope_map(registry_name: Optional[str] = None, resource_group_name: Optional[str] = None, scope_map_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetScopeMapResult: """ Gets the properties of the specified scope map. :param str registry_name: The name of the container registry. :param str resource_group_name: The name of the resource group. The name is case insensitive. :param str scope_map_name: The name of the scope map. """ __args__ = dict() __args__['registryName'] = registry_name __args__['resourceGroupName'] = resource_group_name __args__['scopeMapName'] = scope_map_name opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('azure-native:containerregistry/v20230601preview:getScopeMap', __args__, opts=opts, typ=GetScopeMapResult).value return AwaitableGetScopeMapResult( actions=pulumi.get(__ret__, 'actions'), creation_date=pulumi.get(__ret__, 'creation_date'), description=pulumi.get(__ret__, 'description'), METHOD_NAME=pulumi.get(__ret__, 'id'), name=pulumi.get(__ret__, 'name'), provisioning_state=pulumi.get(__ret__, 'provisioning_state'), system_data=pulumi.get(__ret__, 'system_data'), type=pulumi.get(__ret__, 'type')) @_utilities.lift_output_func(get_scope_map) def get_scope_map_output(registry_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, scope_map_name: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetScopeMapResult]: """ Gets the properties of the specified scope map. :param str registry_name: The name of the container registry. :param str resource_group_name: The name of the resource group. The name is case insensitive. :param str scope_map_name: The name of the scope map. """ ...
299,014
test health check servicer get successful
from unittest.mock import MagicMock, call, patch import pytest from grpc.health.v1 import health_pb2 from kaskada.health.health_check_servicer import HealthCheckServicer @patch("kaskada.health.health_check_client.HealthCheckClientFactory") @patch("kaskada.health.health_check_client.HealthCheckClient") def test_health_check_servicer_check_successful(client_factory, client): client_factory.get_client = MagicMock(return_value=client) client.check = MagicMock( return_value=health_pb2.HealthCheckResponse.ServingStatus.SERVING ) servicer = HealthCheckServicer(client_factory=client_factory) servicer.add_service("test_service", "test_endpoint", True) assert servicer.check() == health_pb2.HealthCheckResponse.ServingStatus.SERVING client_factory.get_client.assert_called_once_with("test_endpoint", True) client.check.assert_called_once() @patch("kaskada.health.health_check_client.HealthCheckClientFactory") @patch("kaskada.health.health_check_client.HealthCheckClient") def test_health_check_servicer_check_unknown_status(client_factory, client): client_factory.get_client = MagicMock(return_value=client) client.check = MagicMock( return_value=health_pb2.HealthCheckResponse.ServingStatus.UNKNOWN ) servicer = HealthCheckServicer(client_factory=client_factory) servicer.add_service("test_service", "test_endpoint", True) assert servicer.check() == health_pb2.HealthCheckResponse.ServingStatus.UNKNOWN client_factory.get_client.assert_called_once_with("test_endpoint", True) client.check.assert_called_once() @patch("kaskada.health.health_check_client.HealthCheckClientFactory") @patch("kaskada.health.health_check_client.HealthCheckClient") @patch("kaskada.health.health_check_client.HealthCheckClient") def test_health_check_servicer_check_multiple_clients_successful( client_factory, client, client_2 ): client_factory.get_client.side_effect = [client, client_2] client.check = MagicMock( return_value=health_pb2.HealthCheckResponse.ServingStatus.SERVING ) client_2.check = MagicMock( return_value=health_pb2.HealthCheckResponse.ServingStatus.SERVING ) servicer = HealthCheckServicer(client_factory=client_factory) servicer.add_service("test_service", "test_endpoint", True) servicer.add_service("test_service_2", "test_endpoint_2", False) assert servicer.check() == health_pb2.HealthCheckResponse.ServingStatus.SERVING client_factory.get_client.assert_has_calls( [call("test_endpoint", True), call("test_endpoint_2", False)] ) client.check.assert_called_once() client_2.check.assert_called_once() @patch("kaskada.health.health_check_client.HealthCheckClientFactory") @patch("kaskada.health.health_check_client.HealthCheckClient") @patch("kaskada.health.health_check_client.HealthCheckClient") def test_health_check_servicer_multiple_clients_one_unsuccessful( client_factory, client, client_2 ): """Tests the servicer with multiple clients where only one reports not ready/UNKNOWN. The servicer's job is to aggregate the worst case health scenario and should report with the get method. """ client_factory.get_client.side_effect = [client, client_2] client.check = MagicMock( return_value=health_pb2.HealthCheckResponse.ServingStatus.SERVING ) client_2.check = MagicMock( return_value=health_pb2.HealthCheckResponse.ServingStatus.UNKNOWN ) servicer = HealthCheckServicer(client_factory=client_factory) servicer.add_service("test_service", "test_endpoint", True) servicer.add_service("test_service_2", "test_endpoint_2", False) assert servicer.check() == health_pb2.HealthCheckResponse.ServingStatus.UNKNOWN client_factory.get_client.assert_has_calls( [call("test_endpoint", True), call("test_endpoint_2", False)] ) client.check.assert_called_once() client_2.check.assert_called_once() assert servicer.get() == health_pb2.HealthCheckResponse.ServingStatus.UNKNOWN assert ( servicer.get(service_name="test_service") == health_pb2.HealthCheckResponse.ServingStatus.SERVING ) assert ( servicer.get(service_name="test_service_2") == health_pb2.HealthCheckResponse.ServingStatus.UNKNOWN ) @patch("kaskada.health.health_check_client.HealthCheckClientFactory") def METHOD_NAME(client_factory): """By default the health check servicer should return successful/serving.""" servicer = HealthCheckServicer(client_factory=client_factory) assert servicer.get() == health_pb2.HealthCheckResponse.ServingStatus.SERVING @patch("kaskada.health.health_check_client.HealthCheckClientFactory") @patch("kaskada.health.health_check_client.HealthCheckClient") def test_health_check_servicer_get_default(client_factory, client): """Tests the get method uses the latest checked health status by adding an unhealthy client. Prior to checking the health, the status should be SERVING. Checking will return UNKNOWN as a mock. After the status should be UNKNOWN """ servicer = HealthCheckServicer(client_factory=client_factory) client_factory.get_client = MagicMock(return_value=client) client.check = MagicMock( return_value=health_pb2.HealthCheckResponse.ServingStatus.UNKNOWN ) servicer = HealthCheckServicer(client_factory=client_factory) servicer.add_service("test_service", "test_endpoint", True) assert servicer.get() == health_pb2.HealthCheckResponse.ServingStatus.SERVING servicer.check() assert servicer.get() == health_pb2.HealthCheckResponse.ServingStatus.UNKNOWN
299,015
test config proxy instance override
# (C) Datadog, Inc. 2022-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from collections import OrderedDict import mock import pytest from requests.exceptions import ConnectTimeout, ProxyError from datadog_checks.base.utils.http import RequestsWrapper from datadog_checks.dev import EnvVars pytestmark = [pytest.mark.unit] def test_config_default(): instance = {} init_config = {} http = RequestsWrapper(instance, init_config) assert http.options['proxies'] is None assert http.no_proxy_uris is None def test_config_proxy_agent(): with mock.patch( 'datadog_checks.base.stubs.datadog_agent.get_config', return_value={'http': 'http_host', 'https': 'https_host', 'no_proxy': 'uri1,uri2;uri3,uri4'}, ): instance = {} init_config = {} http = RequestsWrapper(instance, init_config) assert http.options['proxies'] == {'http': 'http_host', 'https': 'https_host'} assert http.no_proxy_uris == ['uri1', 'uri2', 'uri3', 'uri4'] def test_config_proxy_init_config_override(): with mock.patch( 'datadog_checks.base.stubs.datadog_agent.get_config', return_value={'http': 'unused', 'https': 'unused', 'no_proxy': 'unused'}, ): instance = {} init_config = {'proxy': {'http': 'http_host', 'https': 'https_host', 'no_proxy': 'uri1,uri2;uri3,uri4'}} http = RequestsWrapper(instance, init_config) assert http.options['proxies'] == {'http': 'http_host', 'https': 'https_host'} assert http.no_proxy_uris == ['uri1', 'uri2', 'uri3', 'uri4'] def METHOD_NAME(): with mock.patch( 'datadog_checks.base.stubs.datadog_agent.get_config', return_value={'http': 'unused', 'https': 'unused', 'no_proxy': 'unused'}, ): instance = {'proxy': {'http': 'http_host', 'https': 'https_host', 'no_proxy': 'uri1,uri2;uri3,uri4'}} init_config = {'proxy': {'http': 'unused', 'https': 'unused', 'no_proxy': 'unused'}} http = RequestsWrapper(instance, init_config) assert http.options['proxies'] == {'http': 'http_host', 'https': 'https_host'} assert http.no_proxy_uris == ['uri1', 'uri2', 'uri3', 'uri4'] def test_config_no_proxy_as_list(): with mock.patch( 'datadog_checks.base.stubs.datadog_agent.get_config', return_value={'http': 'http_host', 'https': 'https_host', 'no_proxy': ['uri1', 'uri2', 'uri3', 'uri4']}, ): instance = {} init_config = {} http = RequestsWrapper(instance, init_config) assert http.options['proxies'] == {'http': 'http_host', 'https': 'https_host'} assert http.no_proxy_uris == ['uri1', 'uri2', 'uri3', 'uri4'] def test_config_proxy_skip(): instance = {'proxy': {'http': 'unused', 'https': 'unused', 'no_proxy': 'unused'}, 'skip_proxy': True} init_config = {'proxy': {'http': 'unused', 'https': 'unused', 'no_proxy': 'unused'}} http = RequestsWrapper(instance, init_config) assert http.options['proxies'] == {'http': '', 'https': ''} assert http.no_proxy_uris is None def test_config_proxy_skip_init_config(): instance = {'proxy': {'http': 'unused', 'https': 'unused', 'no_proxy': 'unused'}} init_config = {'proxy': {'http': 'unused', 'https': 'unused', 'no_proxy': 'unused'}, 'skip_proxy': True} http = RequestsWrapper(instance, init_config) assert http.options['proxies'] == {'http': '', 'https': ''} assert http.no_proxy_uris is None def test_proxy_env_vars_skip(): instance = {'skip_proxy': True} init_config = {} http = RequestsWrapper(instance, init_config) with EnvVars({'HTTP_PROXY': 'http://1.2.3.4:567'}): response = http.get('http://www.google.com') response.raise_for_status() with EnvVars({'HTTPS_PROXY': 'https://1.2.3.4:567'}): response = http.get('https://www.google.com') response.raise_for_status() def test_proxy_env_vars_override_skip_fail(): instance = {'skip_proxy': True} init_config = {} http = RequestsWrapper(instance, init_config) with EnvVars({'HTTP_PROXY': 'http://1.2.3.4:567'}): with pytest.raises((ConnectTimeout, ProxyError)): http.get('http://www.google.com', timeout=1, proxies=None) with EnvVars({'HTTPS_PROXY': 'https://1.2.3.4:567'}): with pytest.raises((ConnectTimeout, ProxyError)): http.get('https://www.google.com', timeout=1, proxies=None) def test_proxy_bad(): instance = {'proxy': {'http': 'http://1.2.3.4:567', 'https': 'https://1.2.3.4:567'}} init_config = {} http = RequestsWrapper(instance, init_config) with pytest.raises((ConnectTimeout, ProxyError)): http.get('http://www.google.com', timeout=1) with pytest.raises((ConnectTimeout, ProxyError)): http.get('https://www.google.com', timeout=1) def test_proxy_bad_no_proxy_override_success(): instance = { 'proxy': {'http': 'http://1.2.3.4:567', 'https': 'https://1.2.3.4:567', 'no_proxy': 'unused,google.com'} } init_config = {} http = RequestsWrapper(instance, init_config) response = http.get('http://www.google.com') response.raise_for_status() response = http.get('https://www.google.com') response.raise_for_status() def test_no_proxy_uris_coverage(): http = RequestsWrapper({}, {}) # Coverage is not smart enough to detect that looping an empty # iterable will never occur when gated by `if iterable:`. http.no_proxy_uris = mock.MagicMock() http.no_proxy_uris.__iter__ = lambda self, *args, **kwargs: iter([]) http.no_proxy_uris.__bool__ = lambda self, *args, **kwargs: True # TODO: Remove with Python 2 http.no_proxy_uris.__nonzero__ = lambda self, *args, **kwargs: True http.get('https://www.google.com') @pytest.mark.parametrize( 'proxy,expected_proxy,url', [ ({'http': 'socks5h://myproxy'}, {'http': 'socks5h://myproxy'}, 'http://www.example.org'), ( {'http': 'http://1.2.3.4:567', 'no_proxy': '.foo,bar'}, { 'http': 'http://1.2.3.4:567', }, 'http://www.example.org', ), ({'http': 'http://1.2.3.4:567', 'no_proxy': '.foo,bar,*'}, {'http': '', 'https': ''}, 'http://www.example.org'), ( {'http': 'http://1.2.3.4:567', 'no_proxy': '.google.com,*.example.org,example.com,9'}, {'http': '', 'https': ''}, 'http://www.example.org', ), ( {'http': 'http://1.2.3.4:567', 'no_proxy': '.google.com,*.example.org,example.com,9'}, {'http': '', 'https': ''}, 'http://www.google.com', ), ( {'http': 'http://1.2.3.4:567', 'no_proxy': '.google.com,*.example.org,example.com,9'}, {'http': '', 'https': ''}, 'http://example.com', ), ( { 'http': 'http://1.2.3.4:567', 'no_proxy': '127.0.0.1,127.0.0.2/32,127.1.0.0/25,127.1.1.0/255.255.255.128,127.1.2.0/0.0.0.127', }, { 'http': 'http://1.2.3.4:567', }, 'http://www.example.org', ), ], ) @mock.patch('datadog_checks.base.utils.http.requests') def test_proxy_passes_right_params_to_requests(requests, proxy, expected_proxy, url): instance = {'proxy': proxy} init_config = {} http = RequestsWrapper(instance, init_config) http.get(url) call_args = { 'auth': None, 'cert': None, 'headers': OrderedDict( [('User-Agent', 'Datadog Agent/0.0.0'), ('Accept', '*/*'), ('Accept-Encoding', 'gzip, deflate')] ), 'proxies': expected_proxy, 'timeout': (10.0, 10.0), 'verify': True, 'allow_redirects': True, } requests.get.assert_called_with(url, **call_args)
299,016
test str
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the DataLad package for the # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## '''Unit tests for basic constraints functionality.''' from datalad.tests.utils_pytest import ( assert_equal, assert_raises, ) from ..support import constraints as ct def test_int(): c = ct.EnsureInt() # this should always work assert_equal(c(7), 7) assert_equal(c(7.0), 7) assert_equal(c('7'), 7) assert_equal(c([7, 3]), [7, 3]) # this should always fail assert_raises(ValueError, lambda: c('fail')) assert_raises(ValueError, lambda: c([3, 'fail'])) # this will also fail assert_raises(ValueError, lambda: c('17.0')) assert_equal(c.short_description(), 'int') def test_float(): c = ct.EnsureFloat() # this should always work assert_equal(c(7.0), 7.0) assert_equal(c(7), 7.0) assert_equal(c('7'), 7.0) assert_equal(c([7.0, '3.0']), [7.0, 3.0]) # this should always fail assert_raises(ValueError, lambda: c('fail')) assert_raises(ValueError, lambda: c([3.0, 'fail'])) def test_bool(): c = ct.EnsureBool() # this should always work assert_equal(c(True), True) assert_equal(c(False), False) # all that resuls in True assert_equal(c('True'), True) assert_equal(c('true'), True) assert_equal(c('1'), True) assert_equal(c('yes'), True) assert_equal(c('on'), True) assert_equal(c('enable'), True) # all that resuls in False assert_equal(c('false'), False) assert_equal(c('False'), False) assert_equal(c('0'), False) assert_equal(c('no'), False) assert_equal(c('off'), False) assert_equal(c('disable'), False) # this should always fail assert_raises(ValueError, c, 0) assert_raises(ValueError, c, 1) def METHOD_NAME(): c = ct.EnsureStr() # this should always work assert_equal(c('hello'), 'hello') assert_equal(c('7.0'), '7.0') # this should always fail assert_raises(ValueError, lambda: c(['ab'])) assert_raises(ValueError, lambda: c(['a', 'b'])) assert_raises(ValueError, lambda: c(('a', 'b'))) # no automatic conversion attempted assert_raises(ValueError, lambda: c(7.0)) assert_equal(c.short_description(), 'str') def test_str_min_len(): c = ct.EnsureStr(min_len=1) assert_equal(c('hello'), 'hello') assert_equal(c('h'), 'h') assert_raises(ValueError, c, '') c = ct.EnsureStr(min_len=2) assert_equal(c('hello'), 'hello') assert_raises(ValueError, c, 'h') def test_none(): c = ct.EnsureNone() # this should always work assert_equal(c(None), None) # instance of NoneDeprecated is also None assert_equal(c(ct.NoneDeprecated), None) # this should always fail assert_raises(ValueError, lambda: c('None')) assert_raises(ValueError, lambda: c([])) def test_callable(): c = ct.EnsureCallable() # this should always work assert_equal(c(range), range) assert_raises(ValueError, c, 'range') def test_choice(): c = ct.EnsureChoice('choice1', 'choice2', None) # this should always work assert_equal(c('choice1'), 'choice1') assert_equal(c(None), None) # this should always fail assert_raises(ValueError, lambda: c('fail')) assert_raises(ValueError, lambda: c('None')) def test_keychoice(): c = ct.EnsureKeyChoice(key='some', values=('choice1', 'choice2', None)) assert_equal(c({'some': 'choice1'}), {'some': 'choice1'}) assert_equal(c({'some': None}), {'some': None}) assert_equal(c({'some': None, 'ign': 'ore'}), {'some': None, 'ign': 'ore'}) assert_raises(ValueError, c, 'fail') assert_raises(ValueError, c, 'None') assert_raises(ValueError, c, {'nope': 'None'}) assert_raises(ValueError, c, {'some': 'None'}) assert_raises(ValueError, c, {'some': ('a', 'b')}) def test_range(): c = ct.EnsureRange(min=3, max=7) # this should always work assert_equal(c(3.0), 3.0) # this should always fail assert_raises(ValueError, lambda: c(2.9999999)) assert_raises(ValueError, lambda: c(77)) assert_raises(TypeError, lambda: c('fail')) assert_raises(TypeError, lambda: c((3, 4))) # since no type checks are performed assert_raises(TypeError, lambda: c('7')) # Range doesn't have to be numeric c = ct.EnsureRange(min="e", max="qqq") assert_equal(c('e'), 'e') assert_equal(c('fa'), 'fa') assert_equal(c('qq'), 'qq') assert_raises(ValueError, c, 'a') assert_raises(ValueError, c, 'qqqa') def test_listof(): c = ct.EnsureListOf(str) assert_equal(c(['a', 'b']), ['a', 'b']) assert_equal(c(['a1', 'b2']), ['a1', 'b2']) assert_equal(c('a1 b2'), ['a1 b2']) def test_tupleof(): c = ct.EnsureTupleOf(str) assert_equal(c(('a', 'b')), ('a', 'b')) assert_equal(c(('a1', 'b2')), ('a1', 'b2')) assert_equal(c('a1 b2'), ('a1 b2',)) def test_constraints(): # this should always work c = ct.Constraints(ct.EnsureFloat()) assert_equal(c(7.0), 7.0) c = ct.Constraints(ct.EnsureFloat(), ct.EnsureRange(min=4.0)) assert_equal(c(7.0), 7.0) # __and__ form c = ct.EnsureFloat() & ct.EnsureRange(min=4.0) assert_equal(c(7.0), 7.0) assert_raises(ValueError, c, 3.9) c = ct.Constraints(ct.EnsureFloat(), ct.EnsureRange(min=4), ct.EnsureRange(max=9)) assert_equal(c(7.0), 7.0) assert_raises(ValueError, c, 3.9) assert_raises(ValueError, c, 9.01) # __and__ form c = ct.EnsureFloat() & ct.EnsureRange(min=4) & ct.EnsureRange(max=9) assert_equal(c(7.0), 7.0) assert_raises(ValueError, c, 3.99) assert_raises(ValueError, c, 9.01) # and reordering should not have any effect c = ct.Constraints(ct.EnsureRange(max=4), ct.EnsureRange(min=9), ct.EnsureFloat()) assert_raises(ValueError, c, 3.99) assert_raises(ValueError, c, 9.01) def test_altconstraints(): # this should always work c = ct.AltConstraints(ct.EnsureFloat()) assert_equal(c(7.0), 7.0) c = ct.AltConstraints(ct.EnsureFloat(), ct.EnsureNone()) assert_equal(c.short_description(), '(float or None)') assert_equal(c(7.0), 7.0) assert_equal(c(None), None) # __or__ form c = ct.EnsureFloat() | ct.EnsureNone() assert_equal(c(7.0), 7.0) assert_equal(c(None), None) # this should always fail c = ct.Constraints(ct.EnsureRange(min=0, max=4), ct.EnsureRange(min=9, max=11)) assert_raises(ValueError, c, 7.0) c = ct.EnsureRange(min=0, max=4) | ct.EnsureRange(min=9, max=11) assert_equal(c(3.0), 3.0) assert_equal(c(9.0), 9.0) assert_raises(ValueError, c, 7.0) assert_raises(ValueError, c, -1.0) def test_both(): # this should always work c = ct.AltConstraints( ct.Constraints( ct.EnsureFloat(), ct.EnsureRange(min=7.0, max=44.0)), ct.EnsureNone()) assert_equal(c(7.0), 7.0) assert_equal(c(None), None) # this should always fail assert_raises(ValueError, lambda: c(77.0)) def test_type_str(): assert_equal(ct._type_str((str,)), 'str') assert_equal(ct._type_str(str), 'str')
299,017
event filter
# SPDX-License-Identifier: BSD-3-Clause # Copyright Contributors to the OpenColorIO Project. from collections import defaultdict from pathlib import Path from typing import Optional from PySide2 import QtCore, QtWidgets from .settings import settings from .transform_manager import TransformManager from .utils import get_glyph_icon from .viewer import ImageViewer from .widgets.structure import TabbedDockWidget class ViewerDock(TabbedDockWidget): """ Dockable widget for viewing color transforms on images. """ SETTING_IMAGE_DIR = "image_dir" SETTING_RECENT_IMAGES = "recent_images" SETTING_RECENT_IMAGE_PATH = "path" def __init__( self, recent_images_menu: QtWidgets.QMenu, parent: Optional[QtCore.QObject] = None, ): super().__init__( "Viewer", get_glyph_icon("mdi6.image-filter-center-focus"), parent=parent ) self._recent_images_menu = recent_images_menu self.setAllowedAreas(QtCore.Qt.NoDockWidgetArea) self.tabs.setTabPosition(QtWidgets.QTabWidget.West) self.tabs.currentChanged.connect(self._on_tab_changed) self._tab_bar = self.tabs.tabBar() self._tab_bar.installEventFilter(self) # Widgets self._viewers = defaultdict(list) self.add_image_viewer() # Initialize self._update_recent_images_menu() def METHOD_NAME(self, watched: QtCore.QObject, event: QtCore.QEvent) -> bool: """Tab context menu implementation.""" if watched == self._tab_bar: if event.type() == QtCore.QEvent.ContextMenu: pos = event.pos() tab_index = self._tab_bar.tabAt(pos) tab_widget = self.tabs.widget(tab_index) tab_menu = QtWidgets.QMenu(self._tab_bar) close_action = tab_menu.addAction( "Close", lambda: self._on_tab_close_requested(tab_index) ) if len(self._viewers.get(type(tab_widget), [])) == 1: # Only enable the action if there is more than one viewer of this # type open. close_action.setEnabled(False) tab_menu.popup(self._tab_bar.mapToGlobal(pos)) return True return False def load_image( self, image_path: Optional[Path] = None, new_tab: bool = False ) -> ImageViewer: """ Load an image into a new or existing viewer tab. :param image_path: Optional image path to load :param new_tab: Whether to load image into a new tab instead of the current or first available image viewer. :return: Image viewer instance """ if new_tab or not self._viewers.get(ImageViewer): image_viewer = self.add_image_viewer() else: current_viewer = self.tabs.currentWidget() if isinstance(current_viewer, ImageViewer): image_viewer = current_viewer else: image_viewer = self._viewers[ImageViewer][0] self.tabs.setCurrentWidget(image_viewer) if image_path is None or not image_path.is_file(): image_dir = self._get_image_dir(image_path) # Prompt user to choose an image image_path_str, sel_filter = QtWidgets.QFileDialog.getOpenFileName( self, "Load image", dir=image_dir ) if not image_path_str: return image_viewer image_path = Path(image_path_str) settings.setValue(self.SETTING_IMAGE_DIR, image_path.parent.as_posix()) self._add_recent_image_path(image_path) image_viewer.load_image(image_path=image_path) return image_viewer def add_image_viewer(self) -> ImageViewer: """ Add a new image viewer tab to the dock. :return: Image viewer instance """ image_viewer = ImageViewer() self._viewers[ImageViewer].append(image_viewer) self.add_tab( image_viewer, image_viewer.viewer_type_label(), image_viewer.viewer_type_icon(), ) return image_viewer def update_current_viewer(self) -> None: """ Update the current viewer to reflect the latest config changes. """ viewer = self.tabs.currentWidget() viewer.update() def reset(self) -> None: """ Reset all viewer tabs to a passthrough state. """ for viewer_type, viewers in self._viewers.items(): for viewer in viewers: viewer.reset() TransformManager.reset() def _on_tab_changed(self, index: int) -> None: """ Track GL context with the current viewer. """ viewer = self.tabs.widget(index) if viewer is not None: # Force an update to trigger side effects of a processor change in the # wider application. viewer.update(force=True) def _on_tab_close_requested(self, index: int) -> None: """ Maintain one instance of each viewer type. """ viewer = self.tabs.widget(index) viewer_type = type(viewer) if len(self._viewers.get(viewer_type, [])) > 1: self.tabs.removeTab(index) if viewer in self._viewers[viewer_type]: self._viewers[viewer_type].remove(viewer) def _get_image_dir(self, image_path: Optional[Path] = None) -> str: """ Infer an image load directory from an existing image path or settings. """ image_dir = "" if image_path is not None: image_dir = image_path.parent.as_posix() if not image_dir and settings.contains(self.SETTING_IMAGE_DIR): image_dir = settings.value(self.SETTING_IMAGE_DIR) return image_dir def _get_recent_image_paths(self) -> list[Path]: """ Get the 10 most recently loaded image file paths that still exist. :return: List of image file paths """ recent_images = [] num_images = settings.beginReadArray(self.SETTING_RECENT_IMAGES) for i in range(num_images): settings.setArrayIndex(i) recent_image_path_str = settings.value(self.SETTING_RECENT_IMAGE_PATH) if recent_image_path_str: recent_image_path = Path(recent_image_path_str) if recent_image_path.is_file(): recent_images.append(recent_image_path) settings.endArray() return recent_images def _add_recent_image_path(self, image_path: Path) -> None: """ Add the provided image file path to the top of the recent image files list. :param image_path: Image file path """ image_paths = self._get_recent_image_paths() if image_path in image_paths: image_paths.remove(image_path) image_paths.insert(0, image_path) if len(image_paths) > 10: image_paths = image_path[:10] settings.beginWriteArray(self.SETTING_RECENT_IMAGES) for i, recent_image_path in enumerate(image_paths): settings.setArrayIndex(i) settings.setValue( self.SETTING_RECENT_IMAGE_PATH, recent_image_path.as_posix() ) settings.endArray() # Update menu with latest list self._update_recent_images_menu() def _update_recent_images_menu(self) -> None: """Update recent image menu actions.""" self._recent_images_menu.clear() for recent_image_path in self._get_recent_image_paths(): self._recent_images_menu.addAction( recent_image_path.name, lambda path=recent_image_path: self.load_image(path), )
299,018
write
import logging from _typeshed import ReadableBuffer from collections.abc import Callable, Generator from typing import Any from serial.serialutil import SerialBase LOGGER_LEVELS: dict[str, int] SE: bytes NOP: bytes DM: bytes BRK: bytes IP: bytes AO: bytes AYT: bytes EC: bytes EL: bytes GA: bytes SB: bytes WILL: bytes WONT: bytes DO: bytes DONT: bytes IAC: bytes IAC_DOUBLED: bytes BINARY: bytes ECHO: bytes SGA: bytes COM_PORT_OPTION: bytes SET_BAUDRATE: bytes SET_DATASIZE: bytes SET_PARITY: bytes SET_STOPSIZE: bytes SET_CONTROL: bytes NOTIFY_LINESTATE: bytes NOTIFY_MODEMSTATE: bytes FLOWCONTROL_SUSPEND: bytes FLOWCONTROL_RESUME: bytes SET_LINESTATE_MASK: bytes SET_MODEMSTATE_MASK: bytes PURGE_DATA: bytes SERVER_SET_BAUDRATE: bytes SERVER_SET_DATASIZE: bytes SERVER_SET_PARITY: bytes SERVER_SET_STOPSIZE: bytes SERVER_SET_CONTROL: bytes SERVER_NOTIFY_LINESTATE: bytes SERVER_NOTIFY_MODEMSTATE: bytes SERVER_FLOWCONTROL_SUSPEND: bytes SERVER_FLOWCONTROL_RESUME: bytes SERVER_SET_LINESTATE_MASK: bytes SERVER_SET_MODEMSTATE_MASK: bytes SERVER_PURGE_DATA: bytes RFC2217_ANSWER_MAP: dict[bytes, bytes] SET_CONTROL_REQ_FLOW_SETTING: bytes SET_CONTROL_USE_NO_FLOW_CONTROL: bytes SET_CONTROL_USE_SW_FLOW_CONTROL: bytes SET_CONTROL_USE_HW_FLOW_CONTROL: bytes SET_CONTROL_REQ_BREAK_STATE: bytes SET_CONTROL_BREAK_ON: bytes SET_CONTROL_BREAK_OFF: bytes SET_CONTROL_REQ_DTR: bytes SET_CONTROL_DTR_ON: bytes SET_CONTROL_DTR_OFF: bytes SET_CONTROL_REQ_RTS: bytes SET_CONTROL_RTS_ON: bytes SET_CONTROL_RTS_OFF: bytes SET_CONTROL_REQ_FLOW_SETTING_IN: bytes SET_CONTROL_USE_NO_FLOW_CONTROL_IN: bytes SET_CONTROL_USE_SW_FLOW_CONTOL_IN: bytes SET_CONTROL_USE_HW_FLOW_CONTOL_IN: bytes SET_CONTROL_USE_DCD_FLOW_CONTROL: bytes SET_CONTROL_USE_DTR_FLOW_CONTROL: bytes SET_CONTROL_USE_DSR_FLOW_CONTROL: bytes LINESTATE_MASK_TIMEOUT: int LINESTATE_MASK_SHIFTREG_EMPTY: int LINESTATE_MASK_TRANSREG_EMPTY: int LINESTATE_MASK_BREAK_DETECT: int LINESTATE_MASK_FRAMING_ERROR: int LINESTATE_MASK_PARTIY_ERROR: int LINESTATE_MASK_OVERRUN_ERROR: int LINESTATE_MASK_DATA_READY: int MODEMSTATE_MASK_CD: int MODEMSTATE_MASK_RI: int MODEMSTATE_MASK_DSR: int MODEMSTATE_MASK_CTS: int MODEMSTATE_MASK_CD_CHANGE: int MODEMSTATE_MASK_RI_CHANGE: int MODEMSTATE_MASK_DSR_CHANGE: int MODEMSTATE_MASK_CTS_CHANGE: int PURGE_RECEIVE_BUFFER: bytes PURGE_TRANSMIT_BUFFER: bytes PURGE_BOTH_BUFFERS: bytes RFC2217_PARITY_MAP: dict[str, int] RFC2217_REVERSE_PARITY_MAP: dict[int, str] RFC2217_STOPBIT_MAP: dict[int | float, int] RFC2217_REVERSE_STOPBIT_MAP: dict[int, int | float] M_NORMAL: int M_IAC_SEEN: int M_NEGOTIATE: int REQUESTED: str ACTIVE: str INACTIVE: str REALLY_INACTIVE: str class TelnetOption: connection: Serial name: str option: bytes send_yes: bytes send_no: bytes ack_yes: bytes ack_no: bytes state: str active: bool activation_callback: Callable[[], Any] def __init__( self, connection: Serial, name: str, option: bytes, send_yes: bytes, send_no: bytes, ack_yes: bytes, ack_no: bytes, initial_state: str, activation_callback: Callable[[], Any] | None = None, ) -> None: ... def process_incoming(self, command: bytes) -> None: ... class TelnetSubnegotiation: connection: Serial name: str option: bytes value: bytes | None ack_option: bytes state: str def __init__(self, connection: Serial, name: str, option: bytes, ack_option: bytes | None = None) -> None: ... def set(self, value: bytes) -> None: ... def is_ready(self) -> bool: ... @property def active(self) -> bool: ... def wait(self, timeout: float = 3) -> None: ... def check_answer(self, suboption: bytes) -> None: ... class Serial(SerialBase): logger: logging.Logger | None def open(self) -> None: ... def from_url(self, url: str) -> tuple[str, int]: ... @property def in_waiting(self) -> int: ... def read(self, size: int = 1) -> bytes: ... def METHOD_NAME(self, __b: ReadableBuffer) -> int | None: ... def reset_input_buffer(self) -> None: ... def reset_output_buffer(self) -> None: ... @property def cts(self) -> bool: ... @property def dsr(self) -> bool: ... @property def ri(self) -> bool: ... @property def cd(self) -> bool: ... def telnet_send_option(self, action: bytes, option: bytes) -> None: ... def rfc2217_send_subnegotiation(self, option: bytes, value: bytes = b"") -> None: ... def rfc2217_send_purge(self, value: bytes) -> None: ... def rfc2217_set_control(self, value: bytes) -> None: ... def rfc2217_flow_server_ready(self) -> None: ... def get_modem_state(self) -> int: ... class PortManager: serial: Serial connection: Serial logger: logging.Logger | None mode: int suboption: bytes | None telnet_command: bytes | None modemstate_mask: int last_modemstate: int | None linstate_mask: int def __init__(self, serial_port: Serial, connection: Serial, logger: logging.Logger | None = None) -> None: ... def telnet_send_option(self, action: bytes, option: bytes) -> None: ... def rfc2217_send_subnegotiation(self, option: bytes, value: bytes = b"") -> None: ... def check_modem_lines(self, force_notification: bool = False) -> None: ... def escape(self, data: bytes) -> Generator[bytes, None, None]: ... def filter(self, data: bytes) -> Generator[bytes, None, None]: ...
299,019
start end target type logits
from datasets import Dataset import pytest import sys from pytest import raises from transformers import AutoTokenizer from itertools import groupby from operator import itemgetter import numpy as np from primeqa.mrc.processors.postprocessors.extractive import ExtractivePostProcessor from primeqa.mrc.processors.postprocessors.scorers import SupportedSpanScorers from primeqa.mrc.data_models.target_type import TargetType from tests.primeqa.mrc.common.base import UnitTest from tests.primeqa.mrc.common.parameterization import PARAMETERIZE_INVALID_SUBSAMPLING_PROBABILITIES class TestExtractivePostProcessor(UnitTest): @pytest.fixture(scope='session') def mock_logits_expected_predictions(self): _start_score_of_cls_token = 0 _end_score_of_cls_token = 0 _score_none_token = -10 example1_start_scores = [ [0.5, 0.3, 0.2, 0.1, 0.1], [1.5, 0.7, 0.2, 0.1, 0.1], ] example1_end_scores = [ [0.5, 0.3, 0, 0, 0], [1.5, 0.7, 0, 0, 0], ] example2_start_scores = [ [-1, 2, 1, -3, -2.5, -5, -4, -2, -2, -1, -1.5, -2.5], [-3, -2, -5, -2,-1, -1, -3, -2, -4, -5, -1.5, -2.5], [-3, -2, -5, -2,-1, -1, -3, -2, -4, -5, -1.5, -2.5], ] example2_end_scores = [ [-1, 1, 1.5, -3, -2.5, -5, -4, -2, -2, -1, -1.5, -2.5], [-3, -2, -5, -2,-1, -1, -3, -2, -4, -5, -1.5, -2.5], [-3, -2, -5, -2,-1, -1, -3, -2, -4, -5, -1.5, -2.5], ] _start_scores = [example1_start_scores, example2_start_scores] _end_scores = [ example1_end_scores, example2_end_scores] _target_type_scores = [ np.array([ -4.2624542e-04, 1.2508204e+00, -1.8462906e-02, -4.0960628e-01, -3.8014248e-01, -4.2624542e-04], dtype=np.float32), np.array([ 1.0599241 , 0.01550296, -0.40537557, -0.3395432 , 0.12297338],dtype=np.float32), ] _expected_predictions = { 'foo-abc' : { 'start_index': 0, #8, 'end_index': 0, #8, 'passage_index': 1, 'target_type' : int(TargetType.SPAN_ANSWER), 'span_answer_text': 'Bob' }, 'bar-123': { 'start_index': 1, # 9, 'end_index': 2, #10, 'passage_index': 0, 'target_type' : int(TargetType.NO_ANSWER), 'span_answer_text': 'quick brown' } } return { 'start_score_of_cls_token': _start_score_of_cls_token, 'end_score_of_cls_token': _end_score_of_cls_token, 'score_none_token': _score_none_token, 'start_scores': _start_scores, 'end_scores': _end_scores, 'target_type_scores': _target_type_scores, 'expected_predictions': _expected_predictions } def METHOD_NAME(self, examples, features, mock_logits_expected_predictions): all_start_logits = [] all_end_logits = [] all_target_type_logits = [] adjusted_start_end_index = {} features_itr = groupby(features, key=itemgetter('example_idx')) for example in examples: example_id = example['example_id'] expected = mock_logits_expected_predictions['expected_predictions'][example_id] example_idx, example_features = next(features_itr) example_features = list(example_features) for feat_idx, feature in enumerate(example_features): offset_mapping = feature["offset_mapping"] if feat_idx == expected['passage_index']: for i, offset in enumerate(offset_mapping): if offset != None: adjusted_start_end_index[example_id] = (expected['start_index']+i, expected['end_index'] + i) break start_logits = [] end_logits = [] start_scores_iter = iter(mock_logits_expected_predictions['start_scores'][example_idx][feat_idx]) end_scores_iter = iter(mock_logits_expected_predictions['end_scores'][example_idx][feat_idx]) for i, offset in enumerate(offset_mapping): if i == 0: start_logits.append(mock_logits_expected_predictions['start_score_of_cls_token']) end_logits.append(mock_logits_expected_predictions['end_score_of_cls_token']) elif offset == None: start_logits.append(mock_logits_expected_predictions['score_none_token']) end_logits.append(mock_logits_expected_predictions['score_none_token']) else: start_logits.append(next(start_scores_iter)) end_logits.append(next(end_scores_iter)) start_logits += [sys.float_info.min]*(128-len(start_logits)) all_start_logits.append(np.array( start_logits)) end_logits += [sys.float_info.min]*(128-len(end_logits)) all_end_logits.append(np.array( end_logits)) all_target_type_logits.append(mock_logits_expected_predictions['target_type_scores'][example_idx]) return adjusted_start_end_index, ( np.array(all_start_logits), np.array(all_end_logits), np.array(all_target_type_logits) ) def test_post_processor_has_examples_and_features(self, eval_examples_and_features, mock_logits_expected_predictions): eval_examples, eval_features = eval_examples_and_features postprocessor_class = ExtractivePostProcessor scorer_type='weighted_sum_target_type_and_score_diff' expected_start_end_index, predictions = self.METHOD_NAME(eval_examples, eval_features, mock_logits_expected_predictions) postprocessor = postprocessor_class(k=5, n_best_size=3, max_answer_length=30, scorer_type=SupportedSpanScorers(scorer_type), single_context_multiple_passages=False) example_predictions = postprocessor.process(eval_examples, eval_features, predictions) for example_id, preds in example_predictions.items(): predicted = preds[0] expected = mock_logits_expected_predictions['expected_predictions'][example_id] expected_start_end = expected_start_end_index[example_id] ptargettype = int(np.argmax(predicted['target_type_logits'])) assert (predicted['start_index'], predicted['end_index']) == expected_start_end assert predicted['passage_index'] == expected['passage_index'] assert ptargettype == expected['target_type']
299,020
msg handler
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2020 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from PyQt5.QtWidgets import QFrame, QHBoxLayout, QVBoxLayout, QLabel from PyQt5.QtGui import QPainter, QBrush, QColor, QPen, QFontMetricsF from PyQt5.QtCore import Qt as Qtc from PyQt5.QtCore import QPoint from PyQt5.QtGui import QRadialGradient from gnuradio import gr import pmt class LabeledLEDIndicator(QFrame): # Positions: 1 = above, 2=below, 3=left, 4=right def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, maxSize=80, position=1, alignment=1, valignment=1, parent=None): QFrame.__init__(self, parent) self.numberControl = LEDIndicator( onColor, offColor, initialState, maxSize, parent) if position < 3: layout = QVBoxLayout() else: layout = QHBoxLayout() if not lbl: lbl = " " self.lbl = lbl self.lblcontrol = QLabel(lbl, self) self.lblcontrol.setAlignment(Qtc.AlignCenter) # add top or left if len: if position == 1 or position == 3: layout.addWidget(self.lblcontrol) else: self.hasLabel = False layout.addWidget(self.numberControl) # Add bottom or right if len: if position == 2 or position == 4: layout.addWidget(self.lblcontrol) if alignment == 1: halign = Qtc.AlignCenter elif alignment == 2: halign = Qtc.AlignLeft else: halign = Qtc.AlignRight if valignment == 1: valign = Qtc.AlignVCenter elif valignment == 2: valign = Qtc.AlignTop else: valign = Qtc.AlignBottom layout.setAlignment(halign | valign) self.setLayout(layout) if len: textfont = self.lblcontrol.font() metrics = QFontMetricsF(textfont) maxWidth = int(max((maxSize + 30), (maxSize + metrics.width(lbl) + 4))) maxHeight = int(max((maxSize + 35), (maxSize + metrics.height() + 2))) self.setMinimumSize(maxWidth, maxHeight) else: self.setMinimumSize(maxSize + 2, maxSize + 2) self.show() def setState(self, on_off): self.numberControl.setState(on_off) class LEDIndicator(QFrame): def __init__(self, onColor='green', offColor='red', initialState=False, maxSize=80, parent=None): QFrame.__init__(self, parent) self.maxSize = maxSize self.curState = initialState self.on_color = QColor(onColor) self.off_color = QColor(offColor) self.setMinimumSize(maxSize, maxSize) self.setMaximumSize(maxSize, maxSize) def setState(self, on_off): self.curState = on_off super().update() def paintEvent(self, event): super().paintEvent(event) painter = QPainter(self) size = self.size() brush = QBrush() smallest_dim = size.width() if smallest_dim > size.height(): smallest_dim = size.height() smallest_dim = smallest_dim / 2 smallest_dim -= 2 center_x = int(size.width() / 2) center_y = int(size.height() / 2) centerpoint = QPoint(center_x, center_y) radius = smallest_dim painter.setPen(QPen(QColor('lightgray'), 0)) brush.setStyle(Qtc.SolidPattern) radial = QRadialGradient(center_x, center_y / 2, radius) radial.setColorAt(0, Qtc.white) radial.setColorAt(0.8, Qtc.darkGray) painter.setBrush(QBrush(radial)) painter.drawEllipse(centerpoint, radius, radius) # Draw the colored center radial = QRadialGradient(center_x, center_y / 2, radius) radial.setColorAt(0, Qtc.white) if self.curState: radial.setColorAt(.7, self.on_color) brush.setColor(self.on_color) painter.setPen(QPen(self.on_color, 0)) else: radial.setColorAt(.7, self.off_color) brush.setColor(self.off_color) painter.setPen(QPen(self.off_color, 0)) brush.setStyle(Qtc.SolidPattern) painter.setBrush(QBrush(radial)) if smallest_dim <= 30: radius = radius - 3 elif smallest_dim <= 60: radius = radius - 4 elif smallest_dim <= 100: radius = radius - 5 elif smallest_dim <= 200: radius = radius - 6 elif smallest_dim <= 300: radius = radius - 7 else: radius = radius - 9 painter.drawEllipse(centerpoint, radius, radius) class GrLEDIndicator(gr.sync_block, LabeledLEDIndicator): """ This block makes a basic LED indicator """ def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, maxSize=80, position=1, alignment=1, valignment=1, parent=None): gr.sync_block.__init__(self, name="LEDIndicator", in_sig=None, out_sig=None) LabeledLEDIndicator.__init__(self, lbl, onColor, offColor, initialState, maxSize, position, alignment, valignment, parent) self.lbl = lbl self.message_port_register_in(pmt.intern("state")) self.set_msg_handler(pmt.intern("state"), self.METHOD_NAME) def METHOD_NAME(self, msg): try: new_val = pmt.to_python(pmt.cdr(msg)) if type(new_val) == bool or type(new_val) == int: if type(new_val) == bool: super().setState(new_val) else: if new_val == 1: super().setState(True) else: super().setState(False) else: gr.log.error( "Value received was not an int or a bool: %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) def setState(self, on_off): super().setState(on_off)
299,021
run
# Copyright 2015 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Run wrk against a simple Tomcat web server. This is close to HTTP-RR: * Connections are reused. * The server does very little work. Doubles connections up to a fixed count, reports single connection latency and maximum error-free throughput. `wrk` is a scalable web load generator. `tomcat` is a popular Java web server. """ import functools import logging import operator from absl import flags from perfkitbenchmarker import background_tasks from perfkitbenchmarker import configs from perfkitbenchmarker.linux_packages import tomcat from perfkitbenchmarker.linux_packages import wrk import six import six.moves.urllib.parse flags.DEFINE_integer('tomcat_wrk_test_length', 120, 'Length of time, in seconds, to run wrk for each ' 'connction count', lower_bound=1) flags.DEFINE_integer('tomcat_wrk_max_connections', 128, 'Maximum number of simultaneous connections to attempt', lower_bound=1) flags.DEFINE_boolean('tomcat_wrk_report_all_samples', False, 'If true, report throughput/latency at all connection ' 'counts. If false (the default), report only the ' 'connection counts with lowest p50 latency and highest ' 'throughput.') # Stop when >= 1% of requests have errors MAX_ERROR_RATE = 0.01 FLAGS = flags.FLAGS BENCHMARK_NAME = 'tomcat_wrk' BENCHMARK_CONFIG = """ tomcat_wrk: description: Run wrk against tomcat. vm_groups: server: vm_spec: *default_single_core client: vm_spec: *default_single_core """ MAX_OPEN_FILES = 65536 WARM_UP_DURATION = 30 # Target: simple sample page that generates an SVG. SAMPLE_PAGE_PATH = 'examples/jsp/jsp2/jspx/textRotate.jspx?name=JSPX' NOFILE_LIMIT_CONF = '/etc/security/limits.d/pkb-tomcat.conf' def GetConfig(user_config): return configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) def _IncreaseMaxOpenFiles(vm): vm.RemoteCommand(('echo "{0} soft nofile {1}\n{0} hard nofile {1}" | ' 'sudo tee {2}').format(vm.user_name, MAX_OPEN_FILES, NOFILE_LIMIT_CONF)) def _RemoveOpenFileLimit(vm): vm.RemoteCommand('sudo rm -f {0}'.format(NOFILE_LIMIT_CONF)) def _PrepareServer(vm): """Installs tomcat on the server.""" vm.Install('tomcat') _IncreaseMaxOpenFiles(vm) tomcat.Start(vm) def _PrepareClient(vm): """Install wrk on the client VM.""" _IncreaseMaxOpenFiles(vm) vm.Install('curl') vm.Install('wrk') def Prepare(benchmark_spec): """Install tomcat on one VM and wrk on another. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ tomcat_vm = benchmark_spec.vm_groups['server'][0] wrk_vm = benchmark_spec.vm_groups['client'][0] tomcat_vm.AllowPort(tomcat.TOMCAT_HTTP_PORT) background_tasks.RunThreaded( (lambda f: f()), [ functools.partial(_PrepareServer, tomcat_vm), functools.partial(_PrepareClient, wrk_vm), ], ) def METHOD_NAME(benchmark_spec): """Run wrk against tomcat. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects. """ tomcat_vm = benchmark_spec.vm_groups['server'][0] wrk_vm = benchmark_spec.vm_groups['client'][0] samples = [] errors = 0 connections = 1 duration = FLAGS.tomcat_wrk_test_length max_connections = FLAGS.tomcat_wrk_max_connections target = six.moves.urllib.parse.urljoin( 'http://{0}:{1}'.format(tomcat_vm.ip_address, tomcat.TOMCAT_HTTP_PORT), SAMPLE_PAGE_PATH) logging.info('Warming up for %ds', WARM_UP_DURATION) list(wrk.METHOD_NAME(wrk_vm, connections=1, target=target, duration=WARM_UP_DURATION)) all_by_metric = [] while connections <= max_connections: run_samples = list(wrk.METHOD_NAME(wrk_vm, connections=connections, target=target, duration=duration)) by_metric = {i.metric: i for i in run_samples} errors = by_metric['errors'].value requests = by_metric['requests'].value throughput = by_metric['throughput'].value if requests < 1: logging.warn('No requests issued for %d connections.', connections) error_rate = 1.0 else: error_rate = float(errors) / requests if error_rate <= MAX_ERROR_RATE: all_by_metric.append(by_metric) else: logging.warn('Error rate exceeded maximum (%g > %g)', error_rate, MAX_ERROR_RATE) logging.info('Ran with %d connections; %.2f%% errors, %.2f req/s', connections, error_rate, throughput) # Retry with double the connections connections *= 2 if not all_by_metric: raise ValueError('No requests succeeded.') # Annotate the sample with the best throughput max_throughput = max(all_by_metric, key=lambda x: x['throughput'].value) for sample in six.itervalues(max_throughput): sample.metadata.update(best_throughput=True) # ...and best 50th percentile latency min_p50 = min(all_by_metric, key=lambda x: x['p50 latency'].value) for sample in six.itervalues(min_p50): sample.metadata.update(best_p50=True) sort_key = operator.attrgetter('metric') if FLAGS.tomcat_wrk_report_all_samples: samples = [sample for d in all_by_metric for sample in sorted(six.itervalues(d), key=sort_key)] else: samples = (sorted(six.itervalues(min_p50), key=sort_key) + sorted(six.itervalues(max_throughput), key=sort_key)) for sample in samples: sample.metadata.update(ip_type='external', runtime_in_seconds=duration) return samples def Cleanup(benchmark_spec): """Remove tomcat and wrk. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ tomcat_vm = benchmark_spec.vm_groups['server'][0] tomcat.Stop(tomcat_vm) background_tasks.RunThreaded(_RemoveOpenFileLimit, benchmark_spec.vms)
299,022
set isolation level
import psycopg2 as Database # Some of these imports are unused, but they are inherited from other engines # and should be available as part of the backend ``base.py`` namespace. from django.db.backends.postgresql.base import DatabaseWrapper as DjangoDatabaseWrapper from sentry.utils.strings import strip_lone_surrogates from .creation import SentryDatabaseCreation from .decorators import ( auto_reconnect_connection, auto_reconnect_cursor, capture_transaction_exceptions, more_better_error_messages, ) from .operations import DatabaseOperations __all__ = ("DatabaseWrapper",) from .schema import DatabaseSchemaEditorProxy def remove_null(value): # In psycopg2 2.7+, behavior was introduced where a # NULL byte in a parameter would start raising a ValueError. # psycopg2 chose to do this rather than let Postgres silently # truncate the data, which is it's behavior when it sees a # NULL byte. But for us, we'd rather remove the null value so it's # somewhat legible rather than error. Considering this is better # behavior than the database truncating, seems good to do this # rather than attempting to sanitize all data inputs now manually. if type(value) is bytes: return value.replace(b"\x00", b"") return value.replace("\x00", "") def remove_surrogates(value): # Another hack. postgres does not accept lone surrogates # in utf-8 mode. If we encounter any lone surrogates in # our string we need to remove it. if type(value) is bytes: try: return strip_lone_surrogates(value.decode("utf-8")).encode("utf-8") except UnicodeError: return value return strip_lone_surrogates(value) def clean_bad_params(params): # Support dictionary of parameters for %(key)s placeholders # in raw SQL queries. if isinstance(params, dict): for key, param in params.items(): if isinstance(param, (str, bytes)): params[key] = remove_null(remove_surrogates(param)) return params params = list(params) for idx, param in enumerate(params): if isinstance(param, (str, bytes)): params[idx] = remove_null(remove_surrogates(param)) return params class CursorWrapper: """ A wrapper around the postgresql_psycopg2 backend which handles various events from cursors, such as auto reconnects and lazy time zone evaluation. """ def __init__(self, db, cursor): self.db = db self.cursor = cursor def __getattr__(self, attr): return getattr(self.cursor, attr) def __iter__(self): return iter(self.cursor) @capture_transaction_exceptions @auto_reconnect_cursor @more_better_error_messages def execute(self, sql, params=None): if params is not None: return self.cursor.execute(sql, clean_bad_params(params)) return self.cursor.execute(sql) @capture_transaction_exceptions @auto_reconnect_cursor @more_better_error_messages def executemany(self, sql, paramlist=()): return self.cursor.executemany(sql, paramlist) class DatabaseWrapper(DjangoDatabaseWrapper): creation_class = SentryDatabaseCreation SchemaEditorClass = DatabaseSchemaEditorProxy def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ops = DatabaseOperations(self) @auto_reconnect_connection def METHOD_NAME(self, level): return super().METHOD_NAME(level) @auto_reconnect_connection def _cursor(self, *args, **kwargs): return super()._cursor() # We're overriding this internal method that's present in Django 1.11+, because # things were shuffled around since 1.10 resulting in not constructing a django CursorWrapper # with our CursorWrapper. We need to be passing our wrapped cursor to their wrapped cursor, # not the other way around since then we'll lose things like __enter__ due to the way this # wrapper is working (getattr on self.cursor). def _prepare_cursor(self, cursor): cursor = super()._prepare_cursor(CursorWrapper(self, cursor)) return cursor def close(self, reconnect=False): """ This ensures we don't error if the connection has already been closed. """ if self.connection is not None: if not self.connection.closed: try: self.connection.close() except Database.InterfaceError: # connection was already closed by something # like pgbouncer idle timeout. pass self.connection = None
299,023
split
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2021 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from ... import opcodes as OperandDef from ...core import ExecutableTuple, recursive_tile from ...lib.sparse.core import get_array_module from ...serialization.serializables import KeyField, AnyField, Int32Field from ..core import Tensor from ..datasource import tensor as astensor from ..utils import calc_sliced_size from ..operands import TensorHasInput, TensorOperandMixin class TensorSplit(TensorHasInput, TensorOperandMixin): _op_type_ = OperandDef.ARRAY_SPLIT _input = KeyField("input") _indices_or_sections = AnyField("indices_or_sections") _axis = Int32Field("axis") def __init__(self, axis=None, **kw): super().__init__(_axis=axis, **kw) @property def indices_or_sections(self): return self._indices_or_sections @property def axis(self): return getattr(self, "_axis", 0) @property def output_limit(self): return float("inf") def _set_inputs(self, inputs): super()._set_inputs(inputs) self._input = self._inputs[0] if len(self._inputs) > 1: self._indices_or_sections = self._inputs[1] def __call__(self, a, indices_or_sections, is_split=False): axis = self._axis size = a.shape[axis] if np.isnan(size): raise ValueError( "cannot split array with unknown shape, " "call `.execute()` on input tensor first" ) if ( isinstance(indices_or_sections, Tensor) and hasattr(indices_or_sections.op, "data") and indices_or_sections.op.data is not None ): indices_or_sections = indices_or_sections.op.data try: indices_or_sections = int(indices_or_sections) if is_split: if size % indices_or_sections: raise ValueError( "tensor split does not result in an equal division" ) nparts = indices_or_sections nsplit = (size // indices_or_sections,) * nparts else: nparts = indices_or_sections if size % indices_or_sections == 0: nsplit = (size // indices_or_sections,) * nparts else: nsplit = (size // indices_or_sections + 1,) * ( size % indices_or_sections ) + (size // indices_or_sections,) * ( size - size % indices_or_sections ) except TypeError: if isinstance(indices_or_sections, Tensor): nparts = indices_or_sections.shape[0] + 1 nsplit = (np.nan,) * nparts else: ind = indices_or_sections = get_array_module( indices_or_sections ).asarray(indices_or_sections) if indices_or_sections.ndim != 1 or not np.issubdtype( indices_or_sections.dtype, np.integer ): raise TypeError("slice indices must be integers or None") nparts = indices_or_sections.shape[0] + 1 get = lambda i: None if i < 0 or i >= len(ind) else ind[i] nsplit = [ calc_sliced_size(size, slice(get(j - 1), get(j))) for j in range(nparts) ] inputs = [a] if isinstance(indices_or_sections, Tensor): inputs.append(indices_or_sections) else: self._indices_or_sections = indices_or_sections kws = [ { "i": i, "shape": a.shape[:axis] + (nsplit[i],) + a.shape[axis + 1 :], "order": a.order, } for i in range(nparts) ] return ExecutableTuple(self.new_tensors(inputs, kws=kws, output_limit=nparts)) @classmethod def tile(cls, op): in_tensor = op.input splits = op.outputs axis = op.axis acc_shapes = np.cumsum([s.shape[axis] for s in splits]) out_kws = [dict() for _ in splits] for i, split in enumerate(splits): slc = slice(0 if i == 0 else acc_shapes[i - 1], acc_shapes[i]) new_s = yield from recursive_tile(in_tensor[(slice(None),) * axis + (slc,)]) out_kws[i]["chunks"] = new_s.chunks out_kws[i]["nsplits"] = new_s.nsplits out_kws[i]["shape"] = split.shape out_kws[i]["order"] = op.outputs[i].order new_op = op.copy() return new_op.new_tensors(op.inputs, kws=out_kws, output_limit=len(out_kws)) def METHOD_NAME(a, indices_or_sections, axis=0, is_split=False): op = TensorSplit(axis=axis, dtype=a.dtype) return op(a, indices_or_sections, is_split=is_split) def split(ary, indices_or_sections, axis=0): """ Split a tensor into multiple sub-tensors. Parameters ---------- ary : Tensor Tensor to be divided into sub-tensors. indices_or_sections : int or 1-D tensor If `indices_or_sections` is an integer, N, the array will be divided into N equal tensors along `axis`. If such a split is not possible, an error is raised. If `indices_or_sections` is a 1-D tensor of sorted integers, the entries indicate where along `axis` the array is split. For example, ``[2, 3]`` would, for ``axis=0``, result in - ary[:2] - ary[2:3] - ary[3:] If an index exceeds the dimension of the tensor along `axis`, an empty sub-tensor is returned correspondingly. axis : int, optional The axis along which to split, default is 0. Returns ------- sub-tensors : list of Tensors A list of sub-tensors. Raises ------ ValueError If `indices_or_sections` is given as an integer, but a split does not result in equal division. See Also -------- array_split : Split a tensor into multiple sub-tensors of equal or near-equal size. Does not raise an exception if an equal division cannot be made. hsplit : Split into multiple sub-arrays horizontally (column-wise). vsplit : Split tensor into multiple sub-tensors vertically (row wise). dsplit : Split tensor into multiple sub-tensors along the 3rd axis (depth). concatenate : Join a sequence of tensors along an existing axis. stack : Join a sequence of tensors along a new axis. hstack : Stack tensors in sequence horizontally (column wise). vstack : Stack tensors in sequence vertically (row wise). dstack : Stack tensors in sequence depth wise (along third dimension). Examples -------- >>> import mars.tensor as mt >>> x = mt.arange(9.0) >>> mt.split(x, 3).execute() [array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7., 8.])] >>> x = mt.arange(8.0) >>> mt.split(x, [3, 5, 6, 10]).execute() [array([ 0., 1., 2.]), array([ 3., 4.]), array([ 5.]), array([ 6., 7.]), array([], dtype=float64)] """ return METHOD_NAME(astensor(ary), indices_or_sections, axis=axis, is_split=True)
299,024
is up to date
# # git.py # etl # """ Helpers for working with Git in an ETL flow. """ from dataclasses import dataclass from pathlib import Path from typing import Any, cast import requests import sh CACHE_DIR = Path("~/.owid/git") class RepoAlreadyExists(Exception): pass @dataclass class GithubRepo: org: str repo: str @property def github_url(self) -> str: return f"https://github.com/{self.org}/{self.repo}" @property def cache_dir(self) -> Path: return Path(f"~/.owid/git/{self.org}/{self.repo}").expanduser() def ensure_cloned(self, shallow: bool = True) -> None: """ Ensuret that a copy of this repo has been cloned and is up to date. """ dest_dir = self.cache_dir if not dest_dir.is_dir(): dest_dir.parent.mkdir(parents=True, exist_ok=True) if shallow: sh.git("clone", "--depth=1", self.github_url, dest_dir.as_posix(), _fg=True) else: sh.git("clone", self.github_url, dest_dir.as_posix(), _fg=True) else: self.update_and_reset() def update_and_reset(self) -> None: """ Fetch new changes from origin and do a hard reset of the repo from origin/<current-branch>. The hard reset is to avoid the update breaking if there have been force pushes from master. """ if not self.cache_dir.is_dir(): raise Exception("cannot update repo until repo is cloned") self._git("fetch") self._git("reset", "--hard", f"origin/{self.branch_name}") @property def branch_name(self) -> str: "Return the current branch name of the checked out repo." # in newer versions of git we can do "git branch --show-current" # but these aren't available on Ubuntu 18.04 on live return self._git("symbolic-ref", "--short", "HEAD") @property def latest_sha(self) -> str: master_file = self.cache_dir / ".git/refs/heads/master" with open(master_file, "r") as f: sha = f.read().strip() return sha def _git(self, *args: str, **kwargs: Any) -> str: "Execute a git command in the context of this repo." return cast( str, sh.git("--no-pager", *args, _cwd=self.cache_dir.as_posix(), **kwargs).stdout.decode("utf8").strip(), ) def METHOD_NAME(self) -> bool: "Returns true if remote has no new changes, false otherwise." if not self.cache_dir.is_dir(): return False return self.latest_remote_sha() == self.latest_sha def latest_remote_sha(self) -> str: "Return the latest commit SHA of the remote branch." # we rely on the smart HTTPS protocol for Git served by Github # https://www.git-scm.com/docs/http-protocol # # Responses look like this: # # S: 200 OK # S: Content-Type: application/x-git-upload-pack-advertisement # S: Cache-Control: no-cache # S: # S: 001e# service=git-upload-pack\n # S: 0000 # S: 004895dcfa3633004da0049d3d0fa03f80589cbcaf31 refs/heads/maint\0multi_ack\n # S: 003fd049f6c27a2244e12041955e262a404c7faba355 refs/heads/master\n # S: 003c2cb58b79488a98d2721cea644875a8dd0026b115 refs/tags/v1.0\n # S: 003fa3c2e2402b99163d1d59756e5f207ae21cccba4c refs/tags/v1.0^{}\n # S: 0000 uri = self.github_url + "/info/refs?service=git-upload-pack" resp = requests.get(uri) resp.raise_for_status() lines = resp.content.decode("latin-1").splitlines() for line in lines: # XXX some repos now use "main" instead of "master" if line.count(" ") == 1 and line.endswith("refs/heads/master"): # the first four bytes are the line length, ignore them sha = line.split(" ")[0][4:] return cast(str, sha) raise Exception("Could not find latest remote SHA in response") class GitError(Exception): pass
299,025
opt logging
from __future__ import absolute_import, division, print_function from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer from scitbx.array_family import flex from libtbx.development.timers import Timer import cgi, sys from six.moves import StringIO from spotfinder.applications.stats_distl import optionally_add_saturation_webice,key_adaptor from urlparse import urlparse #backward compatibility with Python 2.5 try: from urlparse import parse_qs except Exception: from cgi import parse_qs def module_safe_items(image): return [ ("%7d","Good Bragg Candidates",key_adaptor(image,'N_spots_inlier')), ("%7.0f","Total integrated signal, pixel-ADC units above local background", key_adaptor(image,'ad_hoc_signal1')), ("%7d","Ice Rings",key_adaptor(image,'ice-ring_impact')), ("%7.1f","Resolution estimate",key_adaptor(image,'resolution')), ("%7.1f","Maximum unit cell",key_adaptor(image,'maxcel')), ] def module_image_stats(S,key): # List of spots between specified high- and low-resolution limits image = S.images[key] spots = image.__getitem__('spots_inlier') integrated = 0.0 for i,spot in enumerate(spots): integrated += flex.sum(spot.wts) image["ad_hoc_signal1"]=integrated canonical_info = [] canonical_info.extend(module_safe_items(image)) optionally_add_saturation_webice(canonical_info,image) for item in canonical_info: if item[2]==None: print("%63s : None"%item[1]) else: print("%63s : %s"%(item[1],item[0]%item[2])) class image_request_handler(BaseHTTPRequestHandler): def do_POST(self): T = Timer("do_POST") parsed = urlparse(self.path) qs = parse_qs(parsed.query) expect = self.headers.getheaders("Expect") if len(expect)>=1: if True in [item.find("100")>=0 for item in expect]: self.send_response(100) # untested; has no apparent affect on libcurl # Get arguments by reading body of request. # We read this in chunks to avoid straining # socket.read(); around the 10 or 15Mb mark, some platforms # begin to have problems (bug #792570). max_chunk_size = 10*1024*1024 size_remaining = int(self.headers["content-length"]) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = ''.join(L) post_data = StringIO(data) # Parse the multipart/form-data contentTypeHeader = self.headers.getheaders('content-type').pop() # Extract the boundary parameter in the content-type header headerParameters = contentTypeHeader.split(";") boundary = headerParameters[1].split("=") boundary = boundary[1].strip() parts = cgi.parse_multipart(post_data, {"boundary":boundary, "content-disposition":self.headers.getheaders('content-disposition') }) print("*****************************") for item in parts.keys(): if len(parts[item][0])< 1000: print(item, parts[item]) print("*****************************") from iotbx.detectors.image_from_http_request import module_or_slice_from_http_request imgobj = module_or_slice_from_http_request(parts) imgobj.read() print("Final image object:") imgobj.show_header() from spotfinder.diffraction.imagefiles import image_files, file_names from spotfinder.diffraction.imagefiles import Spotspickle_argument_module from spotfinder.applications.overall_procedure import spotfinder_no_pickle class server_imagefiles(image_files): def __init__(self): pass Files = server_imagefiles() Files.filenames = file_names(Spotspickle_argument_module(imgobj.filename)) Files.images = [imgobj] S = spotfinder_no_pickle(Files, s3_passthru = "-s3 4", spot_convention = 0) frames = Files.frames() logfile = StringIO() sys.stdout = logfile from spotfinder.applications.stats_distl import pretty_image_stats,notes for frame in frames: #pretty_image_stats(S,frame) #notes(S,frames[0]) module_image_stats(S,frame) sys.stdout = sys.__stdout__ log = logfile.getvalue() print(log) ctype = 'text/plain' self.send_response(200) self.send_header("Content-type", ctype) self.send_header("Content-length",len(log)) self.end_headers() self.wfile.write(log) self.METHOD_NAME() def METHOD_NAME(self): pass if __name__=="__main__": import sys try: port = int(sys.argv[1]) except Exception: print(""" Usage: libtbx.python adsc_server.py <port number> """) server_address = ('', port) image_request_handler.protocol_version = "HTTP/1.0" httpd = HTTPServer(server_address, image_request_handler) sa = httpd.socket.getsockname() print("Serving HTTP on", sa[0], "port", sa[1], "...") httpd.serve_forever()
299,026
test runningmasses
import unittest from .running import * import numpy as np import flavio from flavio.config import config par = {} par['alpha_s'] = 0.1185 par['alpha_e'] = 1/127. par['m_Z'] = 91.1876 par['m_b'] = 4.18 par['m_d'] = 4.8e-3 par['m_s'] = 0.095 par['m_t'] = 173.21 par['m_c'] = 1.275 par['m_u'] = 2.3e-3 par_pdg = par.copy() par_pdg['alpha_s'] = 0.1193 par_pdg['alpha_e'] = 1/127.94 par_pdg['m_Z'] = 91.1876 par_pdg['m_b'] = 4.18 # to compare to RunDec par_noqed = par.copy() par_noqed['alpha_e'] = 0. # to compare to 1107.3100 par_ks = par.copy() par_ks['m_c'] = 1.329 par_ks['m_b'] = 4.183 class TestRunning(unittest.TestCase): def test_alphae(self): # compare to alpha_em at m_tau as given on p. 4 of # http://pdg.lbl.gov/2015/reviews/rpp2014-rev-standard-model.pdf alpha_tau = get_alpha_e(par_pdg, 1.777) self.assertAlmostEqual(1/alpha_tau/133.465,1.,places=3) # check at thresholds mc = config['RGE thresholds']['mc'] self.assertEqual(get_alpha_e(par_pdg, mc), get_alpha_e(par_pdg, mc, nf_out=4)) self.assertEqual(get_alpha_e(par_pdg, mc, nf_out=3), get_alpha_e(par_pdg, mc, nf_out=4)) mb = config['RGE thresholds']['mb'] self.assertEqual(get_alpha_e(par_pdg, mb), get_alpha_e(par_pdg, mb, nf_out=5)) self.assertEqual(get_alpha_e(par_pdg, mb, nf_out=4), get_alpha_e(par_pdg, mb, nf_out=5)) mt = config['RGE thresholds']['mt'] self.assertEqual(get_alpha_e(par_pdg, mt), get_alpha_e(par_pdg, mt, nf_out=6)) self.assertEqual(get_alpha_e(par_pdg, mt, nf_out=5), get_alpha_e(par_pdg, mt, nf_out=6)) def test_alphas(self): alpha_b = get_alpha(par_noqed, 4.2) # compare to 3-loop alpha_s at 4.2 GeV according to RunDec self.assertAlmostEqual(alpha_b['alpha_s']/0.225911,1.,places=4) def METHOD_NAME(self): # compare to RunDec np.testing.assert_almost_equal(get_mb(par, 120.)/2.79211, 1,decimal=2) np.testing.assert_almost_equal(get_mt(par, 120.)/167.225, 1,decimal=2) def test_polemasses(self): np.testing.assert_almost_equal(get_mb_pole(par, nl=2)/4.78248, 1,decimal=2) np.testing.assert_almost_equal(get_mc_pole(par, nl=2)/1.68375, 1,decimal=2) np.testing.assert_almost_equal(get_mb_pole(par, nl=3)/4.92987, 1,decimal=2) def test_ksmass(self): # compare to 1107.3100 # KS -> MSbar conversion self.assertAlmostEqual( flavio.physics.running.masses.mKS2mMS(4.55, 4, get_alpha(par_ks, 4.55)['alpha_s'], Mu=1, nl=2), 4.20, delta=0.01) self.assertAlmostEqual( flavio.physics.running.masses.mKS2mMS(1.15, 3, get_alpha(par_ks, 1.15)['alpha_s'], Mu=1, nl=2), 1.329, delta=0.01) # MSbar -> KS conversion self.assertAlmostEqual(get_mb_KS(par_ks, 1.), 4.553, delta=0.01) self.assertAlmostEqual(get_mc_KS(par_ks, 1.), 1.091, delta=0.13) # this is satisfied poorly! def test_mb1S(self): par = flavio.default_parameters.get_central_all() par['m_b'] = 4.18 par['alpha_s'] = 0.1185 alpha_s = get_alpha(par, par['m_b'], nf_out=5)['alpha_s'] mb1S = get_mb_1S(par, nl=3) self.assertAlmostEqual(mb1S, 4.67, delta=0.005) def test_f_perp(self): par = flavio.default_parameters.get_central_all() self.assertEqual(par['f_perp_K*0'], get_f_perp(par, 'K*0', 2)) self.assertEqual(par['f_perp_K*0'], get_f_perp(par, 'K*0', 2, nf_out=3)) self.assertEqual(par['f_perp_K*0'], get_f_perp(par, 'K*0', 2, nf_out=4)) # rough comparison of 1503.05534 and 0804.0473 self.assertAlmostEqual(get_f_perp(par, 'K*0', 1) / par['f_perp_K*0'], 0.159 / (0.712 * 0.204), delta=0.025) self.assertAlmostEqual(get_f_perp(par, 'K*0', 1) / par['f_perp_K*0'], 0.159 / (0.712 * 0.204), delta=0.025) # just check this doesn't raise get_f_perp(par, 'phi', 100, nf_out=6)
299,027
test query
import unittest import torch import os import numpy as np from naslib.search_spaces import NasBench101SearchSpace from naslib.search_spaces.nasbench101 import conversions import naslib.utils.nb101_api as api SPEC = (0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 4, 2, 3, 3, 3, 1) SAMPLED_SPEC = (0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 2, 3, 3, 1) HASHSPEC = 'ff940d27cbe9ed0a639a68a9c3f87283' # Random HASH from NB101 FIXED_ARCH = (0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 3, 4, 1) def create_dummy_api(): # TODO: Complete nb101_datapath = os.path.join(os.getcwd(), "assets", "nb101_dummy.pkl") nb101_data = api.NASBench(nb101_datapath) return {"api": api, "nb101_data": nb101_data} def create_model(spec, n_classes=10): torch.manual_seed(9001) graph = NasBench101SearchSpace(n_classes=n_classes) graph.set_spec(spec) return graph class NasBench101SearchSpaceTest(unittest.TestCase): def test_set_and_get_spec(self): graph = NasBench101SearchSpace() graph.set_spec(SPEC) retrieved_spec = graph.get_hash() self.assertEqual(SPEC, retrieved_spec) def test_set_and_get_spec_hash(self): graph = NasBench101SearchSpace() dummy_api = create_dummy_api() graph.set_spec(HASHSPEC, dummy_api) retrieved_spec = graph.get_hash() print(retrieved_spec) self.assertEqual(FIXED_ARCH, retrieved_spec) def test_forward_pass(self): torch.manual_seed(9001) graph = create_model(n_classes=10, spec=SPEC) out = graph(torch.randn(3, 3, 32, 32)) self.assertTrue(torch.allclose(out[0].detach(), torch.tensor([0.0737, 0.0128, 0.0086, 0.0214, 0.0912, -0.0532, 0.0479, 0.1870, -0.0248, 0.1075]), rtol=1e-2)) self.assertTrue(torch.allclose(out[1].detach(), torch.tensor([0.0667, 0.0115, 0.0107, 0.0106, 0.0570, -0.0186, 0.0353, 0.1650, -0.0165, 0.0848]), rtol=1e-2)) self.assertTrue(torch.allclose(out[2].detach(), torch.tensor([0.0536, 0.0136, -0.0104, 0.0174, 0.0753, -0.0871, 0.0472, 0.1974, -0.0231, 0.1336]), rtol=1e-2)) self.assertEqual(out.shape, (3, 10)) # TODO: Complete. These tests require a dummy NAS-Bench-101 API. def test_sample_random_architecture(self): graph = NasBench101SearchSpace() np.random.seed(9001) graph.sample_random_architecture(create_dummy_api()) spec = graph.get_hash() self.assertEqual(spec, SAMPLED_SPEC) def METHOD_NAME(self): graph = NasBench101SearchSpace() graph.set_spec(SPEC) def test_get_arch_iterator(self): graph = NasBench101SearchSpace() it = graph.get_arch_iterator(create_dummy_api()) archs = set(it) self.assertEqual(len(archs), 30) self.assertIn('ff97db031fa41552d437b079b2befd80', archs) self.assertIn('ff968f800464555f97c776c71481826d', archs) self.assertIn('ff940d27cbe9ed0a639a68a9c3f87283', archs) def test_mutate(self): graph_parent = create_model(spec=SPEC) graph_child = NasBench101SearchSpace() graph_child.mutate(graph_parent, create_dummy_api()) parent_spec = graph_parent.get_hash() child_spec = graph_child.get_hash() self.assertNotEqual(parent_spec, child_spec) out = graph_child(torch.randn(3, 3, 32, 32)) self.assertEqual(out.shape, (3, 10)) def test_get_nbhd(self): graph = create_model(spec=SPEC) neighbours = graph.get_nbhd(create_dummy_api()) print(len(neighbours)) self.assertEqual(len(neighbours), 12) def test_conversions(self): torch.manual_seed(9001) data = torch.randn(3, 3, 32, 32) graph1 = create_model(spec=SPEC) out1 = graph1(data) spec = conversions.convert_tuple_to_spec(SPEC) graph2 = create_model(spec=spec) out2 = graph2(data) tup = conversions.convert_spec_to_tuple(spec) graph3 = create_model(spec=tup) out3 = graph3(data) self.assertEqual(SPEC, tup) self.assertTrue(torch.allclose(out1, out2)) self.assertTrue(torch.allclose(out1, out3)) self.assertTrue(torch.allclose(out2, out3)) if __name__ == '__main__': unittest.main()
299,028
find eggs
import functools import importlib.metadata import logging import os import pathlib import sys import zipfile import zipimport from typing import Iterator, List, Optional, Sequence, Set, Tuple from pip._vendor.packaging.utils import NormalizedName, canonicalize_name from pip._internal.metadata.base import BaseDistribution, BaseEnvironment from pip._internal.models.wheel import Wheel from pip._internal.utils.deprecation import deprecated from pip._internal.utils.filetypes import WHEEL_EXTENSION from ._compat import BadMetadata, BasePath, get_dist_name, get_info_location from ._dists import Distribution logger = logging.getLogger(__name__) def _looks_like_wheel(location: str) -> bool: if not location.endswith(WHEEL_EXTENSION): return False if not os.path.isfile(location): return False if not Wheel.wheel_file_re.match(os.path.basename(location)): return False return zipfile.is_zipfile(location) class _DistributionFinder: """Finder to locate distributions. The main purpose of this class is to memoize found distributions' names, so only one distribution is returned for each package name. At lot of pip code assumes this (because it is setuptools's behavior), and not doing the same can potentially cause a distribution in lower precedence path to override a higher precedence one if the caller is not careful. Eventually we probably want to make it possible to see lower precedence installations as well. It's useful feature, after all. """ FoundResult = Tuple[importlib.metadata.Distribution, Optional[BasePath]] def __init__(self) -> None: self._found_names: Set[NormalizedName] = set() def _find_impl(self, location: str) -> Iterator[FoundResult]: """Find distributions in a location.""" # Skip looking inside a wheel. Since a package inside a wheel is not # always valid (due to .data directories etc.), its .dist-info entry # should not be considered an installed distribution. if _looks_like_wheel(location): return # To know exactly where we find a distribution, we have to feed in the # paths one by one, instead of dumping the list to importlib.metadata. for dist in importlib.metadata.distributions(path=[location]): info_location = get_info_location(dist) try: raw_name = get_dist_name(dist) except BadMetadata as e: logger.warning("Skipping %s due to %s", info_location, e.reason) continue normalized_name = canonicalize_name(raw_name) if normalized_name in self._found_names: continue self._found_names.add(normalized_name) yield dist, info_location def find(self, location: str) -> Iterator[BaseDistribution]: """Find distributions in a location. The path can be either a directory, or a ZIP archive. """ for dist, info_location in self._find_impl(location): if info_location is None: installed_location: Optional[BasePath] = None else: installed_location = info_location.parent yield Distribution(dist, info_location, installed_location) def find_linked(self, location: str) -> Iterator[BaseDistribution]: """Read location in egg-link files and return distributions in there. The path should be a directory; otherwise this returns nothing. This follows how setuptools does this for compatibility. The first non-empty line in the egg-link is read as a path (resolved against the egg-link's containing directory if relative). Distributions found at that linked location are returned. """ path = pathlib.Path(location) if not path.is_dir(): return for child in path.iterdir(): if child.suffix != ".egg-link": continue with child.open() as f: lines = (line.strip() for line in f) target_rel = next((line for line in lines if line), "") if not target_rel: continue target_location = str(path.joinpath(target_rel)) for dist, info_location in self._find_impl(target_location): yield Distribution(dist, info_location, path) def _find_eggs_in_dir(self, location: str) -> Iterator[BaseDistribution]: from pip._vendor.pkg_resources import find_distributions from pip._internal.metadata import pkg_resources as legacy with os.scandir(location) as it: for entry in it: if not entry.name.endswith(".egg"): continue for dist in find_distributions(entry.path): yield legacy.Distribution(dist) def _find_eggs_in_zip(self, location: str) -> Iterator[BaseDistribution]: from pip._vendor.pkg_resources import find_eggs_in_zip from pip._internal.metadata import pkg_resources as legacy try: importer = zipimport.zipimporter(location) except zipimport.ZipImportError: return for dist in find_eggs_in_zip(importer, location): yield legacy.Distribution(dist) def METHOD_NAME(self, location: str) -> Iterator[BaseDistribution]: """Find eggs in a location. This actually uses the old *pkg_resources* backend. We likely want to deprecate this so we can eventually remove the *pkg_resources* dependency entirely. Before that, this should first emit a deprecation warning for some versions when using the fallback since importing *pkg_resources* is slow for those who don't need it. """ if os.path.isdir(location): yield from self._find_eggs_in_dir(location) if zipfile.is_zipfile(location): yield from self._find_eggs_in_zip(location) @functools.lru_cache(maxsize=None) # Warn a distribution exactly once. def _emit_egg_deprecation(location: Optional[str]) -> None: deprecated( reason=f"Loading egg at {location} is deprecated.", replacement="to use pip for package installation.", gone_in=None, ) class Environment(BaseEnvironment): def __init__(self, paths: Sequence[str]) -> None: self._paths = paths @classmethod def default(cls) -> BaseEnvironment: return cls(sys.path) @classmethod def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment: if paths is None: return cls(sys.path) return cls(paths) def _iter_distributions(self) -> Iterator[BaseDistribution]: finder = _DistributionFinder() for location in self._paths: yield from finder.find(location) for dist in finder.METHOD_NAME(location): # _emit_egg_deprecation(dist.location) # TODO: Enable this. yield dist # This must go last because that's how pkg_resources tie-breaks. yield from finder.find_linked(location) def get_distribution(self, name: str) -> Optional[BaseDistribution]: matches = ( distribution for distribution in self.iter_all_distributions() if distribution.canonical_name == canonicalize_name(name) ) return next(matches, None)
299,029
test encoding numpy scalars within nested extractors
import json import pytest import numpy as np from spikeinterface.core.base import BaseExtractor from spikeinterface.core.core_tools import SIJsonEncoder from spikeinterface.core.generate import generate_recording, generate_sorting @pytest.fixture(scope="module") def numpy_generated_recording(): recording = generate_recording() return recording @pytest.fixture(scope="module") def numpy_generated_sorting(): sorting = generate_sorting() return sorting @pytest.fixture(scope="module") def numpy_array_integer(): return np.arange(0, 3, dtype="int32") @pytest.fixture(scope="module") def numpy_array_float(): return np.ones(3, dtype="float32") @pytest.fixture(scope="module") def numpy_array_bool(numpy_array_float): return numpy_array_float > 0.5 @pytest.fixture(scope="module") def dictionary_with_numpy_scalar_keys(numpy_array_integer, numpy_array_float, numpy_array_bool): numpy_integer_scalar = numpy_array_integer[0] numpy_float_scalar = numpy_array_float[0] numpy_boolean_scalar = numpy_array_bool[1] dictionary = { numpy_integer_scalar: "value_of_numpy_integer_scalar", numpy_float_scalar: "value_of_numpy_float_scalar", numpy_boolean_scalar: "value_of_boolean_scalar", } return dictionary def test_numpy_array_encoding(numpy_array_integer, numpy_array_float, numpy_array_bool): json.dumps(numpy_array_integer, cls=SIJsonEncoder) json.dumps(numpy_array_float, cls=SIJsonEncoder) json.dumps(numpy_array_bool, cls=SIJsonEncoder) def test_encoding_dict_with_array_values(numpy_array_integer, numpy_array_float, numpy_array_bool): dict_with_array_as_values = dict(int=numpy_array_integer, float=numpy_array_float, boolean=numpy_array_bool) json.dumps(dict_with_array_as_values, cls=SIJsonEncoder) def test_encoding_dict_with_array_values_nested(numpy_array_integer, numpy_array_float, numpy_array_bool): nested_dict_with_array_as_values = dict( boolean=numpy_array_bool, nested=dict( int=numpy_array_integer, float=numpy_array_float, double_nested=dict(extra=numpy_array_integer * 2) ), ) json.dumps(nested_dict_with_array_as_values, cls=SIJsonEncoder) def test_encoding_numpy_scalars_values(numpy_array_integer, numpy_array_float, numpy_array_bool): numpy_integer_scalar = numpy_array_integer[0] numpy_float_scalar = numpy_array_float[0] numpy_boolean_scalar = numpy_array_bool[0] dict_with_numpy_scalar_values = dict( integer=numpy_integer_scalar, float=numpy_float_scalar, boolean=numpy_boolean_scalar ) json.dumps(dict_with_numpy_scalar_values, cls=SIJsonEncoder) def test_encoding_numpy_scalars_keys(dictionary_with_numpy_scalar_keys): json.dumps(dictionary_with_numpy_scalar_keys, cls=SIJsonEncoder) def test_encoding_numpy_scalars_keys_nested(numpy_array_integer, numpy_array_float, numpy_array_bool): numpy_integer_scalar = numpy_array_integer[0] numpy_float_scalar = numpy_array_float[0] numpy_boolean_scalar = numpy_array_bool[1] dict_with_nested_numpy_scalars = {numpy_integer_scalar: {numpy_float_scalar: {numpy_boolean_scalar: "deep_value"}}} json.dumps(dict_with_nested_numpy_scalars, cls=SIJsonEncoder) def test_encoding_numpy_scalars_keys_nested_mixed(numpy_array_integer, numpy_array_float, numpy_array_bool): numpy_integer_scalar = numpy_array_integer[0] numpy_float_scalar = numpy_array_float[0] numpy_boolean_scalar = numpy_array_bool[1] another_numpy_integer_scalar = numpy_array_integer[1] another_numpy_float_scalar = numpy_array_float[1] dict_with_nested_numpy_scalars = { numpy_integer_scalar: { another_numpy_float_scalar: False, numpy_float_scalar: {numpy_boolean_scalar: "deep_value"}, }, another_numpy_integer_scalar: [{another_numpy_integer_scalar: "deper_value"}, "list_value"], } json.dumps(dict_with_nested_numpy_scalars, cls=SIJsonEncoder) def test_numpy_dtype_encoding(): json.dumps(np.dtype("int32"), cls=SIJsonEncoder) json.dumps(np.dtype("float32"), cls=SIJsonEncoder) json.dumps(np.dtype("bool"), cls=SIJsonEncoder) def test_numpy_dtype_alises_encoding(): # People tend to use this a dtype instead of the proper classes json.dumps(np.int32, cls=SIJsonEncoder) json.dumps(np.float32, cls=SIJsonEncoder) json.dumps(np.bool_, cls=SIJsonEncoder) # Note that np.bool was deperecated in numpy 1.20.0 def test_recording_encoding(numpy_generated_recording): recording = numpy_generated_recording json.dumps(recording, cls=SIJsonEncoder) def test_sorting_encoding(numpy_generated_sorting): sorting = numpy_generated_sorting json.dumps(sorting, cls=SIJsonEncoder) class DummyExtractor(BaseExtractor): def __init__(self, attribute, other_extractor=None, extractor_list=None, extractor_dict=None): self.an_attribute = attribute self.other_extractor = other_extractor self.extractor_list = extractor_list self.extractor_dict = extractor_dict # this already the case by default self._is_dumpable = True self._is_json_serializable = True self._kwargs = { "attribute": attribute, "other_extractor": other_extractor, "extractor_list": extractor_list, "extractor_dict": extractor_dict, } @pytest.fixture(scope="module") def nested_extractor(dictionary_with_numpy_scalar_keys): inner_extractor = DummyExtractor(attribute=dictionary_with_numpy_scalar_keys) extractor = DummyExtractor(attribute="a random attribute", other_extractor=inner_extractor) return extractor @pytest.fixture(scope="module") def nested_extractor_list(dictionary_with_numpy_scalar_keys): inner_extractor1 = DummyExtractor(attribute=dictionary_with_numpy_scalar_keys) inner_extractor2 = DummyExtractor(attribute=dictionary_with_numpy_scalar_keys) extractor = DummyExtractor(attribute="a random attribute", extractor_list=[inner_extractor1, inner_extractor2]) return extractor @pytest.fixture(scope="module") def nested_extractor_dict(dictionary_with_numpy_scalar_keys): inner_extractor1 = DummyExtractor(attribute=dictionary_with_numpy_scalar_keys) inner_extractor2 = DummyExtractor(attribute=dictionary_with_numpy_scalar_keys) extractor = DummyExtractor( attribute="a random attribute", extractor_dict=dict(inner_extractor1=inner_extractor1, inner_extractor2=inner_extractor2), ) return extractor def METHOD_NAME(nested_extractor): json.dumps(nested_extractor, cls=SIJsonEncoder) def test_encoding_numpy_scalars_within_nested_extractors_list(nested_extractor_list): json.dumps(nested_extractor_list, cls=SIJsonEncoder) def test_encoding_numpy_scalars_within_nested_extractors_dict(nested_extractor_dict): json.dumps(nested_extractor_dict, cls=SIJsonEncoder)
299,030
test empty init
"""A mixin for all common tests that should be run on all algorithm classes.""" import inspect import joblib import pytest from numpydoc.docscrape import NumpyDocString from tpcp import BaseFactory, get_action_method, get_action_params, get_param_names, get_results from gaitmap.base import BaseAlgorithm, BaseType from tests.conftest import compare_algo_objects class TestAlgorithmMixin: algorithm_class = None __test__ = False @pytest.fixture() def valid_instance(self, after_action_instance): return after_action_instance @pytest.fixture() def after_action_instance(self) -> BaseType: pass def test_init(self): """Test that all init paras are passed through untouched.""" field_names = get_param_names(self.algorithm_class) init_dict = {k: k for k in field_names} test_instance = self.algorithm_class(**init_dict) for k, v in init_dict.items(): assert getattr(test_instance, k) == v, k def METHOD_NAME(self): """Test that the class has only optional kwargs.""" self.algorithm_class() def test_all_parameters_documented(self): docs = NumpyDocString(inspect.getdoc(self.algorithm_class)) documented_names = {p.name for p in docs["Parameters"]} actual_names = set(get_param_names(self.algorithm_class)) assert documented_names == actual_names def test_all_attributes_documented(self, after_action_instance): if not after_action_instance: pytest.skip("The testclass did not implement the correct `after_action_instance` fixture.") docs = NumpyDocString(inspect.getdoc(self.algorithm_class)) documented_names = {p.name for p in docs["Attributes"]} actual_names = set(get_results(after_action_instance).keys()) assert documented_names == actual_names def test_all_other_parameters_documented(self, after_action_instance): if not after_action_instance: pytest.skip("The testclass did not implement the correct `after_action_instance` fixture.") docs = NumpyDocString(inspect.getdoc(self.algorithm_class)) documented_names = {p.name for p in docs["Other Parameters"]} actual_names = set(get_action_params(after_action_instance).keys()) assert documented_names == actual_names def test_action_method_returns_self(self, after_action_instance): # call the action method a second time to test the output if not after_action_instance: pytest.skip("The testclass did not implement the correct `after_action_instance` fixture.") parameters = get_action_params(after_action_instance) results = get_action_method(after_action_instance)(**parameters) assert id(results) == id(after_action_instance) def test_set_params_valid(self, valid_instance): instance = valid_instance.clone() valid_names = get_param_names(instance) values = list(range(len(valid_names))) instance.set_params(**dict(zip(valid_names, values))) for k, v in zip(valid_names, values): assert getattr(instance, k) == v, k def test_set_params_invalid(self, valid_instance): instance = valid_instance.clone() with pytest.raises(ValueError) as e: instance.set_params(an_invalid_name=1) assert "an_invalid_name" in str(e) assert self.algorithm_class.__name__ in str(e) def test_json_roundtrip(self, valid_instance): instance = valid_instance.clone() json_str = instance.to_json() instance_from_json = self.algorithm_class.from_json(json_str) compare_algo_objects(instance, instance_from_json) def test_hashing(self, valid_instance): """This checks if caching with joblib will work as expected.""" instance = valid_instance.clone() assert joblib.hash(instance) == joblib.hash(instance.clone()) def test_nested_algo_marked_default(self): init = self.algorithm_class.__init__ if init is object.__init__: # No explicit constructor to introspect pytest.skip() # introspect the constructor arguments to find the _model parameters to represent init_signature = inspect.signature(init) # Consider the constructor parameters excluding 'self' parameters = { p.name: p.default for p in init_signature.parameters.values() if p.name != "self" and p.kind != p.VAR_KEYWORD } nested_algos = {k: v for k, v in parameters.items() if isinstance(v, (BaseAlgorithm, BaseFactory))} if len(nested_algos) == 0: pytest.skip() # If nested algos exists, we check that we get a new instance of the nested object and not the mutable default. # If not, we let the test fail, as we should always wrap such paras in a default explicitly. new_instance = self.algorithm_class().get_params() for k, v in nested_algos.items(): assert new_instance[k] is not v, "nested algorithm defaults should be wrapped in `default`."
299,031
get destination
# SPDX-License-Identifier: Apache-2.0 # # The OpenSearch Contributors require contributions made to # this file be licensed under the Apache-2.0 license or a # compatible open source license. # # Modifications Copyright OpenSearch Contributors. See # GitHub history for details. from ..client.utils import NamespacedClient, _make_path, query_params class AlertingClient(NamespacedClient): @query_params() async def search_monitor(self, body, params=None, headers=None): """ Returns the search result for a monitor. :arg monitor_id: The configuration for the monitor we are trying to search """ return await self.transport.perform_request( "GET", _make_path("_plugins", "_alerting", "monitors", "_search"), params=params, headers=headers, body=body, ) @query_params() async def get_monitor(self, monitor_id, params=None, headers=None): """ Returns the details of a specific monitor. :arg monitor_id: The id of the monitor we are trying to fetch """ return await self.transport.perform_request( "GET", _make_path("_plugins", "_alerting", "monitors", monitor_id), params=params, headers=headers, ) @query_params("dryrun") async def run_monitor(self, monitor_id, params=None, headers=None): """ Runs/Executes a specific monitor. :arg monitor_id: The id of the monitor we are trying to execute :arg dryrun: Shows the results of a run without actions sending any message """ return await self.transport.perform_request( "POST", _make_path("_plugins", "_alerting", "monitors", monitor_id, "_execute"), params=params, headers=headers, ) @query_params() async def create_monitor(self, body=None, params=None, headers=None): """ Creates a monitor with inputs, triggers, and actions. :arg body: The configuration for the monitor (`inputs`, `triggers`, and `actions`) """ return await self.transport.perform_request( "POST", _make_path("_plugins", "_alerting", "monitors"), params=params, headers=headers, body=body, ) @query_params() async def update_monitor(self, monitor_id, body=None, params=None, headers=None): """ Updates a monitor's inputs, triggers, and actions. :arg monitor_id: The id of the monitor we are trying to update :arg body: The configuration for the monitor (`inputs`, `triggers`, and `actions`) """ return await self.transport.perform_request( "PUT", _make_path("_plugins", "_alerting", "monitors", monitor_id), params=params, headers=headers, body=body, ) @query_params() async def delete_monitor(self, monitor_id, params=None, headers=None): """ Deletes a specific monitor. :arg monitor_id: The id of the monitor we are trying to delete """ return await self.transport.perform_request( "DELETE", _make_path("_plugins", "_alerting", "monitors", monitor_id), params=params, headers=headers, ) @query_params() async def METHOD_NAME(self, destination_id=None, params=None, headers=None): """ Returns the details of a specific destination. :arg destination_id: The id of the destination we are trying to fetch. If None, returns all destinations """ return await self.transport.perform_request( "GET", _make_path("_plugins", "_alerting", "destinations", destination_id) if destination_id else _make_path("_plugins", "_alerting", "destinations"), params=params, headers=headers, ) @query_params() async def create_destination(self, body=None, params=None, headers=None): """ Creates a destination for slack, mail, or custom-webhook. :arg body: The configuration for the destination """ return await self.transport.perform_request( "POST", _make_path("_plugins", "_alerting", "destinations"), params=params, headers=headers, body=body, ) @query_params() async def update_destination( self, destination_id, body=None, params=None, headers=None ): """ Updates a destination's inputs, triggers, and actions. :arg destination_id: The id of the destination we are trying to update :arg body: The configuration for the destination """ return await self.transport.perform_request( "PUT", _make_path("_plugins", "_alerting", "destinations", destination_id), params=params, headers=headers, body=body, ) @query_params() async def delete_destination(self, destination_id, params=None, headers=None): """ Deletes a specific destination. :arg destination_id: The id of the destination we are trying to delete """ return await self.transport.perform_request( "DELETE", _make_path("_plugins", "_alerting", "destinations", destination_id), params=params, headers=headers, ) @query_params() async def get_alerts(self, params=None, headers=None): """ Returns all alerts. """ return await self.transport.perform_request( "GET", _make_path("_plugins", "_alerting", "monitors", "alerts"), params=params, headers=headers, ) @query_params() async def acknowledge_alert(self, monitor_id, body=None, params=None, headers=None): """ Acknowledges an alert. :arg monitor_id: The id of the monitor, the alert belongs to :arg body: The alerts to be acknowledged """ return await self.transport.perform_request( "POST", _make_path( "_plugins", "_alerting", "monitors", monitor_id, "_acknowledge", "alerts", ), params=params, headers=headers, body=body, )
299,032
is numerical
""" **data** module provides abstractions for data manipulation: - **Dataset** represents the entire dataset used by a job: providing simple access to subsets like training set, test set, and metadata like target feature, and predictors. - **Datasplit** represents a subset of the dataset, providing access to data, either as a file (``path``), or as vectors/arrays (``y`` for target, ``X`` for predictors) which can also be encoded (``y_enc``, ``X_enc``) - **Feature** provides metadata for a given feature/column as well as encoding functions. """ from abc import ABC, abstractmethod from enum import Enum, auto import logging from typing import List, Union import numpy as np import pandas as pd import scipy.sparse as sp from .datautils import Encoder from .utils import clear_cache, lazy_property, profile, repr_def log = logging.getLogger(__name__) AM = Union[np.ndarray, sp.spmatrix] DF = pd.DataFrame class Feature: def __init__(self, index, name, data_type, values=None, has_missing_values=False, is_target=False): """ :param index: index of the feature in the full data frame. :param name: name of the feature. :param data_type: one of pandas-compatible type ('int', 'float', 'number', 'bool', 'category', 'string', 'object', 'datetime'). :param values: for categorical features, the sorted list of accepted values. :param has_missing_values: True iff the feature has any missing values in the complete dataset. :param is_target: True for the target column. """ self.index = index self.name = name self.data_type = data_type.lower() if data_type is not None else None self.values = values self.has_missing_values = has_missing_values self.is_target = is_target # print(self) def is_categorical(self, strict=True): if strict: return self.data_type == 'category' else: return self.data_type is not None and not self.METHOD_NAME() def METHOD_NAME(self): return self.data_type in ['int', 'float', 'number'] @lazy_property def label_encoder(self): return Encoder('label' if self.values is not None else 'no-op', target=self.is_target, encoded_type=int if self.is_target and not self.METHOD_NAME() else float, missing_values=[None, np.nan, pd.NA], missing_policy='mask' if self.has_missing_values else 'ignore', normalize_fn=self.normalize ).fit(self.values) @lazy_property def one_hot_encoder(self): return Encoder('one-hot' if self.values is not None else 'no-op', target=self.is_target, encoded_type=int if self.is_target and not self.METHOD_NAME() else float, missing_values=[None, np.nan, pd.NA], missing_policy='mask' if self.has_missing_values else 'ignore', normalize_fn=self.normalize ).fit(self.values) def normalize(self, arr): return np.char.lower(np.char.strip(np.asarray(arr).astype(str))) @property def values(self): return self._values @values.setter def values(self, values): self._values = self.normalize(values).tolist() if values is not None else None def __repr__(self): return repr_def(self, 'all') class Datasplit(ABC): def __init__(self, dataset, format): """ :param format: the default format of the data file, obtained through the 'path' property. """ super().__init__() self.dataset = dataset self.format = format @property def path(self) -> str: return self.data_path(self.format) @abstractmethod def data_path(self, format: str) -> str: """ :param format: the format requested for the data file. Currently supported formats are 'arff', 'csv'. :return: the path to the data-split file in the requested format. """ pass @property @abstractmethod def data(self) -> DF: """ :return: all the columns (predictors + target) as a pandas DataFrame. """ pass @lazy_property @profile(logger=log) def X(self) -> DF: """ :return:the predictor columns as a pandas DataFrame. """ predictors_ind = [p.index for p in self.dataset.predictors] return self.data.iloc[:, predictors_ind] @lazy_property @profile(logger=log) def y(self) -> DF: """ :return:the target column as a pandas DataFrame: if you need a Series, just call `y.squeeze()`. """ return self.data.iloc[:, [self.dataset.target.index]] @lazy_property @profile(logger=log) def data_enc(self) -> AM: encoded_cols = [f.label_encoder.transform(self.data.iloc[:, f.index]) for f in self.dataset.features] # optimize mem usage : frameworks use either raw data or encoded ones, # so we can clear the cached raw data once they've been encoded self.release(['data', 'X', 'y']) return np.hstack(tuple(col.reshape(-1, 1) for col in encoded_cols)) @lazy_property @profile(logger=log) def X_enc(self) -> AM: # TODO: should we use one_hot_encoder here instead? # encoded_cols = [p.label_encoder.transform(self.data[:, p.index]) for p in self.dataset.predictors] # return np.hstack(tuple(col.reshape(-1, 1) for col in encoded_cols)) predictors_ind = [p.index for p in self.dataset.predictors] return self.data_enc[:, predictors_ind] @lazy_property @profile(logger=log) def y_enc(self) -> AM: # return self.dataset.target.label_encoder.transform(self.y) return self.data_enc[:, self.dataset.target.index] @profile(logger=log) def release(self, properties=None): clear_cache(self, properties) class DatasetType(Enum): binary = 1 multiclass = 2 regression = 3 timeseries = 4 class Dataset(ABC): def __init__(self): super().__init__() @property @abstractmethod def type(self) -> DatasetType: """ :return: the problem type for the current dataset. """ pass @property @abstractmethod def train(self) -> Datasplit: """ :return: the data subset used to train the model. """ pass @property @abstractmethod def test(self) -> Datasplit: """ :return: the data subset used to score the model. """ pass @property @abstractmethod def features(self) -> List[Feature]: """ :return: the list of all features available in the current dataset, target included. """ pass @property def predictors(self) -> List[Feature]: """ :return: the list of all predictor features available in the current dataset """ return [f for f in self.features if f.name != self.target.name] @property @abstractmethod def target(self) -> Feature: """ :return: the target feature for the current dataset. """ pass @profile(logger=log) def release(self, properties=None): """ Call this to release cached properties and optimize memory once in-memory data are not needed anymore. :param properties: """ self.train.release() self.test.release() clear_cache(self, properties)
299,033
default traffic packet template with seq modifiers
from expects import * import time from common.helper.traffic import (make_traffic_definition, make_traffic_duration, make_traffic_load, make_traffic_template) import client.api import client.models SEQ_MODIFIER_PACKET = [ {'ethernet': {'source': '10:94:00:00:aa:bb', 'modifiers': { 'items': [ {'destination': { 'sequence': {'count': 10, 'start': '00:00:01:00:00:01'}} } ] }} }, {'ipv4': { 'modifiers': { 'items': [ {'source': { 'sequence': {'count': 10, 'start': '198.18.15.1'}} }, {'destination': { 'sequence': {'count': 10, 'start': '198.18.16.1'}} } ], 'tie': 'zip'} }}, 'udp' ] LIST_MODIFIER_PACKET = [ {'ethernet': {'source': '10:94:00:00:aa:bb', 'destination': '10:94:00:00:bb:cc'}}, {'ipv4': { 'modifiers': { 'items': [ {'source': { 'list': ['198.18.15.1', '198.18.15.3', '198.18.15.5'] }}, {'destination': { 'list': ['198.18.16.1', '198.18.16.3', '198.18.16.5'] }} ], 'tie': 'zip'} }}, 'udp' ] GENERATOR_CONFIG_DEFAULT = { 'duration': {'continuous': True}, 'load': {'rate': 10}, 'protocol_counters': ['ethernet', 'ip', 'transport'], 'traffic': [ { 'length': {'fixed': 128}, 'packet': [ {'ethernet': {'source': '10:94:00:00:aa:bb', 'destination': '10:94:00:00:bb:cc'}}, {'ipv4': {'source': '198.18.15.10', 'destination': '198.18.15.20'}}, 'udp' ] } ] } def get_first_port_id(api_client): ports_api = client.api.PortsApi(api_client) ports = ports_api.list_ports() expect(ports).not_to(be_empty) return ports[0].id def get_second_port_id(api_client): ports_api = client.api.PortsApi(api_client) ports = ports_api.list_ports() expect(ports).not_to(be_empty) return ports[1].id def METHOD_NAME(permute_flag=None): model = make_traffic_template(SEQ_MODIFIER_PACKET) for protocol in model.protocols: if protocol.modifiers: for modifier in protocol.modifiers.items: modifier.permute = permute_flag if permute_flag else False return model def default_traffic_packet_template_with_list_modifiers(permute_flag=None): model = make_traffic_template(LIST_MODIFIER_PACKET) for protocol in model.protocols: if protocol.modifiers: for modifier in protocol.modifiers.items: modifier.permute = permute_flag if permute_flag else False return model def packet_generator_config(**kwargs): duration_config = kwargs['duration'] if 'duration' in kwargs else DURATION_CONFIG load_config = kwargs['load'] if 'load' in kwargs else LOAD_CONFIG packet_config = kwargs['traffic'] if 'traffic' in kwargs else TRAFFIC_CONFIG config = client.models.PacketGeneratorConfig() config.duration = make_traffic_duration(duration_config) config.load = make_traffic_load(load_config) config.traffic = list(map(make_traffic_definition, packet_config)) config.order = kwargs['order'] if 'order' in kwargs else 'round-robin' config.protocol_counters = kwargs['protocol_counters'] if 'protocol_counters' in kwargs else None return config def config_model(): return packet_generator_config(**GENERATOR_CONFIG_DEFAULT) def packet_generator_model(api_client): config = packet_generator_config(**GENERATOR_CONFIG_DEFAULT) gen = client.models.PacketGenerator() gen.target_id = get_first_port_id(api_client) gen.config = config return gen def packet_generator_models(api_client): ports_api = client.api.PortsApi(api_client) ports = ports_api.list_ports() expect(ports).to(have_len(be_above(1))) gen1 = packet_generator_model(api_client) gen1.target_id = ports[0].id gen2 = packet_generator_model(api_client) gen2.target_id = ports[1].id return [gen1, gen2] def wait_for_learning_resolved(api_client, generator_id, **kwargs): poll_interval = kwargs['poll_interval'] if 'poll_interval' in kwargs else 1 max_poll_count = kwargs['max_poll_count'] if 'max_poll_count' in kwargs else 3 for _ in range(max_poll_count): gen = api_client.get_packet_generator(generator_id) if gen.learning == 'resolved': return True time.sleep(poll_interval) return Fals
299,034
test registry
import os import random import pytest from web3 import Web3 from nucypher.blockchain.eth.actors import Operator, Ritualist from nucypher.blockchain.eth.agents import ContractAgency, PREApplicationAgent from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.signers.software import Web3Signer from nucypher.config.constants import TEMPORARY_DOMAIN from nucypher.crypto.powers import CryptoPower, TransactingPower from nucypher.policy.conditions.evm import RPCCondition from nucypher.policy.payment import SubscriptionManagerPayment from nucypher.utilities.logging import Logger from tests.constants import ( BONUS_TOKENS_FOR_TESTS, INSECURE_DEVELOPMENT_PASSWORD, MIN_STAKE_FOR_TESTS, MOCK_STAKING_CONTRACT_NAME, TEST_ETH_PROVIDER_URI, TESTERCHAIN_CHAIN_ID, ) from tests.utils.ape import deploy_contracts as ape_deploy_contracts from tests.utils.ape import registry_from_ape_deployments from tests.utils.blockchain import TesterBlockchain from tests.utils.ursula import ( mock_permitted_multichain_connections, setup_multichain_ursulas, ) test_logger = Logger("acceptance-test-logger") @pytest.fixture(scope="session", autouse=True) def mock_condition_blockchains(session_mocker): """adds testerchain's chain ID to permitted conditional chains""" session_mocker.patch.dict( "nucypher.policy.conditions.evm._CONDITION_CHAINS", {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) session_mocker.patch.object( NetworksInventory, "get_polygon_chain_id", return_value=TESTERCHAIN_CHAIN_ID ) session_mocker.patch.object( NetworksInventory, "get_ethereum_chain_id", return_value=TESTERCHAIN_CHAIN_ID ) @pytest.fixture(scope="module", autouse=True) def mock_multichain_configuration(module_mocker, testerchain): module_mocker.patch.object( Ritualist, "_make_condition_provider", return_value=testerchain.provider ) @pytest.fixture(scope='session', autouse=True) def nucypher_contracts(project): nucypher_contracts_dependency_api = project.dependencies["nucypher-contracts"] # simply use first entry - could be from github ('main') or local ('local') _, nucypher_contracts = list(nucypher_contracts_dependency_api.items())[0] nucypher_contracts.compile() return nucypher_contracts @pytest.fixture(scope='module', autouse=True) def deploy_contracts(nucypher_contracts, accounts): deployments = ape_deploy_contracts( nucypher_contracts=nucypher_contracts, accounts=accounts ) return deployments @pytest.fixture(scope='module', autouse=True) def METHOD_NAME(nucypher_contracts, deploy_contracts): registry = registry_from_ape_deployments(nucypher_contracts, deployments=deploy_contracts) return registry @pytest.fixture(scope='module') def testerchain(project, METHOD_NAME) -> TesterBlockchain: # Extract the web3 provider containing EthereumTester from the ape project's chain manager provider = project.chain_manager.provider.web3.provider testerchain = TesterBlockchain(eth_provider=provider) BlockchainInterfaceFactory.register_interface(interface=testerchain, force=True) yield testerchain @pytest.fixture(scope='module') def threshold_staking(testerchain, METHOD_NAME): result = METHOD_NAME.search(contract_name=MOCK_STAKING_CONTRACT_NAME)[0] threshold_staking = testerchain.w3.eth.contract( address=result[2], abi=result[3] ) return threshold_staking @pytest.fixture(scope="module") def staking_providers(testerchain, METHOD_NAME, threshold_staking): pre_application_agent = ContractAgency.get_agent( PREApplicationAgent, registry=METHOD_NAME, provider_uri=TEST_ETH_PROVIDER_URI, ) blockchain = pre_application_agent.blockchain staking_providers = list() for provider_address, operator_address in zip(blockchain.stake_providers_accounts, blockchain.ursulas_accounts): provider_power = TransactingPower(account=provider_address, signer=Web3Signer(testerchain.client)) provider_power.unlock(password=INSECURE_DEVELOPMENT_PASSWORD) # for a random amount amount = MIN_STAKE_FOR_TESTS + random.randrange(BONUS_TOKENS_FOR_TESTS) # initialize threshold stake tx = threshold_staking.functions.setRoles(provider_address).transact() testerchain.wait_for_receipt(tx) tx = threshold_staking.functions.setStakes(provider_address, amount, 0, 0).transact() testerchain.wait_for_receipt(tx) # We assume that the staking provider knows in advance the account of her operator pre_application_agent.bond_operator(staking_provider=provider_address, operator=operator_address, transacting_power=provider_power) operator_power = TransactingPower( account=operator_address, signer=Web3Signer(testerchain.client) ) operator = Operator( is_me=True, operator_address=operator_address, domain=TEMPORARY_DOMAIN, registry=METHOD_NAME, transacting_power=operator_power, eth_provider_uri=testerchain.eth_provider_uri, signer=Web3Signer(testerchain.client), crypto_power=CryptoPower(power_ups=[operator_power]), payment_method=SubscriptionManagerPayment( eth_provider=testerchain.eth_provider_uri, network=TEMPORARY_DOMAIN, registry=METHOD_NAME, ), ) operator.confirm_address() # assume we always need a "pre-confirmed" operator for now. # track staking_providers.append(provider_address) yield staking_providers @pytest.fixture(scope='module') def manual_operator(testerchain): worker_private_key = os.urandom(32).hex() address = testerchain.provider.ethereum_tester.add_account( worker_private_key, password=INSECURE_DEVELOPMENT_PASSWORD ) tx = {'to': address, 'from': testerchain.etherbase_account, 'value': Web3.to_wei('1', 'ether')} txhash = testerchain.client.w3.eth.send_transaction(tx) _receipt = testerchain.wait_for_receipt(txhash) yield address @pytest.fixture(scope="module") def monkeymodule(): from _pytest.monkeypatch import MonkeyPatch mpatch = MonkeyPatch() yield mpatch mpatch.undo() @pytest.fixture(scope="module") def mock_rpc_condition(module_mocker, testerchain, monkeymodule): def configure_mock(condition, provider, *args, **kwargs): condition.provider = provider return testerchain.w3 monkeymodule.setattr(RPCCondition, "_configure_w3", configure_mock) configure_spy = module_mocker.spy(RPCCondition, "_configure_w3") chain_id_check_mock = module_mocker.patch.object(RPCCondition, "_check_chain_id") return configure_spy, chain_id_check_mock @pytest.fixture(scope="module") def multichain_ids(module_mocker): ids = mock_permitted_multichain_connections(mocker=module_mocker) return ids @pytest.fixture(scope="module") def multichain_ursulas(ursulas, multichain_ids, mock_rpc_condition): setup_multichain_ursulas(ursulas=ursulas, chain_ids=multichain_ids) return ursulas
299,035
public tables
from contextlib import contextmanager from testflows.core import * from testflows.asserts import error from rbac.requirements import * from rbac.helper.common import * @TestScenario @Requirements( RQ_SRS_006_RBAC_Table_PublicTables("1.0"), ) def METHOD_NAME(self, node=None): """Check that a user with no privilege is able to select from public tables. """ user_name = f"user_{getuid()}" if node is None: node = self.context.node with user(node, f"{user_name}"): with When("I check the user is able to select on system.one"): node.query("SELECT count(*) FROM system.one", settings = [("user",user_name)]) with And("I check the user is able to select on system.numbers"): node.query("SELECT * FROM system.numbers LIMIT 1", settings = [("user",user_name)]) with And("I check the user is able to select on system.contributors"): node.query("SELECT count(*) FROM system.contributors", settings = [("user",user_name)]) with And("I check the user is able to select on system.functions"): node.query("SELECT count(*) FROM system.functions", settings = [("user",user_name)]) @TestScenario @Requirements( RQ_SRS_006_RBAC_Table_SensitiveTables("1.0"), ) def sensitive_tables(self, node=None): """Check that a user with no privilege is not able to see from these tables. """ user_name = f"user_{getuid()}" if node is None: node = self.context.node with user(node, f"{user_name}"): with Given("I create a query"): node.query("SELECT 1") with When("I select from processes"): output = node.query("SELECT count(*) FROM system.processes", settings = [("user",user_name)]).output assert output == 0, error() with And("I select from query_log"): output = node.query("SELECT count(*) FROM system.query_log", settings = [("user",user_name)]).output assert output == 0, error() with And("I select from query_thread_log"): output = node.query("SELECT count(*) FROM system.query_thread_log", settings = [("user",user_name)]).output assert output == 0, error() with And("I select from clusters"): output = node.query("SELECT count(*) FROM system.clusters", settings = [("user",user_name)]).output assert output == 0, error() with And("I select from events"): output = node.query("SELECT count(*) FROM system.events", settings = [("user",user_name)]).output assert output == 0, error() with And("I select from graphite_retentions"): output = node.query("SELECT count(*) FROM system.graphite_retentions", settings = [("user",user_name)]).output assert output == 0, error() with And("I select from stack_trace"): output = node.query("SELECT count(*) FROM system.stack_trace", settings = [("user",user_name)]).output assert output == 0, error() with And("I select from trace_log"): output = node.query("SELECT count(*) FROM system.trace_log", settings = [("user",user_name)]).output assert output == 0, error() with And("I select from user_directories"): output = node.query("SELECT count(*) FROM system.user_directories", settings = [("user",user_name)]).output assert output == 0, error() with And("I select from zookeeper"): output = node.query("SELECT count(*) FROM system.zookeeper WHERE path = '/clickhouse' ", settings = [("user",user_name)]).output assert output == 0, error() with And("I select from macros"): output = node.query("SELECT count(*) FROM system.macros", settings = [("user",user_name)]).output assert output == 0, error() @TestFeature @Name("public tables") def feature(self, node="clickhouse1"): self.context.node = self.context.cluster.node(node) Scenario(run=METHOD_NAME, setup=instrument_clickhouse_server_log) Scenario(run=sensitive_tables, setup=instrument_clickhouse_server_log)
299,036
validate nb
from nbformat import read as _read, reads as _reads from nbformat import write as _write, writes as _writes from nbformat.notebooknode import NotebookNode import typing from .v1 import MetadataValidatorV1 from .v2 import MetadataValidatorV2 from .common import BaseMetadataValidator, ValidationError from nbformat.notebooknode import NotebookNode class MetadataValidatorV3(BaseMetadataValidator): schema_version = 3 def __init__(self) -> None: super().__init__() self.v1 = MetadataValidatorV1() self.v2 = MetadataValidatorV2() def _upgrade_v2_to_v3(self, cell: NotebookNode) -> NotebookNode: meta = cell.metadata['nbgrader'] meta['schema_version'] = self.schema_version return cell def upgrade_cell_metadata(self, cell: NotebookNode) -> NotebookNode: if 'nbgrader' not in cell.metadata: return cell if 'schema_version' not in cell.metadata['nbgrader']: cell.metadata['nbgrader']['schema_version'] = 0 if cell.metadata['nbgrader']['schema_version'] == 0: cell = self.v1._upgrade_v0_to_v1(cell) if 'nbgrader' not in cell.metadata: return cell if cell.metadata['nbgrader']['schema_version'] == 1: cell = self.v2._upgrade_v1_to_v2(cell) if cell.metadata['nbgrader']['schema_version'] == 2: cell = self._upgrade_v2_to_v3(cell) self._remove_extra_keys(cell) return cell def validate_cell(self, cell: NotebookNode) -> None: super(MetadataValidatorV3, self).validate_cell(cell) if 'nbgrader' not in cell.metadata: return meta = cell.metadata['nbgrader'] grade = meta['grade'] solution = meta['solution'] locked = meta['locked'] task = meta.get('task', False) # check if the cell type has changed if 'cell_type' in meta: if meta['cell_type'] != cell.cell_type: self.log.warning("Cell type has changed from {} to {}!".format( meta['cell_type'], cell.cell_type), cell) # check for a valid grade id if grade or solution or locked: if 'grade_id' not in meta: raise ValidationError("nbgrader cell does not have a grade_id: {}".format(cell.source)) if meta['grade_id'] == '': raise ValidationError("grade_id is empty") # check for valid points if grade: if 'points' not in meta: raise ValidationError("nbgrader cell '{}' does not have points".format( meta['grade_id'])) # check that markdown cells are grade AND solution (not either/or) if not task: if cell.cell_type == "markdown" and grade and not solution: raise ValidationError( "Markdown grade cell '{}' is not marked as a solution cell".format( meta['grade_id'])) if cell.cell_type == "markdown" and not grade and solution: raise ValidationError( "Markdown solution cell is not marked as a grade cell: {}".format(cell.source)) else: if cell.cell_type != "markdown": raise ValidationError( "Task cells have to be markdown: {}".format(cell.source)) def METHOD_NAME(self, nb: NotebookNode) -> None: super(MetadataValidatorV3, self).METHOD_NAME(nb) ids = set([]) for cell in nb.cells: if 'nbgrader' not in cell.metadata: continue grade = cell.metadata['nbgrader']['grade'] solution = cell.metadata['nbgrader']['solution'] locked = cell.metadata['nbgrader']['locked'] if not grade and not solution and not locked: continue grade_id = cell.metadata['nbgrader']['grade_id'] if grade_id in ids: raise ValidationError("Duplicate grade id: {}".format(grade_id)) ids.add(grade_id) def read_v3(source: typing.io.TextIO, as_version: int, **kwargs: typing.Any) -> NotebookNode: nb = _read(source, as_version, **kwargs) MetadataValidatorV3().METHOD_NAME(nb) return nb def write_v3(nb: NotebookNode, fp: typing.io.TextIO, **kwargs: typing.Any) -> None: MetadataValidatorV3().METHOD_NAME(nb) _write(nb, fp, **kwargs) def reads_v3(source: str, as_version: int, **kwargs: typing.Any) -> NotebookNode: nb = _reads(source, as_version, **kwargs) MetadataValidatorV3().METHOD_NAME(nb) return nb def writes_v3(nb: NotebookNode, **kwargs: typing.Any) -> None: MetadataValidatorV3().METHOD_NAME(nb) _writes(nb, **kwargs)
299,037
fields int
""" invariants_fc ============= Autogenerated DPF operator classes. """ from warnings import warn from ansys.dpf.core.dpf_operator import Operator from ansys.dpf.core.inputs import Input, _Inputs from ansys.dpf.core.outputs import Output, _Outputs from ansys.dpf.core.operators.specification import PinSpecification, Specification class invariants_fc(Operator): """Computes the element-wise invariants of all the tensor fields of a fields container. Parameters ---------- fields_container : FieldsContainer Examples -------- >>> from ansys.dpf import core as dpf >>> # Instantiate operator >>> op = dpf.operators.invariant.invariants_fc() >>> # Make input connections >>> my_fields_container = dpf.FieldsContainer() >>> op.inputs.fields_container.connect(my_fields_container) >>> # Instantiate operator and connect inputs in one line >>> op = dpf.operators.invariant.invariants_fc( ... fields_container=my_fields_container, ... ) >>> # Get output data >>> result_fields_int = op.outputs.fields_int() >>> result_fields_eqv = op.outputs.fields_eqv() >>> result_fields_max_shear = op.outputs.fields_max_shear() """ def __init__(self, fields_container=None, config=None, server=None): super().__init__(name="invariants_deriv_fc", config=config, server=server) self._inputs = InputsInvariantsFc(self) self._outputs = OutputsInvariantsFc(self) if fields_container is not None: self.inputs.fields_container.connect(fields_container) @staticmethod def _spec(): description = """Computes the element-wise invariants of all the tensor fields of a fields container.""" spec = Specification( description=description, map_input_pin_spec={ 0: PinSpecification( name="fields_container", type_names=["fields_container"], optional=False, document="""""", ), }, map_output_pin_spec={ 0: PinSpecification( name="fields_int", type_names=["fields_container"], optional=False, document="""Stress intensity field""", ), 1: PinSpecification( name="fields_eqv", type_names=["fields_container"], optional=False, document="""Stress equivalent intensity""", ), 2: PinSpecification( name="fields_max_shear", type_names=["fields_container"], optional=False, document="""Max shear stress field""", ), }, ) return spec @staticmethod def default_config(server=None): """Returns the default config of the operator. This config can then be changed to the user needs and be used to instantiate the operator. The Configuration allows to customize how the operation will be processed by the operator. Parameters ---------- server : server.DPFServer, optional Server with channel connected to the remote or local instance. When ``None``, attempts to use the global server. """ return Operator.default_config(name="invariants_deriv_fc", server=server) @property def inputs(self): """Enables to connect inputs to the operator Returns -------- inputs : InputsInvariantsFc """ return super().inputs @property def outputs(self): """Enables to get outputs of the operator by evaluating it Returns -------- outputs : OutputsInvariantsFc """ return super().outputs class InputsInvariantsFc(_Inputs): """Intermediate class used to connect user inputs to invariants_fc operator. Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.invariant.invariants_fc() >>> my_fields_container = dpf.FieldsContainer() >>> op.inputs.fields_container.connect(my_fields_container) """ def __init__(self, op: Operator): super().__init__(invariants_fc._spec().inputs, op) self._fields_container = Input(invariants_fc._spec().input_pin(0), 0, op, -1) self._inputs.append(self._fields_container) @property def fields_container(self): """Allows to connect fields_container input to the operator. Parameters ---------- my_fields_container : FieldsContainer Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.invariant.invariants_fc() >>> op.inputs.fields_container.connect(my_fields_container) >>> # or >>> op.inputs.fields_container(my_fields_container) """ return self._fields_container class OutputsInvariantsFc(_Outputs): """Intermediate class used to get outputs from invariants_fc operator. Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.invariant.invariants_fc() >>> # Connect inputs : op.inputs. ... >>> result_fields_int = op.outputs.fields_int() >>> result_fields_eqv = op.outputs.fields_eqv() >>> result_fields_max_shear = op.outputs.fields_max_shear() """ def __init__(self, op: Operator): super().__init__(invariants_fc._spec().outputs, op) self._fields_int = Output(invariants_fc._spec().output_pin(0), 0, op) self._outputs.append(self._fields_int) self._fields_eqv = Output(invariants_fc._spec().output_pin(1), 1, op) self._outputs.append(self._fields_eqv) self._fields_max_shear = Output(invariants_fc._spec().output_pin(2), 2, op) self._outputs.append(self._fields_max_shear) @property def METHOD_NAME(self): """Allows to get fields_int output of the operator Returns ---------- my_fields_int : FieldsContainer Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.invariant.invariants_fc() >>> # Connect inputs : op.inputs. ... >>> result_fields_int = op.outputs.fields_int() """ # noqa: E501 return self._fields_int @property def fields_eqv(self): """Allows to get fields_eqv output of the operator Returns ---------- my_fields_eqv : FieldsContainer Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.invariant.invariants_fc() >>> # Connect inputs : op.inputs. ... >>> result_fields_eqv = op.outputs.fields_eqv() """ # noqa: E501 return self._fields_eqv @property def fields_max_shear(self): """Allows to get fields_max_shear output of the operator Returns ---------- my_fields_max_shear : FieldsContainer Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.invariant.invariants_fc() >>> # Connect inputs : op.inputs. ... >>> result_fields_max_shear = op.outputs.fields_max_shear() """ # noqa: E501 return self._fields_max_shear
299,038
sort
# Copyright (c) 2022 Ultimaker B.V. # Uranium is released under the terms of the LGPLv3 or higher. from operator import itemgetter from PyQt6.QtCore import QAbstractListModel, QVariant, QModelIndex, pyqtSlot, pyqtProperty, pyqtSignal from typing import Any, Callable, Dict, List, Optional class ListModel(QAbstractListModel): """Convenience base class for models of a list of items. This class represents a list of dictionary objects that can be exposed to QML. It is intended primarily as a read-only convenience class but supports removing elements so can also be used for limited writing. """ def __init__(self, parent = None) -> None: super().__init__(parent) self._items: List[Dict[str, Any]] = [] self._role_names: Dict[int, bytes] = {} itemsChanged = pyqtSignal() @pyqtProperty(int, notify = itemsChanged) def count(self) -> int: return len(self._items) @pyqtSlot(result = int) def rowCount(self, parent = None) -> int: """This function is necessary because it is abstract in QAbstractListModel. Under the hood, Qt will call this function when it needs to know how many items are in the model. This pyqtSlot will not be linked to the itemsChanged signal, so please use the normal count() function instead. """ return self.count def addRoleName(self, role: int, name: str): # Qt roleNames expects a QByteArray. PyQt 5 does not convert str to # bytearray implicitly so force the conversion manually. self._role_names[role] = name.encode("utf-8") def roleNames(self): return self._role_names def data(self, index, role): """Reimplemented from QAbstractListModel""" if not index.isValid(): return QVariant() return self._items[index.row()][self._role_names[role].decode("utf-8")] @pyqtSlot(int, result="QVariantMap") def getItem(self, index: int) -> Dict[str, Any]: """Get an item from the list""" try: return self._items[index] except: return {} @pyqtProperty("QVariantList", notify = itemsChanged) def items(self) -> List[Dict[str, Any]]: """The list of items in this model.""" return self._items def setItems(self, items: List[Dict[str, Any]]) -> None: """Replace all items at once. :param items: The new list of items. """ # We do not use model reset because of the following: # - it is very slow # - it can cause crashes on Mac OS X for some reason when endResetModel() is called (CURA-6015) # So in this case, we use insertRows(), removeRows() and dataChanged signals to do # smarter model update. old_row_count = len(self._items) new_row_count = len(items) changed_row_count = min(old_row_count, new_row_count) need_to_add = old_row_count < new_row_count need_to_remove = old_row_count > new_row_count # In the case of insertion and deletion, we need to call beginInsertRows()/beginRemoveRows() and # endInsertRows()/endRemoveRows() before we modify the items. # In the case of modification on the existing items, we only need to modify the items and then emit # dataChanged(). # # Here it is simplified to replace the complete items list instead of adding/removing/modifying them one by one, # and it needs to make sure that the necessary signals (insert/remove/modified) are emitted before and after # the item replacement. if need_to_add: self.beginInsertRows(QModelIndex(), old_row_count, new_row_count - 1) elif need_to_remove: self.beginRemoveRows(QModelIndex(), new_row_count, old_row_count - 1) self._items = items if need_to_add: self.endInsertRows() elif need_to_remove: self.endRemoveRows() # Notify that the existing items have been changed. if changed_row_count >= 0: self.dataChanged.emit(self.index(0, 0), self.index(changed_row_count - 1, 0)) # Notify with the custom signal itemsChanged to keep it backwards compatible in case something relies on it. self.itemsChanged.emit() @pyqtSlot(dict) def appendItem(self, item: Dict[str, Any]): """Add an item to the list. :param item: The item to add. """ self.insertItem(len(self._items), item) @pyqtSlot(int, dict) def insertItem(self, index: int, item: Dict[str, Any]) -> None: """Insert an item into the list at an index. :param index: The index where to insert. :param item: The item to add. """ self.beginInsertRows(QModelIndex(), index, index) self._items.insert(index, item) self.endInsertRows() self.itemsChanged.emit() @pyqtSlot(int) def removeItem(self, index: int) -> None: """Remove an item from the list. :param index: The index of the item to remove. """ self.beginRemoveRows(QModelIndex(), index, index) del self._items[index] self.endRemoveRows() self.itemsChanged.emit() @pyqtSlot() def clear(self) -> None: """Clear the list.""" self.beginResetModel() self._items.clear() self.endResetModel() self.itemsChanged.emit() @pyqtSlot(int, str, QVariant) def setProperty(self, index: int, property: str, value: Any) -> None: self._items[index][property] = value self.dataChanged.emit(self.index(index, 0), self.index(index, 0)) def METHOD_NAME(self, fun: Callable[[Any], float], key: Optional[str] = None, reverse = False) -> None: """Sort the list. :param fun: The callable to use for determining the sort key. :param key: Use the sorting function on the underlying data :param reverse: reverse the sorted results """ self.beginResetModel() if key: self._items = sorted(self._items, key = lambda item: fun(itemgetter(key)(item)), reverse = reverse) else: self._items.METHOD_NAME(key = fun, reverse = reverse) self.endResetModel() @pyqtSlot(str, QVariant, result = int) def find(self, key: str, value: Any) -> int: """Find a entry by key value pair :param key: :param value: :return: index of setting if found, None otherwise """ for i in range(len(self._items)): if key in self._items[i]: if self._items[i][key] == value: return i return -1
299,039
jrel op
""" opcode module - potentially shared between dis and other modules which operate on bytecodes (e.g. peephole optimizers). """ __all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs", "haslocal", "hascompare", "hasfree", "opname", "opmap", "HAVE_ARGUMENT", "EXTENDED_ARG"] cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is', 'is not', 'exception match', 'BAD') hasconst = [] hasname = [] hasjrel = [] hasjabs = [] haslocal = [] hascompare = [] hasfree = [] opmap = {} opname = [''] * 256 for op in range(256): opname[op] = '<%r>' % (op,) del op def def_op(name, op): opname[op] = name opmap[name] = op def name_op(name, op): def_op(name, op) hasname.append(op) def METHOD_NAME(name, op): def_op(name, op) hasjrel.append(op) def jabs_op(name, op): def_op(name, op) hasjabs.append(op) # Instruction opcodes for compiled code # Blank lines correspond to available opcodes def_op('STOP_CODE', 0) def_op('POP_TOP', 1) def_op('ROT_TWO', 2) def_op('ROT_THREE', 3) def_op('DUP_TOP', 4) def_op('ROT_FOUR', 5) def_op('NOP', 9) def_op('UNARY_POSITIVE', 10) def_op('UNARY_NEGATIVE', 11) def_op('UNARY_NOT', 12) def_op('UNARY_CONVERT', 13) def_op('UNARY_INVERT', 15) def_op('BINARY_POWER', 19) def_op('BINARY_MULTIPLY', 20) def_op('BINARY_DIVIDE', 21) def_op('BINARY_MODULO', 22) def_op('BINARY_ADD', 23) def_op('BINARY_SUBTRACT', 24) def_op('BINARY_SUBSCR', 25) def_op('BINARY_FLOOR_DIVIDE', 26) def_op('BINARY_TRUE_DIVIDE', 27) def_op('INPLACE_FLOOR_DIVIDE', 28) def_op('INPLACE_TRUE_DIVIDE', 29) def_op('SLICE+0', 30) def_op('SLICE+1', 31) def_op('SLICE+2', 32) def_op('SLICE+3', 33) def_op('STORE_SLICE+0', 40) def_op('STORE_SLICE+1', 41) def_op('STORE_SLICE+2', 42) def_op('STORE_SLICE+3', 43) def_op('DELETE_SLICE+0', 50) def_op('DELETE_SLICE+1', 51) def_op('DELETE_SLICE+2', 52) def_op('DELETE_SLICE+3', 53) def_op('STORE_MAP', 54) def_op('INPLACE_ADD', 55) def_op('INPLACE_SUBTRACT', 56) def_op('INPLACE_MULTIPLY', 57) def_op('INPLACE_DIVIDE', 58) def_op('INPLACE_MODULO', 59) def_op('STORE_SUBSCR', 60) def_op('DELETE_SUBSCR', 61) def_op('BINARY_LSHIFT', 62) def_op('BINARY_RSHIFT', 63) def_op('BINARY_AND', 64) def_op('BINARY_XOR', 65) def_op('BINARY_OR', 66) def_op('INPLACE_POWER', 67) def_op('GET_ITER', 68) def_op('PRINT_EXPR', 70) def_op('PRINT_ITEM', 71) def_op('PRINT_NEWLINE', 72) def_op('PRINT_ITEM_TO', 73) def_op('PRINT_NEWLINE_TO', 74) def_op('INPLACE_LSHIFT', 75) def_op('INPLACE_RSHIFT', 76) def_op('INPLACE_AND', 77) def_op('INPLACE_XOR', 78) def_op('INPLACE_OR', 79) def_op('BREAK_LOOP', 80) def_op('WITH_CLEANUP', 81) def_op('LOAD_LOCALS', 82) def_op('RETURN_VALUE', 83) def_op('IMPORT_STAR', 84) def_op('EXEC_STMT', 85) def_op('YIELD_VALUE', 86) def_op('POP_BLOCK', 87) def_op('END_FINALLY', 88) def_op('BUILD_CLASS', 89) HAVE_ARGUMENT = 90 # Opcodes from here have an argument: name_op('STORE_NAME', 90) # Index in name list name_op('DELETE_NAME', 91) # "" def_op('UNPACK_SEQUENCE', 92) # Number of tuple items METHOD_NAME('FOR_ITER', 93) def_op('LIST_APPEND', 94) name_op('STORE_ATTR', 95) # Index in name list name_op('DELETE_ATTR', 96) # "" name_op('STORE_GLOBAL', 97) # "" name_op('DELETE_GLOBAL', 98) # "" def_op('DUP_TOPX', 99) # number of items to duplicate def_op('LOAD_CONST', 100) # Index in const list hasconst.append(100) name_op('LOAD_NAME', 101) # Index in name list def_op('BUILD_TUPLE', 102) # Number of tuple items def_op('BUILD_LIST', 103) # Number of list items def_op('BUILD_SET', 104) # Number of set items def_op('BUILD_MAP', 105) # Number of dict entries (upto 255) name_op('LOAD_ATTR', 106) # Index in name list def_op('COMPARE_OP', 107) # Comparison operator hascompare.append(107) name_op('IMPORT_NAME', 108) # Index in name list name_op('IMPORT_FROM', 109) # Index in name list METHOD_NAME('JUMP_FORWARD', 110) # Number of bytes to skip jabs_op('JUMP_IF_FALSE_OR_POP', 111) # Target byte offset from beginning of code jabs_op('JUMP_IF_TRUE_OR_POP', 112) # "" jabs_op('JUMP_ABSOLUTE', 113) # "" jabs_op('POP_JUMP_IF_FALSE', 114) # "" jabs_op('POP_JUMP_IF_TRUE', 115) # "" name_op('LOAD_GLOBAL', 116) # Index in name list jabs_op('CONTINUE_LOOP', 119) # Target address METHOD_NAME('SETUP_LOOP', 120) # Distance to target address METHOD_NAME('SETUP_EXCEPT', 121) # "" METHOD_NAME('SETUP_FINALLY', 122) # "" def_op('LOAD_FAST', 124) # Local variable number haslocal.append(124) def_op('STORE_FAST', 125) # Local variable number haslocal.append(125) def_op('DELETE_FAST', 126) # Local variable number haslocal.append(126) def_op('RAISE_VARARGS', 130) # Number of raise arguments (1, 2, or 3) def_op('CALL_FUNCTION', 131) # #args + (#kwargs << 8) def_op('MAKE_FUNCTION', 132) # Number of args with default values def_op('BUILD_SLICE', 133) # Number of items def_op('MAKE_CLOSURE', 134) def_op('LOAD_CLOSURE', 135) hasfree.append(135) def_op('LOAD_DEREF', 136) hasfree.append(136) def_op('STORE_DEREF', 137) hasfree.append(137) def_op('CALL_FUNCTION_VAR', 140) # #args + (#kwargs << 8) def_op('CALL_FUNCTION_KW', 141) # #args + (#kwargs << 8) def_op('CALL_FUNCTION_VAR_KW', 142) # #args + (#kwargs << 8) METHOD_NAME('SETUP_WITH', 143) def_op('EXTENDED_ARG', 145) EXTENDED_ARG = 145 def_op('SET_ADD', 146) def_op('MAP_ADD', 147) del def_op, name_op, METHOD_NAME, jabs_op
299,040
list runtime versions
# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Optional, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._runtime_versions_operations import build_list_runtime_versions_request T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class RuntimeVersionsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.appplatform.v2023_03_01_preview.aio.AppPlatformManagementClient`'s :attr:`runtime_versions` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") self._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def METHOD_NAME(self, **kwargs: Any) -> _models.AvailableRuntimeVersions: """Lists all of the available runtime versions supported by Microsoft.AppPlatform provider. :keyword callable cls: A custom type or function that will be passed the direct response :return: AvailableRuntimeVersions or the result of cls(response) :rtype: ~azure.mgmt.appplatform.v2023_03_01_preview.models.AvailableRuntimeVersions :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop( "api_version", _params.pop("api-version", self._api_version or "2023-03-01-preview") ) cls: ClsType[_models.AvailableRuntimeVersions] = kwargs.pop("cls", None) request = build_list_runtime_versions_request( api_version=api_version, template_url=self.METHOD_NAME.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("AvailableRuntimeVersions", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized METHOD_NAME.metadata = {"url": "/providers/Microsoft.AppPlatform/runtimeVersions"}
299,041
skipping test
# Copyright (c) PyZMQ Developers. # Distributed under the terms of the Modified BSD License. import sys import time from threading import Thread from unittest import TestCase try: from unittest import SkipTest except ImportError: from unittest2 import SkipTest from pytest import mark import zmq from zmq.utils import jsonapi try: import gevent from zmq import green as gzmq have_gevent = True except ImportError: have_gevent = False PYPY = 'PyPy' in sys.version #----------------------------------------------------------------------------- # skip decorators (directly from unittest) #----------------------------------------------------------------------------- _id = lambda x: x skip_pypy = mark.skipif(PYPY, reason="Doesn't work on PyPy") require_zmq_4 = mark.skipif(zmq.zmq_version_info() < (4,), reason="requires zmq >= 4") #----------------------------------------------------------------------------- # Base test class #----------------------------------------------------------------------------- class BaseZMQTestCase(TestCase): green = False teardown_timeout = 10 @property def Context(self): if self.green: return gzmq.Context else: return zmq.Context def socket(self, socket_type): s = self.context.socket(socket_type) self.sockets.append(s) return s def setUp(self): super(BaseZMQTestCase, self).setUp() if self.green and not have_gevent: raise SkipTest("requires gevent") self.context = self.Context.instance() self.sockets = [] def tearDown(self): contexts = set([self.context]) while self.sockets: sock = self.sockets.pop() contexts.add(sock.context) # in case additional contexts are created sock.close(0) for ctx in contexts: t = Thread(target=ctx.term) t.daemon = True t.start() t.join(timeout=self.teardown_timeout) if t.is_alive(): # reset Context.instance, so the failure to term doesn't corrupt subsequent tests zmq.sugar.context.Context._instance = None raise RuntimeError("context could not terminate, open sockets likely remain in test") super(BaseZMQTestCase, self).tearDown() def create_bound_pair(self, type1=zmq.PAIR, type2=zmq.PAIR, interface='tcp://127.0.0.1'): """Create a bound socket pair using a random port.""" s1 = self.context.socket(type1) s1.setsockopt(zmq.LINGER, 0) port = s1.bind_to_random_port(interface) s2 = self.context.socket(type2) s2.setsockopt(zmq.LINGER, 0) s2.connect('%s:%s' % (interface, port)) self.sockets.extend([s1,s2]) return s1, s2 def ping_pong(self, s1, s2, msg): s1.send(msg) msg2 = s2.recv() s2.send(msg2) msg3 = s1.recv() return msg3 def ping_pong_json(self, s1, s2, o): if jsonapi.jsonmod is None: raise SkipTest("No json library") s1.send_json(o) o2 = s2.recv_json() s2.send_json(o2) o3 = s1.recv_json() return o3 def ping_pong_pyobj(self, s1, s2, o): s1.send_pyobj(o) o2 = s2.recv_pyobj() s2.send_pyobj(o2) o3 = s1.recv_pyobj() return o3 def assertRaisesErrno(self, errno, func, *args, **kwargs): try: func(*args, **kwargs) except zmq.ZMQError as e: self.assertEqual(e.errno, errno, "wrong error raised, expected '%s' \ got '%s'" % (zmq.ZMQError(errno), zmq.ZMQError(e.errno))) else: self.fail("Function did not raise any error") def _select_recv(self, multipart, socket, **kwargs): """call recv[_multipart] in a way that raises if there is nothing to receive""" if zmq.zmq_version_info() >= (3,1,0): # zmq 3.1 has a bug, where poll can return false positives, # so we wait a little bit just in case # See LIBZMQ-280 on JIRA time.sleep(0.1) r,w,x = zmq.select([socket], [], [], timeout=kwargs.pop('timeout', 5)) assert len(r) > 0, "Should have received a message" kwargs['flags'] = zmq.DONTWAIT | kwargs.get('flags', 0) recv = socket.recv_multipart if multipart else socket.recv return recv(**kwargs) def recv(self, socket, **kwargs): """call recv in a way that raises if there is nothing to receive""" return self._select_recv(False, socket, **kwargs) def recv_multipart(self, socket, **kwargs): """call recv_multipart in a way that raises if there is nothing to receive""" return self._select_recv(True, socket, **kwargs) class PollZMQTestCase(BaseZMQTestCase): pass class GreenTest: """Mixin for making green versions of test classes""" green = True teardown_timeout = 10 def assertRaisesErrno(self, errno, func, *args, **kwargs): if errno == zmq.EAGAIN: raise SkipTest("Skipping because we're green.") try: func(*args, **kwargs) except zmq.ZMQError: e = sys.exc_info()[1] self.assertEqual(e.errno, errno, "wrong error raised, expected '%s' \ got '%s'" % (zmq.ZMQError(errno), zmq.ZMQError(e.errno))) else: self.fail("Function did not raise any error") def tearDown(self): contexts = set([self.context]) while self.sockets: sock = self.sockets.pop() contexts.add(sock.context) # in case additional contexts are created sock.close() try: gevent.joinall( [gevent.spawn(ctx.term) for ctx in contexts], timeout=self.teardown_timeout, raise_error=True, ) except gevent.Timeout: raise RuntimeError("context could not terminate, open sockets likely remain in test") def skip_green(self): raise SkipTest("Skipping because we are green") def skip_green(f): def METHOD_NAME(self, *args, **kwargs): if self.green: raise SkipTest("Skipping because we are green") else: return f(self, *args, **kwargs) return METHOD_NAME
299,042
check
# Copyright 2022 Battelle Energy Alliance, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This test demonstrates the ability for users to change the clusterEvalMode of a ROM with the new setAdditionalParams method in the externalROMloader file. This method should allow the user to set any ROM parameters that are present in the pickledROM class; however, that is not yet demonstrated in existing tests. The benefit of this method is to allow users to externally evaluate pickled ROM(s) with some ability to customize the evaluation settings. """ import sys import os import numpy as np # Add romLoader to path here = os.path.abspath(os.path.dirname(__file__)) # Paths for the ravenframework and test pk file frameworkPath = os.path.abspath(os.path.join(here, *['..']*4, 'ravenframework')) picklePath = os.path.join(here,'ARMA', 'arma.pk') assert os.path.exists(picklePath) # Appending externalROMloader to path sys.path.append(os.path.abspath(os.path.join(frameworkPath, '..', 'scripts'))) import externalROMloader def METHOD_NAME(runner, before, after, signal): """ Decides of application of setAdditionalParams was successful @ In, runner, externalROMloader object @ In, before/after, list, list of xml objects @ In, signal, string, name of signal that exists in ROM @ Out, results, dict, counts of passes and fails """ # Initializing the results index results = {'pass':0, 'fail':0} # Placeholder input necessary for evaluate method inp = {'scaling':[1]} # Running method of testing interest and evaluating runner.setAdditionalParams(before) res = runner.evaluate(inp)[0] beforeResult = res['_indexMap'][0][signal] # Checking for clustered index in non clustered eval if '_ROM_Cluster' not in beforeResult: results['pass'] += 1 else: results['fail'] += 1 runner.setAdditionalParams(after) res = runner.evaluate(inp)[0] afterResult = res['_indexMap'][0][signal] # Checking for clustered index in clustered eval if '_ROM_Cluster' in afterResult: results['pass'] += 1 else: results['fail'] += 1 # Returning results return results def initialize(picklePath, frameworkPath): """ Initializes the ravenROMexternal object and imports xmlUtils @ In, picklePath, path variable to pickle file in same folder as test @ In, frameworkPath, relative path to framework from working directory @ Out, runner, ROMloader object for externally evaluating ROM(s) """ runner = externalROMloader.ravenROMexternal(picklePath,frameworkPath) return runner def nodeGenerator(clusterEvalMode): """ Defines nodes object specifically for setting clusterEvalMode @ In, clusterEvalMode, string, 'full' or 'clustered' @ Out, nodes, list, list of xml nodes for setting pickleROM parameters """ #NOTE this kind of node definition should apply to any ROM parameter changes for this method # as long as the parameter being set with the xml node exists in the pickleROM object # Importing xml node tool from ravenframework.utils import xmlUtils nodes = [] node = xmlUtils.newNode('loadedROM', attrib={'name': 'ROM', 'subType': 'pickledROM'}) node.append(xmlUtils.newNode('clusterEvalMode', text=clusterEvalMode)) nodes.append(node) return nodes def main(): """ Runs the all the methods of the test script """ # Initializing runner, make sure to call this before nodeGenerator runner = initialize(picklePath, frameworkPath) # Name of signal in the ROM to run test with signal = 'Signal' # Getting 'full' and 'clustered' evaluations before = nodeGenerator('full') after = nodeGenerator('clustered') # Running test function results = METHOD_NAME(runner, before, after, signal) print(results) sys.exit(results['fail']) if __name__ == '__main__': main()
299,043
get config variable
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. from botocore.session import get_session from botocore.handlers import disable_signing import os from awscli.testutils import mock, unittest from awscli.compat import six from awscli.customizations import globalargs class FakeParsedArgs(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def __getattr__(self, arg): return None class FakeSession(object): def __init__(self, session_vars=None, config_file_vars=None): if session_vars is None: session_vars = {} self.session_var_map = session_vars if config_file_vars is None: config_file_vars = {} self.config_file_vars = config_file_vars def METHOD_NAME(self, name, methods=('env', 'config'), default=None): value = None config_name, envvar_name = self.session_var_map[name] if methods is not None: if 'env' in methods and value is None: value = os.environ.get(envvar_name) if 'config' in methods and value is None: value = self.config_file_vars.get(config_name) else: value = default return value class TestGlobalArgsCustomization(unittest.TestCase): def test_parse_query(self): parsed_args = FakeParsedArgs(query='foo.bar') globalargs.resolve_types(parsed_args) # Assert that it looks like a jmespath parsed expression. self.assertFalse(isinstance(parsed_args.query, six.string_types)) self.assertTrue(hasattr(parsed_args.query, 'search')) def test_parse_query_error_message(self): # Invalid jmespath expression. parsed_args = FakeParsedArgs(query='foo.bar.') with self.assertRaises(ValueError): globalargs.resolve_types(parsed_args) globalargs.resolve_types('query') def test_parse_verify_ssl_default_value(self): with mock.patch('os.environ', {}): parsed_args = FakeParsedArgs(verify_ssl=True, ca_bundle=None) session_var_map = {'ca_bundle': ('ca_bundle', 'AWS_CA_BUNDLE')} session = FakeSession(session_vars=session_var_map) globalargs.resolve_verify_ssl(parsed_args, session) # None, so that botocore can apply it's default logic. self.assertIsNone(parsed_args.verify_ssl) def test_parse_verify_ssl_verify_turned_off(self): with mock.patch('os.environ', {}): parsed_args = FakeParsedArgs(verify_ssl=False, ca_bundle=None) session_var_map = {'ca_bundle': ('ca_bundle', 'AWS_CA_BUNDLE')} session = FakeSession(session_vars=session_var_map) globalargs.resolve_verify_ssl(parsed_args, session) self.assertFalse(parsed_args.verify_ssl) def test_cli_overrides_cert_bundle(self): environ = {} with mock.patch('os.environ', environ): parsed_args = FakeParsedArgs( verify_ssl=True, ca_bundle='/path/to/cli_bundle.pem') config_file_vars = {} session_var_map = {'ca_bundle': ('ca_bundle', 'AWS_CA_BUNDLE')} session = FakeSession( session_vars=session_var_map, config_file_vars=config_file_vars) globalargs.resolve_verify_ssl(parsed_args, session) self.assertEqual(parsed_args.verify_ssl, '/path/to/cli_bundle.pem') def test_cli_overrides_env_cert_bundle(self): environ = { 'AWS_CA_BUNDLE': '/path/to/env_bundle.pem', } with mock.patch('os.environ', environ): parsed_args = FakeParsedArgs( verify_ssl=True, ca_bundle='/path/to/cli_bundle.pem') config_file_vars = {} session_var_map = {'ca_bundle': ('ca_bundle', 'AWS_CA_BUNDLE')} session = FakeSession( session_vars=session_var_map, config_file_vars=config_file_vars) globalargs.resolve_verify_ssl(parsed_args, session) self.assertEqual(parsed_args.verify_ssl, '/path/to/cli_bundle.pem') def test_no_verify_ssl_overrides_cli_cert_bundle(self): environ = { 'AWS_CA_BUNDLE': '/path/to/env_bundle.pem', } with mock.patch('os.environ', environ): parsed_args = FakeParsedArgs( verify_ssl=False, ca_bundle='/path/to/cli_bundle.pem') config_file_vars = {} session_var_map = {'ca_bundle': ('ca_bundle', 'AWS_CA_BUNDLE')} session = FakeSession( session_vars=session_var_map, config_file_vars=config_file_vars) globalargs.resolve_verify_ssl(parsed_args, session) self.assertFalse(parsed_args.verify_ssl) def test_no_sign_request_if_option_specified(self): args = FakeParsedArgs(sign_request=False) session = mock.Mock() globalargs.no_sign_request(args, session) emitter = session.get_component('event_emitter') emitter.register_first.assert_called_with( 'choose-signer', disable_signing, unique_id='disable-signing') def test_request_signed_by_default(self): args = FakeParsedArgs(sign_request=True) session = mock.Mock() globalargs.no_sign_request(args, session) self.assertFalse(session.register.called) def test_invalid_endpoint_url(self): # Invalid jmespath expression. parsed_args = FakeParsedArgs(endpoint_url='missing-scheme.com') with self.assertRaises(ValueError): globalargs.resolve_types(parsed_args) def test_valid_endpoint_url(self): parsed_args = FakeParsedArgs(endpoint_url='http://custom-endpoint.com') globalargs.resolve_types(parsed_args) self.assertEqual(parsed_args.endpoint_url, 'http://custom-endpoint.com') def test_cli_read_timeout(self): parsed_args = FakeParsedArgs(read_timeout='60') session = get_session() globalargs.resolve_cli_read_timeout(parsed_args, session) self.assertEqual(parsed_args.read_timeout, 60) self.assertEqual( session.get_default_client_config().read_timeout, 60) def test_cli_connect_timeout(self): parsed_args = FakeParsedArgs(connect_timeout='60') session = get_session() globalargs.resolve_cli_connect_timeout(parsed_args, session) self.assertEqual(parsed_args.connect_timeout, 60) self.assertEqual( session.get_default_client_config().connect_timeout, 60) def test_cli_read_timeout_for_blocking(self): parsed_args = FakeParsedArgs(read_timeout='0') session = get_session() globalargs.resolve_cli_read_timeout(parsed_args, session) self.assertEqual(parsed_args.read_timeout, None) self.assertEqual( session.get_default_client_config().read_timeout, None) def test_cli_connect_timeout_for_blocking(self): parsed_args = FakeParsedArgs(connect_timeout='0') session = get_session() globalargs.resolve_cli_connect_timeout(parsed_args, session) self.assertEqual(parsed_args.connect_timeout, None) self.assertEqual( session.get_default_client_config().connect_timeout, None)
299,044
find first slide show
#@+leo-ver=5-thin #@+node:ekr.20060831165821: * @file ../plugins/slideshow.py #@+<< docstring >> #@+node:ekr.20060831165845.1: ** << docstring >> """ Supports slideshows in Leo outlines. This plugin defines four new commands: - next-slide-show: move to the start of the next slide show, or the first slide show if no slide show has been seen yet. - prev-slide-show: move to the start of the previous slide show, or the first slide show if no slide show has been seen yet. - next-slide: move to the next slide of a present slide show. - prev-slide: move to the previous slide of the present slide show. Slides shows consist of a root @slideshow node with descendant @slide nodes. @slide nodes may be organized via non-@slide nodes that do not appear in the slideshow. All these commands ignore @ignore trees. """ #@-<< docstring >> #@+<< imports >> #@+node:ekr.20060831165845.3: ** << imports >> from leo.core import leoGlobals as g #@-<< imports >> # To do: # - Add sound/script support for slides. # - Save/restore changes to slides when entering/leaving a slide. #@+others #@+node:ekr.20060831165845.4: ** init def init(): """Return True if the plugin has loaded successfully.""" g.registerHandler(('open2', 'new2'), onCreate) g.plugin_signon(__name__) return True #@+node:ekr.20060831165845.5: ** onCreate def onCreate(tag, keys): c = keys.get('c') if c: slideshowController(c) #@+node:ekr.20060831165845.6: ** class slideshowController class slideshowController: #@+others #@+node:ekr.20060831165845.7: *3* __init__ def __init__(self, c): self.c = c self.firstSlideShow = None self.slideShowRoot = None self.slide = None self.createCommands() #@+node:ekr.20060831171016: *3* createCommands (slideshowController) def createCommands(self): c = self.c k = c.k for commandName, func in ( ('next-slide-command', self.nextSlide), ('next-slide-show-command', self.nextSlideShow), ('prev-slide-command', self.prevSlide), ('prev-slide-show-command', self.prevSlideShow), ): k.registerCommand(commandName, func) #@+node:ekr.20060901182318: *3* findFirstSlideShow def METHOD_NAME(self): c = self.c for p in c.all_positions(): h = p.h.strip() if h.startswith('@slideshow'): self.firstSlideShow = p.copy() return p if g.match_word(h, 0, '@ignore'): p = p.nodeAfterTree() self.firstSlideShow = None return None #@+node:ekr.20060904110319: *3* ignored def ignored(self, p): for p2 in p.self_and_parents(): if g.match_word(p2.h, 0, '@ignore') or g.match_word(p2.h, 0, '@noslide'): return True return False #@+node:ekr.20060831171016.5: *3* nextSlide def nextSlide(self, event=None): c = self.c p = c.p if p == self.slide: p = self.slide.threadNext() oldSlide = self.slide else: oldSlide = None while p: h = p.h.strip() if self.ignored(p): p = p.threadNext() elif h.startswith('@slideshow'): self.select(p) return g.es('At %s of slide show' % 'end' if oldSlide else 'start') elif g.match_word(h, 0, '@ignore') or g.match_word(h, 0, '@noslide'): p = p.nodeAfterTree() else: return self.select(p) # elif h.startswith('@slide'): # return self.select(p) # else: p = p.threadNext() return g.es('At end of slide show' if self.slideShowRoot else 'Not in any slide show') #@+node:ekr.20060901142848: *3* nextSlideShow def nextSlideShow(self, event=None): c = self.c self.METHOD_NAME() if not self.firstSlideShow: g.es('No slide show found') return if not self.slideShowRoot: self.select(self.firstSlideShow) return p = c.p h = p.h.strip() if h.startswith('@slideshow'): p = p.threadNext() while p: h = p.h.strip() if self.ignored(p): p = p.threadNext() elif h.startswith('@slideshow'): self.select(p) return elif g.match_word(h, 0, '@ignore'): p = p.nodeAfterTree() else: p = p.threadNext() self.select(self.slideShowRoot) g.es('At start of last slide show') #@+node:ekr.20060831171016.4: *3* prevSlide def prevSlide(self, event=None): c = self.c p = c.p if self.ignored(p): p = p.threadBack() else: if self.slide and self.slide == self.slideShowRoot: return g.es('At start of slide show') if p == self.slide: p = self.slide.threadBack() while p: h = p.h.strip() if self.ignored(p): p = p.threadBack() elif h.startswith('@slideshow'): self.select(p) return g.es('At start of slide show') else: return self.select(p) # elif h.startswith('@slide'): # return self.select(p) # else: p = p.threadBack() p = self.METHOD_NAME() if p: self.select(p) return g.es('At start of first slide show') return g.es('No slide show found') #@+node:ekr.20060901142848.1: *3* prevSlideShow def prevSlideShow(self, event=None): c = self.c self.METHOD_NAME() if not self.firstSlideShow: g.es('No slide show found') return if not self.slideShowRoot: self.select(self.firstSlideShow) return p = c.p h = p.h.strip() if h.startswith('@slideshow'): p = p.threadBack() while p: h = p.h.strip() if self.ignored(p): p = p.threadBack() elif h.startswith('@slideshow'): self.select(p) return else: p = p.threadBack() self.select(self.firstSlideShow) g.es('At start of first slide show') #@+node:ekr.20060901145257: *3* select def select(self, p): """Make p the present slide, and set self.slide and maybe self.slideShowRoot.""" c = self.c h = p.h.strip() w = c.frame.body.wrapper g.es('%s' % h) c.redraw(p) w.see(0) if h.startswith('@slideshow'): self.slideShowRoot = p.copy() self.slide = p.copy() #@-others #@-others #@-leo
299,045
from igakit
""" Computational domain for isogeometric analysis. """ from __future__ import absolute_import import os.path as op import numpy as nm from sfepy.base.base import assert_, Struct from sfepy.discrete.common.domain import Domain from sfepy.discrete.iga import iga from sfepy.discrete.iga import io from sfepy.discrete.iga.extmods.igac import eval_in_tp_coors import six from six.moves import range class NurbsPatch(Struct): """ Single NURBS patch data. """ def __init__(self, knots, degrees, cps, weights, cs, conn): degrees = nm.asarray(degrees, dtype=nm.int32) cs = [nm.asarray(cc, dtype=nm.float64) for cc in cs] if cs[0].ndim == 3: cs = [nm.ascontiguousarray(cc[:, None, ...]) for cc in cs] Struct.__init__(self, name='nurbs', knots=knots, degrees=degrees, cps=cps, weights=weights, cs=cs, conn=conn) self.n_els = [len(ii) for ii in cs] self.dim = len(self.n_els) def _get_ref_coors_1d(self, pars, axis): uk = nm.unique(self.knots[axis]) indices = nm.searchsorted(uk[1:], pars) ref_coors = nm.empty_like(pars) for ii in range(len(uk) - 1): ispan = nm.where(indices == ii)[0] pp = pars[ispan] ref_coors[ispan] = (pp - uk[ii]) / (uk[ii+1] - uk[ii]) return uk, indices, ref_coors def __call__(self, u=None, v=None, w=None, field=None): """ Igakit-like interface for NURBS evaluation. """ pars = [u] if v is not None: pars += [v] if w is not None: pars += [w] indices = [] rcs = [] for ia, par in enumerate(pars): uk, indx, rc = self._get_ref_coors_1d(par, ia) indices.append(indx.astype(nm.uint32)) rcs.append(rc) out = eval_in_tp_coors(field, indices, rcs, self.cps, self.weights, self.degrees, self.cs, self.conn) return out def evaluate(self, field, u=None, v=None, w=None): """ Igakit-like interface for NURBS evaluation. """ return self(u, v, w, field) def _to_igakit(self): import igakit.cad as cad n_efuns = self.degrees + 1 nks = nm.array([len(ii) for ii in self.knots]) shape = tuple(nks - n_efuns) cps = self.cps.reshape(shape + (-1,)) weights = self.weights.reshape(shape) return cad.NURBS(self.knots, cps, weights=weights) def METHOD_NAME(self, inurbs): cs = iga.compute_bezier_extraction(inurbs.knots, inurbs.degree) n_els = [len(ii) for ii in cs] conn, bconn = iga.create_connectivity(n_els, inurbs.knots, inurbs.degree) cps = inurbs.points[..., :self.dim].copy() cps = cps.reshape((-1, self.dim)) return NurbsPatch(inurbs.knots, inurbs.degree, cps, inurbs.weights.ravel(), cs, conn) def elevate(self, times=0): """ Elevate the patch degrees several `times` by one. Returns ------- nurbs : NurbsPatch instance Either `self` if `times` is zero, or a new instance. """ if times == 0: return self aux = self._to_igakit() for ia in range(self.dim): aux.elevate(ia, times) assert_(nm.isfinite(aux.points).all(), 'igakit degree elevation failed for axis %d!' % ia) return self.METHOD_NAME(aux) class IGDomain(Domain): """ Bezier extraction based NURBS domain for isogeometric analysis. """ @staticmethod def from_file(filename): """ filename : str The name of the IGA domain file. """ data = io.read_iga_data(filename) name = op.splitext(filename)[0] return IGDomain.from_data(*(data + (name,))) @staticmethod def read_domain_from_hdf5(fd, group): """ Create a domain from the given hdf5 data group. fd: tables.File HDF5 file handle to read the mesh from. group: tables.group.Group HDF5 data group (of file fd) to read the mesh from. """ data = io.read_iga_data(fd, group) return IGDomain.from_data(*data) def write_domain_to_hdf5(self, fd, group): """ Save the domain to a hdf5 file. fd: tables.File HDF5 file handle to write the mesh to. group: tables.group.Group HDF5 data group (of file fd) to write the mesh to. """ io.write_iga_data(fd, group, *(self._get_io_data() + (self.name,))) def _get_io_data(self): """ Return the data describing the domain for storing the domain in a hdf5 file. TODO - data for regions recreating """ knots = self.nurbs.knots degrees = self.nurbs.degrees cps = self.nurbs.cps weights = self.nurbs.weights cs = self.nurbs.cs conn = self.nurbs.conn bcps = self.bmesh.cps bweights = self.bmesh.weights bconn = self.bmesh.conn return (knots, degrees, cps, weights, cs, conn, bcps, bweights, bconn, self.vertex_set_bcs) @staticmethod def from_data(knots, degrees, cps, weights, cs, conn, bcps, bweights, bconn, regions, name='iga_domain_from_data'): """ Create the IGA domain from the given data. """ nurbs = NurbsPatch(knots, degrees, cps, weights, cs, conn) bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn) domain = IGDomain(name, nurbs=nurbs, bmesh=bmesh, regions=regions) return domain def __init__(self, name, nurbs, bmesh, regions=None, **kwargs): """ Create an IGA domain. Parameters ---------- name : str The domain name. """ Domain.__init__(self, name, nurbs=nurbs, bmesh=bmesh, regions=regions, **kwargs) from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.utils import prepare_remap tconn = iga.get_bezier_topology(bmesh.conn, nurbs.degrees) itc = nm.unique(tconn) remap = prepare_remap(itc, bmesh.conn.max() + 1) ltcoors = bmesh.cps[itc] ltconn = remap[tconn] n_nod, dim = ltcoors.shape n_el = ltconn.shape[0] self.shape = Struct(n_nod=n_nod, dim=dim, tdim=0, n_el=n_el) desc = '%d_%d' % (dim, bmesh.conn.shape[1]) mat_id = nm.zeros(bmesh.conn.shape[0], dtype=nm.int32) eval_mesh = Mesh.from_data(self.name + '_eval', nurbs.cps, None, [nurbs.conn], [mat_id], [desc]) self.eval_mesh = eval_mesh desc = '%d_%d' % (dim, 2**dim) mat_id = nm.zeros(ltconn.shape[0], dtype=nm.int32) self.mesh = Mesh.from_data(self.name + '_topo', ltcoors, None, [ltconn], [mat_id], [desc]) self.cmesh = self.mesh.cmesh self.cmesh_tdim = self.mesh.cmesh_tdim gels = create_geometry_elements() self.cmesh.set_local_entities(gels) self.cmesh.setup_entities() self.shape.tdim = self.cmesh.tdim self.gel = gels[desc] if regions is not None: self.vertex_set_bcs = {} for key, val in six.iteritems(self.regions): self.vertex_set_bcs[key] = remap[val] self.reset_regions()
299,046
test use legacy supplementaries deprecation session update
import warnings from pathlib import Path import pytest import esmvalcore from esmvalcore.config import CFG, Config from esmvalcore.exceptions import ESMValCoreDeprecationWarning def test_no_deprecation_default_cfg(): """Test that default config does not raise any deprecation warnings.""" with warnings.catch_warnings(): warnings.simplefilter('error', category=ESMValCoreDeprecationWarning) CFG.reload() CFG.start_session('my_session') def test_no_deprecation_user_cfg(): """Test that user config does not raise any deprecation warnings.""" config_file = Path(esmvalcore.__file__).parent / 'config-user.yml' with warnings.catch_warnings(): warnings.simplefilter('error', category=ESMValCoreDeprecationWarning) cfg = Config(CFG.copy()) cfg.load_from_file(config_file) cfg.start_session('my_session') def test_offline_default_cfg(): """Test that ``offline`` is added for backwards-compatibility.""" assert CFG['search_esgf'] == 'never' assert CFG['offline'] is True def test_offline_user_cfg(): """Test that ``offline`` is added for backwards-compatibility.""" config_file = Path(esmvalcore.__file__).parent / 'config-user.yml' cfg = Config(CFG.copy()) cfg.load_from_file(config_file) assert cfg['search_esgf'] == 'never' assert cfg['offline'] is True def test_offline_default_session(): """Test that ``offline`` is added for backwards-compatibility.""" session = CFG.start_session('my_session') assert session['search_esgf'] == 'never' assert session['offline'] is True def test_offline_user_session(): """Test that ``offline`` is added for backwards-compatibility.""" config_file = Path(esmvalcore.__file__).parent / 'config-user.yml' cfg = Config(CFG.copy()) cfg.load_from_file(config_file) session = cfg.start_session('my_session') assert session['search_esgf'] == 'never' assert session['offline'] is True def test_offline_deprecation_session_setitem(): """Test that the usage of offline is deprecated.""" msg = "offline" session = CFG.start_session('my_session') session.pop('search_esgf') # test automatic addition of search_esgf with pytest.warns(ESMValCoreDeprecationWarning, match=msg): session['offline'] = True assert session['offline'] is True assert session['search_esgf'] == 'never' def test_offline_deprecation_session_update(): """Test that the usage of offline is deprecated.""" msg = "offline" session = CFG.start_session('my_session') session.pop('search_esgf') # test automatic addition of search_esgf with pytest.warns(ESMValCoreDeprecationWarning, match=msg): session.update({'offline': False}) assert session['offline'] is False assert session['search_esgf'] == 'when_missing' def test_offline_true_deprecation_config(monkeypatch): """Test that the usage of offline is deprecated.""" msg = "offline" monkeypatch.delitem(CFG, 'search_esgf') with pytest.warns(ESMValCoreDeprecationWarning, match=msg): monkeypatch.setitem(CFG, 'offline', True) assert CFG['offline'] is True assert CFG['search_esgf'] == 'never' def test_offline_false_deprecation_config(monkeypatch): """Test that the usage of offline is deprecated.""" msg = "offline" monkeypatch.delitem(CFG, 'search_esgf') with pytest.warns(ESMValCoreDeprecationWarning, match=msg): monkeypatch.setitem(CFG, 'offline', False) assert CFG['offline'] is False assert CFG['search_esgf'] == 'when_missing' def test_use_legacy_supplementaries_default_cfg(): """Test that option is added for backwards-compatibility.""" assert CFG['use_legacy_supplementaries'] is None def test_use_legacy_supplementaries_user_cfg(): """Test that option is added for backwards-compatibility.""" config_file = Path(esmvalcore.__file__).parent / 'config-user.yml' cfg = Config(CFG.copy()) cfg.load_from_file(config_file) assert cfg['use_legacy_supplementaries'] is None def test_use_legacy_supplementaries_default_session(): """Test that option is added for backwards-compatibility.""" session = CFG.start_session('my_session') assert session['use_legacy_supplementaries'] is None def test_use_legacy_supplementaries_user_session(): """Test that option is added for backwards-compatibility.""" config_file = Path(esmvalcore.__file__).parent / 'config-user.yml' cfg = Config(CFG.copy()) cfg.load_from_file(config_file) session = cfg.start_session('my_session') assert session['use_legacy_supplementaries'] is None def test_use_legacy_supplementaries_deprecation_session_setitem(): """Test that the usage of use_legacy_supplementaries is deprecated.""" msg = "use_legacy_supplementaries" session = CFG.start_session('my_session') with pytest.warns(ESMValCoreDeprecationWarning, match=msg): session['use_legacy_supplementaries'] = True assert session['use_legacy_supplementaries'] is True def METHOD_NAME(): """Test that the usage of use_legacy_supplementaries is deprecated.""" msg = "use_legacy_supplementaries" session = CFG.start_session('my_session') with pytest.warns(ESMValCoreDeprecationWarning, match=msg): session.update({'use_legacy_supplementaries': False}) assert session['use_legacy_supplementaries'] is False def test_use_legacy_supplementaries_true_deprecation_config(monkeypatch): """Test that the usage of use_legacy_supplementaries is deprecated.""" msg = "use_legacy_supplementaries" with pytest.warns(ESMValCoreDeprecationWarning, match=msg): monkeypatch.setitem(CFG, 'use_legacy_supplementaries', True) assert CFG['use_legacy_supplementaries'] is True def test_use_legacy_supplementaries_false_deprecation_config(monkeypatch): """Test that the usage of use_legacy_supplementaries is deprecated.""" msg = "use_legacy_supplementaries" with pytest.warns(ESMValCoreDeprecationWarning, match=msg): monkeypatch.setitem(CFG, 'use_legacy_supplementaries', False) assert CFG['use_legacy_supplementaries'] is False
299,047
form valid
from django.apps import apps from django.conf import settings from django.contrib import messages from django.core.exceptions import PermissionDenied from django.http.response import HttpResponseRedirect from django.urls import reverse from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.views import generic from adhocracy4.dashboard import mixins as a4dashboard_mixins from adhocracy4.follows.models import Follow from adhocracy4.rules import mixins as rules_mixins from . import emails from . import models from .forms import NewsletterForm from .forms import RestrictedNewsletterForm Organisation = apps.get_model(settings.A4_ORGANISATIONS_MODEL) class DashboardNewsletterCreateView( a4dashboard_mixins.DashboardBaseMixin, rules_mixins.PermissionRequiredMixin, generic.CreateView, ): menu_item = "newsletter" model = models.Newsletter form_class = NewsletterForm permission_required = "a4projects.add_project" def get_permission_object(self): return self.organisation def _check_permission(self, organisation, user): return ( user.is_superuser or organisation.has_initiator(user) or self._group_permission(organisation, user) ) def _group_permission(self, organisation, user): org_groups = organisation.groups.all() user_groups = user.groups.all() return (org_groups & user_groups).count() > 0 def get_email_kwargs(self): kwargs = {} kwargs.update({"organisation_pk": self.organisation.pk}) return kwargs def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["user"] = self.request.user kwargs["organisation"] = self.organisation kwargs["initial"] = { "sender_name": self.organisation.name, "sender": settings.CONTACT_EMAIL, } if not self._check_permission(self.organisation, self.request.user): kwargs["initial"]["receivers"] = models.PROJECT return kwargs def get_success_url(self): return reverse( "a4dashboard:newsletter-create", kwargs={"organisation_slug": self.organisation.slug}, ) def get_form(self): if self._check_permission(self.organisation, self.request.user): return NewsletterForm(**self.get_form_kwargs()) else: return RestrictedNewsletterForm(**self.get_form_kwargs()) def get_template_names(self): user = self.request.user if self.organisation.has_initiator(user) or user.is_superuser: return ["meinberlin_newsletters/newsletter_dashboard_form.html"] else: return [ "meinberlin_newsletters/" "restricted_newsletter_dashboard_form.html" ] def METHOD_NAME(self, form): # Check if the current user is allowed to send to the selected org organisation = form.cleaned_data["organisation"] if not self._check_permission(organisation, self.request.user): raise PermissionDenied instance = form.save(commit=False) instance.creator = self.request.user instance.sent = timezone.now() instance.save() form.save_m2m() receivers = int(form.cleaned_data["receivers"]) if receivers == models.PROJECT: participant_ids = Follow.objects.filter( project=form.cleaned_data["project"].pk, enabled=True ).values_list("creator", flat=True) elif receivers == models.ORGANISATION: participant_ids = ( Follow.objects.filter( project__organisation=organisation.pk, enabled=True ) .values_list("creator", flat=True) .distinct() ) elif receivers == models.INITIATOR: participant_ids = ( Organisation.objects.get(pk=organisation.pk) .initiators.all() .values_list("pk", flat=True) ) else: participant_ids = [] if receivers == models.PLATFORM: emails.NewsletterEmailAll.send(instance, **self.get_email_kwargs()) else: emails.NewsletterEmail.send( instance, participant_ids=list(participant_ids), **self.get_email_kwargs() ) messages.success( self.request, _("Newsletter has been saved and " "will be sent to the recipients."), ) return HttpResponseRedirect(self.get_success_url())
299,048
move camera
"""This file demonstrates one way to create a mirror effect in Panda. Call :func:`setupMirror()` to create a mirror in the world that reflects everything in front of it. The approach taken here is to create an offscreen buffer with its own camera that renders its view into a texture, which is then applied to the mirror geometry. The mirror's camera is repositioned each frame with a task to keep it always on the opposite side of the mirror from the main camera. This demonstrates the basic interface for offscreen render-to-a-texture in Panda. Similar approaches can be used for related effects, such as a remote spy camera presenting its view onto a closed-circuit television screen. In this example the mirror itself is always perfectly flat--it's just a single polygon, after all--but small distortions of the mirror surface are possible, like a funhouse mirror. However, the reflection itself is always basically planar; for more accurate convex reflections, you will need to use a sphere map or a cube map.""" __all__ = ['setupMirror', 'showFrustum'] from panda3d.core import ( Camera, CardMaker, CullFaceAttrib, GeomNode, Lens, NodePath, PerspectiveLens, Plane, PlaneNode, Point3, Vec3, ) from direct.task import Task from direct.task.TaskManagerGlobal import taskMgr def setupMirror(name, width, height, rootCamera = None, bufferSize = 256, clearColor = None): # The return value is a NodePath that contains a rectangle that # reflects render. You can reparent, reposition, and rotate it # anywhere you like. if rootCamera is None: rootCamera = base.camera root = render.attachNewNode(name) # Create a polygon to be the visible representation of the mirror. cm = CardMaker('mirror') cm.setFrame(width / 2.0, -width / 2.0, -height / 2.0, height / 2.0) cm.setHasUvs(1) card = root.attachNewNode(cm.generate()) # Create a PlaneNode to represent the mirror's position, for # computing where the mirror's camera belongs each frame. plane = Plane(Vec3(0, 1, 0), Point3(0, 0, 0)) planeNode = PlaneNode('mirrorPlane') planeNode.setPlane(plane) planeNP = root.attachNewNode(planeNode) # Now create an offscreen buffer for rendering the mirror's point # of view. The parameters here control the resolution of the # texture. buffer = base.win.makeTextureBuffer(name, bufferSize, bufferSize) if clearColor is None: buffer.setClearColor(base.win.getClearColor()) #buffer.setClearColor(VBase4(0, 0, 1, 1)) else: buffer.setClearColor(clearColor) # Set up a display region on this buffer, and create a camera. dr = buffer.makeDisplayRegion() camera = Camera('mirrorCamera') lens = PerspectiveLens() lens.setFilmSize(width, height) camera.setLens(lens) cameraNP = planeNP.attachNewNode(camera) dr.setCamera(cameraNP) # Since the reflection matrix will reverse the vertex-winding # order of all the polygons in the world, we have to tell the # camera to reverse the direction of its face culling. We also # tell it not to draw (that is, to clip) anything behind the # mirror plane. dummy = NodePath('dummy') dummy.setAttrib(CullFaceAttrib.makeReverse()) dummy.setClipPlane(planeNP) camera.setInitialState(dummy.getState()) # Create a visible representation of the camera so we can see it. #cameraVis = base.loader.loadModel('camera.egg') #if not cameraVis.isEmpty(): # cameraVis.reparentTo(cameraNP) # Spawn a task to keep that camera on the opposite side of the # mirror. def METHOD_NAME(task, cameraNP = cameraNP, plane = plane, planeNP = planeNP, card = card, lens = lens, width = width, height = height, rootCamera = rootCamera): # Set the camera to the mirror-image position of the main camera. cameraNP.setMat(rootCamera.getMat(planeNP) * plane.getReflectionMat()) # Set the cameras roll to the roll of the mirror. Otherwise # mirrored objects will be moved unexpectedly cameraNP.setR(planeNP.getR()-180) # And reset the frustum to exactly frame the mirror's corners. # This is a minor detail, but it helps to provide a realistic # reflection and keep the subject centered. ul = cameraNP.getRelativePoint(card, Point3(-width / 2.0, 0, height / 2.0)) ur = cameraNP.getRelativePoint(card, Point3(width / 2.0, 0, height / 2.0)) ll = cameraNP.getRelativePoint(card, Point3(-width / 2.0, 0, -height / 2.0)) lr = cameraNP.getRelativePoint(card, Point3(width / 2.0, 0, -height / 2.0)) # get the distance from the mirrors camera to the mirror plane camvec = planeNP.getPos() - cameraNP.getPos() camdist = camvec.length() # set the discance on the mirrors corners so it will keep correct # sizes of the mirrored objects ul.setY(camdist) ur.setY(camdist) ll.setY(camdist) lr.setY(camdist) lens.setFrustumFromCorners(ul, ur, ll, lr, Lens.FCCameraPlane | Lens.FCOffAxis | Lens.FCAspectRatio) return Task.cont # Add it with a fairly high priority to make it happen late in the # frame, after the avatar controls (or whatever) have been applied # but before we render. taskMgr.add(METHOD_NAME, name, priority = 40) # Now apply the output of this camera as a texture on the mirror's # visible representation. card.setTexture(buffer.getTexture()) return root def showFrustum(np): # Utility function to reveal the frustum for a particular camera. cameraNP = np.find('**/+Camera') camera = cameraNP.node() lens = camera.getLens() geomNode = GeomNode('frustum') geomNode.addGeom(lens.makeGeometry()) cameraNP.attachNewNode(geomNode) if __name__ == "__main__": from direct.showbase.ShowBase import ShowBase base = ShowBase() panda = base.loader.loadModel("panda") panda.setH(180) panda.setPos(0, 10, -2.5) panda.setScale(0.5) panda.reparentTo(base.render) myMirror = setupMirror("mirror", 10, 10, bufferSize=1024, clearColor=(0, 0, 1, 1)) myMirror.setPos(0, 15, 2.5) myMirror.setH(180) # Uncomment this to show the frustum of the camera in the mirror #showFrustum(render) base.run()
299,049
test dataprotection restorable time range find
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- # pylint: disable=line-too-long # pylint: disable=unused-import from azure.cli.testsdk import ScenarioTest from azure.cli.testsdk.scenario_tests import AllowLargeResponse class RestorableTimeRangeScenarioTest(ScenarioTest): @AllowLargeResponse() def METHOD_NAME(test): test.kwargs.update({ 'location': 'centraluseuap', 'rg': 'clitest-dpp-rg', 'vaultName': 'clitest-bkp-vault-persistent-bi-donotdelete', 'backupInstanceName': 'clitestsabidonotdelete-clitestsabidonotdelete-887c3538-0bfc-11ee-acd3-002b670b472e', 'sourceDataStoreType': 'OperationalStore' }) test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}"', checks=[ test.check('id', "{backupInstanceName}"), test.check('properties.objectType', "AzureBackupFindRestorableTimeRangesResponse"), test.greater_than('length(properties.restorableTimeRanges)', 0) ]) test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--start-time 2001-02-27T12:00:00.0000000Z --end-time 2002-05-14T14:00:00.0000000Z') test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--start-time 2051-02-27T12:00:00.0000000Z --end-time 2052-05-14T14:00:00.0000000Z') test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--start-time 2023-06-16T01:00:00.0000000Z --end-time 2033-06-16T01:00:00.0000000Z') test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--start-time 2023-06-16T01:00:00.000Z --end-time 2033-06-16T01:00:00.000Z') test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--start-time 2023-06-16T01:00:00.00Z --end-time 2033-06-16T01:00:00.00Z') test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--start-time 2023-06-16T01:00:00 --end-time 2033-06-16T01:00:00') test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--start-time 2023-06-16T01:00:00+05:30 --end-time 2033-06-16T01:00:00+05:30') test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--start-time 2023-06-16T01:00:00.0000000Z') test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--start-time 2023-06-16T01:00:00.000Z', expect_failure=True) test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--end-time 2033-06-16T01:00:00.00Z', expect_failure=True) test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--start-time 2023-06-16T01:00:00', expect_failure=True) test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--end-time 2033-06-16T01:00:00+05:30', expect_failure=True) test.cmd('az dataprotection restorable-time-range find --source-data-store-type "{sourceDataStoreType}" -g "{rg}" --vault-name "{vaultName}" --backup-instance-name "{backupInstanceName}" ' '--start-time 2033-06-16T01:00:00.0000000Z --end-time 2023-06-16T01:00:00.0000000Z', expect_failure=True)
299,050
test getstatus4
import unittest from pychess.Utils.const import ( BLACKWON, DRAW, WHITEWON, ATOMICCHESS, WON_KINGEXPLODE, WON_MATE, DRAW_STALEMATE, ) from pychess.Utils.logic import validate, getStatus from pychess.Utils.Move import Move, parseSAN from pychess.Variants.atomic import AtomicBoard from pychess.Utils.lutils.LBoard import LBoard from pychess.Utils.lutils.lmovegen import genAllMoves # ♜ . . ♞ ♚ ♝ ♞ ♜ # ♟ ♟ . ♝ ♟ ♟ ♟ ♟ # . . ♟ . . . . . # . ♘ . . . . . . # . . . ♛ . . . . # . . . . . . . . # ♙ ♙ ♙ ♙ . ♙ ♙ ♙ # ♖ . ♗ ♕ ♔ ♗ . ♖ FEN1 = "r2nkbnr/pp1bpppp/2p5/1N6/3q4/8/PPPP1PPP/R1BQKB1R w KQkq - 0 1" FEN2 = "8/8/8/8/5k2/8/1qK5/8 b - - 0 1" FEN3 = "7k/6R1/8/5K2/8/8/8/8 b - - 0 1" FEN4 = "r4bn1/4p2r/2n2pp1/p2p2Pk/1p4Qp/2P1P3/PP1P3P/R1B1K2R b KQ - 0 1" # ♜ ♞ ♝ ♛ . ♝ ♞ ♜ # ♟ ♟ ♟ ♟ . ♟ ♟ ♟ # . . . . . . ♚ . # . . . . ♟ . . . # . . . . ♙ . ♔ . # . . . . . . . . # ♙ ♙ ♙ ♙ . ♙ ♙ ♙ # ♖ ♘ ♗ ♕ . ♗ ♘ ♖ FEN5 = "rnbq1bnr/pppp1ppp/6k1/4p3/4P1K1/8/PPPP1PPP/RNBQ1BNR w - - 6 5" class AtomicTestCase(unittest.TestCase): def test_validate1(self): """Testing castling rights lose in explosion in Atomic variant""" board = AtomicBoard(setup=FEN1) board = board.move(parseSAN(board, "Nxa7")) print(board) # Rook exploded, no O-O-O anymore! self.assertTrue(validate(board, parseSAN(board, "b6"))) self.assertTrue(not validate(board, parseSAN(board, "a6"))) self.assertTrue(not validate(board, parseSAN(board, "Rb8"))) self.assertTrue(not validate(board, parseSAN(board, "O-O-O"))) def test_validate2(self): """Testing explode king vs mate in Atomic variant""" board = AtomicBoard(setup=FEN1) board = board.move(parseSAN(board, "Nc7+")) print(board) # King explosion takes precedence over mate! self.assertTrue(validate(board, parseSAN(board, "Qxd2"))) self.assertTrue(validate(board, parseSAN(board, "Qxf2"))) self.assertTrue(not validate(board, parseSAN(board, "Qxb2"))) self.assertTrue(not validate(board, parseSAN(board, "Qe4+"))) def test_getstatus1(self): """Testing bare black king is not draw in Atomic variant""" board = AtomicBoard(setup=FEN2) board = board.move(parseSAN(board, "Qxc2")) print(board) self.assertEqual(getStatus(board), (BLACKWON, WON_KINGEXPLODE)) def test_getstatus2(self): """Testing bare white king is not draw in Atomic variant""" board = AtomicBoard(setup=FEN3) self.assertTrue(not validate(board, parseSAN(board, "Kxg7"))) self.assertTrue(not validate(board, parseSAN(board, "Kg8"))) self.assertTrue(not validate(board, parseSAN(board, "Kh7"))) print(board) self.assertEqual(getStatus(board), (DRAW, DRAW_STALEMATE)) def test_getstatus3(self): """Testing possible to mate with the queen unaided in Atomic variant""" board = AtomicBoard(setup=FEN4) print(board) self.assertEqual(getStatus(board), (WHITEWON, WON_MATE)) def METHOD_NAME(self): """Testing possible move into check when king touch saves the king""" board = AtomicBoard(setup=FEN5) print(board) self.assertTrue(validate(board, parseSAN(board, "Kg5"))) def test_apply_pop(self): """Testing Atomic applyMove popMove""" board = LBoard(variant=ATOMICCHESS) board.applyFen(FEN1) print(board) hist_exploding_around0 = [a[:] for a in board.hist_exploding_around] print_apply_pop = False for lmove1 in genAllMoves(board): board.applyMove(lmove1) if board.opIsChecked(): if print_apply_pop: print("popMove1 (invalid)", Move(lmove1)) board.popMove() continue hist_exploding_around1 = [a[:] for a in board.hist_exploding_around] for lmove2 in genAllMoves(board): board.applyMove(lmove2) if print_apply_pop: print(" applyMove2", Move(lmove2)) if board.opIsChecked(): if print_apply_pop: print(" popMove2 (invalid)", Move(lmove2)) board.popMove() continue hist_exploding_around2 = [a[:] for a in board.hist_exploding_around] for lmove3 in genAllMoves(board): board.applyMove(lmove3) if print_apply_pop: print(" applyMove3", Move(lmove3)) if board.opIsChecked(): if print_apply_pop: print(" popMove3 (invalid)", Move(lmove3)) board.popMove() continue board.popMove() if print_apply_pop: print(" popMove3", Move(lmove3)) self.assertEqual( hist_exploding_around2, board.hist_exploding_around ) board.popMove() if print_apply_pop: print(" popMove2", Move(lmove2)) self.assertEqual(hist_exploding_around1, board.hist_exploding_around) board.popMove() if print_apply_pop: print("popMove1", Move(lmove1)) self.assertEqual(hist_exploding_around0, board.hist_exploding_around) if __name__ == "__main__": unittest.main()
299,051
app config
# SPDX-License-Identifier: Apache-2.0 # Copyright 2022 The HuggingFace Authors. from typing import Iterator from libapi.config import UvicornConfig from libcommon.processing_graph import ProcessingGraph from libcommon.queue import _clean_queue_database from libcommon.resources import CacheMongoResource, QueueMongoResource from libcommon.simple_cache import _clean_cache_database from pytest import MonkeyPatch, fixture from api.config import AppConfig, EndpointConfig from api.routes.endpoint import EndpointsDefinition, StepsByInputTypeAndEndpoint # see https://github.com/pytest-dev/pytest/issues/363#issuecomment-406536200 @fixture(scope="session") def monkeypatch_session() -> Iterator[MonkeyPatch]: monkeypatch_session = MonkeyPatch() monkeypatch_session.setenv("CACHE_MONGO_DATABASE", "datasets_server_cache_test") monkeypatch_session.setenv("QUEUE_MONGO_DATABASE", "datasets_server_queue_test") hostname = "localhost" port = "8888" monkeypatch_session.setenv("API_HF_TIMEOUT_SECONDS", "10") monkeypatch_session.setenv("API_UVICORN_HOSTNAME", hostname) monkeypatch_session.setenv("API_UVICORN_PORT", port) monkeypatch_session.setenv("COMMON_HF_ENDPOINT", f"http://{hostname}:{port}") yield monkeypatch_session monkeypatch_session.undo() @fixture(scope="session") def METHOD_NAME(monkeypatch_session: MonkeyPatch) -> AppConfig: METHOD_NAME = AppConfig.from_env() if "test" not in METHOD_NAME.cache.mongo_database or "test" not in METHOD_NAME.queue.mongo_database: raise ValueError("Test must be launched on a test mongo database") return METHOD_NAME @fixture(scope="session") def endpoint_config(monkeypatch_session: MonkeyPatch) -> EndpointConfig: return EndpointConfig( processing_step_names_by_input_type_and_endpoint={ "/splits": { "dataset": ["dataset-split-names"], "config": ["config-split-names-from-streaming"], }, "/first-rows": {"split": ["split-first-rows-from-streaming"]}, "/parquet": {"config": ["config-parquet"]}, } ) @fixture(scope="session") def processing_graph(METHOD_NAME: AppConfig) -> ProcessingGraph: return ProcessingGraph(METHOD_NAME.processing_graph.specification) @fixture(scope="session") def endpoint_definition( endpoint_config: EndpointConfig, processing_graph: ProcessingGraph ) -> StepsByInputTypeAndEndpoint: return EndpointsDefinition(processing_graph, endpoint_config=endpoint_config).steps_by_input_type_and_endpoint @fixture(scope="session") def first_dataset_endpoint(endpoint_definition: StepsByInputTypeAndEndpoint) -> str: return next( endpoint for endpoint, input_types in endpoint_definition.items() if next((endpoint for input_type, _ in input_types.items() if input_type == "dataset"), None) ) @fixture(scope="session") def first_config_endpoint(endpoint_definition: StepsByInputTypeAndEndpoint) -> str: return next( endpoint for endpoint, input_types in endpoint_definition.items() if next((endpoint for input_type, _ in input_types.items() if input_type == "config"), None) ) @fixture(scope="session") def first_split_endpoint(endpoint_definition: StepsByInputTypeAndEndpoint) -> str: return next( endpoint for endpoint, input_types in endpoint_definition.items() if next((endpoint for input_type, _ in input_types.items() if input_type == "split"), None) ) @fixture(autouse=True) def cache_mongo_resource(METHOD_NAME: AppConfig) -> Iterator[CacheMongoResource]: with CacheMongoResource(database=METHOD_NAME.cache.mongo_database, host=METHOD_NAME.cache.mongo_url) as resource: yield resource _clean_cache_database() @fixture(autouse=True) def queue_mongo_resource(METHOD_NAME: AppConfig) -> Iterator[QueueMongoResource]: with QueueMongoResource(database=METHOD_NAME.queue.mongo_database, host=METHOD_NAME.queue.mongo_url) as resource: yield resource _clean_queue_database() @fixture(scope="session") def uvicorn_config(monkeypatch_session: MonkeyPatch) -> UvicornConfig: return UvicornConfig.from_env() @fixture(scope="session") def httpserver_listen_address(uvicorn_config: UvicornConfig) -> tuple[str, int]: return (uvicorn_config.hostname, uvicorn_config.port) @fixture(scope="session") def hf_endpoint(METHOD_NAME: AppConfig) -> str: return METHOD_NAME.common.hf_endpoint @fixture(scope="session") def hf_auth_path(METHOD_NAME: AppConfig) -> str: return METHOD_NAME.api.hf_auth_path
299,052
signextend
""" Ethereum Virtual Machine (EVM) Arithmetic Instructions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. contents:: Table of Contents :backlinks: none :local: Introduction ------------ Implementations of the EVM Arithmetic instructions. """ from ethereum.base_types import U255_CEIL_VALUE, U256, U256_CEIL_VALUE, Uint from ethereum.utils.numeric import get_sign from .. import Evm from ..gas import ( GAS_EXPONENTIATION, GAS_EXPONENTIATION_PER_BYTE, GAS_LOW, GAS_MID, GAS_VERY_LOW, charge_gas, ) from ..stack import pop, push def add(evm: Evm) -> None: """ Adds the top two elements of the stack together, and pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. """ # STACK x = pop(evm.stack) y = pop(evm.stack) # GAS charge_gas(evm, GAS_VERY_LOW) # OPERATION result = x.wrapping_add(y) push(evm.stack, result) # PROGRAM COUNTER evm.pc += 1 def sub(evm: Evm) -> None: """ Subtracts the top two elements of the stack, and pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. """ # STACK x = pop(evm.stack) y = pop(evm.stack) # GAS charge_gas(evm, GAS_VERY_LOW) # OPERATION result = x.wrapping_sub(y) push(evm.stack, result) # PROGRAM COUNTER evm.pc += 1 def mul(evm: Evm) -> None: """ Multiply the top two elements of the stack, and pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. """ # STACK x = pop(evm.stack) y = pop(evm.stack) # GAS charge_gas(evm, GAS_LOW) # OPERATION result = x.wrapping_mul(y) push(evm.stack, result) # PROGRAM COUNTER evm.pc += 1 def div(evm: Evm) -> None: """ Integer division of the top two elements of the stack. Pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. """ # STACK dividend = pop(evm.stack) divisor = pop(evm.stack) # GAS charge_gas(evm, GAS_LOW) # OPERATION if divisor == 0: quotient = U256(0) else: quotient = dividend // divisor push(evm.stack, quotient) # PROGRAM COUNTER evm.pc += 1 def sdiv(evm: Evm) -> None: """ Signed integer division of the top two elements of the stack. Pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. """ # STACK dividend = pop(evm.stack).to_signed() divisor = pop(evm.stack).to_signed() # GAS charge_gas(evm, GAS_LOW) # OPERATION if divisor == 0: quotient = 0 elif dividend == -U255_CEIL_VALUE and divisor == -1: quotient = -U255_CEIL_VALUE else: sign = get_sign(dividend * divisor) quotient = sign * (abs(dividend) // abs(divisor)) push(evm.stack, U256.from_signed(quotient)) # PROGRAM COUNTER evm.pc += 1 def mod(evm: Evm) -> None: """ Modulo remainder of the top two elements of the stack. Pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. """ # STACK x = pop(evm.stack) y = pop(evm.stack) # GAS charge_gas(evm, GAS_LOW) # OPERATION if y == 0: remainder = U256(0) else: remainder = x % y push(evm.stack, remainder) # PROGRAM COUNTER evm.pc += 1 def smod(evm: Evm) -> None: """ Signed modulo remainder of the top two elements of the stack. Pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. """ # STACK x = pop(evm.stack).to_signed() y = pop(evm.stack).to_signed() # GAS charge_gas(evm, GAS_LOW) # OPERATION if y == 0: remainder = 0 else: remainder = get_sign(x) * (abs(x) % abs(y)) push(evm.stack, U256.from_signed(remainder)) # PROGRAM COUNTER evm.pc += 1 def addmod(evm: Evm) -> None: """ Modulo addition of the top 2 elements with the 3rd element. Pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. """ # STACK x = Uint(pop(evm.stack)) y = Uint(pop(evm.stack)) z = Uint(pop(evm.stack)) # GAS charge_gas(evm, GAS_MID) # OPERATION if z == 0: result = U256(0) else: result = U256((x + y) % z) push(evm.stack, result) # PROGRAM COUNTER evm.pc += 1 def mulmod(evm: Evm) -> None: """ Modulo multiplication of the top 2 elements with the 3rd element. Pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. """ # STACK x = Uint(pop(evm.stack)) y = Uint(pop(evm.stack)) z = Uint(pop(evm.stack)) # GAS charge_gas(evm, GAS_MID) # OPERATION if z == 0: result = U256(0) else: result = U256((x * y) % z) push(evm.stack, result) # PROGRAM COUNTER evm.pc += 1 def exp(evm: Evm) -> None: """ Exponential operation of the top 2 elements. Pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. """ # STACK base = Uint(pop(evm.stack)) exponent = Uint(pop(evm.stack)) # GAS # This is equivalent to 1 + floor(log(y, 256)). But in python the log # function is inaccurate leading to wrong results. exponent_bits = exponent.bit_length() exponent_bytes = (exponent_bits + 7) // 8 charge_gas( evm, GAS_EXPONENTIATION + GAS_EXPONENTIATION_PER_BYTE * exponent_bytes ) # OPERATION result = U256(pow(base, exponent, U256_CEIL_VALUE)) push(evm.stack, result) # PROGRAM COUNTER evm.pc += 1 def METHOD_NAME(evm: Evm) -> None: """ Sign extend operation. In other words, extend a signed number which fits in N bytes to 32 bytes. Parameters ---------- evm : The current EVM frame. """ # STACK byte_num = pop(evm.stack) value = pop(evm.stack) # GAS charge_gas(evm, GAS_LOW) # OPERATION if byte_num > 31: # Can't extend any further result = value else: # U256(0).to_be_bytes() gives b'' instead b'\x00'. value_bytes = bytes(value.to_be_bytes32()) # Now among the obtained value bytes, consider only # N `least significant bytes`, where N is `byte_num + 1`. value_bytes = value_bytes[31 - int(byte_num) :] sign_bit = value_bytes[0] >> 7 if sign_bit == 0: result = U256.from_be_bytes(value_bytes) else: num_bytes_prepend = 32 - (byte_num + 1) result = U256.from_be_bytes( bytearray([0xFF] * num_bytes_prepend) + value_bytes ) push(evm.stack, result) # PROGRAM COUNTER evm.pc += 1
299,053
do finalize
# # This file is part of LiteX-Boards. # # Copright (c) 2022 Lone Dynamics Corporation <info@lonedynamics.com> # # SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform import * from litex.build.lattice import LatticeECP5Platform from litex.build.openfpgaloader import OpenFPGALoader # IOs ---------------------------------------------------------------------------------------------- _io_vx = [ # Clock ("clk48", 0, Pins("A7"), IOStandard("LVCMOS33")), # Leds ("user_led", 0, Pins("B1"), IOStandard("LVCMOS33")), ("user_led", 1, Pins("C1"), IOStandard("LVCMOS33")), ("user_led", 2, Pins("D1"), IOStandard("LVCMOS33")), ("rgb_led", 0, Subsignal("r", Pins("B1"), IOStandard("LVCMOS33")), Subsignal("g", Pins("C1"), IOStandard("LVCMOS33")), Subsignal("b", Pins("D1"), IOStandard("LVCMOS33")), ), # SDRAM ("sdram_clock", 0, Pins("F16"), IOStandard("LVTTL33")), ("sdram", 0, Subsignal("a", Pins( "R14 M14 L14 L13 G12 G13 G14 G15", "F12 F13 T15 F14 E14")), Subsignal("ba", Pins("T14 T13")), Subsignal("cs_n", Pins("G16")), Subsignal("cke", Pins("F15")), Subsignal("ras_n", Pins("J16")), Subsignal("cas_n", Pins("K16")), Subsignal("we_n", Pins("L15")), Subsignal("dq", Pins( "R15 R16 P16 P15 N16 N14 M16 M15", "E15 D16 D14 C16 B16 C14 C15 B15")), Subsignal("dm", Pins("L16 E16")), IOStandard("LVTTL33") ), # VGA ("vga", 0, Subsignal("r", Pins("J3")), Subsignal("g", Pins("K3")), Subsignal("b", Pins("H2")), Subsignal("hsync", Pins("J1")), Subsignal("vsync", Pins("J2")), IOStandard("LVCMOS33") ), # Differential Data Multiple Interface ("ddmi", 0, Subsignal("clk_p", Pins("R5"), IOStandard("LVCMOS33D"), Misc("DRIVE=4")), Subsignal("data0_p", Pins("P4"), IOStandard("LVCMOS33D"), Misc("DRIVE=4")), Subsignal("data1_p", Pins("P1"), IOStandard("LVCMOS33D"), Misc("DRIVE=4")), Subsignal("data2_p", Pins("N1"), IOStandard("LVCMOS33D"), Misc("DRIVE=4")), ), # USB-C ("usb", 0, Subsignal("d_p", Pins("T6")), Subsignal("d_n", Pins("R6")), Subsignal("pullup", Pins("R7")), IOStandard("LVCMOS33") ), # USB HOST ("usb_host", 0, Subsignal("dp", Pins("F2")), Subsignal("dm", Pins("E1")), IOStandard("LVCMOS33") ), # UART PMOD ("serial", 0, Subsignal("tx", Pins("PMODA:1")), Subsignal("rx", Pins("PMODA:2")), IOStandard("LVCMOS33") ), # SPI ("spiflash", 0, Subsignal("cs_n", Pins("N8"), Misc("PULLMODE=UP")), Subsignal("clk", Pins("N9")), Subsignal("miso", Pins("T7"), Misc("PULLMODE=UP")), Subsignal("mosi", Pins("T8"), Misc("PULLMODE=UP")), Misc("SLEWRATE=SLOW"), IOStandard("LVCMOS33"), ), ] _io_v1 = [ # SD card w/ SPI interface ("spisdcard", 0, Subsignal("clk", Pins("D6")), Subsignal("mosi", Pins("C6")), Subsignal("cs_n", Pins("B6")), Subsignal("miso", Pins("E6")), Misc("SLEWRATE=FAST"), IOStandard("LVCMOS33"), ), ] _io_v2 = [ # SD card w/ SD-mode interface ("sdcard", 0, Subsignal("cd", Pins("A13")), Subsignal("clk", Pins("D6")), Subsignal("cmd", Pins("C6")), Subsignal("data", Pins("E6 B13 B12 B6")), Misc("SLEW=FAST"), IOStandard("LVCMOS33") ), ] # Connectors --------------------------------------------------------------------------------------- _connectors_vx = [ ("PMODA", "A2 A3 A4 A5 B3 B4 B5 A6"), ("PMODB", "A12 A11 B11 B10 A9 A10 B8 B9"), ] # Platform ----------------------------------------------------------------------------------------- class Platform(LatticeECP5Platform): default_clk_name = "clk48" default_clk_period = 1e9/48e6 def __init__(self, revision="v1", device="45F", toolchain="trellis", **kwargs): assert revision in ["v1", "v2"] assert device in ["25F", "45F", "85F"] self.revision = revision io = _io_vx connectors = _connectors_vx if revision == "v1": io += _io_v1 if revision == "v2": io += _io_v2 LatticeECP5Platform.__init__(self, f"LFE5U-{device}-6BG256", io, connectors, toolchain=toolchain, **kwargs) def create_programmer(self, cable): return OpenFPGALoader(cable=cable) def METHOD_NAME(self, fragment): LatticeECP5Platform.METHOD_NAME(self, fragment) self.add_period_constraint(self.lookup_request("clk48", loose=True), 1e9/48e6)
299,054
test flag n
""" Name: r.what test Purpose: Tests r.what and its flags/options. Author: Sunveer Singh, Google Code-in 2018 Copyright: (C) 2018 by Sunveer Singh and the GRASS Development Team Licence: This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details. """ from grass.gunittest.case import TestCase from grass.gunittest.main import test from grass.gunittest.gmodules import SimpleModule class Testrr(TestCase): input = "elevation" coordinates = (633614.08, 224125.12, 632972.36, 225382.87) points = "comm_colleges" @classmethod def setUpClass(cls): cls.use_temp_region() cls.runModule("g.region", raster=cls.input, flags="p") @classmethod def tearDownClass(cls): cls.del_temp_region() def METHOD_NAME(self): """Testing output with flag n""" string = """1|145096.8591495|154534.264883875||* 2|616341.4371495|146049.750883875||* 3|410595.7191495|174301.828883875||* 4|734153.6871495|169168.437883875||* """ r_what = SimpleModule( "r.what", map=self.input, coordinates=self.coordinates, flags="n" ) r_what.outputs.stdout = string self.assertLooksLike(reference=string, actual=r_what.outputs.stdout) def test_flag_f(self): """Testing output with flag f""" string = """5|706338.2501495|54889.417883875||* 6|758009.7501495|112019.898883875||* 7|754002.7501495|200902.234883875||* 8|704771.7501495|183364.484883875||*""" r_what = SimpleModule( "r.what", map=self.input, coordinates=self.coordinates, flags="f" ) r_what.outputs.stdout = string self.assertLooksLike(reference=string, actual=r_what.outputs.stdout) def test_flag_r(self): """Testing output with flag r""" string = """9|399187.0631495|220018.859883875||* 10|685098.9371495|33282.089883875||* 11|577750.8131495|257153.109883875||* 12|794095.5621495|199742.671883875||*""" r_what = SimpleModule( "r.what", map=self.input, coordinates=self.coordinates, flags="r" ) r_what.outputs.stdout = string self.assertLooksLike(reference=string, actual=r_what.outputs.stdout) def test_flag_i(self): """Testing output with flag i""" string = """13|634688.2501495|100629.616883875||* 14|287638.7811495|207582.624883875||* 15|366218.5321495|222940.625883875||* 16|385212.4371495|236593.109883875||*""" r_what = SimpleModule( "r.what", map=self.input, coordinates=self.coordinates, flags="i" ) r_what.outputs.stdout = string self.assertLooksLike(reference=string, actual=r_what.outputs.stdout) def test_flag_c(self): """Testing output with flag c""" string = """17|628137.4371495|63995.550883875||* 18|782600.5631495|152698.890883875||* 19|502813.9381495|235232.577883875||* 20|705922.6251495|136589.359883875||*""" r_what = SimpleModule( "r.what", map=self.input, coordinates=self.coordinates, flags="c" ) r_what.outputs.stdout = string self.assertLooksLike(reference=string, actual=r_what.outputs.stdout) def test_flag_v(self): """Testing output with flag v""" string = """21|620397.8131495|246847.640883875||* 22|738465.3751495|237233.983883875||* 23|708944.7501495|247632.296883875||* 24|526666.6871495|249780.312883875||*""" r_what = SimpleModule( "r.what", map=self.input, coordinates=self.coordinates, flags="v", points=self.points, ) r_what.outputs.stdout = string self.assertLooksLike(reference=string, actual=r_what.outputs.stdout) if __name__ == "__main__": from grass.gunittest.main import test test()
299,055
delete model
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Amazon Lookout for Vision model code examples used in the service documentation: https://docs.aws.amazon.com/lookout-for-vision/latest/developer-guide/model.html Shows how to create and delete a model. Also, how to view the versions of the models in a project. """ import time import logging from botocore.exceptions import ClientError logger = logging.getLogger(__name__) # snippet-start:[python.example_code.lookoutvision.Models] class Models: # snippet-end:[python.example_code.lookoutvision.Models] """ Provides example methods that create and manage Lookout for Vision models. """ # snippet-start:[python.example_code.lookoutvision.CreateModel] @staticmethod def create_model( lookoutvision_client, project_name, training_results, tag_key=None, tag_key_value=None): """ Creates a version of a Lookout for Vision model. :param lookoutvision_client: A Boto3 Lookout for Vision client. :param project_name: The name of the project in which you want to create a model. :param training_results: The Amazon S3 location where training results are stored. :param tag_key: The key for a tag to add to the model. :param tag_key_value - A value associated with the tag_key. return: The model status and version. """ try: logger.info("Training model...") output_bucket, output_folder = training_results.replace( "s3://", "").split("/", 1) output_config = { "S3Location": {"Bucket": output_bucket, "Prefix": output_folder}} tags = [] if tag_key is not None: tags = [{"Key": tag_key, "Value": tag_key_value}] response = lookoutvision_client.create_model( ProjectName=project_name, OutputConfig=output_config, Tags=tags) logger.info("ARN: %s", response["ModelMetadata"]["ModelArn"]) logger.info("Version: %s", response["ModelMetadata"]["ModelVersion"]) logger.info("Started training...") print("Training started. Training might take several hours to complete.") # Wait until training completes. finished = False status = "UNKNOWN" while finished is False: model_description = lookoutvision_client.describe_model( ProjectName=project_name, ModelVersion=response["ModelMetadata"]["ModelVersion"]) status = model_description["ModelDescription"]["Status"] if status == "TRAINING": logger.info("Model training in progress...") time.sleep(600) continue if status == "TRAINED": logger.info("Model was successfully trained.") else: logger.info( "Model training failed: %s ", model_description["ModelDescription"]["StatusMessage"]) finished = True except ClientError: logger.exception("Couldn't train model.") raise else: return status, response["ModelMetadata"]["ModelVersion"] # snippet-end:[python.example_code.lookoutvision.CreateModel] # snippet-start:[python.example_code.lookoutvision.DescribeModel] @staticmethod def describe_model(lookoutvision_client, project_name, model_version): """ Shows the performance metrics for a trained model. :param lookoutvision_client: A Boto3 Amazon Lookout for Vision client. :param project_name: The name of the project that contains the desired model. :param model_version: The version of the model. """ response = lookoutvision_client.describe_model( ProjectName=project_name, ModelVersion=model_version) model_description = response["ModelDescription"] print(f"\tModel version: {model_description['ModelVersion']}") print(f"\tARN: {model_description['ModelArn']}") if "Description" in model_description: print(f"\tDescription: {model_description['Description']}") print(f"\tStatus: {model_description['Status']}") print(f"\tMessage: {model_description['StatusMessage']}") print(f"\tCreated: {str(model_description['CreationTimestamp'])}") if model_description['Status'] in ("TRAINED", "HOSTED"): training_start = model_description["CreationTimestamp"] training_end = model_description["EvaluationEndTimestamp"] duration = training_end - training_start print(f"\tTraining duration: {duration}") print("\n\tPerformance metrics\n\t-------------------") print(f"\tRecall: {model_description['Performance']['Recall']}") print(f"\tPrecision: {model_description['Performance']['Precision']}") print(f"\tF1: {model_description['Performance']['F1Score']}") training_output_bucket = model_description["OutputConfig"]["S3Location"]["Bucket"] prefix = model_description["OutputConfig"]["S3Location"]["Prefix"] print(f"\tTraining output: s3://{training_output_bucket}/{prefix}") # snippet-end:[python.example_code.lookoutvision.DescribeModel] # snippet-start:[python.example_code.lookoutvision.ListModels] @staticmethod def describe_models(lookoutvision_client, project_name): """ Gets information about all models in a Lookout for Vision project. :param lookoutvision_client: A Boto3 Lookout for Vision client. :param project_name: The name of the project that you want to use. """ try: response = lookoutvision_client.list_models(ProjectName=project_name) print("Project: " + project_name) for model in response["Models"]: Models.describe_model( lookoutvision_client, project_name, model["ModelVersion"]) print() print("Done...") except ClientError: logger.exception("Couldn't list models.") raise # snippet-end:[python.example_code.lookoutvision.ListModels] # snippet-start:[python.example_code.lookoutvision.DeleteModel] @staticmethod def METHOD_NAME(lookoutvision_client, project_name, model_version): """ Deletes a Lookout for Vision model. The model must first be stopped and can't be in training. :param lookoutvision_client: A Boto3 Lookout for Vision client. :param project_name: The name of the project that contains the desired model. :param model_version: The version of the model that you want to delete. """ try: logger.info("Deleting model: %s", model_version) lookoutvision_client.METHOD_NAME( ProjectName=project_name, ModelVersion=model_version) model_exists = True while model_exists: response = lookoutvision_client.list_models(ProjectName=project_name) model_exists = False for model in response["Models"]: if model["ModelVersion"] == model_version: model_exists = True if model_exists is False: logger.info("Model deleted") else: logger.info("Model is being deleted...") time.sleep(2) logger.info("Deleted Model: %s", model_version) except ClientError: logger.exception("Couldn't delete model.") raise # snippet-end:[python.example_code.lookoutvision.DeleteModel]
299,056
unphased diploid gt index
from collections.abc import Sequence from hail.typecheck import typecheck_method from hail.utils import FatalError class Call(object): """ An object that represents an individual's call at a genomic locus. Parameters ---------- alleles : :obj:`list` of :obj:`int` List of alleles that compose the call. phased : :obj:`bool` If ``True``, the alleles are phased and the order is specified by `alleles`. Note ---- This object refers to the Python value returned by taking or collecting Hail expressions, e.g. ``mt.GT.take(5`)``. This is rare; it is much more common to manipulate the :class:`.CallExpression` object, which is constructed using the following functions: - :func:`.call` - :func:`.unphased_diploid_gt_index_call` - :func:`.parse_call` """ def __init__(self, alleles, phased=False): # Intentionally not using the type check annotations which are too slow. assert isinstance(alleles, Sequence) assert isinstance(phased, bool) if len(alleles) > 2: raise NotImplementedError("Calls with greater than 2 alleles are not supported.") self._phased = phased ploidy = len(alleles) if phased or ploidy < 2: self._alleles = alleles else: assert ploidy == 2 a0 = alleles[0] a1 = alleles[1] if a1 < a0: a0, a1 = a1, a0 self._alleles = [a0, a1] def __str__(self): n = self.ploidy if n == 0: if self._phased: return '|-' return '-' if n == 1: if self._phased: return f'|{self._alleles[0]}' return str(self._alleles[0]) assert n == 2 a0 = self._alleles[0] a1 = self._alleles[1] if self._phased: return f'{a0}|{a1}' return f'{a0}/{a1}' def __repr__(self): return 'Call(alleles=%s, phased=%s)' % (self._alleles, self._phased) def __eq__(self, other): return ( self._phased == other._phased and self._alleles == other._alleles ) if isinstance(other, Call) else NotImplemented def __hash__(self): return hash(self._phased) ^ hash(tuple(self._alleles)) def __getitem__(self, item): """Get the i*th* allele. Returns ------- :obj:`int` """ return self._alleles[item] @property def alleles(self): """Get the alleles of this call. Returns ------- :obj:`list` of :obj:`int` """ return self._alleles @property def ploidy(self): """The number of alleles for this call. Returns ------- :obj:`int` """ return len(self._alleles) @property def phased(self): """True if the call is phased. Returns ------- :obj:`bool` """ return self._phased def is_haploid(self): """True if the ploidy == 1. :rtype: bool """ return self.ploidy == 1 def is_diploid(self): """True if the ploidy == 2. :rtype: bool """ return self.ploidy == 2 def is_hom_ref(self): """True if the call has no alternate alleles. :rtype: bool """ if self.ploidy == 0: return False return all(a == 0 for a in self._alleles) def is_het(self): """True if the call contains two different alleles. :rtype: bool """ if self.ploidy < 2: return False return self._alleles[0] != self._alleles[1] def is_hom_var(self): """True if the call contains identical alternate alleles. :rtype: bool """ n = self.ploidy if n == 0: return False a0 = self._alleles[0] if a0 == 0: return False if n == 1: return True assert n == 2 return self._alleles[1] == a0 def is_non_ref(self): """True if the call contains any non-reference alleles. :rtype: bool """ return any(a > 0 for a in self._alleles) def is_het_non_ref(self): """True if the call contains two different alternate alleles. :rtype: bool """ n = self.ploidy if n < 2: return False assert n == 2 a0 = self._alleles[0] a1 = self._alleles[1] return a0 > 0 and a1 > 0 and a0 != a1 def is_het_ref(self): """True if the call contains one reference and one alternate allele. :rtype: bool """ n = self.ploidy if n < 2: return False assert n == 2 a0 = self._alleles[0] a1 = self._alleles[1] return (a0 == 0 and a1 > 0) or (a0 > 0 and a1 == 0) def n_alt_alleles(self): """Returns the count of non-reference alleles. :rtype: int """ n = 0 for a in self._alleles: if a > 0: n += 1 return n @typecheck_method(n_alleles=int) def one_hot_alleles(self, n_alleles): """Returns a list containing the one-hot encoded representation of the called alleles. Examples -------- >>> n_alleles = 2 >>> hom_ref = hl.Call([0, 0]) >>> het = hl.Call([0, 1]) >>> hom_var = hl.Call([1, 1]) >>> het.one_hot_alleles(n_alleles) [1, 1] >>> hom_var.one_hot_alleles(n_alleles) [0, 2] Notes ----- This one-hot representation is the positional sum of the one-hot encoding for each called allele. For a biallelic variant, the one-hot encoding for a reference allele is [1, 0] and the one-hot encoding for an alternate allele is [0, 1]. Parameters ---------- n_alleles : :obj:`int` Number of total alleles, including the reference. Returns ------- :obj:`list` of :obj:`int` """ r = [0] * n_alleles for a in self._alleles: r[a] += 1 return r def METHOD_NAME(self): """Return the genotype index for unphased, diploid calls. Returns ------- :obj:`int` """ if self.ploidy != 2 or self.phased: raise FatalError( "'unphased_diploid_gt_index' is only valid for unphased, diploid calls. Found {}.".format(repr(self))) a0 = self._alleles[0] a1 = self._alleles[1] assert a0 <= a1 return a1 * (a1 + 1) / 2 + a0
299,057
test copy subclass
import copy import sys import tempfile import numpy as np import pytest import torch import torchio as tio from ..utils import TorchioTestCase class TestSubject(TorchioTestCase): """Tests for `Subject`.""" def test_positional_args(self): with pytest.raises(ValueError): tio.Subject(0) def test_input_dict(self): with tempfile.NamedTemporaryFile(delete=False) as f: input_dict = {'image': tio.ScalarImage(f.name)} tio.Subject(input_dict) tio.Subject(**input_dict) def test_no_sample(self): with tempfile.NamedTemporaryFile(delete=False) as f: input_dict = {'image': tio.ScalarImage(f.name)} subject = tio.Subject(input_dict) with pytest.raises(RuntimeError): with pytest.warns(UserWarning): tio.RandomFlip()(subject) def test_history(self): transformed = tio.RandomGamma()(self.sample_subject) assert len(transformed.history) == 1 def test_inconsistent_shape(self): subject = tio.Subject( a=tio.ScalarImage(tensor=torch.rand(1, 2, 3, 4)), b=tio.ScalarImage(tensor=torch.rand(2, 2, 3, 4)), ) subject.spatial_shape with pytest.raises(RuntimeError): subject.shape def test_inconsistent_spatial_shape(self): subject = tio.Subject( a=tio.ScalarImage(tensor=torch.rand(1, 3, 3, 4)), b=tio.ScalarImage(tensor=torch.rand(2, 2, 3, 4)), ) with pytest.raises(RuntimeError): subject.spatial_shape @pytest.mark.skipif(sys.platform == 'win32', reason='Unstable on Windows') def test_plot(self): self.sample_subject.plot( show=False, output_path=self.dir / 'figure.png', cmap_dict={ 't2': 'viridis', 'label': {0: 'yellow', 1: 'blue'}, }, ) @pytest.mark.skipif(sys.platform == 'win32', reason='Unstable on Windows') def test_plot_one_image(self): path = self.get_image_path('t1_plot') subject = tio.Subject(t1=tio.ScalarImage(path)) subject.plot(show=False) def test_same_space(self): # https://github.com/fepegar/torchio/issues/381 affine1 = np.array( [ [ 4.27109375e-14, -8.71264808e-03, 9.99876633e-01, -3.39850907e01, ], [ -5.54687500e-01, -2.71630469e-12, 8.75148028e-17, 1.62282930e02, ], [ 2.71575000e-12, -5.54619070e-01, -1.57073092e-02, 2.28515784e02, ], [0.00000000e00, 0.00000000e00, 0.00000000e00, 1.00000000e00], ] ) affine2 = np.array( [ [ 3.67499773e-08, -8.71257665e-03, 9.99876635e-01, -3.39850922e01, ], [ -5.54687500e-01, 3.67499771e-08, 6.73024385e-08, 1.62282928e02, ], [ -3.73318194e-08, -5.54619071e-01, -1.57071802e-02, 2.28515778e02, ], # noqa: B950 [0.00000000e00, 0.00000000e00, 0.00000000e00, 1.00000000e00], ] ) t = torch.rand(1, 2, 3, 4) subject = tio.Subject( im1=tio.ScalarImage(tensor=t, affine=affine1), im2=tio.ScalarImage(tensor=t, affine=affine2), ) subject.check_consistent_space() def test_delete_image(self): subject = copy.deepcopy(self.sample_subject) subject.remove_image('t1') with pytest.raises(KeyError): subject['t1'] with pytest.raises(AttributeError): subject.t1 def test_2d(self): subject = self.make_2d(self.sample_subject) assert subject.is_2d() def test_different_non_numeric(self): with pytest.raises(RuntimeError): self.sample_subject.check_consistent_attribute('path') def test_bad_arg(self): with pytest.raises(ValueError): tio.Subject(0) def test_no_images(self): with pytest.raises(TypeError): tio.Subject(a=0) def test_copy_subject(self): sub_copy = copy.copy(self.sample_subject) assert isinstance(sub_copy, tio.data.Subject) sub_deep_copy = copy.deepcopy(self.sample_subject) assert isinstance(sub_deep_copy, tio.data.Subject) def METHOD_NAME(self): class DummySubjectSubClass(tio.data.Subject): pass dummy_sub = DummySubjectSubClass(self.sample_subject) sub_copy = copy.copy(dummy_sub) assert isinstance(sub_copy, tio.data.Subject) assert isinstance(sub_copy, DummySubjectSubClass) sub_deep_copy = copy.deepcopy(dummy_sub) assert isinstance(sub_deep_copy, tio.data.Subject) assert isinstance(sub_deep_copy, DummySubjectSubClass) def test_load_unload(self): self.sample_subject.load() for image in self.sample_subject.get_images(intensity_only=False): assert image._loaded self.sample_subject.unload() for image in self.sample_subject.get_images(intensity_only=False): assert not image._loaded
299,058
test get tokens without expiry incident returns
from datetime import datetime, timedelta from io import StringIO import pytz from django.conf import settings from django.core.management import call_command from django.test import TestCase from rest_framework.authtoken.models import Token from argus.dev.management.commands.check_token_expiry import ( close_expiry_incidents_without_expiring_tokens, find_expiring_tokens, get_tokens_without_expiry_incident, ) from argus.incident.factories import SourceSystemFactory from argus.incident.models import Incident, IncidentTagRelation, Tag, create_token_expiry_incident from argus.util.testing import connect_signals, disconnect_signals class CheckTokenExpiryTests(TestCase): def setUp(self): disconnect_signals() self.source_system1 = SourceSystemFactory() self.source_system2 = SourceSystemFactory() self.user1 = self.source_system1.user self.user2 = self.source_system2.user self.expiring_token = Token.objects.create(user=self.user1) self.expiring_token.created = self.expiring_token.created - timedelta(days=100) self.expiring_token.save() self.expiring_token_expiration_date = self.expiring_token.created + timedelta( days=settings.AUTH_TOKEN_EXPIRES_AFTER_DAYS ) self.expiry_incident = create_token_expiry_incident(self.expiring_token, self.expiring_token_expiration_date) self.current_token = Token.objects.create(user=self.user2) self.current_token_expiration_date = self.current_token.created + timedelta( days=settings.AUTH_TOKEN_EXPIRES_AFTER_DAYS ) def tearDown(self): connect_signals() def call_command(self, *args, **kwargs): out = StringIO() call_command( "check_token_expiry", *args, stdout=out, stderr=StringIO(), **kwargs, ) return out.getvalue() def test_find_token_expiry_finds_only_expiring_token(self): self.assertEqual( find_expiring_tokens(5), [ ( self.expiring_token, self.expiring_token_expiration_date, ) ], ) def test_create_token_expiry_incident_creates_incident(self): self.assertTrue(create_token_expiry_incident(self.current_token, self.current_token_expiration_date)) def test_create_token_expiry_incident_raises_error_if_no_given_token(self): with self.assertRaises(ValueError): create_token_expiry_incident(None, None) def test_get_tokens_without_expiry_incident_returns_no_tokens_if_all_have_expiry_incident(self): self.assertEqual( get_tokens_without_expiry_incident([(self.expiring_token, self.expiring_token_expiration_date)]), [] ) def test_get_tokens_without_expiry_incident_returns_token_with_closed_expiry_incident(self): current_token_expiry_incident = create_token_expiry_incident( self.current_token, self.current_token_expiration_date ) current_token_expiry_incident.set_closed(actor=self.user1) self.assertEqual( get_tokens_without_expiry_incident([(self.current_token, self.current_token_expiration_date)]), [(self.current_token, self.current_token_expiration_date)], ) def METHOD_NAME(self): self.expiry_incident.set_closed(actor=self.user1) self.assertEqual( get_tokens_without_expiry_incident( [ (self.expiring_token, self.expiring_token_expiration_date), (self.current_token, self.current_token_expiration_date), ] ), [ (self.expiring_token, self.expiring_token_expiration_date), (self.current_token, self.current_token_expiration_date), ], ) def test_get_tokens_without_expiry_incident_ignores_other_tokens_expiry_incidents(self): self.assertTrue(get_tokens_without_expiry_incident([(self.current_token, self.current_token_expiration_date)])) def test_close_expiry_incidents_without_expiring_tokens_does_not_close_connected_incidents(self): close_expiry_incidents_without_expiring_tokens([(self.expiring_token, self.expiring_token_expiration_date)]) self.assertTrue(Incident.objects.get(pk=self.expiry_incident.pk).open) def test_close_expiry_incidents_without_expiring_tokens_closes_unconnected_incidents(self): close_expiry_incidents_without_expiring_tokens([]) self.assertFalse(Incident.objects.get(pk=self.expiry_incident.pk).open) def test_expiry_incident_is_closed_when_token_deleted(self): self.expiring_token.delete() self.assertFalse(Incident.objects.get(pk=self.expiry_incident.pk).open) def test_expiry_incident_is_closed_when_token_updated(self): self.expiring_token.created = datetime.now(pytz.utc) self.expiring_token.save() self.assertFalse(Incident.objects.get(pk=self.expiry_incident.pk).open) def test_check_token_expiry_can_handle_days_input(self): days = settings.AUTH_TOKEN_EXPIRES_AFTER_DAYS + 1 out = self.call_command(f"--days={days}") self.assertFalse(out) token_expiry_tag = Tag.objects.get(key="problem_type", value="token_expiry") source_system_id_tag = Tag.objects.get(key="source_system_id", value=self.current_token.user.source_system.id) self.assertTrue(token_expiry_tag) self.assertTrue(source_system_id_tag) self.assertTrue( Incident.objects.filter(incident_tag_relations__tag=token_expiry_tag) .filter(incident_tag_relations__tag=source_system_id_tag) .exists() )
299,059
test load data
#!/usr/bin/env python # Copyright (c) 2020 Satpy developers # # This file is part of satpy. # # satpy is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # satpy is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # satpy. If not, see <http://www.gnu.org/licenses/>. """Unittests for GPM IMERG reader.""" import os import unittest from datetime import datetime from unittest import mock import dask.array as da import h5py import numpy as np import xarray as xr from satpy.tests.reader_tests.test_hdf5_utils import FakeHDF5FileHandler DEFAULT_FILE_SHAPE = (3600, 1800) DEFAULT_LAT_DATA = np.linspace(-89.95, 89.95, DEFAULT_FILE_SHAPE[1]).astype(np.float32) DEFAULT_LON_DATA = np.linspace(-179.95, 179.95, DEFAULT_FILE_SHAPE[0]).astype(np.float32) class FakeHDF5FileHandler2(FakeHDF5FileHandler): """Swap-in HDF5 File Handler.""" def _get_geo_data(self, num_rows, num_cols): geo = { 'Grid/lon': xr.DataArray(DEFAULT_LON_DATA, attrs={'units': 'degrees_east', }, dims=('lon')), 'Grid/lat': xr.DataArray(DEFAULT_LAT_DATA, attrs={'units': 'degrees_north', }, dims=('lat')), } return geo def _get_precip_data(self, num_rows, num_cols): selection = { 'Grid/IRprecipitation': xr.DataArray( da.ones((1, num_cols, num_rows), chunks=1024, dtype=np.float32), attrs={ '_FillValue': -9999.9, 'units': 'mm/hr', 'Units': 'mm/hr', 'badval': h5py.h5r.Reference(), 'badvals': np.array([[h5py.h5r.Reference()]]) }, dims=('time', 'lon', 'lat')), } return selection def get_test_content(self, filename, filename_info, filetype_info): """Mimic reader input file content.""" num_rows = 1800 num_cols = 3600 test_content = {} data = {} data = self._get_geo_data(num_rows, num_cols) test_content.update(data) data = self._get_precip_data(num_rows, num_cols) test_content.update(data) return test_content class TestHdf5IMERG(unittest.TestCase): """Test the GPM IMERG reader.""" yaml_file = "gpm_imerg.yaml" def setUp(self): """Wrap HDF5 file handler with our own fake handler.""" from satpy._config import config_search_paths from satpy.readers.gpm_imerg import Hdf5IMERG self.reader_configs = config_search_paths(os.path.join('readers', self.yaml_file)) # http://stackoverflow.com/questions/12219967/how-to-mock-a-base-class-with-python-mock-library self.p = mock.patch.object(Hdf5IMERG, '__bases__', (FakeHDF5FileHandler2,)) self.fake_handler = self.p.start() self.p.is_local = True def tearDown(self): """Stop wrapping the HDF5 file handler.""" self.p.stop() def METHOD_NAME(self): """Test loading data.""" from satpy.readers import load_reader # Filename to test, needed for start and end times filenames = [ '3B-HHR.MS.MRG.3IMERG.20200131-S233000-E235959.1410.V06B.HDF5', ] # Expected projection in area def pdict = {'proj': 'longlat', 'datum': 'WGS84', 'no_defs': None, 'type': 'crs'} reader = load_reader(self.reader_configs) files = reader.select_files_from_pathnames(filenames) self.assertEqual(1, len(files)) reader.create_filehandlers(files) # Make sure we have some files self.assertTrue(reader.file_handlers) res = reader.load(['IRprecipitation']) self.assertEqual(1, len(res)) self.assertEqual(res['IRprecipitation'].start_time, datetime(2020, 1, 31, 23, 30, 0)) self.assertEqual(res['IRprecipitation'].end_time, datetime(2020, 1, 31, 23, 59, 59)) self.assertEqual(res['IRprecipitation'].resolution, 0.1) self.assertEqual(res['IRprecipitation'].area.width, 3600) self.assertEqual(res['IRprecipitation'].area.height, 1800) self.assertEqual(res['IRprecipitation'].area.proj_dict, pdict) np.testing.assert_almost_equal(res['IRprecipitation'].area.area_extent, (-179.95, -89.95, 179.95, 89.95), 5)
299,060
non max suppression
import numpy as np from depthai_sdk.classes import Detections def decode(nn_data): """ Each palm detection is a tensor consisting of 19 numbers: - ymin, xmin, ymax, xmax - x,y-coordinates for the 7 key_points - confidence score :return: """ if nn_data is None: return Detections(nn_data) shape = (128, 128) num_keypoints = 7 min_score_thresh = 0.7 anchors = np.load(__file__.replace("handler.py", "anchors_palm.npy")) # Run the neural network results = to_tensor_result(nn_data) raw_box_tensor = results.get("regressors").reshape(-1, 896, 18) # regress raw_score_tensor = results.get("classificators").reshape(-1, 896, 1) # classification detections = raw_to_detections(raw_box_tensor, raw_score_tensor, anchors, shape, num_keypoints) palm_coords = [ obj[:4] for det in detections for obj in det if obj[-1] > min_score_thresh ] palm_confs = [ obj[-1] for det in detections for obj in det if obj[-1] > min_score_thresh ] if len(palm_coords) == 0: return Detections(nn_data) nms = METHOD_NAME( boxes=np.concatenate(palm_coords).reshape(-1, 4), probs=palm_confs, overlap_threshold=0.1 ) if nms is None: return Detections(nn_data) detections = Detections(nn_data) for i, box in enumerate(nms): detections.add(0, palm_confs[i], tuple(box)) return detections def sigmoid(x): return (1.0 + np.tanh(0.5 * x)) * 0.5 def decode_boxes(raw_boxes, anchors, shape, num_keypoints): """ Converts the predictions into actual coordinates using the anchor boxes. Processes the entire batch at once. """ boxes = np.zeros_like(raw_boxes) x_scale, y_scale = shape x_center = raw_boxes[..., 0] / x_scale * anchors[:, 2] + anchors[:, 0] y_center = raw_boxes[..., 1] / y_scale * anchors[:, 3] + anchors[:, 1] w = raw_boxes[..., 2] / x_scale * anchors[:, 2] h = raw_boxes[..., 3] / y_scale * anchors[:, 3] boxes[..., 1] = y_center - h / 2.0 # xmin boxes[..., 0] = x_center - w / 2.0 # ymin boxes[..., 3] = y_center + h / 2.0 # xmax boxes[..., 2] = x_center + w / 2.0 # ymax for k in range(num_keypoints): offset = 4 + k * 2 keypoint_x = raw_boxes[..., offset] / x_scale * anchors[:, 2] + anchors[:, 0] keypoint_y = ( raw_boxes[..., offset + 1] / y_scale * anchors[:, 3] + anchors[:, 1] ) boxes[..., offset] = keypoint_x boxes[..., offset + 1] = keypoint_y return boxes def raw_to_detections(raw_box_tensor, raw_score_tensor, anchors_, shape, num_keypoints): """ This function converts these two "raw" tensors into proper detections. Returns a list of (num_detections, 17) tensors, one for each image in the batch. This is based on the source code from: mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.cc mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.proto """ detection_boxes = decode_boxes(raw_box_tensor, anchors_, shape, num_keypoints) detection_scores = sigmoid(raw_score_tensor).squeeze(-1) output_detections = [] for i in range(raw_box_tensor.shape[0]): boxes = detection_boxes[i] scores = np.expand_dims(detection_scores[i], -1) output_detections.append(np.concatenate((boxes, scores), -1)) return output_detections def METHOD_NAME(boxes, probs, overlap_threshold=0.3): if len(boxes) == 0: return [], [] if boxes.dtype.kind == "i": boxes = boxes.astype("float") pick = [] x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] area = (x2 - x1) * (y2 - y1) idxs = y2 if probs is not None: idxs = probs idxs = np.argsort(idxs) while len(idxs) > 0: last = len(idxs) - 1 i = idxs[last] pick.append(i) xx1 = np.maximum(x1[i], x1[idxs[:last]]) yy1 = np.maximum(y1[i], y1[idxs[:last]]) xx2 = np.minimum(x2[i], x2[idxs[:last]]) yy2 = np.minimum(y2[i], y2[idxs[:last]]) w = np.maximum(0, xx2 - xx1) h = np.maximum(0, yy2 - yy1) overlap = (w * h) / area[idxs[:last]] idxs = np.delete( idxs, np.concatenate(([last], np.where(overlap > overlap_threshold)[0])) ) return boxes[pick] def to_tensor_result(packet): return { name: np.array(packet.getLayerFp16(name)) for name in [tensor.name for tensor in packet.getRaw().tensors] }
299,061
test permissions updated signal role assignment updated
from unittest.mock import patch import pytest from baserow_enterprise.role.handler import RoleAssignmentHandler from baserow_enterprise.role.models import Role from baserow_enterprise.teams.handler import TeamHandler @pytest.fixture(autouse=True) def enable_enterprise_and_synced_roles_for_all_tests_here( enable_enterprise, synced_roles ): pass @pytest.mark.django_db(transaction=True) @patch("baserow_enterprise.role.receivers.broadcast_to_users") def test_permissions_updated_signal_role_assignment_created( mock_broadcast_to_users, data_fixture ): user = data_fixture.create_user() workspace = data_fixture.create_workspace(user=user) database = data_fixture.create_database_application(workspace=workspace) role_admin = Role.objects.get(uid="ADMIN") RoleAssignmentHandler().assign_role(user, workspace, role_admin, scope=database) mock_broadcast_to_users.delay.assert_called_once() args = mock_broadcast_to_users.delay.call_args assert args[0][0] == [user.id] assert args[0][1] == { "type": "permissions_updated", "group_id": workspace.id, "workspace_id": workspace.id, } @pytest.mark.django_db(transaction=True) @patch("baserow_enterprise.role.receivers.broadcast_to_users") def METHOD_NAME( mock_broadcast_to_users, data_fixture ): user = data_fixture.create_user() workspace = data_fixture.create_workspace(user=user) database = data_fixture.create_database_application(workspace=workspace) role_admin = Role.objects.get(uid="ADMIN") role_builder = Role.objects.get(uid="BUILDER") RoleAssignmentHandler().assign_role(user, workspace, role_admin, scope=database) mock_broadcast_to_users.delay.reset_mock() RoleAssignmentHandler().assign_role(user, workspace, role_builder, scope=database) mock_broadcast_to_users.delay.assert_called_once() args = mock_broadcast_to_users.delay.call_args assert args[0][0] == [user.id] assert args[0][1] == { "type": "permissions_updated", "group_id": workspace.id, "workspace_id": workspace.id, } @pytest.mark.django_db(transaction=True) @patch("baserow_enterprise.role.receivers.broadcast_to_users") def test_permissions_updated_signal_role_assignment_deleted( mock_broadcast_to_users, data_fixture ): user = data_fixture.create_user() workspace = data_fixture.create_workspace(user=user) database = data_fixture.create_database_application(workspace=workspace) role_admin = Role.objects.get(uid="ADMIN") RoleAssignmentHandler().assign_role(user, workspace, role_admin, scope=database) mock_broadcast_to_users.delay.reset_mock() RoleAssignmentHandler().remove_role(user, workspace, scope=database) mock_broadcast_to_users.delay.assert_called_once() args = mock_broadcast_to_users.delay.call_args assert args[0][0] == [user.id] assert args[0][1] == { "type": "permissions_updated", "group_id": workspace.id, "workspace_id": workspace.id, } @pytest.mark.django_db(transaction=True) @patch("baserow_enterprise.role.receivers.broadcast_to_users") def test_permissions_updated_signal_role_workspace_level_permissions_updated( mock_broadcast_to_users, data_fixture ): user = data_fixture.create_user() workspace = data_fixture.create_workspace(members=[user]) role_viewer = Role.objects.get(uid="VIEWER") RoleAssignmentHandler().assign_role(user, workspace, role_viewer) mock_broadcast_to_users.delay.assert_called_once() args = mock_broadcast_to_users.delay.call_args assert args[0][0] == [user.id] assert args[0][1] == { "type": "permissions_updated", "group_id": workspace.id, "workspace_id": workspace.id, } @pytest.mark.django_db(transaction=True) @patch("baserow_enterprise.role.receivers.broadcast_to_users") def test_permissions_updated_signal_role_team_trashed( mock_broadcast_to_users, data_fixture, enterprise_data_fixture ): user = data_fixture.create_user() workspace = data_fixture.create_workspace(user=user) team = enterprise_data_fixture.create_team(workspace=workspace) enterprise_data_fixture.create_subject(team, user) TeamHandler().delete_team(user, team) mock_broadcast_to_users.delay.assert_called_once() args = mock_broadcast_to_users.delay.call_args assert args[0][0] == [user.id] assert args[0][1] == { "type": "permissions_updated", "group_id": workspace.id, "workspace_id": workspace.id, } @pytest.mark.django_db(transaction=True) @patch("baserow_enterprise.role.receivers.broadcast_to_users") def test_permissions_updated_signal_role_team_restored( mock_broadcast_to_users, data_fixture, enterprise_data_fixture ): user = data_fixture.create_user() workspace = data_fixture.create_workspace(user=user) team = enterprise_data_fixture.create_team(workspace=workspace) enterprise_data_fixture.create_subject(team, user) TeamHandler().delete_team(user, team) mock_broadcast_to_users.delay.reset_mock() TeamHandler().restore_team_by_id(user, team.id) mock_broadcast_to_users.delay.assert_called_once() args = mock_broadcast_to_users.delay.call_args assert args[0][0] == [user.id] assert args[0][1] == { "type": "permissions_updated", "group_id": workspace.id, "workspace_id": workspace.id, } @pytest.mark.django_db(transaction=True) @patch("baserow_enterprise.role.receivers.broadcast_to_users") def test_permissions_updated_signal_role_many_users( mock_broadcast_to_users, data_fixture, enterprise_data_fixture ): user_amount = 20 owner = data_fixture.create_user() users = [data_fixture.create_user() for i in range(user_amount)] user_ids = [user.id for user in users] workspace = data_fixture.create_workspace(user=owner, members=users) team = enterprise_data_fixture.create_team(workspace=workspace) for user in users: enterprise_data_fixture.create_subject(team, user) TeamHandler().delete_team(owner, team) mock_broadcast_to_users.delay.assert_called_once() args = mock_broadcast_to_users.delay.call_args assert args[0][0].sort() == user_ids.sort() assert args[0][1] == { "type": "permissions_updated", "group_id": workspace.id, "workspace_id": workspace.id, }
299,062
test get file with tgz extension
import os import tarfile import urllib import zipfile from keras_core.testing import test_case from keras_core.utils import file_utils class TestGetFile(test_case.TestCase): def test_get_file_and_validate_it(self): """Tests get_file from a url, plus extraction and validation.""" dest_dir = self.get_temp_dir() orig_dir = self.get_temp_dir() text_file_path = os.path.join(orig_dir, "test.txt") zip_file_path = os.path.join(orig_dir, "test.zip") tar_file_path = os.path.join(orig_dir, "test.tar.gz") with open(text_file_path, "w") as text_file: text_file.write("Float like a butterfly, sting like a bee.") with tarfile.open(tar_file_path, "w:gz") as tar_file: tar_file.add(text_file_path) with zipfile.ZipFile(zip_file_path, "w") as zip_file: zip_file.write(text_file_path) origin = urllib.parse.urljoin( "file://", urllib.request.pathname2url(os.path.abspath(tar_file_path)), ) path = file_utils.get_file( "test.txt", origin, untar=True, cache_subdir=dest_dir ) filepath = path + ".tar.gz" hashval_sha256 = file_utils.hash_file(filepath) hashval_md5 = file_utils.hash_file(filepath, algorithm="md5") path = file_utils.get_file( "test.txt", origin, md5_hash=hashval_md5, untar=True, cache_subdir=dest_dir, ) path = file_utils.get_file( filepath, origin, file_hash=hashval_sha256, extract=True, cache_subdir=dest_dir, ) self.assertTrue(os.path.exists(filepath)) self.assertTrue(file_utils.validate_file(filepath, hashval_sha256)) self.assertTrue(file_utils.validate_file(filepath, hashval_md5)) os.remove(filepath) origin = urllib.parse.urljoin( "file://", urllib.request.pathname2url(os.path.abspath(zip_file_path)), ) hashval_sha256 = file_utils.hash_file(zip_file_path) hashval_md5 = file_utils.hash_file(zip_file_path, algorithm="md5") path = file_utils.get_file( "test", origin, md5_hash=hashval_md5, extract=True, cache_subdir=dest_dir, ) path = file_utils.get_file( "test", origin, file_hash=hashval_sha256, extract=True, cache_subdir=dest_dir, ) self.assertTrue(os.path.exists(path)) self.assertTrue(file_utils.validate_file(path, hashval_sha256)) self.assertTrue(file_utils.validate_file(path, hashval_md5)) os.remove(path) for file_path, extract in [ (text_file_path, False), (tar_file_path, True), (zip_file_path, True), ]: origin = urllib.parse.urljoin( "file://", urllib.request.pathname2url(os.path.abspath(file_path)), ) hashval_sha256 = file_utils.hash_file(file_path) path = file_utils.get_file( origin=origin, file_hash=hashval_sha256, extract=extract, cache_subdir=dest_dir, ) self.assertTrue(os.path.exists(path)) self.assertTrue(file_utils.validate_file(path, hashval_sha256)) os.remove(path) with self.assertRaisesRegexp( ValueError, 'Please specify the "origin".*' ): _ = file_utils.get_file() def METHOD_NAME(self): """Tests get_file from a url, plus extraction and validation.""" dest_dir = self.get_temp_dir() orig_dir = dest_dir text_file_path = os.path.join(orig_dir, "test.txt") tar_file_path = os.path.join(orig_dir, "test.tar.gz") with open(text_file_path, "w") as text_file: text_file.write("Float like a butterfly, sting like a bee.") with tarfile.open(tar_file_path, "w:gz") as tar_file: tar_file.add(text_file_path) origin = urllib.parse.urljoin( "file://", urllib.request.pathname2url(os.path.abspath(tar_file_path)), ) path = file_utils.get_file( "test.txt.tar.gz", origin, untar=True, cache_subdir=dest_dir ) self.assertTrue(path.endswith(".txt")) self.assertTrue(os.path.exists(path)) def test_get_file_with_integrity_check(self): """Tests get_file with validation before download.""" orig_dir = self.get_temp_dir() file_path = os.path.join(orig_dir, "test.txt") with open(file_path, "w") as text_file: text_file.write("Float like a butterfly, sting like a bee.") hashval = file_utils.hash_file(file_path) origin = urllib.parse.urljoin( "file://", urllib.request.pathname2url(os.path.abspath(file_path)) ) path = file_utils.get_file("test.txt", origin, file_hash=hashval) self.assertTrue(os.path.exists(path)) def test_get_file_with_failed_integrity_check(self): """Tests get_file with validation before download.""" orig_dir = self.get_temp_dir() file_path = os.path.join(orig_dir, "test.txt") with open(file_path, "w") as text_file: text_file.write("Float like a butterfly, sting like a bee.") hashval = "0" * 64 origin = urllib.parse.urljoin( "file://", urllib.request.pathname2url(os.path.abspath(file_path)) ) with self.assertRaisesRegex( ValueError, "Incomplete or corrupted file.*" ): _ = file_utils.get_file("test.txt", origin, file_hash=hashval)
299,063
create data
import copy import io import socket import subprocess from concurrent.futures import ThreadPoolExecutor from pathlib import Path from typing import Any, Dict, Generator, List import numpy as np import pytest from sklearn.datasets import make_blobs, make_regression from sklearn.metrics import accuracy_score TESTS_DIR = Path(__file__).absolute().parent @pytest.fixture(scope='module') def executable(pytestconfig) -> str: """Returns the path to the lightgbm executable.""" return pytestconfig.getoption('execfile') def _find_random_open_port() -> int: """Find a random open port on localhost.""" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(('', 0)) port = s.getsockname()[1] return port # noqa: RET504 def _generate_n_ports(n: int) -> Generator[int, None, None]: return (_find_random_open_port() for _ in range(n)) def _write_dict(d: Dict, file: io.TextIOWrapper) -> None: for k, v in d.items(): file.write(f'{k} = {v}\n') def METHOD_NAME(task: str, n_samples: int = 1_000) -> np.ndarray: """Create the appropriate data for the task. The data is returned as a numpy array with the label as the first column. """ if task == 'binary-classification': centers = [[-4, -4], [4, 4]] X, y = make_blobs(n_samples, centers=centers, random_state=42) elif task == 'regression': X, y = make_regression(n_samples, n_features=4, n_informative=2, random_state=42) return np.hstack([y.reshape(-1, 1), X]) class DistributedMockup: """Simulate distributed training.""" default_train_config = { 'task': 'train', 'pre_partition': True, 'machine_list_file': TESTS_DIR / 'mlist.txt', 'tree_learner': 'data', 'force_row_wise': True, 'verbose': 0, 'num_boost_round': 20, 'num_leaves': 15, 'num_threads': 2, } default_predict_config = { 'task': 'predict', 'data': TESTS_DIR / 'train.txt', 'input_model': TESTS_DIR / 'model0.txt', 'output_result': TESTS_DIR / 'predictions.txt', } def __init__(self, executable: str): self.executable = executable def worker_train(self, i: int) -> subprocess.CompletedProcess: """Start the training process on the `i`-th worker.""" config_path = TESTS_DIR / f'train{i}.conf' cmd = [self.executable, f'config={config_path}'] return subprocess.run(cmd) def _set_ports(self) -> None: """Randomly assign a port for training to each worker and save all ports to mlist.txt.""" ports = set(_generate_n_ports(self.n_workers)) i = 0 max_tries = 100 while i < max_tries and len(ports) < self.n_workers: n_ports_left = self.n_workers - len(ports) candidates = _generate_n_ports(n_ports_left) ports.update(candidates) i += 1 if i == max_tries: raise RuntimeError('Unable to find non-colliding ports.') self.listen_ports = list(ports) with open(TESTS_DIR / 'mlist.txt', 'wt') as f: for port in self.listen_ports: f.write(f'127.0.0.1 {port}\n') def _write_data(self, partitions: List[np.ndarray]) -> None: """Write all training data as train.txt and each training partition as train{i}.txt.""" all_data = np.vstack(partitions) np.savetxt(str(TESTS_DIR / 'train.txt'), all_data, delimiter=',') for i, partition in enumerate(partitions): np.savetxt(str(TESTS_DIR / f'train{i}.txt'), partition, delimiter=',') def fit(self, partitions: List[np.ndarray], train_config: Dict) -> None: """Run the distributed training process on a single machine. For each worker i: 1. The i-th partition is saved as train{i}.txt. 2. A random port is assigned for training. 3. A configuration file train{i}.conf is created. 4. The lightgbm binary is called with config=train{i}.conf in another thread. 5. The trained model is saved as model{i}.txt. Each model file only differs in data and local_listen_port. The whole training set is saved as train.txt. """ self.train_config = copy.deepcopy(self.default_train_config) self.train_config.update(train_config) self.n_workers = self.train_config['num_machines'] self._set_ports() self._write_data(partitions) self.label_ = np.hstack([partition[:, 0] for partition in partitions]) futures = [] with ThreadPoolExecutor(max_workers=self.n_workers) as executor: for i in range(self.n_workers): self.write_train_config(i) train_future = executor.submit(self.worker_train, i) futures.append(train_future) results = [f.result() for f in futures] for result in results: if result.returncode != 0: raise RuntimeError('Error in training') def predict(self, predict_config: Dict[str, Any]) -> np.ndarray: """Compute the predictions using the model created in the fit step. predict_config is used to predict the training set train.txt The predictions are saved as predictions.txt and are then loaded to return them as a numpy array. """ self.predict_config = copy.deepcopy(self.default_predict_config) self.predict_config.update(predict_config) config_path = TESTS_DIR / 'predict.conf' with open(config_path, 'wt') as file: _write_dict(self.predict_config, file) cmd = [self.executable, f'config={config_path}'] result = subprocess.run(cmd) if result.returncode != 0: raise RuntimeError('Error in prediction') return np.loadtxt(str(TESTS_DIR / 'predictions.txt')) def write_train_config(self, i: int) -> None: """Create a file train{i}.conf with the required configuration to train. Each worker gets a different port and piece of the data, the rest are the model parameters contained in `self.config`. """ with open(TESTS_DIR / f'train{i}.conf', 'wt') as file: output_model = TESTS_DIR / f'model{i}.txt' data = TESTS_DIR / f'train{i}.txt' file.write(f'output_model = {output_model}\n') file.write(f'local_listen_port = {self.listen_ports[i]}\n') file.write(f'data = {data}\n') _write_dict(self.train_config, file) def test_classifier(executable): """Test the classification task.""" num_machines = 2 data = METHOD_NAME(task='binary-classification') partitions = np.array_split(data, num_machines) train_params = { 'objective': 'binary', 'num_machines': num_machines, } clf = DistributedMockup(executable) clf.fit(partitions, train_params) y_probas = clf.predict(predict_config={}) y_pred = y_probas > 0.5 assert accuracy_score(clf.label_, y_pred) == 1. def test_regressor(executable): """Test the regression task.""" num_machines = 2 data = METHOD_NAME(task='regression') partitions = np.array_split(data, num_machines) train_params = { 'objective': 'regression', 'num_machines': num_machines, } reg = DistributedMockup(executable) reg.fit(partitions, train_params) y_pred = reg.predict(predict_config={}) np.testing.assert_allclose(y_pred, reg.label_, rtol=0.2, atol=50.)
299,064
get multipath conf facts
import errno import os from leapp.libraries.common import multipathutil from leapp.libraries.common.rpms import has_package from leapp.libraries.stdlib import api from leapp.models import ( CopyFile, InstalledRedHatSignedRPM, MultipathConfFacts8to9, MultipathConfig8to9, TargetUserSpaceUpgradeTasks ) _regexes = ('vendor', 'product', 'revision', 'product_blacklist', 'devnode', 'wwid', 'property', 'protocol') def _parse_config(path): contents = multipathutil.read_config(path) if contents is None: return None conf = MultipathConfig8to9(pathname=path) section = None in_subsection = False for line in contents.split('\n'): try: data = multipathutil.LineData(line, section, in_subsection) except ValueError: continue if data.type == data.TYPE_BLANK: continue if data.type == data.TYPE_SECTION_END: if in_subsection: in_subsection = False elif section: section = None continue if data.type == data.TYPE_SECTION_START: if not section: section = data.section elif not in_subsection: in_subsection = True continue if data.type != data.TYPE_OPTION: continue if section == 'defaults': if data.option == 'enable_foreign': conf.enable_foreign_exists = True elif data.option == 'allow_usb_devices': conf.allow_usb_exists = True elif data.option == 'config_dir': conf.config_dir = data.value if data.option in _regexes and data.value == '*': conf.invalid_regexes_exist = True return conf def _parse_config_dir(config_dir): res = [] try: for config_file in sorted(os.listdir(config_dir)): path = os.path.join(config_dir, config_file) if not path.endswith('.conf'): continue conf = _parse_config(path) if conf: res.append(conf) except OSError as e: if e.errno == errno.ENOENT: api.current_logger().debug('Multipath conf directory ' + '"{}" doesn\'t exist'.format(config_dir)) else: api.current_logger().warning('Failed to read multipath config ' + 'directory ' + '"{}": {}'.format(config_dir, e)) return res def is_processable(): res = has_package(InstalledRedHatSignedRPM, 'device-mapper-multipath') if not res: api.current_logger().debug('device-mapper-multipath is not installed.') return res def METHOD_NAME(config_file='/etc/multipath.conf'): res_configs = [] conf = _parse_config(config_file) if not conf: return None res_configs.append(conf) if conf.config_dir: res_configs.extend(_parse_config_dir(conf.config_dir)) else: res_configs.extend(_parse_config_dir('/etc/multipath/conf.d')) return MultipathConfFacts8to9(configs=res_configs) def produce_copy_to_target_task(): """ Produce task to copy files into the target userspace The multipath configuration files are needed when the upgrade init ramdisk is generated to ensure we are able to boot into the upgrade environment and start the upgrade process itself. By this msg it's told that these files/dirs will be available when the upgrade init ramdisk is generated. See TargetUserSpaceUpgradeTasks and UpgradeInitramfsTasks for more info. """ # TODO(pstodulk): move the function to the multipathconfcheck actor # and get rid of the hardcoded stuff. # - The current behaviour looks from the user POV same as before this # * commit. I am going to keep the proper fix for additional PR as we do # * not want to make the current PR even more complex than now and the solution # * is not so trivial. # - As well, I am missing some information around xDR devices, which are # * possibly not handled correctly (maybe missing some executables?..) # * Update: practically we do not have enough info about xDR drivers, but # * discussed with Ben Marzinski, as the multipath dracut module includes # * the xDR utils stuff, we should handle it in the same way. # * See xdrgetuid, xdrgetinfo (these two utils are now missing in our initramfs) copy_files = [] for fname in ['/etc/multipath.conf', '/etc/multipath', '/etc/xdrdevices.conf']: if os.path.exists(fname): copy_files.append(CopyFile(src=fname)) if copy_files: api.produce(TargetUserSpaceUpgradeTasks(copy_files=copy_files))
299,065
test find marker genes default
import unittest import stereo as st from stereo.utils._download import _download from settings import TEST_DATA_PATH, TEST_IMAGE_PATH, DEMO_DATA_URL class TestMarkerGenes(unittest.TestCase): data = None gef_file = None @classmethod def setUpClass(cls) -> None: file_path = _download(DEMO_DATA_URL, dir_str=TEST_DATA_PATH) cls.gef_file = file_path cls.data = st.io.read_gef(cls.gef_file) cls.data.tl.cal_qc() cls.data.tl.raw_checkpoint() cls.data.tl.normalize_total(target_sum=1e4) cls.data.tl.log1p() cls.data.tl.highly_variable_genes(min_mean=0.0125, max_mean=3, min_disp=0.5, res_key='highly_variable_genes', n_top_genes=None) cls.data.tl.scale() cls.data.tl.pca(use_highly_genes=True, hvg_res_key='highly_variable_genes', n_pcs=20, res_key='pca', svd_solver='arpack') cls.data.tl.neighbors(pca_res_key='pca', n_pcs=30, res_key='neighbors', n_jobs=8) cls.data.tl.leiden(neighbors_res_key='neighbors', res_key='leiden') def setUp(self) -> None: self.gef_file = self.__class__.gef_file self.data = self.__class__.data def METHOD_NAME(self): """ Default Parameters ------------------ cluster_res_key, method: str = 't_test', # t_test or wilcoxon_test case_groups: Union[str, np.ndarray, list] = 'all', control_groups: Union[str, np.ndarray, list] = 'rest', corr_method: str = 'benjamini-hochberg', # 'bonferroni', 'benjamini-hochberg' use_raw: bool = True, use_highly_genes: bool = True, hvg_res_key: Optional[str] = 'highly_variable_genes', res_key: str = 'marker_genes', output: Optional[str] = None, sort_by='scores', n_genes: Union[str, int] = 'all' """ self.data.tl.find_marker_genes(cluster_res_key='leiden') def test_find_marker_genes_method_wilcoxon_test(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', method="wilcoxon_test") def test_find_marker_genes_not_use_raw(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', use_raw=False) def test_find_marker_genes_corr_method_bonferroni(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', corr_method="bonferroni") def test_find_marker_genes_sort_by_log2fc(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', sort_by="log2fc") def test_find_marker_genes_n_genes_none(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', n_genes='auto') def test_find_marker_genes_n_genes_num(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', n_genes=23) def test_find_marker_genes_sort_by_log2fc_n_genes_none(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', sort_by="log2fc", n_genes='auto') def test_find_marker_genes_method_wilcoxon_test_n_genes_none(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', method="wilcoxon_test", n_genes='auto') def test_find_marker_genes_method_wilcoxon_test_sort_by_log2fc_n_genes_none(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', method="wilcoxon_test", sort_by="log2fc", n_genes='auto') def test_find_marker_genes_output(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', output=TEST_DATA_PATH + "/marker_genes1.csv") self.data.plt.marker_genes_scatter(res_key='marker_genes', markers_num=5, out_path=TEST_IMAGE_PATH + "marker_genes_scatter.png") def test_find_marker_genes_sort_by_log2fc_output(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', sort_by="log2fc", output=TEST_DATA_PATH + "/marker_genes2.csv") self.data.plt.marker_gene_volcano(group_name='2.vs.rest', vlines=False, out_path=TEST_IMAGE_PATH + "marker_gene_volcano.png") def test_find_marker_genes_sort_by_log2fc_n_genes_none_output(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', sort_by="log2fc", n_genes='auto', output=TEST_DATA_PATH + "/marker_genes3.csv") self.data.plt.marker_genes_text(res_key='marker_genes', markers_num=10, sort_key='scores', out_path=TEST_IMAGE_PATH + "marker_genes.png") def test_filter_marker_genes_sort_by_log2fc_n_genes_none_output(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', sort_by="log2fc", n_genes='auto', output=TEST_DATA_PATH + "/marker_genes4.csv") self.data.tl.filter_marker_genes(min_fold_change=1, min_in_group_fraction=0.001, max_out_group_fraction=0.1, output=TEST_DATA_PATH + "filter_genes4.csv") self.data.plt.marker_genes_text(res_key='marker_genes', markers_num=10, sort_key='scores', out_path=TEST_IMAGE_PATH + "marker_genes_filtered.png") def test_filter_plot_scatter(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', sort_by="log2fc", n_genes='auto', output=TEST_DATA_PATH + "/marker_genes4.csv") self.data.tl.filter_marker_genes(min_fold_change=1, min_in_group_fraction=0.001, max_out_group_fraction=0.1, output=TEST_DATA_PATH + "filter_genes4.csv") self.data.plt.marker_genes_scatter(res_key='marker_genes', markers_num=5, out_path=TEST_IMAGE_PATH + "marker_genes_scatter_filtered.png") def test_filter_plot_volcano(self): self.data.tl.find_marker_genes(cluster_res_key='leiden', sort_by="log2fc", n_genes='auto', output=TEST_DATA_PATH + "marker_genes4.csv") self.data.tl.filter_marker_genes(min_fold_change=1, min_in_group_fraction=0.001, max_out_group_fraction=0.1, output=TEST_DATA_PATH + "filter_genes4.csv") self.data.plt.marker_gene_volcano(group_name='2.vs.rest', vlines=False, out_path=TEST_IMAGE_PATH + "marker_gene_volcano_filtered.png")
299,066
deformed triad
# Alfonso del Carre import numpy as np import sharpy.utils.algebra as algebra class Element(object): """ This class stores all the required data for the definition of a linear or quadratic beam element. """ ordering = [0, 2, 1] max_nodes_elem = 3 def __init__(self, ielem, n_nodes, global_connectivities, coordinates, frame_of_reference_delta, structural_twist, num_mem, stiff_index, mass_index): # store info in instance # global element number self.ielem = ielem # number of nodes per elem self.n_nodes = n_nodes if self.max_nodes_elem < self.n_nodes: raise AttributeError('Elements with more than 3 nodes are not allowed') # global connectivities (global node numbers) self.global_connectivities = global_connectivities self.reordered_global_connectivities = global_connectivities[self.ordering] # coordinates of the nodes in a-frame (body-fixed frame) self.coordinates_def = coordinates.copy() # frame of reference points self.frame_of_reference_delta = frame_of_reference_delta # structural twist self.structural_twist = structural_twist # number in memory (for fortran routines) self.num_mem = num_mem # stiffness and mass matrices indices (stored in parent beam class) self.stiff_index = stiff_index self.mass_index = mass_index # placeholder for RBMass self.rbmass = None # np.zeros((self.max_nodes_elem, 6, 6)) self.update(self.coordinates_def) def update(self, coordinates_def, psi_def=None): self.coordinates_def = coordinates_def.copy() if psi_def is not None: # element orientation self.psi_def = psi_def.copy() # element length self.calculate_length() if psi_def is None: # ini conditions, initial crv has to be calculated # we need to define the FoR z direction for every beam element v1, v2, v3 = self.get_triad() self.psi_ini = algebra.triad2crv_vec(v1, v2, v3) self.psi_def = self.psi_ini.copy() # copy all the info to _ini fields self.coordinates_ini = self.coordinates_def.copy() def calculate_length(self): # TODO implement length based on integration self.length = np.linalg.norm(self.coordinates_def[0, :] - self.coordinates_def[1, :]) def add_attributes(self, dictionary): for key, value in dictionary.items(): setattr(self, key, value) def generate_curve(self, n_elem_curve, defor=False): curve = np.zeros((n_elem_curve, 3)) t_vec = np.linspace(0, 2, n_elem_curve) for i in range(n_elem_curve): t = t_vec[i] for idim in range(3): if defor: polyfit, _, _ = algebra.get_polyfit(self.coordinates_def, self.ordering) else: polyfit, _, _ = algebra.get_polyfit(self.coordinates_ini, self.ordering) polyf = np.poly1d(polyfit[idim]) curve[i, idim] = (polyf(t)) return curve def get_triad(self): """ Generates two unit vectors in body FoR that define the local FoR for a beam element. These vectors are calculated using `frame_of_reference_delta` :return: """ # now, calculate tangent vector (and coefficients of the polynomial # fit just in case) tangent, polyfit = algebra.tangent_vector( self.coordinates_def, Element.ordering) normal = np.zeros_like(tangent) binormal = np.zeros_like(tangent) # v_vector is the vector with origin the FoR node and delta # equals frame_of_reference_delta for inode in range(self.n_nodes): v_vector = self.frame_of_reference_delta[inode, :] normal[inode, :] = algebra.unit_vector(np.cross( tangent[inode, :], v_vector ) ) binormal[inode, :] = -algebra.unit_vector(np.cross( tangent[inode, :], normal[inode, :] ) ) # we apply twist now for inode in range(self.n_nodes): if not self.structural_twist[inode] == 0.0: rotation_mat = algebra.rotation_matrix_around_axis(tangent[inode, :], self.structural_twist[inode]) normal[inode, :] = np.dot(rotation_mat, normal[inode, :]) binormal[inode, :] = np.dot(rotation_mat, binormal[inode, :]) return tangent, binormal, normal def METHOD_NAME(self, psi=None): if psi is None: return algebra.crv2triad_vec(self.psi_def) else: return algebra.crv2triad_vec(psi)
299,067
e stop
#!/usr/bin/env python3 # Software License Agreement (BSD License) # Copyright © 2021-2023 belongs to Shadow Robot Company Ltd. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. Neither the name of Shadow Robot Company Ltd nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # This software is provided by Shadow Robot Company Ltd "as is" and any express # or implied warranties, including, but not limited to, the implied warranties of # merchantability and fitness for a particular purpose are disclaimed. In no event # shall the copyright holder be liable for any direct, indirect, incidental, special, # exemplary, or consequential damages (including, but not limited to, procurement of # substitute goods or services; loss of use, data, or profits; or business interruption) # however caused and on any theory of liability, whether in contract, strict liability, # or tort (including negligence or otherwise) arising in any way out of the use of this # software, even if advised of the possibility of such damage. from unittest import TestCase from std_msgs.msg import Bool from ur_dashboard_msgs.srv import IsProgramRunning from ur_dashboard_msgs.msg import SafetyMode, RobotMode import rospy class CommonTests(TestCase): """ Base test class to test sr_ur_arm_unlock """ mock_dashboard = {} service_string = {} sr_ur_arm_unlock = None def arm_setup(self, side): self.press_pedal() self.assertTrue(self.get_program_running(side)) def arm_mock_dashboard_server(self, side): self.assertFalse(self.get_program_running(side)) def METHOD_NAME(self, side, _release_estop_before_pedal=True): self.assertFalse(self.get_program_running(side)) self.assertFalse(self.mock_dashboard[side].robot_state.get_robot_mode().robot_mode.mode == RobotMode.RUNNING) self.press_pedal() rospy.sleep(0.01) self.assertTrue(self.mock_dashboard[side].robot_state.get_robot_mode().robot_mode.mode == RobotMode.RUNNING) self.assertTrue(self.get_program_running(side)) self.mock_dashboard[side].robot_state.emergency_stop(latch=True) self.assertTrue(self.mock_dashboard[side].robot_state.get_safety_mode().safety_mode.mode == SafetyMode.ROBOT_EMERGENCY_STOP) self.assertFalse(self.get_program_running(side)) self.assertFalse(self.mock_dashboard[side].robot_state.get_robot_mode().robot_mode.mode == RobotMode.RUNNING) self.mock_dashboard[side].robot_state.emergency_stop(latch=False) self.assertFalse(self.mock_dashboard[side].robot_state.get_safety_mode().safety_mode.mode == SafetyMode.ROBOT_EMERGENCY_STOP) self.press_pedal() self.assertTrue(self.mock_dashboard[side].robot_state.get_safety_mode().safety_mode.mode == SafetyMode.NORMAL) self.assertTrue(self.mock_dashboard[side].robot_state.get_robot_mode().robot_mode.mode == RobotMode.RUNNING) self.assertTrue(self.get_program_running(side)) def fault(self, side): self.press_pedal() self.assertTrue(self.mock_dashboard[side].robot_state.get_robot_mode().robot_mode.mode == RobotMode.RUNNING) self.assertTrue(self.get_program_running(side)) self.mock_dashboard[side].robot_state.fault() self.assertTrue(self.mock_dashboard[side].robot_state.get_safety_mode().safety_mode.mode == SafetyMode.FAULT) self.assertFalse(self.get_program_running(side)) self.press_pedal() self.assertTrue(self.mock_dashboard[side].robot_state.get_safety_mode().safety_mode.mode == SafetyMode.NORMAL) self.assertTrue(self.get_program_running(side)) def arm_power_cycle(self, side): self.assertTrue(self.mock_dashboard[side].robot_state.get_robot_mode().robot_mode.mode == RobotMode.POWER_OFF) self.assertFalse(self.get_program_running(side)) self.press_pedal() self.assertTrue(self.mock_dashboard[side].robot_state.get_robot_mode().robot_mode.mode == RobotMode.RUNNING) self.assertTrue(self.get_program_running(side)) self.press_pedal() self.assertFalse(self.mock_dashboard[side].robot_state.get_robot_mode().robot_mode.mode == RobotMode.RUNNING) self.assertFalse(self.get_program_running(side)) def get_program_running(self, side): service_call = rospy.ServiceProxy(self.service_string[side], IsProgramRunning) response = service_call() return response.program_running def press_pedal(self): self.sr_ur_arm_unlock.release_or_brake_arm_cb(Bool(True)) def arm_fault_bimanual(self, sides): self.assertFalse(self.get_program_running('right')) self.assertFalse(self.get_program_running('left')) self.assertTrue(self.mock_dashboard['right'].robot_state.get_robot_mode().robot_mode.mode == RobotMode.POWER_OFF) self.assertTrue(self.mock_dashboard['left'].robot_state.get_robot_mode().robot_mode.mode == RobotMode.POWER_OFF) self.press_pedal() self.assertTrue(self.mock_dashboard['right'].robot_state.get_robot_mode().robot_mode.mode == RobotMode.RUNNING) self.assertTrue(self.mock_dashboard['left'].robot_state.get_robot_mode().robot_mode.mode == RobotMode.RUNNING) self.assertTrue(self.get_program_running('right')) self.assertTrue(self.get_program_running('left')) for side in sides: self.mock_dashboard[side].robot_state.fault() for side in sides: self.assertTrue(self.mock_dashboard[side].robot_state.get_safety_mode().safety_mode.mode == SafetyMode.FAULT) self.press_pedal() for side in sides: self.assertFalse(self.mock_dashboard[side].robot_state.get_safety_mode().safety_mode.mode == SafetyMode.FAULT) self.assertTrue(self.get_program_running('right')) self.assertTrue(self.get_program_running('left'))
299,068
test no user
""" Tests for REST API Authentication """ import ddt from django.contrib.auth.models import Group from django.test import TestCase from rest_framework.exceptions import AuthenticationFailed from rest_framework.test import APIRequestFactory from credentials.apps.api.authentication import JwtAuthentication, pipeline_set_user_roles from credentials.apps.api.tests.mixins import JwtMixin from credentials.apps.core.constants import Role from credentials.apps.core.tests.factories import UserFactory @ddt.ddt class TestJWTAuthentication(JwtMixin, TestCase): """ Test id_token authentication used with the browseable API. """ USERNAME = "test-username" def test_no_preferred_username(self): """ Ensure the service gracefully handles an inability to extract a username from the id token. """ # with preferred_username: all good authentication = JwtAuthentication() user = authentication.authenticate_credentials({"preferred_username": self.USERNAME}) self.assertEqual(user.username, self.USERNAME) # missing preferred_username: exception authentication = JwtAuthentication() with self.assertRaises(AuthenticationFailed): authentication.authenticate_credentials({}) def test_admin_user(self): """ Ensure the service gracefully handles an admin role from the id token. """ authentication = JwtAuthentication() user = authentication.authenticate_credentials({"preferred_username": self.USERNAME, "administrator": True}) self.assertEqual(user.username, self.USERNAME) self.assertTrue(user.is_staff) self.assertEqual(len(user.groups.all()), 1) self.assertEqual(user.groups.all()[0].name, Role.ADMINS) @ddt.data("exp", "iat") def test_required_claims(self, claim): """ Verify that tokens that do not carry 'exp' or 'iat' claims are rejected """ authentication = JwtAuthentication() user = UserFactory() jwt_payload = self.default_payload(user) del jwt_payload[claim] jwt_value = self.generate_token(jwt_payload) request = APIRequestFactory().get("dummy", HTTP_AUTHORIZATION=f"JWT {jwt_value}") with self.assertRaises(AuthenticationFailed): authentication.authenticate(request) @ddt.ddt class TestPipelineUserRoles(TestCase): """ Ensure that user roles are set correctly based on a payload containing claims about the user, during login via social auth. """ def setUp(self): self.user = UserFactory.create() super().setUp() def assert_has_admin_role(self, has_role=True): """ Shorthand convenience. """ _assert = self.assertTrue if has_role else self.assertFalse _assert(self.user.groups.filter(name=Role.ADMINS).exists()) def assert_pipeline_result(self, result): """ Shorthand convenience. Ensures that the output of the pipeline function adheres to the social auth pipeline interface and won't break the auth flow. """ self.assertEqual(result, {"user": self.user}) def test_admin_role_is_assigned(self): """ Make sure the user is assigned the ADMINS role if the "administrator" claim is set to true. """ self.assert_has_admin_role(False) result = pipeline_set_user_roles({"administrator": True}, self.user) self.assert_has_admin_role() self.assert_pipeline_result(result) @ddt.data({"administrator": False}, {}) def test_admin_role_is_unassigned(self, payload): """ Make sure the user is unassigned from the ADMINS role, even if they previously had that role, if the "administrator" claim is not set to true. """ self.user.groups.add(Group.objects.get(name=Role.ADMINS)) self.assert_has_admin_role() result = pipeline_set_user_roles(payload, self.user) self.assert_has_admin_role(False) self.assert_pipeline_result(result) def METHOD_NAME(self): """ Make sure nothing breaks if the user wasn't authenticated or was otherwise popped somewhere along the pipeline. """ result = pipeline_set_user_roles({}, None) self.assertEqual(result, {})
299,069
set lfn file name
#!/usr/bin/env python """ Remove files from the FileCatalog (and all replicas from Storage Elements) Examples: $ drm /your/lfn/goes/here $ drm -F myfilecontaininglfns.txt """ import os import DIRAC from DIRAC import S_OK, gLogger from DIRAC.Core.Base.Script import Script from DIRAC.Interfaces.Utilities.DCommands import DSession from DIRAC.Interfaces.Utilities.DCommands import DCatalog from DIRAC.Interfaces.Utilities.DCommands import pathFromArgument from DIRAC.Interfaces.Utilities.DConfigCache import ConfigCache class Params: """handles input options for drm command""" def __init__(self): """creates a Params class with default values""" self.lfnFileName = "" self.targetSE = "" self.rmDirFlag = False def METHOD_NAME(self, lfnFile): """sets filename for file containing the lfns to de deleted""" self.lfnFileName = lfnFile return S_OK() def setSE(self, targetSE): """ sets the name of the storage element from which the files are to be removed """ self.targetSE = targetSE return S_OK() def setDirFlag(self, _): """flag to remove directories recursively""" self.rmDirFlag = True return S_OK() def registerCLISwitches(self): """adds options to the DIRAC options parser""" Script.registerArgument(["lfn: logical file name"], mandatory=False) Script.registerSwitch("F:", "lfnFile=", "file containing a list of LFNs", self.METHOD_NAME) Script.registerSwitch("D:", "destination-se=", "Storage Element from where to remove replica", self.setSE) Script.registerSwitch("r", "", "remove directory recursively", self.setDirFlag) @Script() def main(): """where all the action is""" configCache = ConfigCache() options = Params() options.registerCLISwitches() Script.parseCommandLine(ignoreErrors=True) args = Script.getPositionalArgs() configCache.cacheConfig() session = DSession() catalog = DCatalog() if not args and not options.lfnFileName: gLogger.error(f"No argument provided for:\n{Script.scriptName}") Script.showHelp(exitCode=-1) lfns = set() for path in args: lfns.add(pathFromArgument(session, path)) if options.lfnFileName: if not os.path.exists(options.lfnFileName): gLogger.error(f"non-existent file {options.lfnFileName}:") DIRAC.exit(-1) lfnFile = open(options.lfnFileName) lfnList = lfnFile.readlines() # ignore empty lines anywhere in the file lfnList = [lfn.strip() for lfn in lfnList] lfnSet = {pathFromArgument(session, lfn) for lfn in lfnList if lfn} lfns.update(lfnSet) from DIRAC.Interfaces.API.Dirac import Dirac from DIRAC.Core.Utilities.ReturnValues import returnSingleResult from DIRAC.DataManagementSystem.Client.DataManager import DataManager dirac = Dirac() dm = DataManager() nLfns = len(lfns) if nLfns > 1: gLogger.notice(f"Removing {nLfns} objects") exitCode = 0 goodCounter = 0 badCounter = 0 for lfn in lfns: if options.rmDirFlag and not catalog.isFile(lfn): result = returnSingleResult(dm.cleanLogicalDirectory(lfn)) if result["OK"]: goodCounter += 1 else: gLogger.error(result["Message"]) badCounter += 1 exitCode = 3 else: if options.targetSE: result = returnSingleResult(dirac.removeReplica(lfn, options.targetSE, printOutput=False)) else: result = returnSingleResult(dirac.removeFile(lfn, printOutput=False)) if not result["OK"]: if "No such file or directory" == result["Message"]: gLogger.notice(f"{lfn} no such file") else: gLogger.error(f"{lfn}: {result['Message']}") badCounter += 1 exitCode = 2 else: goodCounter += 1 if goodCounter % 10 == 0: gLogger.notice(f"{goodCounter} files removed") if badCounter: gLogger.notice(f"{badCounter} files failed removal") gLogger.notice(f"\n{goodCounter} object(s) removed in total") if badCounter: gLogger.notice(f"{badCounter} object(s) failed removal in total") DIRAC.exit(exitCode) if __name__ == "__main__": main()
299,070
assert identical variable
# SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2023 Scipp contributors (https://github.com/scipp) # @author Jan-Lukas Wynen """Custom assertions for pytest-based tests. To get the best error messages, tell pytest to rewrite assertions in this module. Place the following code in your ``conftest.py``: .. code-block:: python pytest.register_assert_rewrite('scipp.testing.assertions') """ from contextlib import contextmanager from typing import Any, Iterator, Mapping, TypeVar import numpy as np from ..core import DataArray, DataGroup, Dataset, Variable from ..core.comparison import identical # Exception notes are formatted as 'PREPOSITION {loc}', # where 'loc' is set by the concrete assertion functions to indicate coords, attrs, etc. # 'PREPOSITION' is replaced at the top level to produce exception messages like: # # [...] # in coord 'x' # of data group item 'b' # of data group item 'a' T = TypeVar('T') def assert_identical(a: T, b: T) -> None: """Raise an AssertionError if two objects are not identical. For Scipp objects, ``assert_identical(a, b)`` is equivalent to ``assert sc.identical(a, b, equal_nan=True)`` but produces a more precise error message in pytest. If this function is called with arguments that are not supported by :func:`scipp.identical`, it calls ``assert a == b``. This function requires exact equality including equal types. For example, ``assert_identical(1, 1.0)`` will raise. NaN elements of Scipp variables are treated as equal. Parameters ---------- a: The actual object to check. b: The desired, expected object. Raises ------ AssertionError If the objects are not identical. """ try: _assert_identical_impl(a, b) except AssertionError as exc: if hasattr(exc, '__notes__'): # See comment above. notes = [] rest = -1 for i, note in enumerate(exc.__notes__): if 'PREPOSITION' in note: notes.append(note.replace('PREPOSITION', 'in')) rest = i break notes.extend( note.replace('PREPOSITION', 'of') for note in exc.__notes__[rest + 1 :] ) exc.__notes__ = notes raise def _assert_identical_impl(a: T, b: T) -> None: assert type(a) == type(b) if isinstance(a, Variable): METHOD_NAME(a, b) elif isinstance(a, DataArray): _assert_identical_data_array(a, b) elif isinstance(a, Dataset): _assert_identical_dataset(a, b) elif isinstance(a, DataGroup): _assert_identical_datagroup(a, b) else: assert a == b def METHOD_NAME(a: Variable, b: Variable) -> None: assert a.sizes == b.sizes assert a.unit == b.unit assert a.dtype == b.dtype assert (a.bins is None) == (b.bins is None) if a.bins is None: _assert_identical_dense_variable_data(a, b) else: _assert_identical_binned_variable_data(a, b) def _assert_identical_binned_variable_data(a: Variable, b: Variable) -> None: # Support for iterating over bin contents is limited in Python. # So, simply use `identical` even though it does not produce good error messages. assert a.bins.unit == b.bins.unit assert identical(a, b) def _assert_identical_dense_variable_data(a: Variable, b: Variable) -> None: with _add_note('values'): np.testing.assert_array_equal( a.values, b.values, err_msg='when comparing values' ) if a.variances is not None: assert b.variances is not None, 'a has variances but b does not' with _add_note('variances'): np.testing.assert_array_equal( a.variances, b.variances, err_msg='when comparing variances' ) else: assert b.variances is None, 'a has no variances but b does' def _assert_identical_data_array(a: DataArray, b: DataArray) -> None: METHOD_NAME(a.data, b.data) _assert_mapping_eq(a.coords, b.coords, 'coord') _assert_mapping_eq(a.attrs, b.attrs, 'attr') _assert_mapping_eq(a.masks, b.masks, 'mask') def _assert_identical_dataset(a: Dataset, b: Dataset) -> None: _assert_mapping_eq(a, b, 'dataset item') def _assert_identical_datagroup(a: DataGroup, b: DataGroup) -> None: _assert_mapping_eq(a, b, 'data group item') def _assert_mapping_eq( a: Mapping[str, Any], b: Mapping[str, Any], map_name: str ) -> None: with _add_note(map_name + 's'): assert a.keys() == b.keys() for name, var_a in a.items(): with _add_note("{} '{}'", map_name, name): _assert_identical_impl(var_a, b[name]) @contextmanager def _add_note(loc: str, *args: str) -> Iterator[None]: try: yield except AssertionError as exc: if hasattr(exc, 'add_note'): # Needs Python >= 3.11 exc.add_note(f'PREPOSITION {loc.format(*args)}') raise __all__ = ['assert_identical']
299,071
test md5 hash
"""Test runway.cfngin.hooks.awslambda.source_code.""" # pylint: disable=protected-access, unnecessary-dunder-call from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING import pytest from mock import Mock, call from runway.cfngin.hooks.awslambda.source_code import SourceCode if TYPE_CHECKING: from pytest_mock import MockerFixture MODULE = "runway.cfngin.hooks.awslambda.source_code" class TestSourceCode: """Test SourceCode.""" def test___eq___other(self, tmp_path: Path) -> None: """Test __eq__.""" assert SourceCode(tmp_path) != tmp_path assert SourceCode(tmp_path) != str(tmp_path) def test___eq___source_code(self, tmp_path: Path) -> None: """Test __eq__.""" assert SourceCode(tmp_path) == SourceCode(tmp_path) assert SourceCode(tmp_path) == SourceCode(str(tmp_path)) assert SourceCode(tmp_path) != SourceCode(tmp_path / "foo") def test___fspath__(self, tmp_path: Path) -> None: """Test __fspath__.""" assert SourceCode(tmp_path).__fspath__() == str(tmp_path) def test___init__(self, mocker: MockerFixture, tmp_path: Path) -> None: """Test __init__.""" gitignore_filter = mocker.patch("igittigitt.IgnoreParser", Mock()) gitignore_filter.return_value = gitignore_filter obj = SourceCode(tmp_path) assert obj._include_files_in_hash == [] assert obj.gitignore_filter == gitignore_filter gitignore_filter.assert_called_once_with() assert obj.project_root == tmp_path assert obj.root_directory == tmp_path gitignore_filter.parse_rule_files.assert_called_once_with(tmp_path) gitignore_filter.add_rule.assert_has_calls( [call(".git/", tmp_path), call(".gitignore", tmp_path)] ) def test___init___gitignore_filter_provided(self, tmp_path: Path) -> None: """Test __init__ gitignore_filter provided.""" gitignore_filter = Mock() obj = SourceCode( tmp_path, gitignore_filter=gitignore_filter, include_files_in_hash=[tmp_path], ) assert obj._include_files_in_hash == [tmp_path] assert obj.gitignore_filter == gitignore_filter gitignore_filter.parse_rule_files.assert_not_called() gitignore_filter.add_rule.assert_not_called() def test___init___handle_str(self, mocker: MockerFixture, tmp_path: Path) -> None: """Test __init__ root_directory provided as str.""" gitignore_filter = mocker.patch("igittigitt.IgnoreParser", Mock()) gitignore_filter.return_value = gitignore_filter src_path = tmp_path / "src" obj = SourceCode(str(src_path), project_root=str(tmp_path)) assert obj.project_root == tmp_path assert obj.root_directory == src_path assert isinstance(obj.root_directory, Path) def test___iter__(self, tmp_path: Path) -> None: """Test __iter__.""" src_path = tmp_path / "src" src_path.mkdir() file0 = src_path / "foo0.txt" file0.touch() file1 = src_path / "foo1.txt" file1.touch() (src_path / "dir").mkdir() gitignore_filter = Mock(match=Mock(side_effect=[False, True])) assert ( len( list( iter( SourceCode( src_path, gitignore_filter=gitignore_filter, project_root=tmp_path, ) ) ) ) == 1 ) gitignore_filter.match.assert_has_calls( [call(file0), call(file1)], any_order=True ) def test___str__(self, tmp_path: Path) -> None: """Test __str__.""" assert str(SourceCode(tmp_path)) == str(tmp_path) def test___truediv__(self, tmp_path: Path) -> None: """Test __truediv__.""" assert SourceCode(tmp_path) / "foo" == tmp_path / "foo" def test_add_filter_rule(self, tmp_path: Path) -> None: """Test add_filter_rule.""" gitignore_filter = Mock() pattern = "foobar/" src_path = tmp_path / "src" obj = SourceCode( src_path, gitignore_filter=gitignore_filter, project_root=tmp_path ) assert not obj.add_filter_rule(pattern) gitignore_filter.add_rule.assert_called_once_with( pattern=pattern, base_path=src_path ) def METHOD_NAME(self, mocker: MockerFixture, tmp_path: Path) -> None: """Test md5_hash.""" file_hash = Mock(hexdigest="success") mock_file_hash_class = mocker.patch( f"{MODULE}.FileHash", return_value=file_hash ) mock_md5 = mocker.patch("hashlib.md5") src_path = tmp_path / "src" src_path.mkdir() test_file = src_path / "test.txt" assert ( SourceCode( src_path, gitignore_filter=Mock(), include_files_in_hash=[test_file], project_root=tmp_path, ).md5_hash == file_hash.hexdigest ) mock_file_hash_class.assert_called_once_with(mock_md5.return_value) file_hash.add_files.assert_called_once_with([test_file], relative_to=tmp_path) @pytest.mark.parametrize("reverse", [False, True]) def test_sorted(self, mocker: MockerFixture, reverse: bool, tmp_path: Path) -> None: """Test sorted.""" mock_sorted = mocker.patch(f"{MODULE}.sorted", return_value="success") obj = SourceCode(tmp_path) assert obj.sorted(reverse=reverse) mock_sorted.assert_called_once_with(obj, reverse=reverse)
299,072
alarm handler
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2023, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import annotations # isort:skip import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports import os import signal import subprocess import sys import time from pathlib import Path from typing import ( TYPE_CHECKING, Literal, NoReturn, Union, ) if TYPE_CHECKING: from types import FrameType from typing_extensions import TypeAlias # External imports import _pytest.config import _pytest.mark import _pytest.python #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- BASE_DIR = Path(__file__).parent.parent CASE_DIR = BASE_DIR / "tests" / "cross" / "cases" BASELINE_DIR = BASE_DIR / "tests" / "baselines" / "cross" #----------------------------------------------------------------------------- # Setup #----------------------------------------------------------------------------- def pytest_generate_tests(metafunc: _pytest.python.Metafunc) -> None: if "case_path" not in metafunc.fixturenames: return config = metafunc.config params = [ pytest.param(str(path.relative_to(CASE_DIR)), config) for path in CASE_DIR.rglob("*.py") ] metafunc.parametrize("case_path,config", params) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- @pytest.mark.skipif(sys.platform == "win32", reason="not supported on windows") def test_cross(case_path: str, config: _pytest.config.Config) -> None: status, _, out, err = _run_test_case(CASE_DIR / case_path) if status == 0: baseline = (BASELINE_DIR / case_path).with_suffix(".json5") os.makedirs(baseline.parent, exist_ok=True) with baseline.open("w", encoding="utf-8") as file: file.write(out) baseline_path = baseline.relative_to(BASE_DIR) result = load_baseline(baseline_path) if result is None: assert False, "missing baseline; commit the baseline and re-run tests" status, out, _ = diff_baseline(baseline_path) if status != 0: print(out) assert False, "baseline differs" else: print(err) assert False, "test case failed to run" #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- ProcStatus: TypeAlias = Union[int, Literal["timeout"]] TIMEOUT = 10 # seconds def _run_test_case(path: Path) -> tuple[ProcStatus, float, str, str]: code = f"""\ __file__ = {str(path)!r} import random random.seed(1) import numpy as np np.random.seed(1) import warnings warnings.filterwarnings("ignore", ".*", UserWarning, "matplotlib.font_manager") with open(__file__, "rb") as file: source = file.read() global_vars = {{}} exec(compile(source, __file__, "exec"), global_vars) output = global_vars.get("output") if output is None: raise RuntimeError("'output' not exported from a test case") from bokeh.document import Document from bokeh.model import Model if isinstance(output, Model): doc = Document() doc.add_root(output) elif isinstance(output, Document): doc = output else: raise RuntimeError("invalid 'output', expected a 'Model' or 'Document'") rep = doc.to_json(deferred=False) del rep["title"] del rep["version"] import json5 json = json5.dumps(rep, sort_keys=False, indent=2) print(json) """ cmd = [sys.executable, "-c", code] cwd = path.parent env = os.environ.copy() class Timeout(Exception): pass if sys.platform != "win32": def METHOD_NAME(sig: int, frame: FrameType | None) -> NoReturn: raise Timeout signal.signal(signal.SIGALRM, METHOD_NAME) signal.alarm(TIMEOUT) start = time.time() with subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: status: ProcStatus try: status = proc.wait() except Timeout: proc.kill() status = "timeout" finally: if sys.platform != "win32": signal.alarm(0) end = time.time() assert proc.stdout is not None assert proc.stderr is not None out = proc.stdout.read().decode("utf-8") err = proc.stderr.read().decode("utf-8") return (status, end - start, out, err) def git(*args: str) -> tuple[int, str, str]: proc = subprocess.Popen(["git", *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() out = stdout.decode("utf-8", errors="ignore") err = stderr.decode("utf-8", errors="ignore") return (proc.returncode, out, err) def load_baseline(baseline_path: Path, ref: str = "HEAD") -> str | None: status, out, _ = git("show", f"{ref}:./{baseline_path!s}") return out if status == 0 else None def diff_baseline(baseline_path: Path, ref: str = "HEAD") -> tuple[int, str, str]: return git("diff", "--color", "--exit-code", ref, "--", str(baseline_path)) #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
299,073
set connections
""" defines: - ClippingPropertiesWindow """ from pyNastran.gui.qt_version import qt_int as qt_version from qtpy import QtCore from qtpy.QtWidgets import ( QLabel, QLineEdit, QPushButton, QGridLayout, QApplication, QVBoxLayout) from pyNastran.utils.locale import func_str from pyNastran.gui.utils.qt.pydialog import PyDialog, QFloatEdit from pyNastran.gui.utils.qt.checks.qlineedit import check_float class ClippingPropertiesWindow(PyDialog): """ +---------------------+ | Clipping Properties | +------------------------------+ | Clipping Min ______ Default | | Clipping Max ______ Default | | | | Apply OK Cancel | +------------------------------+ """ def __init__(self, data, win_parent=None): """creates ClippingPropertiesWindow""" #Init the base class PyDialog.__init__(self, data, win_parent) self.set_font_size(data['font_size']) self._updated_clipping = False self._default_min = data['min_clip'] self._default_max = data['max_clip'] #self.setupUi(self) self.setWindowTitle('Clipping Properties') self.create_widgets() self.create_layout() self.METHOD_NAME() #self.show() def create_widgets(self): # Min self.min_label = QLabel("Min:") self.min_edit = QFloatEdit(func_str(self._default_min)) self.min_button = QPushButton("Default") # Max self.max_label = QLabel("Max:") self.max_edit = QFloatEdit(func_str(self._default_max)) self.max_button = QPushButton("Default") # closing self.ok_button = QPushButton("OK") def create_layout(self): grid = QGridLayout() grid.addWidget(self.min_label, 0, 0) grid.addWidget(self.min_edit, 0, 1) grid.addWidget(self.min_button, 0, 2) grid.addWidget(self.max_label, 1, 0) grid.addWidget(self.max_edit, 1, 1) grid.addWidget(self.max_button, 1, 2) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addStretch() vbox.addWidget(self.ok_button) self.setLayout(vbox) def METHOD_NAME(self): """creates the actions for the menu""" self.min_button.clicked.connect(self.on_default_min) self.max_button.clicked.connect(self.on_default_max) self.min_edit.textChanged.connect(self.on_apply) self.max_edit.textChanged.connect(self.on_apply) self.ok_button.clicked.connect(self.on_ok) def on_default_min(self): self.min_edit.setText(func_str(self._default_min)) self.min_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_max(self): self.max_edit.setText(func_str(self._default_max)) self.max_edit.setStyleSheet("QLineEdit{background: white;}") def on_validate(self): min_value, flag0 = check_float(self.min_edit) max_value, flag1 = check_float(self.max_edit) if flag0 and flag1: self.out_data['min_clip'] = min(min_value, max_value) self.out_data['max_clip'] = max(min_value, max_value) self.out_data['clicked_ok'] = True return True return False def on_apply(self): passed = self.on_validate() if passed: self.win_parent.clipping_obj.apply_clipping(self.out_data) return passed def on_ok(self): passed = self.on_apply() if passed: self.close() #self.destroy() def on_cancel(self): self.out_data['close'] = True self.close() def main(): # pragma: no cover # kills the program when you hit Cntl+C from the command line # doesn't save the current state as presumably there's been an error import signal signal.signal(signal.SIGINT, signal.SIG_DFL) import sys # Someone is launching this directly # Create the QApplication app = QApplication(sys.argv) #The Main window d = { 'font_size': 10, 'min_clip' : 0., 'max_clip' : 10, } main_window = ClippingPropertiesWindow(d) main_window.show() # Enter the main loop app.exec_() if __name__ == '__main__': # pragma: no cover main()
299,074
leapdays
import datetime import enum import sys from _typeshed import Unused from collections.abc import Iterable, Sequence from time import struct_time from typing import ClassVar from typing_extensions import Literal, TypeAlias __all__ = [ "IllegalMonthError", "IllegalWeekdayError", "setfirstweekday", "firstweekday", "isleap", "leapdays", "weekday", "monthrange", "monthcalendar", "prmonth", "month", "prcal", "calendar", "timegm", "month_name", "month_abbr", "day_name", "day_abbr", "Calendar", "TextCalendar", "HTMLCalendar", "LocaleTextCalendar", "LocaleHTMLCalendar", "weekheader", ] if sys.version_info >= (3, 10): __all__ += ["FRIDAY", "MONDAY", "SATURDAY", "SUNDAY", "THURSDAY", "TUESDAY", "WEDNESDAY"] if sys.version_info >= (3, 12): __all__ += [ "Day", "Month", "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER", ] _LocaleType: TypeAlias = tuple[str | None, str | None] class IllegalMonthError(ValueError): def __init__(self, month: int) -> None: ... class IllegalWeekdayError(ValueError): def __init__(self, weekday: int) -> None: ... def isleap(year: int) -> bool: ... def METHOD_NAME(y1: int, y2: int) -> int: ... def weekday(year: int, month: int, day: int) -> int: ... def monthrange(year: int, month: int) -> tuple[int, int]: ... class Calendar: firstweekday: int def __init__(self, firstweekday: int = 0) -> None: ... def getfirstweekday(self) -> int: ... def setfirstweekday(self, firstweekday: int) -> None: ... def iterweekdays(self) -> Iterable[int]: ... def itermonthdates(self, year: int, month: int) -> Iterable[datetime.date]: ... def itermonthdays2(self, year: int, month: int) -> Iterable[tuple[int, int]]: ... def itermonthdays(self, year: int, month: int) -> Iterable[int]: ... def monthdatescalendar(self, year: int, month: int) -> list[list[datetime.date]]: ... def monthdays2calendar(self, year: int, month: int) -> list[list[tuple[int, int]]]: ... def monthdayscalendar(self, year: int, month: int) -> list[list[int]]: ... def yeardatescalendar(self, year: int, width: int = 3) -> list[list[int]]: ... def yeardays2calendar(self, year: int, width: int = 3) -> list[list[tuple[int, int]]]: ... def yeardayscalendar(self, year: int, width: int = 3) -> list[list[int]]: ... def itermonthdays3(self, year: int, month: int) -> Iterable[tuple[int, int, int]]: ... def itermonthdays4(self, year: int, month: int) -> Iterable[tuple[int, int, int, int]]: ... class TextCalendar(Calendar): def prweek(self, theweek: int, width: int) -> None: ... def formatday(self, day: int, weekday: int, width: int) -> str: ... def formatweek(self, theweek: int, width: int) -> str: ... def formatweekday(self, day: int, width: int) -> str: ... def formatweekheader(self, width: int) -> str: ... def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = True) -> str: ... def prmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> None: ... def formatmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: ... def formatyear(self, theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ... def pryear(self, theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None: ... def firstweekday() -> int: ... def monthcalendar(year: int, month: int) -> list[list[int]]: ... def prweek(theweek: int, width: int) -> None: ... def week(theweek: int, width: int) -> str: ... def weekheader(width: int) -> str: ... def prmonth(theyear: int, themonth: int, w: int = 0, l: int = 0) -> None: ... def month(theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: ... def calendar(theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ... def prcal(theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None: ... class HTMLCalendar(Calendar): cssclasses: ClassVar[list[str]] cssclass_noday: ClassVar[str] cssclasses_weekday_head: ClassVar[list[str]] cssclass_month_head: ClassVar[str] cssclass_month: ClassVar[str] cssclass_year: ClassVar[str] cssclass_year_head: ClassVar[str] def formatday(self, day: int, weekday: int) -> str: ... def formatweek(self, theweek: int) -> str: ... def formatweekday(self, day: int) -> str: ... def formatweekheader(self) -> str: ... def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... def formatmonth(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... def formatyear(self, theyear: int, width: int = 3) -> str: ... def formatyearpage( self, theyear: int, width: int = 3, css: str | None = "calendar.css", encoding: str | None = None ) -> str: ... class different_locale: def __init__(self, locale: _LocaleType) -> None: ... def __enter__(self) -> None: ... def __exit__(self, *args: Unused) -> None: ... class LocaleTextCalendar(TextCalendar): def __init__(self, firstweekday: int = 0, locale: _LocaleType | None = None) -> None: ... class LocaleHTMLCalendar(HTMLCalendar): def __init__(self, firstweekday: int = 0, locale: _LocaleType | None = None) -> None: ... def formatweekday(self, day: int) -> str: ... def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... c: TextCalendar def setfirstweekday(firstweekday: int) -> None: ... def format(cols: int, colwidth: int = 20, spacing: int = 6) -> str: ... def formatstring(cols: int, colwidth: int = 20, spacing: int = 6) -> str: ... def timegm(tuple: tuple[int, ...] | struct_time) -> int: ... # Data attributes day_name: Sequence[str] day_abbr: Sequence[str] month_name: Sequence[str] month_abbr: Sequence[str] if sys.version_info >= (3, 12): class Month(enum.IntEnum): JANUARY: Literal[1] FEBRUARY: Literal[2] MARCH: Literal[3] APRIL: Literal[4] MAY: Literal[5] JUNE: Literal[6] JULY: Literal[7] AUGUST: Literal[8] SEPTEMBER: Literal[9] OCTOBER: Literal[10] NOVEMBER: Literal[11] DECEMBER: Literal[12] JANUARY = Month.JANUARY FEBRUARY = Month.FEBRUARY MARCH = Month.MARCH APRIL = Month.APRIL MAY = Month.MAY JUNE = Month.JUNE JULY = Month.JULY AUGUST = Month.AUGUST SEPTEMBER = Month.SEPTEMBER OCTOBER = Month.OCTOBER NOVEMBER = Month.NOVEMBER DECEMBER = Month.DECEMBER class Day(enum.IntEnum): MONDAY: Literal[0] TUESDAY: Literal[1] WEDNESDAY: Literal[2] THURSDAY: Literal[3] FRIDAY: Literal[4] SATURDAY: Literal[5] SUNDAY: Literal[6] MONDAY = Day.MONDAY TUESDAY = Day.TUESDAY WEDNESDAY = Day.WEDNESDAY THURSDAY = Day.THURSDAY FRIDAY = Day.FRIDAY SATURDAY = Day.SATURDAY SUNDAY = Day.SUNDAY else: MONDAY: Literal[0] TUESDAY: Literal[1] WEDNESDAY: Literal[2] THURSDAY: Literal[3] FRIDAY: Literal[4] SATURDAY: Literal[5] SUNDAY: Literal[6] EPOCH: Literal[1970]
299,075
test read lut
# !/usr/bin/env python """Define the unit tests for the :mod:`colour.io.luts.__init__` module.""" from __future__ import annotations import numpy as np import os import shutil import tempfile import unittest from colour.io import LUTSequence, read_LUT, write_LUT __author__ = "Colour Developers" __copyright__ = "Copyright 2013 Colour Developers" __license__ = "BSD-3-Clause - https://opensource.org/licenses/BSD-3-Clause" __maintainer__ = "Colour Developers" __email__ = "colour-developers@colour-science.org" __status__ = "Production" __all__ = [ "ROOT_LUTS", "TestReadLUT", "TestWriteLUT", ] ROOT_LUTS: str = os.path.join(os.path.dirname(__file__), "resources") class TestReadLUT(unittest.TestCase): """ Define :func:`colour.io.luts.__init__.read_LUT` definition unit tests methods. """ def METHOD_NAME(self): """Test :func:`colour.io.luts.__init__.read_LUT` definition.""" LUT_1 = read_LUT( os.path.join(ROOT_LUTS, "sony_spi1d", "eotf_sRGB_1D.spi1d") ) np.testing.assert_array_almost_equal( LUT_1.table, np.array( [ -7.73990000e-03, 5.16000000e-04, 1.22181000e-02, 3.96819000e-02, 8.71438000e-02, 1.57439400e-01, 2.52950100e-01, 3.75757900e-01, 5.27729400e-01, 7.10566500e-01, 9.25840600e-01, 1.17501630e00, 1.45946870e00, 1.78049680e00, 2.13933380e00, 2.53715520e00, ] ), ) self.assertEqual(LUT_1.name, "eotf sRGB 1D") self.assertEqual(LUT_1.dimensions, 1) np.testing.assert_array_equal(LUT_1.domain, np.array([-0.1, 1.5])) self.assertEqual(LUT_1.size, 16) self.assertListEqual( LUT_1.comments, ['Generated by "Colour 0.3.11".', '"colour.models.eotf_sRGB".'], ) LUT_2 = read_LUT( os.path.join(ROOT_LUTS, "resolve_cube", "LogC_Video.cube") ) np.testing.assert_array_almost_equal( LUT_2[0].table, np.array( [ [0.00000000, 0.00000000, 0.00000000], [0.02708500, 0.02708500, 0.02708500], [0.06304900, 0.06304900, 0.06304900], [0.11314900, 0.11314900, 0.11314900], [0.18304900, 0.18304900, 0.18304900], [0.28981100, 0.28981100, 0.28981100], [0.41735300, 0.41735300, 0.41735300], [0.54523100, 0.54523100, 0.54523100], [0.67020500, 0.67020500, 0.67020500], [0.78963000, 0.78963000, 0.78963000], [0.88646800, 0.88646800, 0.88646800], [0.94549100, 0.94549100, 0.94549100], [0.97644900, 0.97644900, 0.97644900], [0.98924800, 0.98924800, 0.98924800], [0.99379700, 0.99379700, 0.99379700], [1.00000000, 1.00000000, 1.00000000], ] ), ) self.assertEqual(LUT_2[1].size, 4) def test_raise_exception_read_LUT(self): """ Test :func:`colour.io.luts.__init__.read_LUT` definition raised exception. """ self.assertRaises( ValueError, read_LUT, os.path.join(ROOT_LUTS, "sony_spi1d", "Exception_Raising.spi1d"), ) class TestWriteLUT(unittest.TestCase): """ Define :func:`colour.io.luts.__init__.write_LUT` definition unit tests methods. """ def setUp(self): """Initialise the common tests attributes.""" self._temporary_directory = tempfile.mkdtemp() def tearDown(self): """After tests actions.""" shutil.rmtree(self._temporary_directory) def test_write_LUT(self): """Test :func:`colour.io.luts.__init__.write_LUT` definition.""" LUT_1_r = read_LUT( os.path.join(ROOT_LUTS, "sony_spi1d", "eotf_sRGB_1D.spi1d") ) write_LUT( LUT_1_r, os.path.join(self._temporary_directory, "eotf_sRGB_1D.spi1d"), ) LUT_1_t = read_LUT( os.path.join(self._temporary_directory, "eotf_sRGB_1D.spi1d") ) self.assertEqual(LUT_1_r, LUT_1_t) write_LUT( LUTSequence(LUT_1_r), os.path.join(self._temporary_directory, "eotf_sRGB_1D.spi1d"), ) self.assertEqual(LUT_1_r, LUT_1_t) LUT_2_r = read_LUT( os.path.join( ROOT_LUTS, "resolve_cube", "Three_Dimensional_Table_With_Shaper.cube", ) ) write_LUT( LUT_2_r, os.path.join( self._temporary_directory, "Three_Dimensional_Table_With_Shaper.cube", ), ) LUT_2_t = read_LUT( os.path.join( self._temporary_directory, "Three_Dimensional_Table_With_Shaper.cube", ) ) self.assertEqual(LUT_2_r, LUT_2_t) if __name__ == "__main__": unittest.main()
299,076
module import filter
#!/usr/bin/env python # # Copyright 2016-present the Material Components for iOS authors. All Rights # Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import re import sys from collections import namedtuple # Prefix of all MDC umbrella headers. UMBRELLA_HEADER_PREFIX = 'Material' # Import prefixes that should not be checked. IMPORT_FILTER_PREFIXES = ( # Objective-C imports 'Availability.h', 'CoreFoundation/', 'CoreGraphics/', 'Foundation/', 'QuartzCore/', 'UIKit/', 'objc/', # Third-party imports 'MDF', 'Motion', ) # Import suffixes that should not be checked. IMPORT_FILTER_SUFFIXES = ( # Color themers do not have umbrella headers. 'ColorThemer.h', ) # Regex to match import of two kinds: # 1) #import "Foo.h", group #1 # 2) #import <Foo.h>, group #2 IMPORT_RE = re.compile(r'#import (\"(.*\.h)\"|\<(.*\.h)\>)') def umbrella_header(component): """Returns an umbrella header for the component.""" return '{}{}.h'.format(UMBRELLA_HEADER_PREFIX, component) def framework_umbrella_header(component): """Returns a framework umbrella header for the component.""" return 'MaterialComponents/{}'.format(umbrella_header(component)) # Context in which the check is executed. # @checked_file - the name of the file that is checked. # @module_files - list of files in currently analyzed sub-component. CheckContext = namedtuple('CheckContext', ['checked_file', 'module_files']) class ImportChecks(object): """A class containing factory methods for various checks and filters.""" @staticmethod def import_filter(): """Returns a function to filter Objective-C and third-party framework imports.""" def check(import_str, _): filter = import_str.startswith(IMPORT_FILTER_PREFIXES) or \ import_str.endswith(IMPORT_FILTER_SUFFIXES) return filter, None return check @staticmethod def METHOD_NAME(): """Returns a function to filter same module file imports.""" def check(import_str, check_context): return any(module_file.endswith(import_str) for module_file in check_context.module_files), None return check @staticmethod def non_umbrella_header_check(): """Returns a function to check that an umbrella header is imported.""" def check(import_str, check_context): if not import_str.startswith(UMBRELLA_HEADER_PREFIX): error_msg = '{} imports a non-umbrella header: {}'.format(check_context.checked_file, import_str) return True, error_msg return False, None return check @staticmethod def own_umbrella_header_check(umbrella_header): """Returns a function to check that checked component umbrella header is not used.""" def check(import_str, check_context): if import_str == umbrella_header: return True, '{} imports an own umbrella header: {}'.format(check_context.checked_file, import_str) return False, None return check class ImportChecker(object): """A class to run checks over the import strings.""" def __init__(self, check_functions): self.check_functions = check_functions def check_import(self, import_str, check_context): """Runs checks over the import string and returns an error message in check failed.""" for check in self.check_functions: stop, error_msg = check(import_str, check_context) if error_msg: return error_msg if stop: break return None @staticmethod def src_checker(component): """Returns an 'src' code checker.""" return ImportChecker([ ImportChecks.import_filter(), ImportChecks.own_umbrella_header_check(umbrella_header(component)), ImportChecks.own_umbrella_header_check(framework_umbrella_header(component)), ImportChecks.METHOD_NAME(), ImportChecks.non_umbrella_header_check(), ]) @staticmethod def general_checker(): """Returns a general purpose checker.""" return ImportChecker([ ImportChecks.import_filter(), ImportChecks.METHOD_NAME(), ImportChecks.non_umbrella_header_check(), ]) def imports_in_file(file_path): """Returns a list of import strings.""" imports = [] with open(file_path) as f: for line in f.readlines(): match = IMPORT_RE.match(line) if not match: # No imports found in file. continue groups = match.groups() if groups[1]: imports.append(groups[1]) elif groups[2]: imports.append(groups[2]) return imports def list_objc_files(path, skip_dirs=()): """Returns a list of Objective-C files in the path.""" files_relative_paths = [] for dirpath, dirnames, files in os.walk(path): for f in files: if os.path.basename(dirpath) in skip_dirs: continue if f.endswith(('.h', '.m')): files_relative_paths.append(os.path.relpath(os.path.join(dirpath, f), path)) return files_relative_paths def check_src_path(src_path, component_name): """Returns whether src_path has any import errors.""" sub_modules = [] submodules_have_errors = False for dir in os.listdir(src_path): # If a directory in 'src' is capitalized, treat it as a separate module. if os.path.isdir(os.path.join(src_path, dir)) and dir[0].isupper(): sub_modules.append(dir) check_successful = check_path(os.path.join(src_path, dir)) submodules_have_errors = submodules_have_errors or check_successful src_has_errors = check_path(src_path, checker=ImportChecker.src_checker(component_name), excludes=sub_modules) return src_has_errors or submodules_have_errors def check_path(path, checker=ImportChecker.general_checker(), excludes=()): """Returns whether imports in files at path have import errors.""" has_errors = False files = list_objc_files(path, skip_dirs=excludes) for f in files: check_context = CheckContext(checked_file=os.path.basename(f), module_files=files) imports = imports_in_file(os.path.join(path, f)) for import_str in imports: error = checker.check_import(import_str, check_context) if error: print 'ERROR:', error has_errors = True return has_errors def main(args): if len(args) < 1: print 'ERROR: Component path should be passed as an input parameter.' sys.exit(-1) component_path = os.path.normpath(args[0]) component_name = os.path.basename(component_path) src_path = os.path.join(component_path, 'src') examples_path = os.path.join(component_path, 'examples') has_errors = check_src_path(src_path, component_name) or \ check_path(examples_path) sys.exit(-1 if has_errors else 0) if __name__ == '__main__': main(sys.argv[1:])
299,077
log hazard
# -*- coding: utf-8 -*- import autograd.numpy as np from autograd.numpy import exp, log from scipy.special import gammainccinv, gammaincinv from autograd_gamma import gammaincc, gammainc, gammaln, gammainccln, gammaincln from lifelines.fitters import KnownModelParametricUnivariateFitter from lifelines.utils import CensoringType from lifelines.utils.safe_exp import safe_exp from autograd.scipy.stats import norm class GeneralizedGammaFitter(KnownModelParametricUnivariateFitter): r""" This class implements a Generalized Gamma model for univariate data. The model has parameterized form: The survival function is: .. math:: S(t)=\left\{ \begin{array}{} 1-\Gamma_{RL}\left( \frac{1}{{{\lambda }^{2}}};\frac{{e}^{\lambda \left( \frac{\log(t)-\mu }{\sigma} \right)}}{\lambda ^{2}} \right) \textit{ if } \lambda> 0 \\ \Gamma_{RL}\left( \frac{1}{{{\lambda }^{2}}};\frac{{e}^{\lambda \left( \frac{\log(t)-\mu }{\sigma} \right)}}{\lambda ^{2}} \right) \textit{ if } \lambda \le 0 \\ \end{array} \right.\,\! where :math:`\Gamma_{RL}` is the regularized lower incomplete Gamma function. This model has the Exponential, Weibull, Gamma and Log-Normal as sub-models, and thus can be used as a way to test which model to use: 1. When :math:`\lambda = 1` and :math:`\sigma = 1`, then the data is Exponential. 2. When :math:`\lambda = 1` then the data is Weibull. 3. When :math:`\sigma = \lambda` then the data is Gamma. 4. When :math:`\lambda = 0` then the data is Log-Normal. 5. When :math:`\lambda = -1` then the data is Inverse-Weibull. 6. When :math:`\sigma = -\lambda` then the data is Inverse-Gamma. After calling the ``.fit`` method, you have access to properties like: ``cumulative_hazard_``, ``survival_function_``, A summary of the fit is available with the method ``print_summary()``. Important ------------- The parameterization implemented has :math:`\log\sigma`, thus there is a `ln_sigma_` in the output. Exponentiate this parameter to recover :math:`\sigma`. Important ------------- This model is experimental. It's API may change in the future. Also, it's convergence is not very stable. Parameters ----------- alpha: float, optional (default=0.05) the level in the confidence intervals. Examples -------- .. code:: python from lifelines import GeneralizedGammaFitter from lifelines.datasets import load_waltons waltons = load_waltons() ggf = GeneralizedGammaFitter() ggf.fit(waltons['T'], waltons['E']) ggf.plot() ggf.summary Attributes ---------- cumulative_hazard_ : DataFrame The estimated cumulative hazard (with custom timeline if provided) hazard_ : DataFrame The estimated hazard (with custom timeline if provided) survival_function_ : DataFrame The estimated survival function (with custom timeline if provided) cumulative_density_ : DataFrame The estimated cumulative density function (with custom timeline if provided) density_: DataFrame The estimated density function (PDF) (with custom timeline if provided) variance_matrix_ : DataFrame The variance matrix of the coefficients median_survival_time_: float The median time to event lambda_: float The fitted parameter in the model rho_: float The fitted parameter in the model alpha_: float The fitted parameter in the model durations: array The durations provided event_observed: array The event_observed variable provided timeline: array The time line to use for plotting and indexing entry: array or None The entry array provided, or None """ _scipy_fit_method = "SLSQP" _fitted_parameter_names = ["mu_", "ln_sigma_", "lambda_"] _bounds = [(None, None), (None, None), (None, None)] _compare_to_values = np.array([0.0, 0.0, 1.0]) def _create_initial_point(self, Ts, E, *args): if CensoringType.is_right_censoring(self): log_data = log(Ts[0]) elif CensoringType.is_left_censoring(self): log_data = log(Ts[1]) elif CensoringType.is_interval_censoring(self): # this fails if Ts[1] == Ts[0], so we add a some fudge factors. log_data = log(Ts[1] - Ts[0] + 0.1) return np.array([log_data.mean(), log(log_data.std() + 0.01), 0.1]) def _cumulative_hazard(self, params, times): mu_, ln_sigma_, lambda_ = params sigma_ = safe_exp(ln_sigma_) Z = (log(times) - mu_) / sigma_ ilambda_2 = 1 / lambda_ ** 2 clipped_exp = np.clip(safe_exp(lambda_ * Z) * ilambda_2, 1e-300, 1e20) if lambda_ > 0: v = -gammainccln(ilambda_2, clipped_exp) elif lambda_ < 0: v = -gammaincln(ilambda_2, clipped_exp) else: v = -norm.logsf(Z) return v def METHOD_NAME(self, params, times): mu_, ln_sigma_, lambda_ = params ilambda_2 = 1 / lambda_ ** 2 Z = (log(times) - mu_) / safe_exp(ln_sigma_) clipped_exp = np.clip(safe_exp(lambda_ * Z) * ilambda_2, 1e-300, 1e20) if lambda_ > 0: v = ( log(lambda_) - log(times) - ln_sigma_ - gammaln(ilambda_2) + -2 * log(lambda_) * ilambda_2 - clipped_exp + Z / lambda_ - gammainccln(ilambda_2, clipped_exp) ) elif lambda_ < 0: v = ( log(-lambda_) - log(times) - ln_sigma_ - gammaln(ilambda_2) - 2 * log(-lambda_) * ilambda_2 - clipped_exp + Z / lambda_ - gammaincln(ilambda_2, clipped_exp) ) else: v = norm.logpdf(Z, loc=0, scale=1) - ln_sigma_ - log(times) - norm.logsf(Z) return v def percentile(self, p): lambda_ = self.lambda_ sigma_ = exp(self.ln_sigma_) if lambda_ > 0: return exp(sigma_ * log(gammainccinv(1 / lambda_ ** 2, p) * lambda_ ** 2) / lambda_) * exp(self.mu_) return exp(sigma_ * log(gammaincinv(1 / lambda_ ** 2, p) * lambda_ ** 2) / lambda_) * exp(self.mu_)
299,078
title
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'GetRuleResult', 'AwaitableGetRuleResult', 'get_rule', 'get_rule_output', ] @pulumi.output_type class GetRuleResult: """ A collection of values returned by getRule. """ def __init__(__self__, id=None, included_permissions=None, name=None, stage=None, METHOD_NAME=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if included_permissions and not isinstance(included_permissions, list): raise TypeError("Expected argument 'included_permissions' to be a list") pulumi.set(__self__, "included_permissions", included_permissions) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if stage and not isinstance(stage, str): raise TypeError("Expected argument 'stage' to be a str") pulumi.set(__self__, "stage", stage) if METHOD_NAME and not isinstance(METHOD_NAME, str): raise TypeError("Expected argument 'title' to be a str") pulumi.set(__self__, "title", METHOD_NAME) @property @pulumi.getter def id(self) -> str: """ The provider-assigned unique ID for this managed resource. """ return pulumi.get(self, "id") @property @pulumi.getter(name="includedPermissions") def included_permissions(self) -> Sequence[str]: """ specifies the list of one or more permissions to include in the custom role, such as - `iam.roles.get` """ return pulumi.get(self, "included_permissions") @property @pulumi.getter def name(self) -> str: return pulumi.get(self, "name") @property @pulumi.getter def stage(self) -> str: """ indicates the stage of a role in the launch lifecycle, such as `GA`, `BETA` or `ALPHA`. """ return pulumi.get(self, "stage") @property @pulumi.getter def METHOD_NAME(self) -> str: """ is a friendly title for the role, such as "Role Viewer" """ return pulumi.get(self, "title") class AwaitableGetRuleResult(GetRuleResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetRuleResult( id=self.id, included_permissions=self.included_permissions, name=self.name, stage=self.stage, METHOD_NAME=self.METHOD_NAME) def get_rule(name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRuleResult: """ Use this data source to get information about a Google IAM Role. ```python import pulumi import pulumi_gcp as gcp roleinfo = gcp.iam.get_rule(name="roles/compute.viewer") pulumi.export("theRolePermissions", roleinfo.included_permissions) ``` :param str name: The name of the Role to lookup in the form `roles/{ROLE_NAME}`, `organizations/{ORGANIZATION_ID}/roles/{ROLE_NAME}` or `projects/{PROJECT_ID}/roles/{ROLE_NAME}` """ __args__ = dict() __args__['name'] = name opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('gcp:iam/getRule:getRule', __args__, opts=opts, typ=GetRuleResult).value return AwaitableGetRuleResult( id=pulumi.get(__ret__, 'id'), included_permissions=pulumi.get(__ret__, 'included_permissions'), name=pulumi.get(__ret__, 'name'), stage=pulumi.get(__ret__, 'stage'), METHOD_NAME=pulumi.get(__ret__, 'title')) @_utilities.lift_output_func(get_rule) def get_rule_output(name: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetRuleResult]: """ Use this data source to get information about a Google IAM Role. ```python import pulumi import pulumi_gcp as gcp roleinfo = gcp.iam.get_rule(name="roles/compute.viewer") pulumi.export("theRolePermissions", roleinfo.included_permissions) ``` :param str name: The name of the Role to lookup in the form `roles/{ROLE_NAME}`, `organizations/{ORGANIZATION_ID}/roles/{ROLE_NAME}` or `projects/{PROJECT_ID}/roles/{ROLE_NAME}` """ ...
299,079
leave call
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import argparse import os import libcst as cst import pathlib import sys from typing import (Any, Callable, Dict, List, Sequence, Tuple) def partition( predicate: Callable[[Any], bool], iterator: Sequence[Any] ) -> Tuple[List[Any], List[Any]]: """A stable, out-of-place partition.""" results = ([], []) for i in iterator: results[int(predicate(i))].append(i) # Returns trueList, falseList return results[1], results[0] class recommenderCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'get_insight': ('name', ), 'get_insight_type_config': ('name', ), 'get_recommendation': ('name', ), 'get_recommender_config': ('name', ), 'list_insights': ('parent', 'page_size', 'page_token', 'filter', ), 'list_recommendations': ('parent', 'page_size', 'page_token', 'filter', ), 'mark_insight_accepted': ('name', 'etag', 'state_metadata', ), 'mark_recommendation_claimed': ('name', 'etag', 'state_metadata', ), 'mark_recommendation_dismissed': ('name', 'etag', ), 'mark_recommendation_failed': ('name', 'etag', 'state_metadata', ), 'mark_recommendation_succeeded': ('name', 'etag', 'state_metadata', ), 'update_insight_type_config': ('insight_type_config', 'update_mask', 'validate_only', ), 'update_recommender_config': ('recommender_config', 'update_mask', 'validate_only', ), } def METHOD_NAME(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: try: key = original.func.attr.value kword_params = self.METHOD_TO_PARAMS[key] except (AttributeError, KeyError): # Either not a method from the API or too convoluted to be sure. return updated # If the existing code is valid, keyword args come after positional args. # Therefore, all positional args must map to the first parameters. args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) if any(k.keyword.value == "request" for k in kwargs): # We've already fixed this file, don't fix it again. return updated kwargs, ctrl_kwargs = partition( lambda a: a.keyword.value not in self.CTRL_PARAMS, kwargs ) args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) request_arg = cst.Arg( value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that # those could have been passed positionally or by keyword. for name, arg in zip(kword_params, args + kwargs)]), keyword=cst.Name("request") ) return updated.with_changes( args=[request_arg] + ctrl_kwargs ) def fix_files( in_dir: pathlib.Path, out_dir: pathlib.Path, *, transformer=recommenderCallTransformer(), ): """Duplicate the input dir to the output dir, fixing file method calls. Preconditions: * in_dir is a real directory * out_dir is a real, empty directory """ pyfile_gen = ( pathlib.Path(os.path.join(root, f)) for root, _, files in os.walk(in_dir) for f in files if os.path.splitext(f)[1] == ".py" ) for fpath in pyfile_gen: with open(fpath, 'r') as f: src = f.read() # Parse the code and insert method call fixes. tree = cst.parse_module(src) updated = tree.visit(transformer) # Create the path and directory structure for the new file. updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) updated_path.parent.mkdir(parents=True, exist_ok=True) # Generate the updated source file at the corresponding path. with open(updated_path, 'w') as f: f.write(updated.code) if __name__ == '__main__': parser = argparse.ArgumentParser( description="""Fix up source that uses the recommender client library. The existing sources are NOT overwritten but are copied to output_dir with changes made. Note: This tool operates at a best-effort level at converting positional parameters in client method calls to keyword based parameters. Cases where it WILL FAIL include A) * or ** expansion in a method call. B) Calls via function or method alias (includes free function calls) C) Indirect or dispatched calls (e.g. the method is looked up dynamically) These all constitute false negatives. The tool will also detect false positives when an API method shares a name with another method. """) parser.add_argument( '-d', '--input-directory', required=True, dest='input_dir', help='the input directory to walk for python files to fix up', ) parser.add_argument( '-o', '--output-directory', required=True, dest='output_dir', help='the directory to output files fixed via un-flattening', ) args = parser.parse_args() input_dir = pathlib.Path(args.input_dir) output_dir = pathlib.Path(args.output_dir) if not input_dir.is_dir(): print( f"input directory '{input_dir}' does not exist or is not a directory", file=sys.stderr, ) sys.exit(-1) if not output_dir.is_dir(): print( f"output directory '{output_dir}' does not exist or is not a directory", file=sys.stderr, ) sys.exit(-1) if os.listdir(output_dir): print( f"output directory '{output_dir}' is not empty", file=sys.stderr, ) sys.exit(-1) fix_files(input_dir, output_dir)
299,080
check labels file header
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """tf.data.Dataset interface to the MNIST dataset. This is cloned from https://github.com/tensorflow/models/blob/master/official/mnist/dataset.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import gzip import os import shutil import tempfile import numpy as np from six.moves import urllib import tensorflow as tf def read32(bytestream): """Read 4 bytes from bytestream as an unsigned 32-bit integer.""" dt = np.dtype(np.uint32).newbyteorder('>') return np.frombuffer(bytestream.read(4), dtype=dt)[0] def check_image_file_header(filename): """Validate that filename corresponds to images for the MNIST dataset.""" with tf.gfile.Open(filename, 'rb') as f: magic = read32(f) read32(f) # num_images, unused rows = read32(f) cols = read32(f) if magic != 2051: raise ValueError('Invalid magic number %d in MNIST file %s' % (magic, f.name)) if rows != 28 or cols != 28: raise ValueError( 'Invalid MNIST file %s: Expected 28x28 images, found %dx%d' % (f.name, rows, cols)) def METHOD_NAME(filename): """Validate that filename corresponds to labels for the MNIST dataset.""" with tf.gfile.Open(filename, 'rb') as f: magic = read32(f) read32(f) # num_items, unused if magic != 2049: raise ValueError('Invalid magic number %d in MNIST file %s' % (magic, f.name)) def download(directory, filename): """Download (and unzip) a file from the MNIST dataset if not already done.""" filepath = os.path.join(directory, filename) if tf.gfile.Exists(filepath): return filepath if not tf.gfile.Exists(directory): tf.gfile.MakeDirs(directory) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ url = 'https://storage.googleapis.com/cvdf-datasets/mnist/' + filename + '.gz' _, zipped_filepath = tempfile.mkstemp(suffix='.gz') print('Downloading %s to %s' % (url, zipped_filepath)) urllib.request.urlretrieve(url, zipped_filepath) with gzip.open(zipped_filepath, 'rb') as f_in, \ tf.gfile.Open(filepath, 'wb') as f_out: shutil.copyfileobj(f_in, f_out) os.remove(zipped_filepath) return filepath def dataset(directory, images_file, labels_file): """Download and parse MNIST dataset.""" images_file = download(directory, images_file) labels_file = download(directory, labels_file) check_image_file_header(images_file) METHOD_NAME(labels_file) def decode_image(image): # Normalize from [0, 255] to [0.0, 1.0] image = tf.decode_raw(image, tf.uint8) image = tf.cast(image, tf.float32) image = tf.reshape(image, [784]) return image / 255.0 def decode_label(label): label = tf.decode_raw(label, tf.uint8) # tf.string -> [tf.uint8] label = tf.reshape(label, []) # label is a scalar return tf.to_int32(label) images = tf.data.FixedLengthRecordDataset( images_file, 28 * 28, header_bytes=16).map(decode_image) labels = tf.data.FixedLengthRecordDataset( labels_file, 1, header_bytes=8).map(decode_label) return tf.data.Dataset.zip((images, labels)) def train(directory): """tf.data.Dataset object for MNIST training data.""" return dataset(directory, 'train-images-idx3-ubyte', 'train-labels-idx1-ubyte') def test(directory): """tf.data.Dataset object for MNIST test data.""" return dataset(directory, 't10k-images-idx3-ubyte', 't10k-labels-idx1-ubyte')
299,081
delete database
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE.txt in the project root for # license information. # ------------------------------------------------------------------------- from azure.cosmos.aio import CosmosClient import azure.cosmos.exceptions as exceptions from azure.cosmos import ThroughputProperties import asyncio import config # ---------------------------------------------------------------------------------------------------------- # Prerequisites - # # 1. An Azure Cosmos account - # https://docs.microsoft.com/azure/cosmos-db/create-sql-api-python#create-a-database-account # # 2. Microsoft Azure Cosmos PyPi package - # https://pypi.python.org/pypi/azure-cosmos/ # ---------------------------------------------------------------------------------------------------------- # Sample - demonstrates the basic CRUD operations on a Database resource for Azure Cosmos # # 1. Query for Database (QueryDatabases) # # 2. Create Database (CreateDatabase) # # 3. Get a Database by its Id property (ReadDatabase) # # 4. List all Database resources on an account (ReadDatabases) # # 5. Delete a Database given its Id property (DeleteDatabase) # ---------------------------------------------------------------------------------------------------------- HOST = config.settings['host'] MASTER_KEY = config.settings['master_key'] DATABASE_ID = config.settings['database_id'] async def find_database(client, id): print('1. Query for Database') # Because the asynchronous client returns an asynchronous iterator object for methods that use # return several databases using queries, we do not need to await the function. However, attempting # to cast this object into a list directly will throw an error; instead, iterate over the databases # to populate your list using an async for loop like shown here or in the list_databases() method query_databases_response = client.query_databases(query={ "query": "SELECT * FROM r WHERE r.id=@id", "parameters": [ { "name":"@id", "value": id } ] }) databases = [database async for database in query_databases_response] if len(databases) > 0: print('Database with id \'{0}\' was found'.format(id)) else: print('No database with id \'{0}\' was found'. format(id)) # Alternatively, you can directly iterate over the asynchronous iterator without building a separate # list if you don't need the ordering or indexing capabilities async for database in query_databases_response: print(database['id']) async def create_database(client, id): print("\n2. Create Database") try: await client.create_database(id=id) print('Database with id \'{0}\' created'.format(id)) except exceptions.CosmosResourceExistsError: print('A database with id \'{0}\' already exists'.format(id)) print("\n2.8 Create Database - With auto scale settings") try: await client.create_database( id=id, offer_throughput=ThroughputProperties(auto_scale_max_throughput=5000, auto_scale_increment_percent=0)) print('Database with id \'{0}\' created'.format(id)) except exceptions.CosmosResourceExistsError: print('A database with id \'{0}\' already exists'.format(id)) # Alternatively, you can also use the create_database_if_not_exists method to avoid using a try catch # This method attempts to read the database first, and based on the result either creates or returns # the existing database. Due to the additional overhead from attempting a read, it is recommended # to use the create_database() method if you know the database doesn't already exist. await client.create_database_if_not_exists(id=id) async def read_database(client, id): print("\n3. Get a Database by id") try: database = client.get_database_client(id) await database.read() print('Database with id \'{0}\' was found, it\'s link is {1}'.format(id, database.database_link)) except exceptions.CosmosResourceNotFoundError: print('A database with id \'{0}\' does not exist'.format(id)) async def list_databases(client): print("\n4. List all Databases on an account") print('Databases:') # Because the asynchronous client returns an asynchronous iterator object for methods that use # return several databases using queries, we do not need to await the function. However, attempting # to cast this object into a list directly will throw an error; instead, iterate over the databases # to populate your list using an async for loop like shown here or in the find_database() method list_databases_response = client.list_databases() databases = [database async for database in list_databases_response] if len(databases) == 0: return for database in databases: print(database['id']) # Alternatively, you can directly iterate over the asynchronous iterator without building a separate # list if you don't need the ordering or indexing capabilities async for database in list_databases_response: print(database['id']) async def METHOD_NAME(client, id): print("\n5. Delete Database") try: await client.METHOD_NAME(id) print('Database with id \'{0}\' was deleted'.format(id)) except exceptions.CosmosResourceNotFoundError: print('A database with id \'{0}\' does not exist'.format(id)) async def run_sample(): async with CosmosClient(HOST, {'masterKey': MASTER_KEY}) as client: try: # query for a database await find_database(client, DATABASE_ID) # create a database await create_database(client, DATABASE_ID) # get a database using its id await read_database(client, DATABASE_ID) # list all databases on an account await list_databases(client) # delete database by id await METHOD_NAME(client, DATABASE_ID) except exceptions.CosmosHttpResponseError as e: print('\nrun_sample has caught an error. {0}'.format(e.message)) finally: print("\nrun_sample done") if __name__ == '__main__': asyncio.run(run_sample())
299,082
pool conversion
# Copyright 2021 VMware, Inc. # SPDX-License-Identifier: Apache License 2.0 """ Pool Conversion Goes here """ import logging from avi.migrationtools.ace_converter.ace_constants import POOL_SKIP from avi.migrationtools.ace_converter.ace_utils import update_excel # logging init LOG = logging.getLogger(__name__) class PoolConverter(object): def __init__(self, parsed, tenant_ref, common_utils, cloud_ref, tenant, vrf_ref): self.parsed = parsed self.tenant_ref = tenant_ref self.common_utils = common_utils self.cloud_ref = cloud_ref self.tenant = tenant self.vrf_ref = vrf_ref def get_ips_of_server(self, server_name): for server in self.parsed['rserver']: if server['host'] == server_name: for server_ip in server['desc']: if "ip address" in server_ip.keys(): return server_ip['ip address'] return False def get_ips_of_pool(self, farm_name): """ Get ips from server farms """ pool_ip_list = list() for val in self.parsed('serverfarm'): if val['host'] == farm_name: for server_name in val['desc']: if 'rserver' in server_name.keys(): if self.get_ips_of_server(server_name['rserver']): pool_ip_list.append( self.get_ips_of_server(server_name['rserver'])) return pool_ip_list def METHOD_NAME(self, data): """ Pool conversion over here Pool Contains: - servers """ default_port = "80" pool_list = list() for pool in self.parsed.get('serverfarm', ''): probe = None monitor_ref = None server = None temp_pool = dict() name = pool.get('host', '') app_persistance = self.find_app_persistance(name, data) app_ref = self.common_utils.get_object_ref( app_persistance, 'applicationpersistenceprofile', tenant=self.tenant) if app_persistance: temp_pool.update( { 'application_persistence_profile_ref': app_ref }) skipped_list = list() server = [] server_port = [] lb_method = "LB_ALGORITHM_ROUND_ROBIN" for pools in pool['desc']: farm_set = set(pools.keys()) skipped_list_temp = list(farm_set.intersection(set(POOL_SKIP))) if skipped_list_temp: skipped_list.extend(skipped_list_temp) if 'predictor' in pools: ace_lb_method = pools['predictor'] if ace_lb_method.strip() == 'leastconns': lb_method = 'LB_ALGORITHM_LEAST_CONNECTIONS' if "rserver" in pools.keys(): if 'port' in pools.keys(): use_port = pools['port'] else: use_port = default_port server_obj = self.server_converter( pools['rserver'], use_port, server_port=server_port) server.extend(server_obj) if data.get('HealthMonitor'): for hm in data['HealthMonitor']: if pools.get('probe') == hm['name']: probe = pools['probe'] if probe: monitor_ref = self.common_utils.get_object_ref( probe, 'healthmonitor', tenant=self.tenant) if server: pool_dict = { "lb_algorithm": lb_method, "name": name, "cloud_ref": self.cloud_ref, "tenant_ref": self.tenant_ref, "servers": server, "health_monitor_refs": [ ], "fail_action": { "type": "FAIL_ACTION_CLOSE_CONN" }, "description": None } if monitor_ref: pool_dict['health_monitor_refs'].append(monitor_ref) if self.vrf_ref: pool_dict['vrf_ref'] = self.vrf_ref temp_pool.update(pool_dict) # update excel sheet update_excel('serverfarm', name, avi_obj=temp_pool, skip=skipped_list) pool_list.append(temp_pool) return pool_list def server_converter(self, servers_list, use_port, server_port=[]): """ Server Conversion \n :param @name: Server name :param @port: Service Port * Get - the server name * Reply - with server avi object """ server_list = list() server = '' for server_name in servers_list: rserver, port = server_name.split(':') found_server = None if self.parsed.get('rserver', ''): found_server = [obj for obj in self.parsed['rserver'] if obj['host'] == rserver] if not found_server: LOG.warning("rserver %s not found ..".format(servers_list)) return False desc = '' enabled = (True if servers_list[server_name] == 'inservice' else False) # server conversion for serv in found_server[0]['desc']: # checking for ip address ,default port ? if 'ip address' in serv.keys(): server = serv['ip address'] # checking for desc if 'description' in serv.keys(): desc = serv['description'] if server != '': sp_str = '%s:%s' % (server, port) if sp_str not in server_port: server_port.append(sp_str) server_list.append({ "ip": { "addr": server, "type": "V4", }, "enabled": enabled, "description": desc, "port": port }) # Update Excel Sheet update_excel('rserver', server_name, avi_obj=server_list) return server_list def find_app_persistance(self, pool_name, data): """ Find the app persistance tagged to the pool """ app_persitance = False for sticky in self.parsed.get('sticky', ''): name = sticky['name'] for app in data['ApplicationPersistenceProfile']: if app['name'] == name: app_persitance = name break return app_persitance
299,083
test main library
# Data Parallel Control (dpctl) # # Copyright 2020-2022 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Defines unit test cases for miscellaneous functions. """ import ctypes import ctypes.util import glob import os import os.path import re import subprocess import sys import pytest import dpctl def _get_mkl_version_if_present(): class MKLVersion(ctypes.Structure): _fields_ = [ ("MajorVersion", ctypes.c_int), ("MinorVersion", ctypes.c_int), ("UpdateVersion", ctypes.c_int), ("ProductStatus", ctypes.c_char_p), ("Build", ctypes.c_char_p), ("Processor", ctypes.c_char_p), ("Platform", ctypes.c_char_p), ] lib = ctypes.util.find_library("mkl_rt") if lib is None: return None try: lib = ctypes.cdll.LoadLibrary(lib) get_ver_fn = lib.mkl_get_version except Exception: return None get_ver_fn.argtypes = [] get_ver_fn.restype = MKLVersion mkl_ver = get_ver_fn() return ".".join( [ str(mkl_ver.MajorVersion), str(mkl_ver.UpdateVersion), str(mkl_ver.MinorVersion), ] ) def test_get_include(): incl = dpctl.get_include() assert type(incl) is str assert incl != "" assert os.path.isdir(incl) def test_get_dpcppversion(): """Intent of this test is to verify that libraries from dpcpp_cpp_rt conda package used at run-time are not from an older oneAPI. Since these libraries currently do not report the version, this test was using a proxy (version of Intel(R) Math Kernel Library). """ incl_dir = dpctl.get_include() libs = glob.glob(os.path.join(incl_dir, "..", "*DPCTLSyclInterface*")) libs = sorted(libs) assert len(libs) > 0 lib = ctypes.cdll.LoadLibrary(libs[0]) fn = lib.DPCTLService_GetDPCPPVersion fn.restype = ctypes.c_char_p fn.argtypes = [] dpcpp_ver = fn() assert len(dpcpp_ver) > 0 dpcpp_ver = dpcpp_ver.decode("utf-8") mkl_ver = _get_mkl_version_if_present() if mkl_ver is not None: if not mkl_ver >= dpcpp_ver: pytest.xfail( reason="Flaky test: Investigate Math Kernel Library " f"library version {mkl_ver} being older than " f"DPC++ version {dpcpp_ver} used to build dpctl" ) def test___version__(): dpctl_ver = getattr(dpctl, "__version__", None) assert type(dpctl_ver) is str assert "unknown" not in dpctl_ver assert "untagged" not in dpctl_ver # Reg expr from PEP-440, relaxed to allow for semantic variant # 0.9.0dev0 allowed, vs. PEP-440 compliant 0.9.0.dev0 reg_expr = ( r"^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))" r"*((a|b|rc)(0|[1-9][0-9]*))?(\.?post(0|[1-9][0-9]*))?(\.?dev(" r"0|[1-9][0-9]*))?(\+.*)?$" ) assert re.match(reg_expr, dpctl_ver) is not None def test_dev_utils(): import tempfile import dpctl._diagnostics as dd ctx_mngr = dd.syclinterface_diagnostics try: device = dpctl.SyclDevice() except dpctl.SyclDeviceCreationError: pytest.skip("Default-constructed device could not be created") with ctx_mngr(): device.parent_device with ctx_mngr(verbosity="error"): device.parent_device with pytest.raises(ValueError): with ctx_mngr(verbosity="blah"): device.parent_device with tempfile.TemporaryDirectory() as temp_dir: with ctx_mngr(log_dir=temp_dir): device.parent_device with pytest.raises(ValueError): with ctx_mngr(log_dir="/not_a_dir"): device.parent_device def test_syclinterface(): install_dir = os.path.dirname(os.path.abspath(dpctl.__file__)) paths = glob.glob(os.path.join(install_dir, "*DPCTLSyclInterface*")) if "linux" in sys.platform: assert len(paths) > 1 and any( [os.path.islink(fn) for fn in paths] ), "All library instances are hard links" elif sys.platform in ["win32", "cygwin"]: exts = [] for fn in paths: _, file_ext = os.path.splitext(fn) exts.append(file_ext.lower()) assert ( ".lib" in exts ), "Installation does not have DPCTLSyclInterface.lib" assert ( ".dll" in exts ), "Installation does not have DPCTLSyclInterface.dll" else: raise RuntimeError("Unsupported system") def test_main_includes(): res = subprocess.run( [sys.executable, "-m", "dpctl", "--includes"], capture_output=True ) assert res.returncode == 0 assert res.stdout assert res.stdout.decode("utf-8").startswith("-I") def METHOD_NAME(): res = subprocess.run( [sys.executable, "-m", "dpctl", "--library"], capture_output=True ) assert res.returncode == 0 assert res.stdout assert res.stdout.decode("utf-8").startswith("-L") def test_cmakedir(): res = subprocess.run( [sys.executable, "-m", "dpctl", "--cmakedir"], capture_output=True ) assert res.returncode == 0 assert res.stdout cmake_dir = res.stdout.decode("utf-8").strip() assert os.path.exists(os.path.join(cmake_dir, "FindDpctl.cmake")) def test_main_full_list(): res = subprocess.run( [sys.executable, "-m", "dpctl", "-f"], capture_output=True ) assert res.returncode == 0 if dpctl.get_num_devices() > 0: assert res.stdout assert res.stdout.decode("utf-8") def test_main_long_list(): res = subprocess.run( [sys.executable, "-m", "dpctl", "-l"], capture_output=True ) assert res.returncode == 0 if dpctl.get_num_devices() > 0: assert res.stdout assert res.stdout.decode("utf-8") def test_main_summary(): res = subprocess.run( [sys.executable, "-m", "dpctl", "-s"], capture_output=True ) assert res.returncode == 0 if dpctl.get_num_devices() > 0: assert res.stdout assert res.stdout.decode("utf-8") def test_main_warnings(): res = subprocess.run( [sys.executable, "-m", "dpctl", "-s", "--includes"], capture_output=True ) assert res.returncode == 0 assert res.stdout or dpctl.get_num_devices() == 0 assert "UserWarning" in res.stderr.decode("utf-8") assert "is being ignored." in res.stderr.decode("utf-8") res = subprocess.run( [sys.executable, "-m", "dpctl", "-s", "--includes", "--cmakedir"], capture_output=True, ) assert res.returncode == 0 assert res.stdout or dpctl.get_num_devices() == 0 assert "UserWarning" in res.stderr.decode("utf-8") assert "are being ignored." in res.stderr.decode("utf-8")
299,084
clear
""" Available at repository https://github.com/LuminosoInsight/ordered-set salt.utils.oset ~~~~~~~~~~~~~~~~ An OrderedSet is a custom MutableSet that remembers its order, so that every entry has an index that can be looked up. Based on a recipe originally posted to ActiveState Recipes by Raymond Hettiger, and released under the MIT license. Rob Speer's changes are as follows: - changed the content from a doubly-linked list to a regular Python list. Seriously, who wants O(1) deletes but O(N) lookups by index? - add() returns the index of the added item - index() just returns the index of an item - added a __getstate__ and __setstate__ so it can be pickled - added __getitem__ """ from collections.abc import MutableSet SLICE_ALL = slice(None) __version__ = "2.0.1" def is_iterable(obj): """ Are we being asked to look up a list of things, instead of a single thing? We check for the `__iter__` attribute so that this can cover types that don't have to be known by this module, such as NumPy arrays. Strings, however, should be considered as atomic values to look up, not iterables. The same goes for tuples, since they are immutable and therefore valid entries. We don't need to check for the Python 2 `unicode` type, because it doesn't have an `__iter__` attribute anyway. """ return ( hasattr(obj, "__iter__") and not isinstance(obj, str) and not isinstance(obj, tuple) ) class OrderedSet(MutableSet): """ An OrderedSet is a custom MutableSet that remembers its order, so that every entry has an index that can be looked up. """ def __init__(self, iterable=None): self.items = [] self.map = {} if iterable is not None: self |= iterable def __len__(self): return len(self.items) def __getitem__(self, index): """ Get the item at a given index. If `index` is a slice, you will get back that slice of items. If it's the slice [:], exactly the same object is returned. (If you want an independent copy of an OrderedSet, use `OrderedSet.copy()`.) If `index` is an iterable, you'll get the OrderedSet of items corresponding to those indices. This is similar to NumPy's "fancy indexing". """ if index == SLICE_ALL: return self elif hasattr(index, "__index__") or isinstance(index, slice): result = self.items[index] if isinstance(result, list): return OrderedSet(result) else: return result elif is_iterable(index): return OrderedSet([self.items[i] for i in index]) else: raise TypeError( "Don't know how to index an OrderedSet by {}".format(repr(index)) ) def copy(self): return OrderedSet(self) def __getstate__(self): if not self.items: # The state can't be an empty list. # We need to return a truthy value, or else __setstate__ won't be run. # # This could have been done more gracefully by always putting the state # in a tuple, but this way is backwards- and forwards- compatible with # previous versions of OrderedSet. return (None,) else: return list(self) def __setstate__(self, state): if state == (None,): self.__init__([]) else: self.__init__(state) def __contains__(self, key): return key in self.map def add(self, key): # pylint: disable=arguments-differ """ Add `key` as an item to this OrderedSet, then return its index. If `key` is already in the OrderedSet, return the index it already had. """ if key not in self.map: self.map[key] = len(self.items) self.items.append(key) return self.map[key] append = add def update(self, sequence): """ Update the set with the given iterable sequence, then return the index of the last element inserted. """ item_index = None try: for item in sequence: item_index = self.add(item) except TypeError: raise ValueError( "Argument needs to be an iterable, got {}".format(type(sequence)) ) return item_index def index(self, key): """ Get the index of a given entry, raising an IndexError if it's not present. `key` can be an iterable of entries that is not a string, in which case this returns a list of indices. """ if is_iterable(key): return [self.index(subkey) for subkey in key] return self.map[key] def pop(self): """ Remove and return the last element from the set. Raises KeyError if the set is empty. """ if not self.items: raise KeyError("Set is empty") elem = self.items[-1] del self.items[-1] del self.map[elem] return elem def discard(self, key): # pylint: disable=arguments-differ """ Remove an element. Do not raise an exception if absent. The MutableSet mixin uses this to implement the .remove() method, which *does* raise an error when asked to remove a non-existent item. """ if key in self: i = self.map[key] del self.items[i] del self.map[key] for k, v in self.map.items(): if v >= i: self.map[k] = v - 1 def METHOD_NAME(self): """ Remove all items from this OrderedSet. """ del self.items[:] self.map.METHOD_NAME() def __iter__(self): return iter(self.items) def __reversed__(self): return reversed(self.items) def __repr__(self): if not self: return "{}()".format(self.__class__.__name__) return "{}({})".format(self.__class__.__name__, repr(list(self))) def __eq__(self, other): if isinstance(other, OrderedSet): return len(self) == len(other) and self.items == other.items try: other_as_set = set(other) except TypeError: # If `other` can't be converted into a set, it's not equal. return False else: return set(self) == other_as_set
299,085
interaction
import signal import sys from bdb import Bdb from cmd import Cmd from collections.abc import Callable, Iterable, Mapping, Sequence from inspect import _SourceObjectType from types import CodeType, FrameType, TracebackType from typing import IO, Any, ClassVar, TypeVar from typing_extensions import ParamSpec, Self __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace", "post_mortem", "help"] _T = TypeVar("_T") _P = ParamSpec("_P") line_prefix: str # undocumented class Restart(Exception): ... def run(statement: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> None: ... def runeval(expression: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> Any: ... def runctx(statement: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> None: ... def runcall(func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... def set_trace(*, header: str | None = None) -> None: ... def post_mortem(t: TracebackType | None = None) -> None: ... def pm() -> None: ... class Pdb(Bdb, Cmd): # Everything here is undocumented, except for __init__ commands_resuming: ClassVar[list[str]] aliases: dict[str, str] mainpyfile: str _wait_for_mainpyfile: bool rcLines: list[str] commands: dict[int, list[str]] commands_doprompt: dict[int, bool] commands_silent: dict[int, bool] commands_defining: bool commands_bnum: int | None lineno: int | None stack: list[tuple[FrameType, int]] curindex: int curframe: FrameType | None curframe_locals: Mapping[str, Any] def __init__( self, completekey: str = "tab", stdin: IO[str] | None = None, stdout: IO[str] | None = None, skip: Iterable[str] | None = None, nosigint: bool = False, readrc: bool = True, ) -> None: ... def forget(self) -> None: ... def setup(self, f: FrameType | None, tb: TracebackType | None) -> None: ... def execRcLines(self) -> None: ... def bp_commands(self, frame: FrameType) -> bool: ... def METHOD_NAME(self, frame: FrameType | None, traceback: TracebackType | None) -> None: ... def displayhook(self, obj: object) -> None: ... def handle_command_def(self, line: str) -> bool: ... def defaultFile(self) -> str: ... def lineinfo(self, identifier: str) -> tuple[None, None, None] | tuple[str, str, int]: ... def checkline(self, filename: str, lineno: int) -> int: ... def _getval(self, arg: str) -> object: ... def print_stack_trace(self) -> None: ... def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = "\n-> ") -> None: ... def lookupmodule(self, filename: str) -> str | None: ... if sys.version_info < (3, 11): def _runscript(self, filename: str) -> None: ... def do_commands(self, arg: str) -> bool | None: ... def do_break(self, arg: str, temporary: bool = ...) -> bool | None: ... def do_tbreak(self, arg: str) -> bool | None: ... def do_enable(self, arg: str) -> bool | None: ... def do_disable(self, arg: str) -> bool | None: ... def do_condition(self, arg: str) -> bool | None: ... def do_ignore(self, arg: str) -> bool | None: ... def do_clear(self, arg: str) -> bool | None: ... def do_where(self, arg: str) -> bool | None: ... def do_up(self, arg: str) -> bool | None: ... def do_down(self, arg: str) -> bool | None: ... def do_until(self, arg: str) -> bool | None: ... def do_step(self, arg: str) -> bool | None: ... def do_next(self, arg: str) -> bool | None: ... def do_run(self, arg: str) -> bool | None: ... def do_return(self, arg: str) -> bool | None: ... def do_continue(self, arg: str) -> bool | None: ... def do_jump(self, arg: str) -> bool | None: ... def do_debug(self, arg: str) -> bool | None: ... def do_quit(self, arg: str) -> bool | None: ... def do_EOF(self, arg: str) -> bool | None: ... def do_args(self, arg: str) -> bool | None: ... def do_retval(self, arg: str) -> bool | None: ... def do_p(self, arg: str) -> bool | None: ... def do_pp(self, arg: str) -> bool | None: ... def do_list(self, arg: str) -> bool | None: ... def do_whatis(self, arg: str) -> bool | None: ... def do_alias(self, arg: str) -> bool | None: ... def do_unalias(self, arg: str) -> bool | None: ... def do_help(self, arg: str) -> bool | None: ... do_b = do_break do_cl = do_clear do_w = do_where do_bt = do_where do_u = do_up do_d = do_down do_unt = do_until do_s = do_step do_n = do_next do_restart = do_run do_r = do_return do_c = do_continue do_cont = do_continue do_j = do_jump do_q = do_quit do_exit = do_quit do_a = do_args do_rv = do_retval do_l = do_list do_h = do_help def help_exec(self) -> None: ... def help_pdb(self) -> None: ... def sigint_handler(self, signum: signal.Signals, frame: FrameType) -> None: ... def message(self, msg: str) -> None: ... def error(self, msg: str) -> None: ... if sys.version_info >= (3, 12): def set_convenience_variable(self, frame: FrameType, name: str, value: Any) -> None: ... def _select_frame(self, number: int) -> None: ... def _getval_except(self, arg: str, frame: FrameType | None = None) -> object: ... def _print_lines( self, lines: Sequence[str], start: int, breaks: Sequence[int] = (), frame: FrameType | None = None ) -> None: ... def _cmdloop(self) -> None: ... def do_display(self, arg: str) -> bool | None: ... def do_interact(self, arg: str) -> bool | None: ... def do_longlist(self, arg: str) -> bool | None: ... def do_source(self, arg: str) -> bool | None: ... def do_undisplay(self, arg: str) -> bool | None: ... do_ll = do_longlist def _complete_location(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... def _complete_bpnumber(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... def _complete_expression(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... def complete_undisplay(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... def complete_unalias(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... complete_commands = _complete_bpnumber complete_break = _complete_location complete_b = _complete_location complete_tbreak = _complete_location complete_enable = _complete_bpnumber complete_disable = _complete_bpnumber complete_condition = _complete_bpnumber complete_ignore = _complete_bpnumber complete_clear = _complete_location complete_cl = _complete_location complete_debug = _complete_expression complete_print = _complete_expression complete_p = _complete_expression complete_pp = _complete_expression complete_source = _complete_expression complete_whatis = _complete_expression complete_display = _complete_expression if sys.version_info < (3, 11): def _runmodule(self, module_name: str) -> None: ... # undocumented def find_function(funcname: str, filename: str) -> tuple[str, str, int] | None: ... def main() -> None: ... def help() -> None: ... if sys.version_info < (3, 10): def getsourcelines(obj: _SourceObjectType) -> tuple[list[str], int]: ... def lasti2lineno(code: CodeType, lasti: int) -> int: ... class _rstr(str): def __repr__(self) -> Self: ...
299,086
test tool library
# -*- coding: utf-8 -*- # *************************************************************************** # * Copyright (c) 2019 sliptonic <shopinthewoods@gmail.com> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** import Path.Tool.Bit as PathToolBit import PathTests.PathTestUtils as PathTestUtils import glob import os TestToolDir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "Tools") TestInvalidDir = os.path.join( TestToolDir, "some", "silly", "path", "that", "should", "not", "exist" ) TestToolBitName = "test-path-tool-bit-bit-00.fctb" TestToolShapeName = "test-path-tool-bit-shape-00.fcstd" TestToolLibraryName = "test-path-tool-bit-library-00.fctl" def testToolShape(path=TestToolDir, name=TestToolShapeName): return os.path.join(path, "Shape", name) def testToolBit(path=TestToolDir, name=TestToolBitName): return os.path.join(path, "Bit", name) def METHOD_NAME(path=TestToolDir, name=TestToolLibraryName): return os.path.join(path, "Library", name) def printTree(path, indent): print("{} {}".format(indent, os.path.basename(path))) if os.path.isdir(path): if os.path.basename(path).startswith("__"): print("{} ...".format(indent)) else: for foo in sorted(glob.glob(os.path.join(path, "*"))): printTree(foo, "{} ".format(indent)) class TestPathToolBit(PathTestUtils.PathTestBase): def test(self): """Log test setup directory structure""" # Enable this test if there are errors showing up in the build system with the # paths that work OK locally. It'll print out the directory tree, and if it # doesn't look right you know where to look for it print() print("realpath : {}".format(os.path.realpath(__file__))) print(" Tools : {}".format(TestToolDir)) print(" dir : {}".format(os.path.dirname(os.path.realpath(__file__)))) printTree(os.path.dirname(os.path.realpath(__file__)), " :") def test00(self): """Find a tool shape from file name""" path = PathToolBit.findToolShape("endmill.fcstd") self.assertIsNot(path, None) self.assertNotEqual(path, "endmill.fcstd") def test01(self): """Not find a relative path shape if not stored in default location""" path = PathToolBit.findToolShape(TestToolShapeName) self.assertIsNone(path) def test02(self): """Find a relative path shape if it's local to a bit path""" path = PathToolBit.findToolShape(TestToolShapeName, testToolBit()) self.assertIsNot(path, None) self.assertEqual(path, testToolShape()) def test03(self): """Not find a tool shape from an invalid absolute path.""" path = PathToolBit.findToolShape(testToolShape(TestInvalidDir)) self.assertIsNone(path) def test04(self): """Find a tool shape from a valid absolute path.""" path = PathToolBit.findToolShape(testToolShape()) self.assertIsNot(path, None) self.assertEqual(path, testToolShape()) def test10(self): """Find a tool bit from file name""" path = PathToolBit.findToolBit("5mm_Endmill.fctb") self.assertIsNot(path, None) self.assertNotEqual(path, "5mm_Endmill.fctb") def test11(self): """Not find a relative path bit if not stored in default location""" path = PathToolBit.findToolBit(TestToolBitName) self.assertIsNone(path) def test12(self): """Find a relative path bit if it's local to a library path""" path = PathToolBit.findToolBit(TestToolBitName, METHOD_NAME()) self.assertIsNot(path, None) self.assertEqual(path, testToolBit()) def test13(self): """Not find a tool bit from an invalid absolute path.""" path = PathToolBit.findToolBit(testToolBit(TestInvalidDir)) self.assertIsNone(path) def test14(self): """Find a tool bit from a valid absolute path.""" path = PathToolBit.findToolBit(testToolBit()) self.assertIsNot(path, None) self.assertEqual(path, testToolBit()) def test20(self): """Find a tool library from file name""" path = PathToolBit.findToolLibrary("Default.fctl") self.assertIsNot(path, None) self.assertNotEqual(path, "Default.fctl") def test21(self): """Not find a relative path library if not stored in default location""" path = PathToolBit.findToolLibrary(TestToolLibraryName) self.assertIsNone(path) def test22(self): """[skipped] Find a relative path library if it's local to <what?>""" # this is not a valid test for libraries because t self.assertTrue(True) def test23(self): """Not find a tool library from an invalid absolute path.""" path = PathToolBit.findToolLibrary(METHOD_NAME(TestInvalidDir)) self.assertIsNone(path) def test24(self): """Find a tool library from a valid absolute path.""" path = PathToolBit.findToolBit(testToolBit()) self.assertIsNot(path, None) self.assertEqual(path, testToolBit())
299,087
finish page
# ===-- __init__.py -------------------------------------------------------===## # # The KLEE Symbolic Virtual Machine # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # # ===----------------------------------------------------------------------===## from __future__ import division ### import math, os, random from Graphics.Geometry import vec2 from reportlab.pdfgen import canvas #from reportlab.graphics import shapes from reportlab.pdfbase import pdfmetrics """ class Canvas: def startDrawing(self, (w,h)): def endDrawing(self): def getAspect(self): def setColor(self, r, g, b): def setLineWidth(self, width): def drawOutlineBox(self, x0, y0, x1, y1): def drawFilledBox(self, x0, y0, x1, y1): def drawFilledPolygon(self, pts): def drawOutlineCircle(self, x, y, r): def startDrawPoints(self): def endDrawPoints(self): def drawPoint(self, x, y): def setPointSize(self, size): def drawLine(self, a, b): def drawLines(self, ptPairs): def drawLineStrip(self, pts): def pushTransform(self): def popTransform(self): def translate(self, x, y): def scale(self, x, y): def setFontSize(self, size): def drawString(self, (x, y), text): """ class BaseCanvas: def drawPoints(self, pts): self.startDrawPoints() for pt in pts: self.drawPoint(pt) self.endDrawPoints() def drawStringCentered(self, boxLL, boxUR, text): ll,ur = self.getStringBBox(text) stringSize = vec2.sub(ur,ll) boxSize = vec2.sub(boxUR,boxLL) deltaSize = vec2.sub(boxSize, stringSize) halfDeltaSize = vec2.mulN(deltaSize, .5) self.drawString(vec2.add(boxLL,halfDeltaSize), text) def getStringSize(self, string): ll,ur = self.getStringBBox(string) return vec2.sub(ur,ll) class PdfCanvas(BaseCanvas): def __init__(self, name, basePos=(300,400), baseScale=(250,250), pageSize=None): self._font = 'Times-Roman' self.c = canvas.Canvas(name, pagesize=pageSize) self.pointSize = 1 self.scaleX = self.scaleY = 1 self.state = [] self.basePos = tuple(basePos) self.baseScale = tuple(baseScale) self.lastFontSizeSet = None self.kLineScaleFactor = 1.95 def getAspect(self): return 1.0,1.0 def startDrawing(self): self.pointSize = 1 self.scaleX = self.scaleY = 1 self.translate((self.basePos[0] + self.baseScale[0], self.basePos[1] + self.baseScale[1])) self.scale(self.baseScale) self.setColor(0,0,0) self.setLineWidth(1) self.setPointSize(1) def METHOD_NAME(self): self.c.showPage() self.pointSize = 1 self.scaleX = self.scaleY = 1 self.translate((self.basePos[0] + self.baseScale[0], self.basePos[1] + self.baseScale[1])) self.scale(self.baseScale) self.setColor(0,0,0) self.setLineWidth(1) self.setPointSize(1) if self.lastFontSizeSet is not None: self.setFontSize(self.lastFontSizeSet) def endDrawing(self): self.c.showPage() self.c.save() def setColor(self, r, g, b): self.c.setStrokeColorRGB(r,g,b) self.c.setFillColorRGB(r,g,b) def setLineWidth(self, width): avgScale = (self.scaleX+self.scaleY)/2 self.c.setLineWidth(width/(self.kLineScaleFactor*avgScale)) def setPointSize(self, size): avgScale = (self.scaleX+self.scaleY)/2 self.pointSize = size/(4*avgScale) def drawOutlineBox(self, (x0, y0), (x1, y1)): self.c.rect(x0, y0, x1-x0, y1-y0, stroke=1, fill=0) def drawFilledBox(self, (x0, y0), (x1, y1)): self.c.rect(x0, y0, x1-x0, y1-y0, stroke=0, fill=1) def drawOutlineCircle(self, (x, y), r): self.c.circle(x, y, r, stroke=1, fill=0) def drawFilledCircle(self, (x, y), r): self.c.circle(x, y, r, stroke=0, fill=1) def drawFilledPolygon(self, pts): p = self.c.beginPath() p.moveTo(*pts[-1]) for x,y in pts: p.lineTo(x,y) self.c.drawPath(p, fill=1, stroke=0) def drawOutlinePolygon(self, pts): p = self.c.beginPath() p.moveTo(* pts[0]) for x,y in pts[1:]: p.lineTo(x,y) p.close() self.c.drawPath(p, fill=0, stroke=1) def startDrawPoints(self): pass def endDrawPoints(self): pass def drawPoint(self, (x, y)): self.c.circle(x, y, self.pointSize, stroke=0, fill=1) def drawLine(self, a, b): self.drawLines([(a,b)]) def drawLines(self, ptPairs): p = self.c.beginPath() for a,b in ptPairs: p.moveTo(a[0],a[1]) p.lineTo(b[0],b[1]) self.c.drawPath(p) def drawLineStrip(self, pts): p = self.c.beginPath() p.moveTo(pts[0][0],pts[0][1]) for pt in pts[1:]: p.lineTo(pt[0],pt[1]) self.c.drawPath(p) def drawBezier(self, (p0,p1,p2,p3)): self.c.bezier(*(p0+p1+p2+p3)) def pushTransform(self): self.state.append( (self.scaleX,self.scaleY) ) self.c.saveState() def popTransform(self): self.c.restoreState() self.scaleX,self.scaleY = self.state.pop() def translate(self, (x, y)): self.c.translate(x, y) def rotate(self, angle): self.c.rotate(angle*180/math.pi) def scale(self, (x, y)): self.scaleX *= x self.scaleY *= y self.c.scale(x, y) def setFont(self, fontName): self._font = {"Symbol":"Symbol", "Times":"Times-Roman"}.get(fontName,fontName) def setFontSize(self, size): self.lastFontSizeSet = size avgScale = (self.scaleX+self.scaleY)/2 self.fontSize = size/(2*avgScale) self.c.setFont(self._font, self.fontSize) # self.c.setFont("Times-Roman", size/(2*avgScale)) def drawString(self, (x, y), text): self.c.drawString(x, y, text) def drawOutlineString(self, (x,y), text): t = self.c.beginText(x, y) t.setTextRenderMode(1) t.textLine(text) t.setTextRenderMode(0) self.c.drawText(t) def getStringBBox(self, text): font = pdfmetrics.getFont(self._font) width = pdfmetrics.stringWidth(text, self._font, self.fontSize) ll = (0,0) ur = (width, (1.0 - font.face.ascent/2048.)*self.fontSize) ur = (width, (1.0 - font.face.ascent/2048.)*self.fontSize) return ll,ur
299,088
bar
from typing import List import warnings from .utils import get_env_type, RegistryCallable import vaex import vaex.settings _progressbar_registry = RegistryCallable("vaex.progressbar", "progressbar") # these are registered in the entry_points def simple(type=None, title="processing", max_value=1): import vaex.misc.progressbar as pb return pb.ProgressBar(0, 1, title=title) def widget(type=None, title="processing", max_value=1): import vaex.misc.progressbar as pb return pb.ProgressBarWidget(0, 1, title=title) def rich(type=None, title="processing", max_value=1): import vaex.misc.progressbar as pb return pb.ProgressBarRich(0, 1, title=title) _last_progress_tree = None _last_traceback = None _progress_tree_stack = [] class ProgressTree: def __init__(self, children=None, next=None, METHOD_NAME=None, parent=None, name=None, hide=False): global _last_progress_tree, _last_traceback self.next = next self.children : List[ProgressTree] = children or list() self.finished = False self.last_fraction = None self.fraction = 0 self.root = self if parent is None else parent.root self.passes_start = None self.METHOD_NAME = METHOD_NAME self.parent = parent self.name = name self.hide = hide self.cancelled = False self.oncancel = lambda: None if self.METHOD_NAME: self.METHOD_NAME.start() if parent is None and not hide: if _last_progress_tree is None: _last_progress_tree = self import traceback _last_traceback = ''.join(traceback.format_stack(limit=8)) else: if vaex.DEBUG_MODE: warnings.warn("Already a root progress tree exists, you may want to pass down the progress argument", stacklevel=4) import traceback trace = ''.join(traceback.format_stack(limit=7)) print('progress tree triggerd from:\n', trace) print("====\nPrevious traceback:\n", _last_traceback) def cancel(self): self.cancelled = True def __repr__(self): name = self.__class__.__module__ + "." + self.__class__.__name__ return "<%s(name=%r)> instance at 0x%x" % (name, self.name, id(self)) def __enter__(self): _progress_tree_stack.append(self) if self.METHOD_NAME: self.METHOD_NAME.start() return self def __exit__(self, *args): _progress_tree_stack.pop() self.exit() def exit(self): global _last_progress_tree if self.parent is None: _last_progress_tree = None self(1) if self.METHOD_NAME: self.METHOD_NAME.exit() def exit_on(self, promise): def ok(arg): self.exit() return arg def error(arg): self.exit() raise arg return promise.then(ok, error) # return promise def hidden(self): '''Will add a child node that is hidden and not participate in progress calculations''' pb = ProgressTree(hide=True) return pb def add(self, name=None): pb = ProgressTree(parent=self, name=name) if self.METHOD_NAME and hasattr(self.METHOD_NAME, 'add_child') and not self.hide: pb.METHOD_NAME = self.METHOD_NAME.add_child(pb, None, name) self.children.append(pb) self.finished = False self.fraction = sum([c.fraction for c in self.children]) / len(self.children) self(self.fraction) if self.root.METHOD_NAME: # could be that it was stopped self.root.METHOD_NAME.start() return pb def add_task(self, task, name=None, status_ready="from cache"): pb = self.add(name) pb.oncancel = task.cancel task.signal_progress.connect(pb) if task.isFulfilled: pb(status_ready) pb(1) def on_error(exc): if pb.METHOD_NAME: pb.METHOD_NAME.set_status(str(exc)) pb(pb.last_fraction) pb.finished = True if pb.root is not pb: pb.root(None) def on_start(executor): passes = executor.passes if self.root.passes_start is None: self.root.passes_start = passes if pb.METHOD_NAME: pb.METHOD_NAME.set_passes(passes - self.root.passes_start + 1) task.signal_start.connect(on_start) task.then(None, on_error).end() return pb def __call__(self, fraction_or_status): if isinstance(fraction_or_status, str): self.status = fraction_or_status if self.METHOD_NAME: self.METHOD_NAME.set_status(self.status) return True fraction = fraction_or_status if fraction != 1.0: self.finished = False if self.cancelled: return False # ignore fraction result = True if len(self.children) == 0: self.fraction = fraction else: self.fraction = sum([c.fraction if not c.finished else 1 for c in self.children]) / len(self.children) fraction = self.fraction if fraction != self.last_fraction: # avoid too many calls if fraction == 1 and not self.finished: # make sure we call finish only once self.finished = True if self.METHOD_NAME: self.METHOD_NAME.finish() elif fraction != 1: if self.METHOD_NAME: self.METHOD_NAME.update(fraction) if self.next: result = self.next(fraction) if self.parent: assert self in self.parent.children result = self.parent(None) in [None, True] and result # fraction is not used anyway.. if result is False: self.oncancel() self.last_fraction = fraction return result def METHOD_NAME(type_name=None, title="processing", max_value=1): if type_name is None: type_name = vaex.settings.main.progress.force if type_name is None: type_name = vaex.settings.main.progress.type return _progressbar_registry[type_name](title=title) def tree(f=None, next=None, name=None, title=None): if f in [False, None] and _progress_tree_stack: f = _progress_tree_stack[-1] if f in [False, None] and vaex.settings.main.progress.force: f = vaex.settings.main.progress.force if name is None: name = title if title is None: name = title if isinstance(f, ProgressTree): # collapse nameless or similarly named progressbars in 1 if title is None or f.METHOD_NAME and f.METHOD_NAME.title == title: return f else: return f.add(title) if callable(f): next = f f = False if f in [None, False]: return ProgressTree(next=next, name=name) else: if f is True: return ProgressTree(METHOD_NAME=METHOD_NAME(title=title), next=next, name=name) elif isinstance(f, str): return ProgressTree(METHOD_NAME=METHOD_NAME(f, title=title), next=next, name=name) else: return ProgressTree(next=next, name=name)
299,089
raw group attr
""" GAMICFile class and utility functions. """ import h5py import numpy as np class GAMICFile: """ A class to read GAMIC files. Parameters ---------- filename : str Filename of GAMIC HDF5 file. Attributes ---------- nsweeps : int Number of sweeps (or scans) in the file. rays_per_sweep : array of int32 Number of rays in each sweep. total_rays : int Total number of rays in all sweeps. start_ray, end_ray : array of int32 Index of the first (start) and last (end) ray in each sweep, 0-based. _hfile : HDF5 file Open HDF5 file object from which data is read. _scans : list Name of the HDF5 group for each scan. """ def __init__(self, filename): """initialize object.""" self._hfile = h5py.File(filename, "r") self.nsweeps = self._hfile["what"].attrs["sets"] self._scans = ["scan%i" % (i) for i in range(self.nsweeps)] self.rays_per_sweep = self.how_attrs("ray_count", "int32") self.total_rays = sum(self.rays_per_sweep) self.gates_per_sweep = self.how_attrs("bin_count", "int32") self.max_num_gates = max(self.gates_per_sweep) # check uniformity of range_step, raise if not uniform range_samples = self.how_attrs("range_samples", "int32") range_step = self.how_attrs("range_step", "float") * range_samples if len(np.unique(range_step)) > 1: raise ValueError("range scale changes between sweeps") # starting and ending ray for each sweep self.start_ray = np.cumsum(np.append([0], self.rays_per_sweep[:-1])) self.end_ray = np.cumsum(self.rays_per_sweep) - 1 return def close(self): """Close the file.""" self._hfile.close() # file checks def is_file_complete(self): """True if all scans in file, False otherwise.""" # check than scan0, scan1, ... scan[nsweeps-1] are present for scan in self._scans: if scan not in self._hfile: return False return True def is_file_single_scan_type(self): """True is all scans are the same scan type, False otherwise.""" scan_type = self._hfile["scan0/what"].attrs["scan_type"] for scan in self._scans: if self._hfile[scan]["what"].attrs["scan_type"] != scan_type: return False return True # attribute look up def where_attr(self, attr, dtype): """Return an array containing a attribute from the where group.""" return np.array([self._hfile["where"].attrs[attr]], dtype=dtype) def how_attr(self, attr, dtype): """Return an array containing a attribute from the how group.""" return np.array([self._hfile["how"].attrs[attr]], dtype=dtype) def is_attr_in_group(self, group, attr): """True is attribute is present in the group, False otherwise.""" return attr in self._hfile[group].attrs def METHOD_NAME(self, group, attr): """Return an attribute from a group with no reformatting.""" return self._hfile[group].attrs[attr] def raw_scan0_group_attr(self, group, attr): """Return an attribute from the scan0 group with no reformatting.""" return self._hfile["/scan0"][group].attrs[attr] # scan/sweep based attribute lookup def how_attrs(self, attr, dtype): """Return an array of an attribute for each scan's how group.""" return np.array( [self._hfile[s]["how"].attrs[attr] for s in self._scans], dtype=dtype ) def how_ext_attrs(self, attr): """ Return a list of an attribute in each scan's how/extended group. """ return [ float(self._hfile[s]["how"]["extended"].attrs[attr]) for s in self._scans ] def what_attrs(self, attr, dtype): """Return a list of an attribute for each scan's what group.""" return np.array( [self._hfile[s]["what"].attrs[attr] for s in self._scans], dtype=dtype ) # misc looping def moment_groups(self): """Return a list of groups under scan0 where moments are stored.""" return [k for k in self._hfile["/scan0"] if k.startswith("moment_")] def moment_names(self, scan0_groups): """Return a list of moment names for a list of scan0 groups.""" if hasattr(self._hfile["/scan0"][scan0_groups[0]].attrs["moment"], "decode"): return [ self._hfile["/scan0"][k].attrs["moment"].decode("utf-8") for k in scan0_groups ] else: return [self._hfile["/scan0"][k].attrs["moment"] for k in scan0_groups] def is_field_in_ray_header(self, field): """True if field is present in ray_header, False otherwise.""" return field in self._hfile[self._scans[0]]["ray_header"].dtype.names def ray_header(self, field, dtype): """Return an array containing a ray_header field for each sweep.""" data = np.empty((self.total_rays,), dtype=dtype) for scan, start, end in zip(self._scans, self.start_ray, self.end_ray): data[start : end + 1] = self._hfile[scan]["ray_header"][field] return data def moment_data(self, group, dtype): """Read in moment data from all sweeps.""" data = np.ma.zeros((self.total_rays, self.max_num_gates), dtype=dtype) data[:] = np.ma.masked # volume data initially all masked for scan, start, end in zip(self._scans, self.start_ray, self.end_ray): # read in sweep data if field exists in scan. if group in self._hfile[scan]: sweep_data = _get_gamic_sweep_data(self._hfile[scan][group]) data[start : end + 1, : sweep_data.shape[1]] = sweep_data[:] return data def sweep_expand(self, arr, dtype="float32"): """Expand an sweep indexed array to be ray indexed""" return np.repeat(arr, self.rays_per_sweep).astype(dtype) def _get_gamic_sweep_data(group): """Get GAMIC HDF5 sweep data from an HDF5 group.""" dyn_range_min = group.attrs["dyn_range_min"] dyn_range_max = group.attrs["dyn_range_max"] raw_data = group[:] fmt = group.attrs["format"] if hasattr(fmt, "decode"): fmt = fmt.decode("UTF-8") if fmt == "UV16": # unsigned 16-bit integer data, 0 indicates a masked value assert raw_data.dtype == np.uint16 scale = (dyn_range_max - dyn_range_min) / 65535.0 offset = dyn_range_min sweep_data = np.ma.masked_array( raw_data * scale + offset, mask=(raw_data == 0), dtype="float32" ) elif fmt == "UV8": # unsigned 8-bit integer data, 0 indicates a masked value assert raw_data.dtype == np.uint8 scale = (dyn_range_max - dyn_range_min) / 255.0 offset = dyn_range_min sweep_data = np.ma.masked_array( raw_data * scale + offset, mask=(raw_data == 0), dtype="float32" ) elif fmt == "F": assert raw_data.dtype.type == np.float32 sweep_data = np.ma.masked_array( raw_data, mask=np.isnan(raw_data), dtype="float32" ) else: raise NotImplementedError("GAMIC data format: %s", fmt) return sweep_data
299,090
create acl for
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.core.exceptions import ValidationError from rest_framework import viewsets, serializers, status, filters from rest_framework.response import Response from physical.models import Environment, Pool from account.models import Team from api.team import TeamSerializer from util.aclapi import AddACLAccess from system.models import Configuration class PoolSerializer(serializers.HyperlinkedModelSerializer): teams = TeamSerializer(many=True, read_only=True) class Meta: model = Pool fields = ( 'id', 'name', 'environment', 'teams' ) class PoolAPI(viewsets.ModelViewSet): model = Pool serializer_class = PoolSerializer permission_classes = [] authentication_classes = [] filter_backends = (filters.OrderingFilter,) filter_fields = ( "name", "environment", "teams" ) def validate_required_fields(self, data): required_fields = ( "cluster_name", "cluster_id", "project_id", "cluster_endpoint", "domain", "rancher_endpoint", "rancher_token", "dbaas_token", "teams", "vpc", "storageclass" ) for field in required_fields: if not data.get(field, ''): error = "{} is required".format(field) raise ValidationError(error) def update_environment(self, data): env_name = data.get('environment', '') k8s_envs = Environment.k8s_envs() env = Environment.objects.get( name=env_name if env_name else k8s_envs[0] ) data['environment'] = env def validate_and_get_teams(self, team_names): teams = [] for team_name in team_names: team = Team.objects.filter(name=team_name).first() if not team: error = 'Team {} not found'.format(team_name) raise ValidationError(error) teams.append(team) return teams def validade_toke(self, teams, token): for team in teams: if token == team.token: return error = 'Token {} is not valid.'.format(token) raise ValidationError(error) def get_queryset(self): params = self.request.GET.dict() filter_params = {} for k, v in params.iteritems(): if k.split('__')[0] in self.filter_fields: filter_params[k] = v return self.model.objects.filter(**filter_params) def METHOD_NAME(self, vpc, env, pool_name): sources = Configuration.get_by_name_as_list('application_networks') destinations = [vpc] cli = AddACLAccess( env, sources, destinations, description="ACl created when pool {} was created".format( pool_name ) ) cli.create_acl(execute_job=True) def create(self, request): serializer = self.get_serializer( data=request.DATA, files=request.FILES) data = serializer.init_data self.validate_required_fields(data) self.update_environment(data) team_names = data.pop('teams') teams = self.validate_and_get_teams(team_names) dbaas_token = data.get('dbaas_token') self.validade_toke(teams, dbaas_token) pool_name = "{}:{}".format( data.get('cluster_name'), data.get('cluster_id') ) data['name'] = pool_name pool, created = self.model.objects.get_or_create( name=pool_name, defaults=data ) if not created: for attr, value in data.items(): setattr(pool, attr, value) pool.save() pool.teams.clear() for team in teams: pool.teams.add(team) vpc = data.get('vpc') self.METHOD_NAME(vpc, data['environment'], pool_name) headers = self.get_success_headers(data) return Response( {"pool": pool.id}, status=status.HTTP_201_CREATED, headers=headers ) # def destroy(self, request, *args, **kwargs): # instance = self.get_object() # UserMiddleware.set_current_user(request.user) # if instance.is_in_quarantine or instance.is_protected: # return Response(status=status.HTTP_401_UNAUTHORIZED) # instance.delete() # return Response(status=status.HTTP_204_NO_CONTENT)
299,091
deletion protected
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs __all__ = [ 'GetReplicationSetResult', 'AwaitableGetReplicationSetResult', 'get_replication_set', 'get_replication_set_output', ] @pulumi.output_type class GetReplicationSetResult: """ A collection of values returned by getReplicationSet. """ def __init__(__self__, arn=None, created_by=None, METHOD_NAME=None, id=None, last_modified_by=None, regions=None, status=None, tags=None): if arn and not isinstance(arn, str): raise TypeError("Expected argument 'arn' to be a str") pulumi.set(__self__, "arn", arn) if created_by and not isinstance(created_by, str): raise TypeError("Expected argument 'created_by' to be a str") pulumi.set(__self__, "created_by", created_by) if METHOD_NAME and not isinstance(METHOD_NAME, bool): raise TypeError("Expected argument 'deletion_protected' to be a bool") pulumi.set(__self__, "deletion_protected", METHOD_NAME) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if last_modified_by and not isinstance(last_modified_by, str): raise TypeError("Expected argument 'last_modified_by' to be a str") pulumi.set(__self__, "last_modified_by", last_modified_by) if regions and not isinstance(regions, list): raise TypeError("Expected argument 'regions' to be a list") pulumi.set(__self__, "regions", regions) if status and not isinstance(status, str): raise TypeError("Expected argument 'status' to be a str") pulumi.set(__self__, "status", status) if tags and not isinstance(tags, dict): raise TypeError("Expected argument 'tags' to be a dict") pulumi.set(__self__, "tags", tags) @property @pulumi.getter def arn(self) -> str: """ The Amazon Resouce Name (ARN) of the replication set. """ return pulumi.get(self, "arn") @property @pulumi.getter(name="createdBy") def created_by(self) -> str: """ The ARN of the user who created the replication set. """ return pulumi.get(self, "created_by") @property @pulumi.getter(name="deletionProtected") def METHOD_NAME(self) -> bool: """ If `true`, the last remaining Region in a replication set can’t be deleted. """ return pulumi.get(self, "deletion_protected") @property @pulumi.getter def id(self) -> str: """ The provider-assigned unique ID for this managed resource. """ return pulumi.get(self, "id") @property @pulumi.getter(name="lastModifiedBy") def last_modified_by(self) -> str: """ The ARN of the user who last modified the replication set. """ return pulumi.get(self, "last_modified_by") @property @pulumi.getter def regions(self) -> Sequence['outputs.GetReplicationSetRegionResult']: return pulumi.get(self, "regions") @property @pulumi.getter def status(self) -> str: """ The current status of the Region. * Valid Values: `ACTIVE` | `CREATING` | `UPDATING` | `DELETING` | `FAILED` """ return pulumi.get(self, "status") @property @pulumi.getter def tags(self) -> Mapping[str, str]: """ All tags applied to the replication set. """ return pulumi.get(self, "tags") class AwaitableGetReplicationSetResult(GetReplicationSetResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetReplicationSetResult( arn=self.arn, created_by=self.created_by, METHOD_NAME=self.METHOD_NAME, id=self.id, last_modified_by=self.last_modified_by, regions=self.regions, status=self.status, tags=self.tags) def get_replication_set(tags: Optional[Mapping[str, str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetReplicationSetResult: """ > **NOTE:** The AWS Region specified by a provider must always be one of the Regions specified for the replication set. Use this data source to manage a replication set in AWS Systems Manager Incident Manager. ## Example Usage ### Basic Usage ```python import pulumi import pulumi_aws as aws example = aws.ssmincidents.get_replication_set() ``` :param Mapping[str, str] tags: All tags applied to the replication set. """ __args__ = dict() __args__['tags'] = tags opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('aws:ssmincidents/getReplicationSet:getReplicationSet', __args__, opts=opts, typ=GetReplicationSetResult).value return AwaitableGetReplicationSetResult( arn=pulumi.get(__ret__, 'arn'), created_by=pulumi.get(__ret__, 'created_by'), METHOD_NAME=pulumi.get(__ret__, 'deletion_protected'), id=pulumi.get(__ret__, 'id'), last_modified_by=pulumi.get(__ret__, 'last_modified_by'), regions=pulumi.get(__ret__, 'regions'), status=pulumi.get(__ret__, 'status'), tags=pulumi.get(__ret__, 'tags')) @_utilities.lift_output_func(get_replication_set) def get_replication_set_output(tags: Optional[pulumi.Input[Optional[Mapping[str, str]]]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetReplicationSetResult]: """ > **NOTE:** The AWS Region specified by a provider must always be one of the Regions specified for the replication set. Use this data source to manage a replication set in AWS Systems Manager Incident Manager. ## Example Usage ### Basic Usage ```python import pulumi import pulumi_aws as aws example = aws.ssmincidents.get_replication_set() ``` :param Mapping[str, str] tags: All tags applied to the replication set. """ ...
299,092
dnsname match
''' This is merely a copy of the actual code which comes verbatim from Python 3.4. If this code is already available on the system, the system copy should be used instead, as the system copy may be more current. If it is not available, then this copy will be used. ''' # ************************** # This file included in salt to prevent version dep issues for match_hostname. # When updating the bundled match_hostname include this message and the disable # pylint: skip-file # ************************** import re __version__ = '3.4.0.2' class CertificateError(ValueError): pass def METHOD_NAME(dn, hostname, max_wildcards=1): """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 """ pats = [] if not dn: return False # Ported from python3-syntax: # leftmost, *remainder = dn.split(r'.') parts = dn.split(r'.') leftmost = parts[0] remainder = parts[1:] wildcards = leftmost.count('*') if wildcards > max_wildcards: # Issue #17980: avoid denials of service by refusing more # than one wildcard per fragment. A survey of established # policy among SSL implementations showed it to be a # reasonable choice. raise CertificateError( "too many wildcards in certificate DNS name: " + repr(dn)) # speed up common case w/o wildcards if not wildcards: return dn.lower() == hostname.lower() # RFC 6125, section 6.4.3, subitem 1. # The client SHOULD NOT attempt to match a presented identifier in which # the wildcard character comprises a label other than the left-most label. if leftmost == '*': # When '*' is a fragment by itself, it matches a non-empty dotless # fragment. pats.append('[^.]+') elif leftmost.startswith('xn--') or hostname.startswith('xn--'): # RFC 6125, section 6.4.3, subitem 3. # The client SHOULD NOT attempt to match a presented identifier # where the wildcard character is embedded within an A-label or # U-label of an internationalized domain name. pats.append(re.escape(leftmost)) else: # Otherwise, '*' matches any dotless string, e.g. www* pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) # add the remaining fragments, ignore any wildcards for frag in remainder: pats.append(re.escape(frag)) pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) return pat.match(hostname) def match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing. """ if not cert: raise ValueError("empty or no certificate") dnsnames = [] san = cert.get('subjectAltName', ()) for key, value in san: if key == 'DNS': if METHOD_NAME(value, hostname): return dnsnames.append(value) if not dnsnames: # The subject is only checked when there is no dNSName entry # in subjectAltName for sub in cert.get('subject', ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == 'commonName': if METHOD_NAME(value, hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise CertificateError("hostname %r " "doesn't match either of %s" % (hostname, ', '.join(map(repr, dnsnames)))) elif len(dnsnames) == 1: raise CertificateError("hostname %r " "doesn't match %r" % (hostname, dnsnames[0])) else: raise CertificateError("no appropriate commonName or " "subjectAltName fields were found")
299,093
test settings no request
from django.template import Context, RequestContext, Template, engines from django.test import TestCase from django.test.utils import override_settings from wagtail.coreutils import get_dummy_request from wagtail.models import Site from wagtail.test.utils import WagtailTestUtils from .base import GenericSettingsTestMixin @override_settings(ALLOWED_HOSTS=["testserver", "localhost", "other"]) class GenericSettingTemplateTestCase( GenericSettingsTestMixin, WagtailTestUtils, TestCase ): def render(self, request, string, context=None): template = Template(string) context = RequestContext(request, context) return template.render(context) class GenericSettingContextProcessorTestCase(GenericSettingTemplateTestCase): def test_accessing_setting(self): """Check that the context processor works""" request = self.get_request() self.assertEqual( self.render(request, "{{ settings.tests.TestGenericSetting.title }}"), self.default_settings.title, ) def test_model_case_insensitive(self): """Model names should be case insensitive""" request = self.get_request() self.assertEqual( self.render(request, "{{ settings.tests.testgenericsetting.title }}"), self.default_settings.title, ) self.assertEqual( self.render(request, "{{ settings.tests.TESTGENERICSETTING.title }}"), self.default_settings.title, ) self.assertEqual( self.render(request, "{{ settings.tests.TestGenericSetting.title }}"), self.default_settings.title, ) self.assertEqual( self.render(request, "{{ settings.tests.tEstgEnerICsEttIng.title }}"), self.default_settings.title, ) def test_models_cached(self): """Accessing a setting should only hit the DB once per request instance, even if using that request to rendering multiple times""" request = self.get_request() get_title = "{{ settings.tests.testgenericsetting.title }}" # force site query beforehand Site.find_for_request(request) with self.assertNumQueries(1): for i in range(1, 4): with self.subTest(attempt=i): self.assertEqual( self.render(request, get_title * i), self.default_settings.title * i, ) class GenericSettingTemplateTagTestCase(GenericSettingTemplateTestCase): def test_no_context_processor(self): """ Assert that not running the context processor means settings are not in the context, as expected. """ template = Template("{{ settings.tests.TestGenericSetting.title }}") context = Context() self.assertEqual(template.render(context), "") def test_get_settings_request_context(self): """Check that the {% get_settings %} tag works""" request = self.get_request() context = Context({"request": request}) template = Template( "{% load wagtailsettings_tags %}" "{% get_settings %}" "{{ settings.tests.testgenericsetting.title }}" ) self.assertEqual(template.render(context), self.default_settings.title) def test_get_settings_no_request(self): """Check that the {% get_settings %} tag works with no request""" context = Context() template = Template( "{% load wagtailsettings_tags %}" "{% get_settings %}" "{{ settings.tests.testgenericsetting.title }}" ) self.assertEqual(template.render(context), self.default_settings.title) def test_get_settings_variable_assignment_request_context(self): """ Check that assigning the setting to a context variable with {% get_settings as wagtail_settings %} works. """ request = self.get_request() context = Context({"request": request}) template = Template( "{% load wagtailsettings_tags %}" "{% get_settings as wagtail_settings %}" "{{ wagtail_settings.tests.testgenericsetting.title }}" ) self.assertEqual(template.render(context), self.default_settings.title) # Also check that the default 'settings' variable hasn't been set template = Template( "{% load wagtailsettings_tags %}" "{% get_settings as wagtail_settings %}" "{{ settings.tests.testgenericsetting.title }}" ) self.assertEqual(template.render(context), "") class GenericSettingJinjaContextProcessorTestCase(GenericSettingTemplateTestCase): def setUp(self): super().setUp() self.engine = engines["jinja2"] def render(self, string, context=None, request_context=True): if context is None: context = {} # Add a request to the template, to simulate a RequestContext if request_context: site = Site.objects.get(is_default_site=True) context["request"] = get_dummy_request(site=site) template = self.engine.from_string(string) return template.render(context) def test_accessing_setting(self): """Check that the context processor works""" self.assertEqual( self.render('{{ settings("tests.TestGenericSetting").title }}'), self.default_settings.title, ) def test_model_case_insensitive(self): """Model names should be case insensitive""" self.assertEqual( self.render('{{ settings("tests.testgenericsetting").title }}'), self.default_settings.title, ) self.assertEqual( self.render('{{ settings("tests.TESTGENERICSETTING").title }}'), self.default_settings.title, ) self.assertEqual( self.render('{{ settings("tests.TestGenericSetting").title }}'), self.default_settings.title, ) self.assertEqual( self.render('{{ settings("tests.tEstgEnerICsEttIng").title }}'), self.default_settings.title, ) def test_models_cached(self): """Accessing a setting should only hit the DB once per render""" get_title = '{{ settings("tests.testgenericsetting").title }}' request = self.get_request() # run extra query before hand Site.find_for_request(request) for i in range(1, 4): with self.assertNumQueries(1): context = {"request": request} template = self.engine.from_string(get_title * i) self.assertEqual( template.render(context), self.default_settings.title * i ) def METHOD_NAME(self): """ Check that {{ settings }} does not throw an error if it can not find a request to work with """ context = {} template = '{{ settings("tests.testgenericsetting").title }}' self.assertEqual( self.render(template, context, request_context=False), self.default_settings.title, )
299,094
key bisect find
import contextlib import os import elftools from .errors import CLEError, CLEFileNotFoundError # https://code.woboq.org/userspace/glibc/include/libc-pointer-arith.h.html#43 def ALIGN_DOWN(base, size): return base & -size # https://code.woboq.org/userspace/glibc/include/libc-pointer-arith.h.html#50 def ALIGN_UP(base, size): return ALIGN_DOWN(base + size - 1, size) # To verify the mmap behavior you can compile and run the following program. Fact is that mmap file mappings # always map in the entire page into memory from the file if available. If not, it gets zero padded # pylint: disable=pointless-string-statement # #include <stdio.h> # #include <sys/types.h> # #include <sys/stat.h> # #include <unistd.h> # #include <fcntl.h> # #include <sys/mman.h> # # void make_test_file() # { # void* data = (void*)0xdead0000; # int fd = open("./test.data", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); # for (int i = 0; i < 0x1800; i += sizeof(void*)) // Only write 1 1/2 pages worth # { # write(fd, &data, sizeof(void*)); # data += sizeof(void*); # } # close(fd); # } # int main(int argc, char* argv[]) # { # make_test_file(); # # int fd = open("./test.data", O_RDONLY); # unsigned char* mapping = mmap(NULL, 0x123, PROT_READ, MAP_PRIVATE, fd, 4096); # # for (int i=0; i < 0x1000; i++) # { # printf("%02x ", mapping[i]); # if (i % sizeof(void*) == (sizeof(void*) - 1)) # printf("| "); # if (i % 16 == 15) # printf("\n"); # } # } def get_mmaped_data(stream, offset, length, page_size): if offset % page_size != 0: raise CLEError( "libc helper for mmap: Invalid page offset, should be multiple of page size! " f"Stream {stream}, offset {offset}, length: {length}" ) read_length = ALIGN_UP(length, page_size) stream.seek(offset) data = stream.read(read_length) return data.ljust(read_length, b"\0") @contextlib.contextmanager def stream_or_path(obj, perms="rb"): if hasattr(obj, "read") and hasattr(obj, "seek"): obj.seek(0) yield obj else: if not os.path.exists(obj): raise CLEFileNotFoundError("%r is not a valid path" % obj) with open(obj, perms) as f: yield f def key_bisect_floor_key(lst, key, lo=0, hi=None, keyfunc=lambda x: x): if lo < 0: raise ValueError("lo must be non-negative") if hi is None: hi = len(lst) while lo < hi: mid = (lo + hi) // 2 if keyfunc(lst[mid]) <= key: lo = mid + 1 else: hi = mid if lo <= len(lst) and lo > 0: return lst[lo - 1] return None def METHOD_NAME(lst, item, lo=0, hi=None, keyfunc=lambda x: x): if lo < 0: raise ValueError("lo must be non-negative") if hi is None: hi = len(lst) while lo < hi: mid = (lo + hi) // 2 if keyfunc(lst[mid]) <= keyfunc(item): lo = mid + 1 else: hi = mid return lo def key_bisect_insort_left(lst, item, lo=0, hi=None, keyfunc=lambda x: x): if lo < 0: raise ValueError("lo must be non-negative") if hi is None: hi = len(lst) while lo < hi: mid = (lo + hi) // 2 if keyfunc(lst[mid]) < keyfunc(item): lo = mid + 1 else: hi = mid lst.insert(lo, item) def key_bisect_insort_right(lst, item, lo=0, hi=None, keyfunc=lambda x: x): if lo < 0: raise ValueError("lo must be non-negative") if hi is None: hi = len(lst) while lo < hi: mid = (lo + hi) // 2 if keyfunc(lst[mid]) <= keyfunc(item): lo = mid + 1 else: hi = mid lst.insert(lo, item) def get_text_offset(path): """ Offset of text section in the binary. """ with stream_or_path(path) as f: e = elftools.elf.elffile.ELFFile(f) return e.get_section_by_name(".text").header.sh_offset
299,095
test restart failed
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from unittest.mock import patch from audit.models import ( AuditLog, AuditLogOperationResult, AuditLogOperationType, AuditObjectType, ) from cm.models import ADCM, TaskLog from django.contrib.contenttypes.models import ContentType from django.urls import reverse from django.utils import timezone from rbac.models import User from rest_framework.response import Response from rest_framework.status import HTTP_404_NOT_FOUND from adcm.tests.base import BaseTestCase class TestTaskAudit(BaseTestCase): def setUp(self) -> None: super().setUp() self.adcm = ADCM.objects.first() self.task = TaskLog.objects.create( object_id=self.adcm.pk, object_type=ContentType.objects.get(app_label="cm", model="adcm"), start_date=timezone.now(), finish_date=timezone.now(), ) self.task_restarted_str = "Task restarted" def check_log( self, log: AuditLog, operation_name: str, operation_result: AuditLogOperationResult, user: User, obj: ADCM | None, ): if obj: self.assertEqual(log.audit_object.object_id, obj.pk) self.assertEqual(log.audit_object.object_name, obj.name) self.assertEqual(log.audit_object.object_type, AuditObjectType.ADCM) self.assertFalse(log.audit_object.is_deleted) else: self.assertFalse(obj) self.assertEqual(log.operation_name, operation_name) self.assertEqual(log.operation_type, AuditLogOperationType.UPDATE) self.assertEqual(log.operation_result, operation_result) self.assertIsInstance(log.operation_time, datetime) self.assertEqual(log.user.username, user.username) self.assertEqual(log.object_changes, {}) def test_cancel(self): with patch("api.job.views.cancel_task"): self.client.put(path=reverse(viewname="v1:tasklog-cancel", kwargs={"task_pk": self.task.pk})) log: AuditLog = AuditLog.objects.order_by("operation_time").last() self.check_log( log=log, operation_name="Task cancelled", operation_result=AuditLogOperationResult.SUCCESS, user=self.test_user, obj=self.adcm, ) def test_cancel_denied(self): with self.no_rights_user_logged_in: response: Response = self.client.put( path=reverse(viewname="v1:tasklog-cancel", kwargs={"task_pk": self.task.pk}), ) log: AuditLog = AuditLog.objects.order_by("operation_time").last() self.assertEqual(response.status_code, HTTP_404_NOT_FOUND) self.check_log( log=log, operation_name="Task cancelled", operation_result=AuditLogOperationResult.DENIED, user=self.no_rights_user, obj=self.adcm, ) def test_restart(self): with patch("api.job.views.restart_task"): self.client.put(path=reverse(viewname="v1:tasklog-restart", kwargs={"task_pk": self.task.pk})) log: AuditLog = AuditLog.objects.order_by("operation_time").last() self.check_log( log=log, operation_name=self.task_restarted_str, operation_result=AuditLogOperationResult.SUCCESS, user=self.test_user, obj=self.adcm, ) def test_restart_denied(self): with self.no_rights_user_logged_in: response: Response = self.client.put( path=reverse(viewname="v1:tasklog-restart", kwargs={"task_pk": self.task.pk}), ) log: AuditLog = AuditLog.objects.order_by("operation_time").last() self.assertEqual(response.status_code, HTTP_404_NOT_FOUND) self.check_log( log=log, operation_name=self.task_restarted_str, operation_result=AuditLogOperationResult.DENIED, user=self.no_rights_user, obj=self.adcm, ) def METHOD_NAME(self): task_pks = TaskLog.objects.all().values_list("pk", flat=True).order_by("-pk") with patch("api.job.views.restart_task"): response: Response = self.client.put( path=reverse(viewname="v1:tasklog-restart", kwargs={"task_pk": task_pks[0] + 1}), ) log: AuditLog = AuditLog.objects.order_by("operation_time").last() self.assertEqual(response.status_code, HTTP_404_NOT_FOUND) self.check_log( log=log, operation_name=self.task_restarted_str, operation_result=AuditLogOperationResult.FAIL, user=self.test_user, obj=None, )
299,096
ms camera pan delta
# # camera.py -- mode for operating OpenGL camera # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """Camera Mode enables bindings that can manipulate the camera in a Ginga image viewer operating with a OpenGL backend. .. note:: Camera Mode does not work unless the viewer is using an OpenGL backend. Enter the mode by ----------------- * Space, then "c" Exit the mode by ---------------- * Esc Default bindings in mode ------------------------ * s : save the current camera settings, to restore later * r : reset to the saved camera settings * 3 : change the camera view into 3D mode * scroll : track camera (dolly in and out) * left drag : camera orbit the view * right drag : camera pan the view """ from ginga.modes.mode_base import Mode class CameraMode(Mode): def __init__(self, viewer, settings=None): super().__init__(viewer, settings=settings) self.actions = dict( dmod_camera=['__c', None, 'pan'], kp_camera_save=['camera+s'], kp_camera_reset=['camera+r'], kp_camera_toggle3d=['camera+3'], sc_camera_track=['camera+scroll'], ms_camera_orbit=['camera+left'], METHOD_NAME=['camera+right']) def __str__(self): return 'camera' def start(self): pass def stop(self): self.onscreen_message(None) def get_camera(self, viewer): renderer = viewer.renderer if not hasattr(renderer, 'camera'): return None, None return renderer.camera ##### KEYBOARD ACTION CALLBACKS ##### def kp_camera_reset(self, viewer, event, data_x, data_y): event.accept() camera = self.get_camera(viewer) if camera is None: # this viewer doesn't have a camera return False camera.reset() camera.calc_gl_transform() self.onscreen_message("Reset camera", delay=0.5) viewer.update_widget() def kp_camera_save(self, viewer, event, data_x, data_y): event.accept() camera = self.get_camera(viewer) if camera is None: # this viewer doesn't have a camera return False camera.save_positions() self.onscreen_message("Saved camera position", delay=0.5) def kp_camera_toggle3d(self, viewer, event, data_x, data_y): event.accept() camera = self.get_camera(viewer) if camera is None: # this viewer doesn't have a camera return False renderer = viewer.renderer renderer.mode3d = not renderer.mode3d viewer.update_widget() ##### SCROLL ACTION CALLBACKS ##### def sc_camera_track(self, viewer, event, msg=True): camera = self.get_camera(viewer) if camera is None: # this viewer doesn't have a camera return False event.accept() zoom_accel = self.settings.get('scroll_zoom_acceleration', 6.0) delta = event.amount * zoom_accel direction = self.get_direction(event.direction) if direction == 'down': delta = - delta camera.track(delta) camera.calc_gl_transform() scales = camera.get_scale_2d() # TODO: need to set scale in viewer settings, without triggering a # scale operation on this viewer viewer.update_widget() ##### MOUSE ACTION CALLBACKS ##### def ms_camera_orbit(self, viewer, event, data_x, data_y, msg=True): camera = self.get_camera(viewer) if camera is None: # this viewer doesn't have a camera return False event.accept() x, y = self.get_win_xy(viewer) if event.state == 'move': camera.orbit(self._start_x, self._start_y, x, y) self._start_x, self._start_y = x, y camera.calc_gl_transform() ## pos = tuple(camera.position.get()) ## mst = "Camera position: (%.4f, %.4f, %.4f)" % pos ## if msg: ## self.onscreen_message(mst, delay=0.5) tup = camera.position.get() elif event.state == 'down': self._start_x, self._start_y = x, y ## else: ## self.onscreen_message(None) viewer.update_widget() def METHOD_NAME(self, viewer, event, data_x, data_y, msg=True): camera = self.get_camera(viewer) if camera is None: # this viewer doesn't have a camera return False event.accept() x, y = self.get_win_xy(viewer) if event.state == 'move': dx, dy = x - self._start_x, self._start_y - y camera.pan_delta(dx, dy) self._start_x, self._start_y = x, y camera.calc_gl_transform() elif event.state == 'down': self._start_x, self._start_y = x, y ## if msg: ## self.onscreen_message("Camera translate", delay=1.0) ## else: ## self.onscreen_message(None) # TODO: need to get the updated pan position and set it in # viewer's settings without triggering a callback to the viewer # itself tup = camera.position.get() data_x, data_y = viewer.tform['data_to_native'].from_(tup[:2]) viewer.update_widget()
299,097
signatures
# coding=utf-8 # *** WARNING: this file was generated by pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = [ 'ListFirewallPolicyIdpsSignatureResult', 'AwaitableListFirewallPolicyIdpsSignatureResult', 'list_firewall_policy_idps_signature', 'list_firewall_policy_idps_signature_output', ] @pulumi.output_type class ListFirewallPolicyIdpsSignatureResult: """ Query result """ def __init__(__self__, matching_records_count=None, METHOD_NAME=None): if matching_records_count and not isinstance(matching_records_count, float): raise TypeError("Expected argument 'matching_records_count' to be a float") pulumi.set(__self__, "matching_records_count", matching_records_count) if METHOD_NAME and not isinstance(METHOD_NAME, list): raise TypeError("Expected argument 'signatures' to be a list") pulumi.set(__self__, "signatures", METHOD_NAME) @property @pulumi.getter(name="matchingRecordsCount") def matching_records_count(self) -> Optional[float]: """ Number of total records matching the query. """ return pulumi.get(self, "matching_records_count") @property @pulumi.getter def METHOD_NAME(self) -> Optional[Sequence['outputs.SingleQueryResultResponse']]: """ Array containing the results of the query """ return pulumi.get(self, "signatures") class AwaitableListFirewallPolicyIdpsSignatureResult(ListFirewallPolicyIdpsSignatureResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return ListFirewallPolicyIdpsSignatureResult( matching_records_count=self.matching_records_count, METHOD_NAME=self.METHOD_NAME) def list_firewall_policy_idps_signature(filters: Optional[Sequence[pulumi.InputType['FilterItems']]] = None, firewall_policy_name: Optional[str] = None, order_by: Optional[pulumi.InputType['OrderBy']] = None, resource_group_name: Optional[str] = None, results_per_page: Optional[int] = None, search: Optional[str] = None, skip: Optional[int] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListFirewallPolicyIdpsSignatureResult: """ Retrieves the current status of IDPS signatures for the relevant policy Azure REST API version: 2023-02-01. :param Sequence[pulumi.InputType['FilterItems']] filters: Contain all filters names and values :param str firewall_policy_name: The name of the Firewall Policy. :param pulumi.InputType['OrderBy'] order_by: Column to sort response by :param str resource_group_name: The name of the resource group. :param int results_per_page: The number of the results to return in each page :param str search: Search term in all columns :param int skip: The number of records matching the filter to skip """ __args__ = dict() __args__['filters'] = filters __args__['firewallPolicyName'] = firewall_policy_name __args__['orderBy'] = order_by __args__['resourceGroupName'] = resource_group_name __args__['resultsPerPage'] = results_per_page __args__['search'] = search __args__['skip'] = skip opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('azure-native:network:listFirewallPolicyIdpsSignature', __args__, opts=opts, typ=ListFirewallPolicyIdpsSignatureResult).value return AwaitableListFirewallPolicyIdpsSignatureResult( matching_records_count=pulumi.get(__ret__, 'matching_records_count'), METHOD_NAME=pulumi.get(__ret__, 'signatures')) @_utilities.lift_output_func(list_firewall_policy_idps_signature) def list_firewall_policy_idps_signature_output(filters: Optional[pulumi.Input[Optional[Sequence[pulumi.InputType['FilterItems']]]]] = None, firewall_policy_name: Optional[pulumi.Input[str]] = None, order_by: Optional[pulumi.Input[Optional[pulumi.InputType['OrderBy']]]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, results_per_page: Optional[pulumi.Input[Optional[int]]] = None, search: Optional[pulumi.Input[Optional[str]]] = None, skip: Optional[pulumi.Input[Optional[int]]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[ListFirewallPolicyIdpsSignatureResult]: """ Retrieves the current status of IDPS signatures for the relevant policy Azure REST API version: 2023-02-01. :param Sequence[pulumi.InputType['FilterItems']] filters: Contain all filters names and values :param str firewall_policy_name: The name of the Firewall Policy. :param pulumi.InputType['OrderBy'] order_by: Column to sort response by :param str resource_group_name: The name of the resource group. :param int results_per_page: The number of the results to return in each page :param str search: Search term in all columns :param int skip: The number of records matching the filter to skip """ ...
299,098
get prometheus connect
import logging import os from typing import TYPE_CHECKING, Dict, List, Optional from cachetools import TTLCache from prometrix import ( AWSPrometheusConfig, AzurePrometheusConfig, CoralogixPrometheusConfig, PrometheusConfig, VictoriaMetricsPrometheusConfig, ) from robusta.core.exceptions import NoPrometheusUrlFound from robusta.core.model.base_params import PrometheusParams from robusta.core.model.env_vars import PROMETHEUS_SSL_ENABLED, SERVICE_CACHE_TTL_SEC from robusta.utils.service_discovery import find_service_url AZURE_RESOURCE = os.environ.get("AZURE_RESOURCE", "https://prometheus.monitor.azure.com") AZURE_METADATA_ENDPOINT = os.environ.get( "AZURE_METADATA_ENDPOINT", "http://169.254.169.254/metadata/identity/oauth2/token" ) AZURE_TOKEN_ENDPOINT = os.environ.get( "AZURE_TOKEN_ENDPOINT", f"https://login.microsoftonline.com/{os.environ.get('AZURE_TENANT_ID')}/oauth2/token" ) CORALOGIX_PROMETHEUS_TOKEN = os.environ.get("CORALOGIX_PROMETHEUS_TOKEN") AWS_ACCESS_KEY = os.environ.get("AWS_ACCESS_KEY") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_SERVICE_NAME = os.environ.get("AWS_SERVICE_NAME") AWS_REGION = os.environ.get("AWS_REGION") VICTORIA_METRICS_CONFIGURED = os.environ.get("VICTORIA_METRICS_CONFIGURED", "false").lower() == "true" if TYPE_CHECKING: from prometheus_api_client import PrometheusConnect def generate_prometheus_config(prometheus_params: PrometheusParams) -> PrometheusConfig: is_victoria_metrics = VICTORIA_METRICS_CONFIGURED url: Optional[str] = ( prometheus_params.prometheus_url if prometheus_params.prometheus_url else PrometheusDiscovery.find_prometheus_url() ) if not url: url = PrometheusDiscovery.find_vm_url() is_victoria_metrics = is_victoria_metrics is not None if not url: raise NoPrometheusUrlFound("Prometheus url could not be found. Add 'prometheus_url' under global_config") baseconfig = { "url": url, "disable_ssl": not PROMETHEUS_SSL_ENABLED, "additional_labels": prometheus_params.prometheus_additional_labels, "prometheus_url_query_string": prometheus_params.prometheus_url_query_string, } # aws config if AWS_ACCESS_KEY: return AWSPrometheusConfig( access_key=AWS_ACCESS_KEY, secret_access_key=AWS_SECRET_ACCESS_KEY, service_name=AWS_SERVICE_NAME, aws_region=AWS_REGION, **baseconfig, ) # coralogix config if CORALOGIX_PROMETHEUS_TOKEN: return CoralogixPrometheusConfig(**baseconfig, prometheus_token=CORALOGIX_PROMETHEUS_TOKEN) # Azure config azure_managed_id = os.environ.get("AZURE_USE_MANAGED_ID") azure_client_secret = os.environ.get("AZURE_CLIENT_SECRET") if azure_managed_id or azure_client_secret: return AzurePrometheusConfig( **baseconfig, azure_resource=AZURE_RESOURCE, azure_metadata_endpoint=AZURE_METADATA_ENDPOINT, azure_token_endpoint=AZURE_TOKEN_ENDPOINT, azure_use_managed_id=azure_managed_id, azure_client_id=os.environ.get("AZURE_CLIENT_ID"), azure_client_secret=azure_client_secret, ) if is_victoria_metrics: return VictoriaMetricsPrometheusConfig(**baseconfig) return PrometheusConfig(**baseconfig) def METHOD_NAME(prometheus_params: PrometheusParams) -> "CustomPrometheusConnect": # due to cli import dependency errors without prometheus package installed from prometrix import get_custom_prometheus_connect config = generate_prometheus_config(prometheus_params) return get_custom_prometheus_connect(config) def get_prometheus_flags(prom: "CustomPrometheusConnect") -> Optional[Dict]: """ This returns the prometheus flags and stores the prometheus retention time in retentionTime """ data = prom.get_prometheus_flags() if not data: return # retentionTime is stored differently in VM and prometheus data["retentionTime"] = data.get("storage.tsdb.retention.time", "") or data.get("-retentionPeriod", "") return data class ServiceDiscovery: cache: TTLCache = TTLCache(maxsize=5, ttl=SERVICE_CACHE_TTL_SEC) @classmethod def find_url(cls, selectors: List[str], error_msg: str) -> Optional[str]: """ Try to autodiscover the url of an in-cluster service """ cache_key = ",".join(selectors) cached_value = cls.cache.get(cache_key) if cached_value: return cached_value for label_selector in selectors: service_url = find_service_url(label_selector) if service_url: cls.cache[cache_key] = service_url return service_url logging.debug(error_msg) return None class PrometheusDiscovery(ServiceDiscovery): @classmethod def find_prometheus_url(cls) -> Optional[str]: return super().find_url( selectors=[ "app=kube-prometheus-stack-prometheus", "app=prometheus,component=server,release!=kubecost", "app=prometheus-server", "app=prometheus-operator-prometheus", "app=prometheus-msteams", "app=rancher-monitoring-prometheus", "app=prometheus-prometheus", "app.kubernetes.io/component=query,app.kubernetes.io/name=thanos", "app.kubernetes.io/name=thanos-query", "app=thanos-query", "app=thanos-querier", ], error_msg="Prometheus url could not be found. Add 'prometheus_url' under global_config", ) @classmethod def find_vm_url(cls) -> Optional[str]: return super().find_url( selectors=[ "app.kubernetes.io/name=vmsingle", "app.kubernetes.io/name=victoria-metrics-single", "app.kubernetes.io/name=vmselect", "app=vmselect", ], error_msg="Victoria Metrics url could not be found. Add 'prometheus_url' under global_config", ) class AlertManagerDiscovery(ServiceDiscovery): @classmethod def find_alert_manager_url(cls) -> Optional[str]: return super().find_url( selectors=[ "app=kube-prometheus-stack-alertmanager", "app=prometheus,component=alertmanager", "app=prometheus-operator-alertmanager", "app=alertmanager", "app=rancher-monitoring-alertmanager", "app=prometheus-alertmanager", "operated-alertmanager=true", "app.kubernetes.io/name=alertmanager", "app.kubernetes.io/name=vmalertmanager", ], error_msg="Alert manager url could not be found. Add 'alertmanager_url' under global_config", )
299,099
test omit
import pytest from checkov.common.bridgecrew.check_type import CheckType from checkov.common.models.enums import CheckResult from checkov.common.output.record import Record from checkov.common.output.report import Report from checkov.common.util.secrets_omitter import SecretsOmitter, SecretsOmitterStatus @pytest.mark.parametrize( "r1,r2,expected_result", [ ([10, 20], [15, 17], True), ([10, 20], [18, 21], True), ([10, 20], [9, 12], True), ([10, 20], [20, 25], True), ([10, 20], [30, 40], False) ], ) def test_line_ranges_overlap(r1, r2, expected_result): assert expected_result == SecretsOmitter._line_range_overlaps(r1, r2) @pytest.mark.parametrize( "code_block,expected_range,expected_lines", [ ([(1, 'ab***'), (2, 'abcd')], [1, 1], ['ab***']), ([(1, 'abcd'), (2, 'abc')], [-1, -1], []), ([(1, 'ab***'), (2, 'bc*'), (3, 'efg******')], [1, 3], ['ab***', 'bc*', 'efg******']) ], ) def test_get_secret_lines(code_block, expected_range, expected_lines): line_range, lines = SecretsOmitter.get_secret_lines(code_block) assert line_range == expected_range assert lines == expected_lines @pytest.mark.parametrize( "reports", [ ([Report(CheckType.SECRETS)]), ([Report(CheckType.GITHUB_ACTIONS)]) ], ) def test_omit_insufficient_reports(reports): assert SecretsOmitter(reports).omit() == SecretsOmitterStatus.INSUFFICIENT_REPORTS def METHOD_NAME(): file_path = 'filepath' failed_secrets_record = Record(check_id='a', check_name='a', check_result={"result": CheckResult.FAILED}, code_block=[(1, 'ab***'), (2, 'bc*'), (3, 'efg******'), (4, 'abcd'), (5, 'abc')], file_path=file_path, file_line_range=[], resource='', evaluations={}, check_class='', file_abs_path='' ) secrets_report = Report(CheckType.SECRETS) secrets_report.add_record(failed_secrets_record) record = Record(check_id='b', check_name='b', check_result={"result": CheckResult.PASSED}, code_block=[(2, 'SECRET'), (3, 'SECRET'), (4, 'abcd'), (5, 'abc')], file_path=file_path, file_line_range=[2, 5], resource='', evaluations={}, check_class='', file_abs_path='' ) report = Report(CheckType.GITHUB_ACTIONS) report.add_record(record) res = SecretsOmitter([secrets_report, report]).omit() assert res == SecretsOmitterStatus.SUCCESS assert report.passed_checks[0].code_block == [(2, 'bc*'), (3, 'efg******'), (4, 'abcd'), (5, 'abc')] def test_omit_should_skip(): """ This test verifies that records containing None in file_line_range will be skipped """ file_path = 'filepath' failed_secrets_record = Record(check_id='a', check_name='a', check_result={"result": CheckResult.FAILED}, code_block=[(1, 'ab***'), (2, 'bc*'), (3, 'efg******'), (4, 'abcd'), (5, 'abc')], file_path=file_path, file_line_range=[], resource='', evaluations={}, check_class='', file_abs_path='' ) secrets_report = Report(CheckType.SECRETS) secrets_report.add_record(failed_secrets_record) record = Record(check_id='b', check_name='b', check_result={"result": CheckResult.PASSED}, code_block=[(2, 'SECRET'), (3, 'SECRET'), (4, 'abcd'), (5, 'abc')], file_path=file_path, file_line_range=[2, None], resource='', evaluations={}, check_class='', file_abs_path='' ) report = Report(CheckType.GITHUB_ACTIONS) report.add_record(record) res = SecretsOmitter([secrets_report, report]).omit() assert res == SecretsOmitterStatus.SUCCESS # Asserting code block is unchanged assert report.passed_checks[0].code_block == [(2, 'SECRET'), (3, 'SECRET'), (4, 'abcd'), (5, 'abc')] def test_omit_with_abs_file_path(): abs_file_path = 'abs/filepath' failed_secrets_record = Record(check_id='a', check_name='a', check_result={"result": CheckResult.FAILED}, code_block=[(1, 'ab***'), (2, 'bc*'), (3, 'efg******'), (4, 'abcd'), (5, 'abc')], file_path=abs_file_path, file_line_range=[], resource='', evaluations={}, check_class='', file_abs_path=abs_file_path ) secrets_report = Report(CheckType.SECRETS) secrets_report.add_record(failed_secrets_record) record = Record(check_id='b', check_name='b', check_result={"result": CheckResult.PASSED}, code_block=[(2, 'SECRET'), (3, 'SECRET'), (4, 'abcd'), (5, 'abc')], file_path='different_file_path', file_line_range=[2, 5], resource='', evaluations={}, check_class='', file_abs_path=abs_file_path ) report = Report(CheckType.GITHUB_ACTIONS) report.add_record(record) res = SecretsOmitter([secrets_report, report]).omit() assert res == SecretsOmitterStatus.SUCCESS assert report.passed_checks[0].code_block == [(2, 'bc*'), (3, 'efg******'), (4, 'abcd'), (5, 'abc')