hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
1c4407450f29ef110bf3b72088dfff08feacca6b
5,291
py
Python
src/arg_utils.py
Nicolas-Reyland/python-polygon
2847bebc58d50219ae8fc7eb5cc14d6b8d1161ed
[ "MIT" ]
1
2021-09-03T08:17:11.000Z
2021-09-03T08:17:11.000Z
src/arg_utils.py
Nicolas-Reyland/python-polygon
2847bebc58d50219ae8fc7eb5cc14d6b8d1161ed
[ "MIT" ]
null
null
null
src/arg_utils.py
Nicolas-Reyland/python-polygon
2847bebc58d50219ae8fc7eb5cc14d6b8d1161ed
[ "MIT" ]
null
null
null
from __future__ import annotations from argparse import ArgumentParser import os ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) DEFAULT_ARGS_JSON_FILE_PATH = "default-args.json" class ArgumentError(Exception): """ Simple class, representing an commandline-argument error. """ pass def gen_arg_parser() -> ArgumentParser: """ Generate argument parser. Generate an ArgumentParser for all Chaikin3D arguments. Generally, there is a short and long argument (short: -char, long: --words). Returns: ArgumentParser instance """ parser = ArgumentParser( description="Apply the Chaikin algorithm, expanded to the 3D space" ) # polyhedron parser.add_argument("-i", "--input", type=str, help="input file", required=True) parser.add_argument( "-rm", "--rotate-mesh", help="Rotate the mesh when loading a file", action="store_true", ) # chaikin algorithm parser.add_argument( "-cg", "--chaikin-generations", type=int, default=0, help="number of chaikin generations", ) parser.add_argument( "-cc", "--chaikin-coef", type=float, default=4.0, help="Chaikin coefficient" ) parser.add_argument( "-oe", "--order-edges", type=str, default="none", help='Order edges ["none", "first", "all"]', ) parser.add_argument("-v", "--verbose", help="verbose mode", action="store_true") parser.add_argument("-vv", "--vverbose", help="very-verbose", action="store_true") # what to plot parser.add_argument( "-r", "--renderer", type=str, default="plotly", help='renderer ["plotly", "mpl"]', ) parser.add_argument( "-p", "--plot", type=str, default="simple", help='plot type ["none", "simple", "full", "evolution", "animation"]', ) parser.add_argument( "-hme", "--hide-main-edges", help='Hide the main edges (for plots: "simple", "full" and "evolution")', action="store_true", ) parser.add_argument( "-sge", "--show-graphical-edges", help='Show the graphical edges (for plots: "simple", "full" and "evolution")', action="store_true", ) # how to plot parser.add_argument( "-a", "--alpha", type=float, default=0.8, help="Alpha/Opacity value for mesh rendering", ) parser.add_argument( "-pc", "--polygon-color", type=str, default="lightblue", help="Polygon color" ) parser.add_argument( "-nc", "--node-color", type=str, default="green", help="Node color" ) parser.add_argument( "-mec", "--main-edge-color", type=str, default="darkred", help="Main edge color", ) parser.add_argument( "-gec", "--graphical-edge-color", type=str, default="black", help="Graphical edge", ) # output parser.add_argument( "-o", "--output", type=str, default=None, help="Output file path (wavefront '.obj' or '.html' format)", ) return parser def read_args(arg_parser: ArgumentParser) -> dict[str, str | bool]: """ Read and parse the command-line arguments. Args: arg_parser (ArgumentParser): Argument parser. Returns: A: Instance of class 'A', created inside this function. You can access the elements of this class by variable name or by using bracket notation (value = a["key"]). The keys are the command line arguments (spaces are used instead of '-'/'_'). Raises: ArgumentError: The specified renderer is not known """ # parse the command line arguments args = vars(arg_parser.parse_args()) args = dict( map( lambda kvpair: (kvpair[0].replace("_", " ").replace("-", " "), kvpair[1]), args.items(), ) ) # order-edges assert args["order edges"] in ("none", "first", "all"), ArgumentError( f'Invalid value for "order-edges" option: {args["order edges"]}' ) # output file if args["output"] is not None: assert args["output"].endswith(".obj") or args["output"].endswith( ".html" ), f"Invalid file extension: '{args['output']}'. Must end with '.obj' or '.html'" # verbosity level if args["vverbose"]: args["verbosity"] = 2 args["verbose"] = True elif args["verbose"]: args["verbosity"] = 1 else: args["verbosity"] = 0 # add 'show-main-edges' value, based on 'hide-main-edges' args["show main edges"] = not args["hide main edges"] # renderer if args["renderer"] == "plotly": from plotly_renderer import Renderer elif args["renderer"] == "mpl": from mpl_renderer import Renderer else: raise ArgumentError(f'Unkown renderer: {args["renderer"]}') args["renderer class"] = Renderer A = type( "A", (), dict((k.replace(" ", "_"), v) for k, v in args.items()) | {"__getitem__": lambda self, value: args[value]}, ) return A()
26.994898
89
0.567757
from __future__ import annotations from argparse import ArgumentParser import os ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) DEFAULT_ARGS_JSON_FILE_PATH = "default-args.json" class ArgumentError(Exception): pass def gen_arg_parser() -> ArgumentParser: parser = ArgumentParser( description="Apply the Chaikin algorithm, expanded to the 3D space" ) parser.add_argument("-i", "--input", type=str, help="input file", required=True) parser.add_argument( "-rm", "--rotate-mesh", help="Rotate the mesh when loading a file", action="store_true", ) parser.add_argument( "-cg", "--chaikin-generations", type=int, default=0, help="number of chaikin generations", ) parser.add_argument( "-cc", "--chaikin-coef", type=float, default=4.0, help="Chaikin coefficient" ) parser.add_argument( "-oe", "--order-edges", type=str, default="none", help='Order edges ["none", "first", "all"]', ) parser.add_argument("-v", "--verbose", help="verbose mode", action="store_true") parser.add_argument("-vv", "--vverbose", help="very-verbose", action="store_true") parser.add_argument( "-r", "--renderer", type=str, default="plotly", help='renderer ["plotly", "mpl"]', ) parser.add_argument( "-p", "--plot", type=str, default="simple", help='plot type ["none", "simple", "full", "evolution", "animation"]', ) parser.add_argument( "-hme", "--hide-main-edges", help='Hide the main edges (for plots: "simple", "full" and "evolution")', action="store_true", ) parser.add_argument( "-sge", "--show-graphical-edges", help='Show the graphical edges (for plots: "simple", "full" and "evolution")', action="store_true", ) parser.add_argument( "-a", "--alpha", type=float, default=0.8, help="Alpha/Opacity value for mesh rendering", ) parser.add_argument( "-pc", "--polygon-color", type=str, default="lightblue", help="Polygon color" ) parser.add_argument( "-nc", "--node-color", type=str, default="green", help="Node color" ) parser.add_argument( "-mec", "--main-edge-color", type=str, default="darkred", help="Main edge color", ) parser.add_argument( "-gec", "--graphical-edge-color", type=str, default="black", help="Graphical edge", ) parser.add_argument( "-o", "--output", type=str, default=None, help="Output file path (wavefront '.obj' or '.html' format)", ) return parser def read_args(arg_parser: ArgumentParser) -> dict[str, str | bool]: args = vars(arg_parser.parse_args()) args = dict( map( lambda kvpair: (kvpair[0].replace("_", " ").replace("-", " "), kvpair[1]), args.items(), ) ) assert args["order edges"] in ("none", "first", "all"), ArgumentError( f'Invalid value for "order-edges" option: {args["order edges"]}' ) if args["output"] is not None: assert args["output"].endswith(".obj") or args["output"].endswith( ".html" ), f"Invalid file extension: '{args['output']}'. Must end with '.obj' or '.html'" if args["vverbose"]: args["verbosity"] = 2 args["verbose"] = True elif args["verbose"]: args["verbosity"] = 1 else: args["verbosity"] = 0 args["show main edges"] = not args["hide main edges"] if args["renderer"] == "plotly": from plotly_renderer import Renderer elif args["renderer"] == "mpl": from mpl_renderer import Renderer else: raise ArgumentError(f'Unkown renderer: {args["renderer"]}') args["renderer class"] = Renderer A = type( "A", (), dict((k.replace(" ", "_"), v) for k, v in args.items()) | {"__getitem__": lambda self, value: args[value]}, ) return A()
true
true
1c4407904b26ff7709bfbd7dfc2fb50b553a83f6
25,483
py
Python
tensorflow/python/autograph/operators/control_flow_test.py
fwtan/tensorflow
efa3fb28d94b7937edaafb5874c191ad0e2149ca
[ "Apache-2.0" ]
1
2020-05-14T03:53:01.000Z
2020-05-14T03:53:01.000Z
tensorflow/python/autograph/operators/control_flow_test.py
fwtan/tensorflow
efa3fb28d94b7937edaafb5874c191ad0e2149ca
[ "Apache-2.0" ]
2
2021-08-25T16:05:52.000Z
2022-02-10T01:51:12.000Z
tensorflow/python/autograph/operators/control_flow_test.py
taotesea/tensorflow
5e6479904941624cf7ce58ab3d236375c8012ef4
[ "Apache-2.0" ]
1
2020-08-07T12:49:50.000Z
2020-08-07T12:49:50.000Z
# Lint as: python3 # Copyright 2017 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. # ============================================================================== """Tests for control_flow module.""" # Unfortunately pylint has false positives when nonlocal is present. # pylint:disable=unused-variable from __future__ import absolute_import from __future__ import division from __future__ import print_function import re import sys import numpy as np import six from tensorflow.python.autograph.operators import control_flow from tensorflow.python.autograph.operators import variables as variable_operators from tensorflow.python.autograph.utils import ag_logging from tensorflow.python.data.ops import dataset_ops from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import func_graph from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gen_math_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variables from tensorflow.python.ops.ragged import ragged_factory_ops from tensorflow.python.platform import test @test_util.run_all_in_graph_and_eager_modes class ForLoopTest(test.TestCase): def test_tensor(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( constant_op.constant([1, 2, 3, 4]), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(self.evaluate(s), (1234,)) def test_range_tensor(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( math_ops.range(5), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'iterate_names': 'i'}) self.assertEqual(self.evaluate(s), (1234,)) def test_range_tensor_explicit_limit_delta(self): def body(i): nonlocal s s = s * 100 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( math_ops.range(-17, -3, 5), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'iterate_names': 'i'}) self.assertEqual(self.evaluate(s), (-171207,)) def test_range_tensor_explicit_limit_negative_delta(self): def body(i): nonlocal s s = s * 100 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( math_ops.range(17, 3, -5), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'iterate_names': 'i'}) self.assertEqual(self.evaluate(s), (171207,)) def test_range_tensor_random_delta(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 random_one = random_ops.random_uniform((), 1, 2, dtype=dtypes.int32) control_flow.for_stmt( math_ops.range(0, 5, random_one), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'iterate_names': 'i'}) self.assertEqual(self.evaluate(s), (1234,)) def test_range_tensor_random_negative_delta(self): def body(i): nonlocal s s = s * 100 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 random_neg_five = random_ops.random_uniform((), -5, -4, dtype=dtypes.int32) control_flow.for_stmt( math_ops.range(17, 3, random_neg_five), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'iterate_names': 'i'}) self.assertEqual(self.evaluate(s), (171207,)) def test_tensor_with_extra_test_object_vars(self): class MutableObject(object): field_1 = constant_op.constant(0, dtype=dtypes.int32) field_2 = constant_op.constant(1, dtype=dtypes.int32) state = MutableObject() def body(i): state.field_1 += i state.field_2 *= i def get_state(): return state.field_1, state.field_2 def set_state(loop_vars): state.field_1, state.field_2 = loop_vars control_flow.for_stmt( iter_=constant_op.constant([1, 2, 3, 4]), body=body, extra_test=lambda: state.field_1 < 6, get_state=get_state, set_state=set_state, symbol_names=('state.field_1', 'state.field_2'), opts={}) self.assertEqual(self.evaluate((state.field_1, state.field_2)), (6, 6)) def test_python(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( range(5), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(s, 1234) def test_python_generator_with_extra_test(self): def new_generator(): for i in range(1, 5): yield i gen = new_generator() def run_loop(): s = 0 c = 0 def body(i): nonlocal s, c s = s * 10 + i c += 1 control_flow.for_stmt( gen, extra_test=lambda: c == 0, # Break after first iteration body=body, get_state=None, set_state=None, symbol_names=('s', 'c'), opts={}) return s, c self.assertEqual(run_loop(), (1, 1)) self.assertEqual(run_loop(), (2, 1)) self.assertEqual(run_loop(), (3, 1)) self.assertEqual(next(gen), 4) def test_python_generator_with_extra_test_no_iterations(self): def new_generator(): for i in range(5): yield i gen = new_generator() def run_loop(): s = 0 def body(i): nonlocal s s = s * 10 + i control_flow.for_stmt( gen, extra_test=lambda: False, # Break before loop body=body, get_state=None, set_state=None, symbol_names=('s',), opts={}) return s self.assertEqual(run_loop(), 0) self.assertEqual(run_loop(), 0) self.assertEqual(next(gen), 0) def test_tf_dataset(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = constant_op.constant(0, dtype=dtypes.int64) control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=None, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(self.evaluate(s), (1234,)) def test_dataset_with_extra_test(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = constant_op.constant(0, dtype=dtypes.int64) control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=lambda: s < 3, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(self.evaluate(s), (12,)) def test_dataset_with_extra_test_collection_vars(self): def body(i): nonlocal s l[0] += i s += i def set_state(loop_vars): nonlocal s l[0], s = loop_vars s = constant_op.constant(0, dtype=dtypes.int64) l = [constant_op.constant(0, dtype=dtypes.int64)] control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=lambda: s < 3, body=body, get_state=lambda: (l[0], s), set_state=set_state, symbol_names=('l[0]', 's'), opts={}) self.assertEqual(self.evaluate((l[0], s)), (3, 3)) def test_dataset_with_extra_test_iteration_limiting(self): def body(it): nonlocal i with ops.control_dependencies((control_flow_ops.Assert(i < 3, (i,)),)): i = it def set_state(loop_vars): nonlocal i i, = loop_vars i = constant_op.constant(0, dtype=dtypes.int64) control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=lambda: i < 3, body=body, get_state=lambda: (i,), set_state=set_state, symbol_names=('i',), opts={}) self.assertEqual(self.evaluate(i), (3,)) def test_tf_dataset_no_loop_vars(self): def body(i): v.assign(v.read_value() * 10 + i) v = variables.Variable(0, dtype=dtypes.int64) self.evaluate(v.initializer) # tf.function required for the automatic control dependencies, and because # ops test for its presence. @def_function.function def test_fn(): control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=None, body=body, get_state=lambda: (), set_state=lambda _: None, symbol_names=(), opts={}) self.evaluate(test_fn()) self.assertEqual(self.evaluate(v.read_value()), 1234) def test_tf_iterator(self): # graph-mode iterators are only supported inside tf.function. @def_function.function def test_fn(): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = constant_op.constant(0, dtype=dtypes.int64) control_flow.for_stmt( iter(dataset_ops.Dataset.range(5)), extra_test=None, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) return s self.assertAllEqual(test_fn(), 1234) def test_tf_iterator_shape_invariants(self): # graph-mode iterators are only supported inside tf.function. @def_function.function def test_fn(): def body(i): nonlocal s s = array_ops.concat([s, [i]], 0) def set_state(loop_vars): nonlocal s s, = loop_vars s = constant_op.constant([], dtype=dtypes.int64) control_flow.for_stmt( iter(dataset_ops.Dataset.range(5)), extra_test=None, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'shape_invariants': [(s, tensor_shape.TensorShape([None]))]}) return s self.assertAllEqual(test_fn(), [0, 1, 2, 3, 4]) def test_tf_iterator_no_loop_vars(self): def body(i): v.assign(v.read_value() * 10 + i) v = variables.Variable(0, dtype=dtypes.int64) self.evaluate(v.initializer) # tf.function required for the automatic control dependencies. @def_function.function def test_fn(): control_flow.for_stmt( iter(dataset_ops.Dataset.range(5)), extra_test=None, body=body, get_state=lambda: (), set_state=lambda _: None, symbol_names=(), opts={}) self.evaluate(test_fn()) self.assertEqual(self.evaluate(v.read_value()), 1234) def test_tf_ragged_tensor(self): def body(i): nonlocal s s = s * 10 + i[0] def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( ragged_factory_ops.constant([[1], [2, 4], [3]]), extra_test=None, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(self.evaluate(s), (123,)) def test_tf_ragged_tensor_higher_dimensional(self): def body(i): nonlocal s s = s * 10 + i[0][0] def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 ragged_3d = [ [[1], [1, 1], [1]], [[2], [2]], ] control_flow.for_stmt( ragged_factory_ops.constant(ragged_3d), extra_test=None, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(self.evaluate(s), (12,)) def test_tf_ragged_tensor_no_loop_vars(self): v = variables.Variable(0, dtype=dtypes.int32) self.evaluate(v.initializer) def body(i): v.assign(v.read_value() * 10 + i[0]) # tf.function required for the automatic control dependencies. @def_function.function(autograph=False) def test_fn(): control_flow.for_stmt( ragged_factory_ops.constant([[1], [2, 4], [3]]), extra_test=None, body=body, get_state=lambda: (), set_state=lambda _: None, symbol_names=(), opts={}) self.evaluate(test_fn()) # Note: 123 = ((0*10 + 1)*10+2)*10+3 (first element of each row). self.assertEqual(self.evaluate(v.read_value()), 123) def _basic_loop(self, init_value, body_fn): def body(i): nonlocal s s = body_fn(i, s) def set_state(loop_vars): nonlocal s s, = loop_vars s = init_value control_flow.for_stmt( constant_op.constant([1, 2, 3, 4]), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) return s def test_tensor_illegal_input(self): with self.assertRaisesRegex(ValueError, '"s" may not be None'): self._basic_loop(None, lambda i, s: s) with self.assertRaisesRegex(ValueError, '"s" must be defined'): self._basic_loop(variable_operators.Undefined(''), lambda i, s: s) def test_tensor_none_output(self): with self.assertRaisesRegex(ValueError, '"s" is None at the end'): self._basic_loop(0, lambda i, s: None) def test_tensor_dtype_change(self): with self.assertRaisesRegex(TypeError, '"s".* dtype float32 after'): self._basic_loop(0, lambda i, s: 1.0) def test_tensor_shape_change(self): with self.assertRaisesRegex(ValueError, r'"s".* shape \(1,\) after'): self._basic_loop(0, lambda i, s: np.array([1], dtype=np.int32)) @test_util.run_all_in_graph_and_eager_modes class WhileLoopTest(test.TestCase): def test_tensor(self): def body(): nonlocal i, s s = s * 10 + i i += 1 def set_state(loop_vars): nonlocal i, s i, s = loop_vars i = 0 n = constant_op.constant(5) s = 0 control_flow.while_stmt( test=lambda: i < n, body=body, get_state=lambda: (i, s), set_state=set_state, symbol_names=('i', 's'), opts={}) self.assertEqual(self.evaluate((i, s)), (5, 1234)) def test_tensor_with_side_effecting_condition(self): v = variables.Variable(0) # tf.function required for the automatic control dependencies. @def_function.function def test_fn(): def cond(): v.assign(v.read_value() * 10 + i) return i < n def body(): nonlocal i i += 1 def set_state(loop_vars): nonlocal i i, = loop_vars i = 0 n = constant_op.constant(5) control_flow.while_stmt( test=cond, body=body, get_state=lambda: (i,), set_state=set_state, symbol_names=('i',), opts={}) return i self.evaluate(v.initializer) self.assertEqual(self.evaluate(test_fn()), (5,)) self.assertEqual(self.evaluate(v), (12345,)) def test_tensor_with_python_state(self): class MutableObject(object): field = constant_op.constant(0, dtype=dtypes.int32) state = MutableObject() def body(): nonlocal i state.field = state.field * 10 + i i += 1 def set_state(loop_vars): nonlocal i i, state.field = loop_vars i = 0 n = constant_op.constant(5) control_flow.while_stmt( test=lambda: i < n, body=body, get_state=lambda: (i, state.field), set_state=set_state, symbol_names=('i', 'state.field'), opts={}) self.assertEqual(self.evaluate((i, state.field)), (5, 1234)) def test_python(self): def body(): nonlocal i, s s = s * 10 + i i += 1 i = 0 s = 0 n = 5 control_flow.while_stmt( test=lambda: i < n, body=body, get_state=None, set_state=None, symbol_names=('i', 's'), opts={}) self.assertEqual(s, 1234) def test_python_with_tensor_state(self): def body(): nonlocal i, s s = s * 10 + i i += 1 i = 0 s = constant_op.constant(0) n = 5 control_flow.while_stmt( test=lambda: i < n, body=body, get_state=None, set_state=None, symbol_names=('i', 's'), opts={}) self.assertEqual(i, 5) self.assertEqual(self.evaluate(s), 1234) def test_python_while_infinite(self): if not __debug__: self.skipTest('Feature disabled in optimized mode.') with test.mock.patch.object(control_flow, 'PYTHON_MAX_ITERATIONS', 100): with self.assertRaisesRegexp(ValueError, 'iteration limit'): control_flow.while_stmt( test=lambda: True, body=lambda: None, get_state=None, set_state=None, symbol_names=(), opts={}) def test_python_for_infinite(self): if not __debug__: self.skipTest('Feature disabled in optimized mode.') with test.mock.patch.object(control_flow, 'PYTHON_MAX_ITERATIONS', 100): with self.assertRaisesRegexp(ValueError, 'iteration limit'): control_flow.for_stmt( iter_=range(101), extra_test=None, body=lambda i: None, get_state=None, set_state=None, symbol_names=(), opts={}) def test_python_while_large_unroll_warning(self): if not __debug__: self.skipTest('Feature disabled in optimized mode.') with test.mock.patch.object( control_flow, 'INEFFICIENT_UNROLL_MIN_ITERATIONS', 10): with ops.Graph().as_default(): out_capturer = six.StringIO() with test.mock.patch.object(sys, 'stdout', out_capturer): with test.mock.patch.object(ag_logging, 'echo_log_to_stdout', True): def custom_iterator(): for i in range(11): c = constant_op.constant(i) yield c i = 0 control_flow.for_stmt( iter_=custom_iterator(), extra_test=None, body=lambda i: None, get_state=None, set_state=None, symbol_names=(), opts={}) self.assertTrue(re.match( r'.* Large unrolled loop.*Const.*', out_capturer.getvalue())) def test_python_for_large_unroll_warning(self): if not __debug__: self.skipTest('Feature disabled in optimized mode.') with test.mock.patch.object( control_flow, 'INEFFICIENT_UNROLL_MIN_ITERATIONS', 10): with ops.Graph().as_default(): out_capturer = six.StringIO() with test.mock.patch.object(sys, 'stdout', out_capturer): with test.mock.patch.object(ag_logging, 'echo_log_to_stdout', True): def body(): nonlocal i gen_math_ops.add(i, 1) i += 1 i = 0 control_flow.while_stmt( test=lambda: i < 100, body=body, get_state=None, set_state=None, symbol_names=('i',), opts={}) self.assertTrue(re.match( r'.* Large unrolled loop.*Add.*', out_capturer.getvalue())) def _basic_loop(self, init_value, body_fn): def body(): nonlocal i, s s = body_fn(i, s) i += 1 def set_state(loop_vars): nonlocal i, s i, s = loop_vars i = 0 n = constant_op.constant(5) s = init_value control_flow.while_stmt( test=lambda: i < n, body=body, get_state=lambda: (i, s), set_state=set_state, symbol_names=('i', 's'), opts={}) return s def test_tensor_illegal_input(self): with self.assertRaisesRegex(ValueError, '"s" may not be None'): self._basic_loop(None, lambda i, s: s) with self.assertRaisesRegex(ValueError, '"s" must be defined'): self._basic_loop(variable_operators.Undefined(''), lambda i, s: s) def test_tensor_none_output(self): with self.assertRaisesRegex(ValueError, '"s" is None at the end'): self._basic_loop(0, lambda i, s: None) def test_tensor_dtype_change(self): with self.assertRaisesRegex(TypeError, '"s".* dtype float32 after'): self._basic_loop(0, lambda i, s: 1.0) def test_tensor_shape_change(self): with self.assertRaisesRegex(ValueError, r'"s".* shape \(1,\) after'): self._basic_loop(0, lambda i, s: np.array([1], dtype=np.int32)) @test_util.run_all_in_graph_and_eager_modes class IfStmtTest(test.TestCase): def test_tensor(self): def test_fn(cond): return control_flow.if_stmt( cond=cond, body=lambda: constant_op.constant(1), orelse=lambda: constant_op.constant(-1), get_state=lambda: (), set_state=lambda _: None, basic_symbol_names=('_',), composite_symbol_names=()) self.assertEqual(1, self.evaluate(test_fn(constant_op.constant(True)))) self.assertEqual(-1, self.evaluate(test_fn(constant_op.constant(False)))) def test_tensor_multiple_returns(self): def test_fn(cond): return control_flow.if_stmt( cond=cond, body=lambda: (constant_op.constant(1), constant_op.constant(2)), orelse=lambda: (constant_op.constant(-1), constant_op.constant(-2)), get_state=lambda: (), set_state=lambda _: None, basic_symbol_names=('_',), composite_symbol_names=()) self.assertEqual((1, 2), self.evaluate(test_fn(constant_op.constant(True)))) self.assertEqual((-1, -2), self.evaluate(test_fn(constant_op.constant(False)))) def test_python(self): def test_fn(cond): return control_flow.if_stmt( cond=cond, body=lambda: 1, orelse=lambda: -1, get_state=lambda: (), set_state=lambda _: None, basic_symbol_names=('_',), composite_symbol_names=()) self.assertEqual(1, test_fn(True)) self.assertEqual(-1, test_fn(False)) def test_python_multiple_returns(self): def test_fn(cond): return control_flow.if_stmt( cond=cond, body=lambda: (1, 2), orelse=lambda: (-1, -2), get_state=lambda: (), set_state=lambda _: None, basic_symbol_names=('_',), composite_symbol_names=()) self.assertEqual((1, 2), test_fn(True)) self.assertEqual((-1, -2), test_fn(False)) def _basic_cond(self, true_value, false_value): # Eager cond had different semantics, we don't test those here. with func_graph.FuncGraph('tmp').as_default(): return control_flow.if_stmt( cond=constant_op.constant(True), body=true_value, orelse=false_value, get_state=lambda: (), set_state=lambda _: None, basic_symbol_names=('s',), composite_symbol_names=()) def test_tensor_none_output(self): with self.assertRaisesRegex( ValueError, '"s" is None at the end of the TRUE branch'): self._basic_cond(lambda: None, lambda: 1) with self.assertRaisesRegex( ValueError, '"s" is None at the end of the FALSE branch'): self._basic_cond(lambda: 1, lambda: None) def test_tensor_undefined_output(self): with self.assertRaisesRegex( ValueError, "must also be initialized in the if.*'s'"): self._basic_cond(lambda: variable_operators.Undefined('s'), lambda: 1) with self.assertRaisesRegex( ValueError, "must also be initialized in the else.*'s'"): self._basic_cond(lambda: 1, lambda: variable_operators.Undefined('s')) def test_tensor_dtype_change(self): with self.assertRaisesRegex(TypeError, '"s" has dtype int32.*but.*float32'): self._basic_cond(lambda: 1, lambda: 1.0) if __name__ == '__main__': test.main()
28.251663
81
0.608563
from __future__ import absolute_import from __future__ import division from __future__ import print_function import re import sys import numpy as np import six from tensorflow.python.autograph.operators import control_flow from tensorflow.python.autograph.operators import variables as variable_operators from tensorflow.python.autograph.utils import ag_logging from tensorflow.python.data.ops import dataset_ops from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import func_graph from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gen_math_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variables from tensorflow.python.ops.ragged import ragged_factory_ops from tensorflow.python.platform import test @test_util.run_all_in_graph_and_eager_modes class ForLoopTest(test.TestCase): def test_tensor(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( constant_op.constant([1, 2, 3, 4]), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(self.evaluate(s), (1234,)) def test_range_tensor(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( math_ops.range(5), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'iterate_names': 'i'}) self.assertEqual(self.evaluate(s), (1234,)) def test_range_tensor_explicit_limit_delta(self): def body(i): nonlocal s s = s * 100 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( math_ops.range(-17, -3, 5), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'iterate_names': 'i'}) self.assertEqual(self.evaluate(s), (-171207,)) def test_range_tensor_explicit_limit_negative_delta(self): def body(i): nonlocal s s = s * 100 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( math_ops.range(17, 3, -5), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'iterate_names': 'i'}) self.assertEqual(self.evaluate(s), (171207,)) def test_range_tensor_random_delta(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 random_one = random_ops.random_uniform((), 1, 2, dtype=dtypes.int32) control_flow.for_stmt( math_ops.range(0, 5, random_one), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'iterate_names': 'i'}) self.assertEqual(self.evaluate(s), (1234,)) def test_range_tensor_random_negative_delta(self): def body(i): nonlocal s s = s * 100 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 random_neg_five = random_ops.random_uniform((), -5, -4, dtype=dtypes.int32) control_flow.for_stmt( math_ops.range(17, 3, random_neg_five), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'iterate_names': 'i'}) self.assertEqual(self.evaluate(s), (171207,)) def test_tensor_with_extra_test_object_vars(self): class MutableObject(object): field_1 = constant_op.constant(0, dtype=dtypes.int32) field_2 = constant_op.constant(1, dtype=dtypes.int32) state = MutableObject() def body(i): state.field_1 += i state.field_2 *= i def get_state(): return state.field_1, state.field_2 def set_state(loop_vars): state.field_1, state.field_2 = loop_vars control_flow.for_stmt( iter_=constant_op.constant([1, 2, 3, 4]), body=body, extra_test=lambda: state.field_1 < 6, get_state=get_state, set_state=set_state, symbol_names=('state.field_1', 'state.field_2'), opts={}) self.assertEqual(self.evaluate((state.field_1, state.field_2)), (6, 6)) def test_python(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( range(5), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(s, 1234) def test_python_generator_with_extra_test(self): def new_generator(): for i in range(1, 5): yield i gen = new_generator() def run_loop(): s = 0 c = 0 def body(i): nonlocal s, c s = s * 10 + i c += 1 control_flow.for_stmt( gen, extra_test=lambda: c == 0, body=body, get_state=None, set_state=None, symbol_names=('s', 'c'), opts={}) return s, c self.assertEqual(run_loop(), (1, 1)) self.assertEqual(run_loop(), (2, 1)) self.assertEqual(run_loop(), (3, 1)) self.assertEqual(next(gen), 4) def test_python_generator_with_extra_test_no_iterations(self): def new_generator(): for i in range(5): yield i gen = new_generator() def run_loop(): s = 0 def body(i): nonlocal s s = s * 10 + i control_flow.for_stmt( gen, extra_test=lambda: False, body=body, get_state=None, set_state=None, symbol_names=('s',), opts={}) return s self.assertEqual(run_loop(), 0) self.assertEqual(run_loop(), 0) self.assertEqual(next(gen), 0) def test_tf_dataset(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = constant_op.constant(0, dtype=dtypes.int64) control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=None, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(self.evaluate(s), (1234,)) def test_dataset_with_extra_test(self): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = constant_op.constant(0, dtype=dtypes.int64) control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=lambda: s < 3, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(self.evaluate(s), (12,)) def test_dataset_with_extra_test_collection_vars(self): def body(i): nonlocal s l[0] += i s += i def set_state(loop_vars): nonlocal s l[0], s = loop_vars s = constant_op.constant(0, dtype=dtypes.int64) l = [constant_op.constant(0, dtype=dtypes.int64)] control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=lambda: s < 3, body=body, get_state=lambda: (l[0], s), set_state=set_state, symbol_names=('l[0]', 's'), opts={}) self.assertEqual(self.evaluate((l[0], s)), (3, 3)) def test_dataset_with_extra_test_iteration_limiting(self): def body(it): nonlocal i with ops.control_dependencies((control_flow_ops.Assert(i < 3, (i,)),)): i = it def set_state(loop_vars): nonlocal i i, = loop_vars i = constant_op.constant(0, dtype=dtypes.int64) control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=lambda: i < 3, body=body, get_state=lambda: (i,), set_state=set_state, symbol_names=('i',), opts={}) self.assertEqual(self.evaluate(i), (3,)) def test_tf_dataset_no_loop_vars(self): def body(i): v.assign(v.read_value() * 10 + i) v = variables.Variable(0, dtype=dtypes.int64) self.evaluate(v.initializer) @def_function.function def test_fn(): control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=None, body=body, get_state=lambda: (), set_state=lambda _: None, symbol_names=(), opts={}) self.evaluate(test_fn()) self.assertEqual(self.evaluate(v.read_value()), 1234) def test_tf_iterator(self): @def_function.function def test_fn(): def body(i): nonlocal s s = s * 10 + i def set_state(loop_vars): nonlocal s s, = loop_vars s = constant_op.constant(0, dtype=dtypes.int64) control_flow.for_stmt( iter(dataset_ops.Dataset.range(5)), extra_test=None, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) return s self.assertAllEqual(test_fn(), 1234) def test_tf_iterator_shape_invariants(self): @def_function.function def test_fn(): def body(i): nonlocal s s = array_ops.concat([s, [i]], 0) def set_state(loop_vars): nonlocal s s, = loop_vars s = constant_op.constant([], dtype=dtypes.int64) control_flow.for_stmt( iter(dataset_ops.Dataset.range(5)), extra_test=None, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={'shape_invariants': [(s, tensor_shape.TensorShape([None]))]}) return s self.assertAllEqual(test_fn(), [0, 1, 2, 3, 4]) def test_tf_iterator_no_loop_vars(self): def body(i): v.assign(v.read_value() * 10 + i) v = variables.Variable(0, dtype=dtypes.int64) self.evaluate(v.initializer) @def_function.function def test_fn(): control_flow.for_stmt( iter(dataset_ops.Dataset.range(5)), extra_test=None, body=body, get_state=lambda: (), set_state=lambda _: None, symbol_names=(), opts={}) self.evaluate(test_fn()) self.assertEqual(self.evaluate(v.read_value()), 1234) def test_tf_ragged_tensor(self): def body(i): nonlocal s s = s * 10 + i[0] def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 control_flow.for_stmt( ragged_factory_ops.constant([[1], [2, 4], [3]]), extra_test=None, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(self.evaluate(s), (123,)) def test_tf_ragged_tensor_higher_dimensional(self): def body(i): nonlocal s s = s * 10 + i[0][0] def set_state(loop_vars): nonlocal s s, = loop_vars s = 0 ragged_3d = [ [[1], [1, 1], [1]], [[2], [2]], ] control_flow.for_stmt( ragged_factory_ops.constant(ragged_3d), extra_test=None, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) self.assertEqual(self.evaluate(s), (12,)) def test_tf_ragged_tensor_no_loop_vars(self): v = variables.Variable(0, dtype=dtypes.int32) self.evaluate(v.initializer) def body(i): v.assign(v.read_value() * 10 + i[0]) @def_function.function(autograph=False) def test_fn(): control_flow.for_stmt( ragged_factory_ops.constant([[1], [2, 4], [3]]), extra_test=None, body=body, get_state=lambda: (), set_state=lambda _: None, symbol_names=(), opts={}) self.evaluate(test_fn()) self.assertEqual(self.evaluate(v.read_value()), 123) def _basic_loop(self, init_value, body_fn): def body(i): nonlocal s s = body_fn(i, s) def set_state(loop_vars): nonlocal s s, = loop_vars s = init_value control_flow.for_stmt( constant_op.constant([1, 2, 3, 4]), extra_test=lambda: True, body=body, get_state=lambda: (s,), set_state=set_state, symbol_names=('s',), opts={}) return s def test_tensor_illegal_input(self): with self.assertRaisesRegex(ValueError, '"s" may not be None'): self._basic_loop(None, lambda i, s: s) with self.assertRaisesRegex(ValueError, '"s" must be defined'): self._basic_loop(variable_operators.Undefined(''), lambda i, s: s) def test_tensor_none_output(self): with self.assertRaisesRegex(ValueError, '"s" is None at the end'): self._basic_loop(0, lambda i, s: None) def test_tensor_dtype_change(self): with self.assertRaisesRegex(TypeError, '"s".* dtype float32 after'): self._basic_loop(0, lambda i, s: 1.0) def test_tensor_shape_change(self): with self.assertRaisesRegex(ValueError, r'"s".* shape \(1,\) after'): self._basic_loop(0, lambda i, s: np.array([1], dtype=np.int32)) @test_util.run_all_in_graph_and_eager_modes class WhileLoopTest(test.TestCase): def test_tensor(self): def body(): nonlocal i, s s = s * 10 + i i += 1 def set_state(loop_vars): nonlocal i, s i, s = loop_vars i = 0 n = constant_op.constant(5) s = 0 control_flow.while_stmt( test=lambda: i < n, body=body, get_state=lambda: (i, s), set_state=set_state, symbol_names=('i', 's'), opts={}) self.assertEqual(self.evaluate((i, s)), (5, 1234)) def test_tensor_with_side_effecting_condition(self): v = variables.Variable(0) @def_function.function def test_fn(): def cond(): v.assign(v.read_value() * 10 + i) return i < n def body(): nonlocal i i += 1 def set_state(loop_vars): nonlocal i i, = loop_vars i = 0 n = constant_op.constant(5) control_flow.while_stmt( test=cond, body=body, get_state=lambda: (i,), set_state=set_state, symbol_names=('i',), opts={}) return i self.evaluate(v.initializer) self.assertEqual(self.evaluate(test_fn()), (5,)) self.assertEqual(self.evaluate(v), (12345,)) def test_tensor_with_python_state(self): class MutableObject(object): field = constant_op.constant(0, dtype=dtypes.int32) state = MutableObject() def body(): nonlocal i state.field = state.field * 10 + i i += 1 def set_state(loop_vars): nonlocal i i, state.field = loop_vars i = 0 n = constant_op.constant(5) control_flow.while_stmt( test=lambda: i < n, body=body, get_state=lambda: (i, state.field), set_state=set_state, symbol_names=('i', 'state.field'), opts={}) self.assertEqual(self.evaluate((i, state.field)), (5, 1234)) def test_python(self): def body(): nonlocal i, s s = s * 10 + i i += 1 i = 0 s = 0 n = 5 control_flow.while_stmt( test=lambda: i < n, body=body, get_state=None, set_state=None, symbol_names=('i', 's'), opts={}) self.assertEqual(s, 1234) def test_python_with_tensor_state(self): def body(): nonlocal i, s s = s * 10 + i i += 1 i = 0 s = constant_op.constant(0) n = 5 control_flow.while_stmt( test=lambda: i < n, body=body, get_state=None, set_state=None, symbol_names=('i', 's'), opts={}) self.assertEqual(i, 5) self.assertEqual(self.evaluate(s), 1234) def test_python_while_infinite(self): if not __debug__: self.skipTest('Feature disabled in optimized mode.') with test.mock.patch.object(control_flow, 'PYTHON_MAX_ITERATIONS', 100): with self.assertRaisesRegexp(ValueError, 'iteration limit'): control_flow.while_stmt( test=lambda: True, body=lambda: None, get_state=None, set_state=None, symbol_names=(), opts={}) def test_python_for_infinite(self): if not __debug__: self.skipTest('Feature disabled in optimized mode.') with test.mock.patch.object(control_flow, 'PYTHON_MAX_ITERATIONS', 100): with self.assertRaisesRegexp(ValueError, 'iteration limit'): control_flow.for_stmt( iter_=range(101), extra_test=None, body=lambda i: None, get_state=None, set_state=None, symbol_names=(), opts={}) def test_python_while_large_unroll_warning(self): if not __debug__: self.skipTest('Feature disabled in optimized mode.') with test.mock.patch.object( control_flow, 'INEFFICIENT_UNROLL_MIN_ITERATIONS', 10): with ops.Graph().as_default(): out_capturer = six.StringIO() with test.mock.patch.object(sys, 'stdout', out_capturer): with test.mock.patch.object(ag_logging, 'echo_log_to_stdout', True): def custom_iterator(): for i in range(11): c = constant_op.constant(i) yield c i = 0 control_flow.for_stmt( iter_=custom_iterator(), extra_test=None, body=lambda i: None, get_state=None, set_state=None, symbol_names=(), opts={}) self.assertTrue(re.match( r'.* Large unrolled loop.*Const.*', out_capturer.getvalue())) def test_python_for_large_unroll_warning(self): if not __debug__: self.skipTest('Feature disabled in optimized mode.') with test.mock.patch.object( control_flow, 'INEFFICIENT_UNROLL_MIN_ITERATIONS', 10): with ops.Graph().as_default(): out_capturer = six.StringIO() with test.mock.patch.object(sys, 'stdout', out_capturer): with test.mock.patch.object(ag_logging, 'echo_log_to_stdout', True): def body(): nonlocal i gen_math_ops.add(i, 1) i += 1 i = 0 control_flow.while_stmt( test=lambda: i < 100, body=body, get_state=None, set_state=None, symbol_names=('i',), opts={}) self.assertTrue(re.match( r'.* Large unrolled loop.*Add.*', out_capturer.getvalue())) def _basic_loop(self, init_value, body_fn): def body(): nonlocal i, s s = body_fn(i, s) i += 1 def set_state(loop_vars): nonlocal i, s i, s = loop_vars i = 0 n = constant_op.constant(5) s = init_value control_flow.while_stmt( test=lambda: i < n, body=body, get_state=lambda: (i, s), set_state=set_state, symbol_names=('i', 's'), opts={}) return s def test_tensor_illegal_input(self): with self.assertRaisesRegex(ValueError, '"s" may not be None'): self._basic_loop(None, lambda i, s: s) with self.assertRaisesRegex(ValueError, '"s" must be defined'): self._basic_loop(variable_operators.Undefined(''), lambda i, s: s) def test_tensor_none_output(self): with self.assertRaisesRegex(ValueError, '"s" is None at the end'): self._basic_loop(0, lambda i, s: None) def test_tensor_dtype_change(self): with self.assertRaisesRegex(TypeError, '"s".* dtype float32 after'): self._basic_loop(0, lambda i, s: 1.0) def test_tensor_shape_change(self): with self.assertRaisesRegex(ValueError, r'"s".* shape \(1,\) after'): self._basic_loop(0, lambda i, s: np.array([1], dtype=np.int32)) @test_util.run_all_in_graph_and_eager_modes class IfStmtTest(test.TestCase): def test_tensor(self): def test_fn(cond): return control_flow.if_stmt( cond=cond, body=lambda: constant_op.constant(1), orelse=lambda: constant_op.constant(-1), get_state=lambda: (), set_state=lambda _: None, basic_symbol_names=('_',), composite_symbol_names=()) self.assertEqual(1, self.evaluate(test_fn(constant_op.constant(True)))) self.assertEqual(-1, self.evaluate(test_fn(constant_op.constant(False)))) def test_tensor_multiple_returns(self): def test_fn(cond): return control_flow.if_stmt( cond=cond, body=lambda: (constant_op.constant(1), constant_op.constant(2)), orelse=lambda: (constant_op.constant(-1), constant_op.constant(-2)), get_state=lambda: (), set_state=lambda _: None, basic_symbol_names=('_',), composite_symbol_names=()) self.assertEqual((1, 2), self.evaluate(test_fn(constant_op.constant(True)))) self.assertEqual((-1, -2), self.evaluate(test_fn(constant_op.constant(False)))) def test_python(self): def test_fn(cond): return control_flow.if_stmt( cond=cond, body=lambda: 1, orelse=lambda: -1, get_state=lambda: (), set_state=lambda _: None, basic_symbol_names=('_',), composite_symbol_names=()) self.assertEqual(1, test_fn(True)) self.assertEqual(-1, test_fn(False)) def test_python_multiple_returns(self): def test_fn(cond): return control_flow.if_stmt( cond=cond, body=lambda: (1, 2), orelse=lambda: (-1, -2), get_state=lambda: (), set_state=lambda _: None, basic_symbol_names=('_',), composite_symbol_names=()) self.assertEqual((1, 2), test_fn(True)) self.assertEqual((-1, -2), test_fn(False)) def _basic_cond(self, true_value, false_value): with func_graph.FuncGraph('tmp').as_default(): return control_flow.if_stmt( cond=constant_op.constant(True), body=true_value, orelse=false_value, get_state=lambda: (), set_state=lambda _: None, basic_symbol_names=('s',), composite_symbol_names=()) def test_tensor_none_output(self): with self.assertRaisesRegex( ValueError, '"s" is None at the end of the TRUE branch'): self._basic_cond(lambda: None, lambda: 1) with self.assertRaisesRegex( ValueError, '"s" is None at the end of the FALSE branch'): self._basic_cond(lambda: 1, lambda: None) def test_tensor_undefined_output(self): with self.assertRaisesRegex( ValueError, "must also be initialized in the if.*'s'"): self._basic_cond(lambda: variable_operators.Undefined('s'), lambda: 1) with self.assertRaisesRegex( ValueError, "must also be initialized in the else.*'s'"): self._basic_cond(lambda: 1, lambda: variable_operators.Undefined('s')) def test_tensor_dtype_change(self): with self.assertRaisesRegex(TypeError, '"s" has dtype int32.*but.*float32'): self._basic_cond(lambda: 1, lambda: 1.0) if __name__ == '__main__': test.main()
true
true
1c440820431ca1ad195527bd8221ac39c820de89
1,174
py
Python
pcdet/models/model_utils/layers.py
collector-m/H-23D_R-CNN
40c89c7a6910b738f7e4ed1d0dbb32b1ca99a016
[ "Apache-2.0" ]
49
2021-08-02T02:04:32.000Z
2022-03-31T03:24:23.000Z
pcdet/models/model_utils/layers.py
collector-m/H-23D_R-CNN
40c89c7a6910b738f7e4ed1d0dbb32b1ca99a016
[ "Apache-2.0" ]
5
2021-08-11T06:29:14.000Z
2022-01-23T02:59:29.000Z
pcdet/models/model_utils/layers.py
collector-m/H-23D_R-CNN
40c89c7a6910b738f7e4ed1d0dbb32b1ca99a016
[ "Apache-2.0" ]
3
2021-08-08T12:11:31.000Z
2021-11-30T15:07:32.000Z
import torch import torch.nn as nn class ConvBNReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, eps=1e-3, momentum=0.01): super().__init__() self.block = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=kernel_size//2, bias=False), nn.BatchNorm2d(out_channels, eps=eps, momentum=momentum), nn.ReLU(inplace=True) ) def forward(self, x): out = self.block(x) return out class SeparateConvBNReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, eps=1e-3, momentum=0.01): super().__init__() self.block = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, \ padding=kernel_size//2, groups=in_channels, bias=False), nn.BatchNorm2d(out_channels, eps=eps, momentum=momentum), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, 1, stride=1, padding=0, bias=False), nn.BatchNorm2d(out_channels, eps=eps, momentum=momentum), nn.ReLU(inplace=True) ) def forward(self, x): out = self.block(x) return out
32.611111
107
0.681431
import torch import torch.nn as nn class ConvBNReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, eps=1e-3, momentum=0.01): super().__init__() self.block = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=kernel_size//2, bias=False), nn.BatchNorm2d(out_channels, eps=eps, momentum=momentum), nn.ReLU(inplace=True) ) def forward(self, x): out = self.block(x) return out class SeparateConvBNReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, eps=1e-3, momentum=0.01): super().__init__() self.block = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, \ padding=kernel_size//2, groups=in_channels, bias=False), nn.BatchNorm2d(out_channels, eps=eps, momentum=momentum), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, 1, stride=1, padding=0, bias=False), nn.BatchNorm2d(out_channels, eps=eps, momentum=momentum), nn.ReLU(inplace=True) ) def forward(self, x): out = self.block(x) return out
true
true
1c440acc35d3ac6fc5cec55840701662ea24566a
2,257
py
Python
lib/GenomeImporter/GenomeImporterClient.py
ModelSEED/GenomeImporter
c7af3e37e194315efa59276eed026373b13af658
[ "MIT" ]
null
null
null
lib/GenomeImporter/GenomeImporterClient.py
ModelSEED/GenomeImporter
c7af3e37e194315efa59276eed026373b13af658
[ "MIT" ]
null
null
null
lib/GenomeImporter/GenomeImporterClient.py
ModelSEED/GenomeImporter
c7af3e37e194315efa59276eed026373b13af658
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- ############################################################ # # Autogenerated by the KBase type compiler - # any changes made here will be overwritten # ############################################################ from __future__ import print_function # the following is a hack to get the baseclient to import whether we're in a # package or not. This makes pep8 unhappy hence the annotations. try: # baseclient and this client are in a package from .baseclient import BaseClient as _BaseClient # @UnusedImport except: # no they aren't from baseclient import BaseClient as _BaseClient # @Reimport class GenomeImporter(object): def __init__( self, url=None, timeout=30 * 60, user_id=None, password=None, token=None, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url is None: raise ValueError('A url is required') self._service_ver = None self._client = _BaseClient( url, timeout=timeout, user_id=user_id, password=password, token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def import_external_genome(self, params, context=None): """ Function to import a list of genomes from a specified source :param params: instance of type "ImportGenomeParams" (Input parameters for the import_external_genome function) -> structure: parameter "genome_ids" of String, parameter "source" of String, parameter "workspace" of String :returns: instance of type "ImportGenomeResults" (Output structure for the import_external_genome function) -> structure: parameter "report_name" of String, parameter "report_ref" of String """ return self._client.call_method( 'GenomeImporter.import_external_genome', [params], self._service_ver, context) def status(self, context=None): return self._client.call_method('GenomeImporter.status', [], self._service_ver, context)
41.796296
79
0.633584
true
true
1c440ae2da9545be2fbe11a7cf25b19d6daad111
2,515
py
Python
alttprbot_discord/util/embed_formatter.py
skyscooby/sahasrahbot
16fce824bd024f6357a8f260e2447ba477dcdac2
[ "MIT" ]
15
2019-10-15T21:35:59.000Z
2022-03-31T19:49:39.000Z
alttprbot_discord/util/embed_formatter.py
skyscooby/sahasrahbot
16fce824bd024f6357a8f260e2447ba477dcdac2
[ "MIT" ]
12
2019-10-06T01:33:13.000Z
2022-03-10T14:35:16.000Z
alttprbot_discord/util/embed_formatter.py
skyscooby/sahasrahbot
16fce824bd024f6357a8f260e2447ba477dcdac2
[ "MIT" ]
28
2019-11-25T23:49:56.000Z
2022-03-10T04:03:31.000Z
import discord def config(ctx, configdict): embed = discord.Embed( title="Server Configuration", description="List of configuration parameters for this server.", color=discord.Colour.teal()) for item in configdict: embed.add_field(name=item['parameter'], value=item['value']) return embed async def reaction_group_list(ctx, reaction_groups): embed = discord.Embed( title="Server Reaction Groups", description="List of server reaction groups.", color=discord.Colour.gold()) for item in reaction_groups: channel = ctx.guild.get_channel(item['channel_id']) message = await channel.fetch_message(item['message_id']) name = '{id}: {name}'.format( id=item['id'], name=item['name'] ) value = 'Description: {description}\n\nChannel: {channel}\nMessage Link: {messagelink}\nBot Managed: {botmanaged}'.format( description=item['description'], channel=channel.mention, messagelink=message.jump_url, botmanaged='something') embed.add_field(name=name, value=value, inline=False) return embed def reaction_role_list(ctx, reaction_roles): embed = discord.Embed( title="Reaction Roles for Group", description="List of reaction roles for specified group.", color=discord.Colour.gold()) for item in reaction_roles: role_obj = ctx.guild.get_role(item['role_id']) name = '{id}: {name}'.format( id=item['id'], name=item['name'] ) value = 'Role: {role}\nDescription: {description}\nEmoji: {emoji}\nProtected: {protected}'.format( role=role_obj, description=item['description'], emoji=item['emoji'], protected=bool( item['protect_mentions'])) embed.add_field(name=name, value=value, inline=False) return embed def reaction_menu(ctx, group, roles): embed = discord.Embed( title=group['name'], description=group['description'], color=discord.Colour.green(), timestamp=discord.utils.utcnow() ) value = '' for role in roles: value = value + '{emoji} `{name}`: {description}\n'.format( emoji=role['emoji'], name=role['name'], description=role['description'] ) embed.add_field(name='Roles', value=value, inline=False) embed.set_footer(text=group['id']) return embed
37.537313
131
0.611531
import discord def config(ctx, configdict): embed = discord.Embed( title="Server Configuration", description="List of configuration parameters for this server.", color=discord.Colour.teal()) for item in configdict: embed.add_field(name=item['parameter'], value=item['value']) return embed async def reaction_group_list(ctx, reaction_groups): embed = discord.Embed( title="Server Reaction Groups", description="List of server reaction groups.", color=discord.Colour.gold()) for item in reaction_groups: channel = ctx.guild.get_channel(item['channel_id']) message = await channel.fetch_message(item['message_id']) name = '{id}: {name}'.format( id=item['id'], name=item['name'] ) value = 'Description: {description}\n\nChannel: {channel}\nMessage Link: {messagelink}\nBot Managed: {botmanaged}'.format( description=item['description'], channel=channel.mention, messagelink=message.jump_url, botmanaged='something') embed.add_field(name=name, value=value, inline=False) return embed def reaction_role_list(ctx, reaction_roles): embed = discord.Embed( title="Reaction Roles for Group", description="List of reaction roles for specified group.", color=discord.Colour.gold()) for item in reaction_roles: role_obj = ctx.guild.get_role(item['role_id']) name = '{id}: {name}'.format( id=item['id'], name=item['name'] ) value = 'Role: {role}\nDescription: {description}\nEmoji: {emoji}\nProtected: {protected}'.format( role=role_obj, description=item['description'], emoji=item['emoji'], protected=bool( item['protect_mentions'])) embed.add_field(name=name, value=value, inline=False) return embed def reaction_menu(ctx, group, roles): embed = discord.Embed( title=group['name'], description=group['description'], color=discord.Colour.green(), timestamp=discord.utils.utcnow() ) value = '' for role in roles: value = value + '{emoji} `{name}`: {description}\n'.format( emoji=role['emoji'], name=role['name'], description=role['description'] ) embed.add_field(name='Roles', value=value, inline=False) embed.set_footer(text=group['id']) return embed
true
true
1c440b1e1de464dfdff22caf8ef6161d4e39e699
5,094
py
Python
tests/python/contrib/test_cmsisnn/test_pooling.py
jwfromm/relax
f120282007778706199243ee88b50697c2b9550c
[ "Apache-2.0" ]
2,084
2020-11-25T02:31:53.000Z
2022-03-31T11:33:47.000Z
tests/python/contrib/test_cmsisnn/test_pooling.py
jwfromm/relax
f120282007778706199243ee88b50697c2b9550c
[ "Apache-2.0" ]
3,022
2020-11-24T14:02:31.000Z
2022-03-31T23:55:31.000Z
tests/python/contrib/test_cmsisnn/test_pooling.py
jwfromm/relax
f120282007778706199243ee88b50697c2b9550c
[ "Apache-2.0" ]
977
2020-11-25T00:54:52.000Z
2022-03-31T12:47:08.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """CMSIS-NN integration tests: Conv2D""" import itertools import numpy as np import pytest import tvm from tvm import relay from tvm.relay.op.contrib import cmsisnn from tests.python.relay.aot.aot_test_utils import ( AOTTestModel, AOT_CORSTONE300_RUNNER, AOT_DEFAULT_RUNNER, generate_ref_data, compile_and_run, ) from utils import ( skip_if_no_reference_system, make_module, count_num_calls, get_range_for_dtype_str, get_same_padding, get_conv2d_qnn_params, make_qnn_relu, ) def make_model(pool_op, shape, pool_size, strides, padding, dtype, scale, zero_point, relu_type): """Return a model and any parameters it may have""" op = relay.var("input", shape=shape, dtype=dtype) pad_ = (0, 0, 0, 0) if padding == "SAME": dilation = (1, 1) pad_ = get_same_padding((shape[1], shape[2]), pool_size, dilation, strides) op = relay.nn.pad( op, pad_width=[(0, 0), (pad_[0], pad_[2]), (pad_[1], pad_[3]), (0, 0)], pad_value=zero_point, pad_mode="constant", ) if pool_op == relay.nn.avg_pool2d: op = relay.cast(op, "int32") op = pool_op( op, pool_size=pool_size, strides=strides, padding=pad_, ceil_mode=True, layout="NHWC" ) if pool_op == relay.nn.avg_pool2d: op = relay.cast(op, dtype) op = make_qnn_relu(op, relu_type, scale, zero_point, dtype) return op @tvm.testing.requires_cmsisnn @pytest.mark.parametrize("in_shape", [(1, 28, 28, 12), (1, 64, 100, 4)]) @pytest.mark.parametrize( "pool_size, strides, padding", [((3, 3), (2, 2), "SAME"), ((2, 2), (1, 1), "VALID")] ) @pytest.mark.parametrize("relu_type", ["RELU"]) @pytest.mark.parametrize("pool_type", [relay.nn.max_pool2d, relay.nn.avg_pool2d]) @pytest.mark.parametrize("zero_point, scale", [(-34, 0.0256)]) def test_op_int8( in_shape, pool_size, strides, padding, relu_type, pool_type, zero_point, scale, ): interface_api = "c" use_unpacked_api = True test_runner = AOT_CORSTONE300_RUNNER dtype = "int8" model = make_model( pool_type, in_shape, pool_size, strides, padding, dtype, scale, zero_point, relu_type, ) orig_mod = make_module(model) cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod) # validate pattern matching attrs = [ cmsisnn_mod[var.name_hint].attrs for var in cmsisnn_mod.get_global_vars() if cmsisnn_mod[var.name_hint].attrs ] assert any(attrs), "At least one function with external attributes was expected." compilers = [ key == "Compiler" and value == "cmsis-nn" for attr in attrs for key, value in attr.items() ] assert any(compilers), "Module does not contain function for cmsisnn target." assert count_num_calls(orig_mod) == count_num_calls( cmsisnn_mod ), "Number of calls changed during partitioning" # validate the output in_min, in_max = get_range_for_dtype_str(dtype) np.random.seed(0) inputs = { "input": np.random.randint(in_min, high=in_max, size=in_shape, dtype="int8"), } output_list = generate_ref_data(orig_mod["main"], inputs) compile_and_run( AOTTestModel( module=cmsisnn_mod, inputs=inputs, outputs=output_list, params=None, output_tolerance=1, ), test_runner, interface_api, use_unpacked_api, ) @tvm.testing.requires_cmsisnn def test_invalid_parameters(): model = make_model( pool_op=relay.nn.avg_pool2d, shape=(1, 28, 28, 12), pool_size=(1, 1), strides=(1, 1), padding="VALID", dtype="uint8", scale=1, zero_point=-33, relu_type="RELU", ) orig_mod = make_module(model) cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod) # validate pattern matching attrs = [ cmsisnn_mod[var.name_hint].attrs for var in cmsisnn_mod.get_global_vars() if cmsisnn_mod[var.name_hint].attrs ] assert not any(attrs), "No function should have an external attribute." if __name__ == "__main__": sys.exit(pytest.main([__file__] + sys.argv[1:]))
29.275862
98
0.65371
import itertools import numpy as np import pytest import tvm from tvm import relay from tvm.relay.op.contrib import cmsisnn from tests.python.relay.aot.aot_test_utils import ( AOTTestModel, AOT_CORSTONE300_RUNNER, AOT_DEFAULT_RUNNER, generate_ref_data, compile_and_run, ) from utils import ( skip_if_no_reference_system, make_module, count_num_calls, get_range_for_dtype_str, get_same_padding, get_conv2d_qnn_params, make_qnn_relu, ) def make_model(pool_op, shape, pool_size, strides, padding, dtype, scale, zero_point, relu_type): op = relay.var("input", shape=shape, dtype=dtype) pad_ = (0, 0, 0, 0) if padding == "SAME": dilation = (1, 1) pad_ = get_same_padding((shape[1], shape[2]), pool_size, dilation, strides) op = relay.nn.pad( op, pad_width=[(0, 0), (pad_[0], pad_[2]), (pad_[1], pad_[3]), (0, 0)], pad_value=zero_point, pad_mode="constant", ) if pool_op == relay.nn.avg_pool2d: op = relay.cast(op, "int32") op = pool_op( op, pool_size=pool_size, strides=strides, padding=pad_, ceil_mode=True, layout="NHWC" ) if pool_op == relay.nn.avg_pool2d: op = relay.cast(op, dtype) op = make_qnn_relu(op, relu_type, scale, zero_point, dtype) return op @tvm.testing.requires_cmsisnn @pytest.mark.parametrize("in_shape", [(1, 28, 28, 12), (1, 64, 100, 4)]) @pytest.mark.parametrize( "pool_size, strides, padding", [((3, 3), (2, 2), "SAME"), ((2, 2), (1, 1), "VALID")] ) @pytest.mark.parametrize("relu_type", ["RELU"]) @pytest.mark.parametrize("pool_type", [relay.nn.max_pool2d, relay.nn.avg_pool2d]) @pytest.mark.parametrize("zero_point, scale", [(-34, 0.0256)]) def test_op_int8( in_shape, pool_size, strides, padding, relu_type, pool_type, zero_point, scale, ): interface_api = "c" use_unpacked_api = True test_runner = AOT_CORSTONE300_RUNNER dtype = "int8" model = make_model( pool_type, in_shape, pool_size, strides, padding, dtype, scale, zero_point, relu_type, ) orig_mod = make_module(model) cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod) attrs = [ cmsisnn_mod[var.name_hint].attrs for var in cmsisnn_mod.get_global_vars() if cmsisnn_mod[var.name_hint].attrs ] assert any(attrs), "At least one function with external attributes was expected." compilers = [ key == "Compiler" and value == "cmsis-nn" for attr in attrs for key, value in attr.items() ] assert any(compilers), "Module does not contain function for cmsisnn target." assert count_num_calls(orig_mod) == count_num_calls( cmsisnn_mod ), "Number of calls changed during partitioning" in_min, in_max = get_range_for_dtype_str(dtype) np.random.seed(0) inputs = { "input": np.random.randint(in_min, high=in_max, size=in_shape, dtype="int8"), } output_list = generate_ref_data(orig_mod["main"], inputs) compile_and_run( AOTTestModel( module=cmsisnn_mod, inputs=inputs, outputs=output_list, params=None, output_tolerance=1, ), test_runner, interface_api, use_unpacked_api, ) @tvm.testing.requires_cmsisnn def test_invalid_parameters(): model = make_model( pool_op=relay.nn.avg_pool2d, shape=(1, 28, 28, 12), pool_size=(1, 1), strides=(1, 1), padding="VALID", dtype="uint8", scale=1, zero_point=-33, relu_type="RELU", ) orig_mod = make_module(model) cmsisnn_mod = cmsisnn.partition_for_cmsisnn(orig_mod) attrs = [ cmsisnn_mod[var.name_hint].attrs for var in cmsisnn_mod.get_global_vars() if cmsisnn_mod[var.name_hint].attrs ] assert not any(attrs), "No function should have an external attribute." if __name__ == "__main__": sys.exit(pytest.main([__file__] + sys.argv[1:]))
true
true
1c440b708248398fce0129be28a565447b2b4b8c
8,025
py
Python
pyEX/tests/test_refdata.py
andrescevp/pyEX
4c8daa411b01133a292d341a78f6e1b80cc2be99
[ "Apache-2.0" ]
null
null
null
pyEX/tests/test_refdata.py
andrescevp/pyEX
4c8daa411b01133a292d341a78f6e1b80cc2be99
[ "Apache-2.0" ]
null
null
null
pyEX/tests/test_refdata.py
andrescevp/pyEX
4c8daa411b01133a292d341a78f6e1b80cc2be99
[ "Apache-2.0" ]
null
null
null
# for Coverage from mock import patch, MagicMock class TestAll: def setup(self): pass # setup() before each test method def teardown(self): pass # teardown() after each test method @classmethod def setup_class(cls): pass # setup_class() before any methods in this class @classmethod def teardown_class(cls): pass # teardown_class() after any methods in this class def test_symbols(self): from pyEX.refdata import ( symbols, iexSymbols, mutualFundSymbols, otcSymbols, internationalSymbols, fxSymbols, ) with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 symbols() iexSymbols() mutualFundSymbols() otcSymbols() internationalSymbols() internationalSymbols("GB") internationalSymbols(exchange="test") mock.return_value.json = MagicMock( return_value={"currencies": [], "pairs": []} ) fxSymbols() def test_symbolsDF(self): from pyEX.refdata import symbolsDF from pyEX import Client with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) c = Client(version="sandbox") symbolsDF() c.iexSymbolsDF() c.mutualFundSymbolsDF() c.otcSymbolsDF() c.internationalSymbolsDF() c.internationalSymbolsDF("GB") c.internationalSymbolsDF(exchange="test") c.symbolsList() c.iexSymbolsList() c.mutualFundSymbolsList() c.otcSymbolsList() c.internationalSymbolsList() c.internationalSymbolsList("GB") c.internationalSymbolsList(exchange="test") mock.return_value.json = MagicMock( return_value={"currencies": [], "pairs": []} ) c.fxSymbolsDF() c.fxSymbolsList() def test_calendar(self): from pyEX import Client with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) c = Client(version="sandbox") c.calendar() c.holidays() def test_calendarDF(self): from pyEX import Client with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) c = Client(version="sandbox") c.calendarDF() c.holidaysDF() def test_corporateActions(self): from pyEX.refdata import corporateActions with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 corporateActions() corporateActions("20170202") def test_corporateActionsDF(self): from pyEX.refdata import corporateActionsDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) corporateActionsDF() def test_dividends(self): from pyEX.refdata import refDividends with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 refDividends() refDividends("20170202") def test_dividendsDF(self): from pyEX.refdata import refDividendsDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) refDividendsDF() def test_nextDayExtDate(self): from pyEX.refdata import nextDayExtDate with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 nextDayExtDate() nextDayExtDate("20170202") def test_nextDayExtDateDF(self): from pyEX.refdata import nextDayExtDateDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) nextDayExtDateDF() def test_directory(self): from pyEX.refdata import directory with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 directory() directory("20170202") def test_directoryDF(self): from pyEX.refdata import directoryDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) directoryDF() def test_sectors(self): from pyEX.refdata import sectors with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 sectors() def test_sectorsDF(self): from pyEX.refdata import sectorsDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) sectorsDF() def test_exchanges(self): from pyEX.refdata import exchanges, internationalExchanges with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 exchanges() internationalExchanges() def test_exchangesDF(self): from pyEX.refdata import exchangesDF, internationalExchangesDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) exchangesDF() internationalExchangesDF() def test_figi(self): from pyEX.refdata import figi with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 figi("") def test_figiDF(self): from pyEX.refdata import figiDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) figiDF("") def test_tags(self): from pyEX.refdata import tags with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 tags() def test_tagsDF(self): from pyEX.refdata import tagsDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) tagsDF()
33.024691
70
0.594891
from mock import patch, MagicMock class TestAll: def setup(self): pass def teardown(self): pass @classmethod def setup_class(cls): pass @classmethod def teardown_class(cls): pass def test_symbols(self): from pyEX.refdata import ( symbols, iexSymbols, mutualFundSymbols, otcSymbols, internationalSymbols, fxSymbols, ) with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 symbols() iexSymbols() mutualFundSymbols() otcSymbols() internationalSymbols() internationalSymbols("GB") internationalSymbols(exchange="test") mock.return_value.json = MagicMock( return_value={"currencies": [], "pairs": []} ) fxSymbols() def test_symbolsDF(self): from pyEX.refdata import symbolsDF from pyEX import Client with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) c = Client(version="sandbox") symbolsDF() c.iexSymbolsDF() c.mutualFundSymbolsDF() c.otcSymbolsDF() c.internationalSymbolsDF() c.internationalSymbolsDF("GB") c.internationalSymbolsDF(exchange="test") c.symbolsList() c.iexSymbolsList() c.mutualFundSymbolsList() c.otcSymbolsList() c.internationalSymbolsList() c.internationalSymbolsList("GB") c.internationalSymbolsList(exchange="test") mock.return_value.json = MagicMock( return_value={"currencies": [], "pairs": []} ) c.fxSymbolsDF() c.fxSymbolsList() def test_calendar(self): from pyEX import Client with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) c = Client(version="sandbox") c.calendar() c.holidays() def test_calendarDF(self): from pyEX import Client with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) c = Client(version="sandbox") c.calendarDF() c.holidaysDF() def test_corporateActions(self): from pyEX.refdata import corporateActions with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 corporateActions() corporateActions("20170202") def test_corporateActionsDF(self): from pyEX.refdata import corporateActionsDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) corporateActionsDF() def test_dividends(self): from pyEX.refdata import refDividends with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 refDividends() refDividends("20170202") def test_dividendsDF(self): from pyEX.refdata import refDividendsDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) refDividendsDF() def test_nextDayExtDate(self): from pyEX.refdata import nextDayExtDate with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 nextDayExtDate() nextDayExtDate("20170202") def test_nextDayExtDateDF(self): from pyEX.refdata import nextDayExtDateDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) nextDayExtDateDF() def test_directory(self): from pyEX.refdata import directory with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 directory() directory("20170202") def test_directoryDF(self): from pyEX.refdata import directoryDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) directoryDF() def test_sectors(self): from pyEX.refdata import sectors with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 sectors() def test_sectorsDF(self): from pyEX.refdata import sectorsDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) sectorsDF() def test_exchanges(self): from pyEX.refdata import exchanges, internationalExchanges with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 exchanges() internationalExchanges() def test_exchangesDF(self): from pyEX.refdata import exchangesDF, internationalExchangesDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) exchangesDF() internationalExchangesDF() def test_figi(self): from pyEX.refdata import figi with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 figi("") def test_figiDF(self): from pyEX.refdata import figiDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) figiDF("") def test_tags(self): from pyEX.refdata import tags with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 tags() def test_tagsDF(self): from pyEX.refdata import tagsDF with patch("requests.get") as mock, patch("pickle.dump"): mock.return_value = MagicMock() mock.return_value.status_code = 200 mock.return_value.json = MagicMock(return_value=[]) tagsDF()
true
true
1c440b889b1465133c187d8b8d2d064e1d116e83
6,186
py
Python
pandas/tests/resample/test_timedelta.py
CJL89/pandas
6210077d32a9e9675526ea896e6d1f9189629d4a
[ "BSD-3-Clause" ]
603
2020-12-23T13:49:32.000Z
2022-03-31T23:38:03.000Z
pandas/tests/resample/test_timedelta.py
CJL89/pandas
6210077d32a9e9675526ea896e6d1f9189629d4a
[ "BSD-3-Clause" ]
387
2020-12-15T14:54:04.000Z
2022-03-31T07:00:21.000Z
pandas/tests/resample/test_timedelta.py
CJL89/pandas
6210077d32a9e9675526ea896e6d1f9189629d4a
[ "BSD-3-Clause" ]
35
2021-03-26T03:12:04.000Z
2022-03-23T10:15:10.000Z
from datetime import timedelta import numpy as np import pytest import pandas as pd from pandas import DataFrame, Series import pandas._testing as tm from pandas.core.indexes.timedeltas import timedelta_range def test_asfreq_bug(): df = DataFrame(data=[1, 3], index=[timedelta(), timedelta(minutes=3)]) result = df.resample("1T").asfreq() expected = DataFrame( data=[1, np.nan, np.nan, 3], index=timedelta_range("0 day", periods=4, freq="1T"), ) tm.assert_frame_equal(result, expected) def test_resample_with_nat(): # GH 13223 index = pd.to_timedelta(["0s", pd.NaT, "2s"]) result = DataFrame({"value": [2, 3, 5]}, index).resample("1s").mean() expected = DataFrame( {"value": [2.5, np.nan, 5.0]}, index=timedelta_range("0 day", periods=3, freq="1S"), ) tm.assert_frame_equal(result, expected) def test_resample_as_freq_with_subperiod(): # GH 13022 index = timedelta_range("00:00:00", "00:10:00", freq="5T") df = DataFrame(data={"value": [1, 5, 10]}, index=index) result = df.resample("2T").asfreq() expected_data = {"value": [1, np.nan, np.nan, np.nan, np.nan, 10]} expected = DataFrame( data=expected_data, index=timedelta_range("00:00:00", "00:10:00", freq="2T") ) tm.assert_frame_equal(result, expected) def test_resample_with_timedeltas(): expected = DataFrame({"A": np.arange(1480)}) expected = expected.groupby(expected.index // 30).sum() expected.index = pd.timedelta_range("0 days", freq="30T", periods=50) df = DataFrame( {"A": np.arange(1480)}, index=pd.to_timedelta(np.arange(1480), unit="T") ) result = df.resample("30T").sum() tm.assert_frame_equal(result, expected) s = df["A"] result = s.resample("30T").sum() tm.assert_series_equal(result, expected["A"]) def test_resample_single_period_timedelta(): s = Series(list(range(5)), index=pd.timedelta_range("1 day", freq="s", periods=5)) result = s.resample("2s").sum() expected = Series( [1, 5, 4], index=pd.timedelta_range("1 day", freq="2s", periods=3) ) tm.assert_series_equal(result, expected) def test_resample_timedelta_idempotency(): # GH 12072 index = pd.timedelta_range("0", periods=9, freq="10L") series = Series(range(9), index=index) result = series.resample("10L").mean() expected = series tm.assert_series_equal(result, expected) def test_resample_offset_with_timedeltaindex(): # GH 10530 & 31809 rng = timedelta_range(start="0s", periods=25, freq="s") ts = Series(np.random.randn(len(rng)), index=rng) with_base = ts.resample("2s", offset="5s").mean() without_base = ts.resample("2s").mean() exp_without_base = timedelta_range(start="0s", end="25s", freq="2s") exp_with_base = timedelta_range(start="5s", end="29s", freq="2s") tm.assert_index_equal(without_base.index, exp_without_base) tm.assert_index_equal(with_base.index, exp_with_base) def test_resample_categorical_data_with_timedeltaindex(): # GH #12169 df = DataFrame({"Group_obj": "A"}, index=pd.to_timedelta(list(range(20)), unit="s")) df["Group"] = df["Group_obj"].astype("category") result = df.resample("10s").agg(lambda x: (x.value_counts().index[0])) expected = DataFrame( {"Group_obj": ["A", "A"], "Group": ["A", "A"]}, index=pd.TimedeltaIndex([0, 10], unit="s", freq="10s"), ) expected = expected.reindex(["Group_obj", "Group"], axis=1) expected["Group"] = expected["Group_obj"] tm.assert_frame_equal(result, expected) def test_resample_timedelta_values(): # GH 13119 # check that timedelta dtype is preserved when NaT values are # introduced by the resampling times = timedelta_range("1 day", "6 day", freq="4D") df = DataFrame({"time": times}, index=times) times2 = timedelta_range("1 day", "6 day", freq="2D") exp = Series(times2, index=times2, name="time") exp.iloc[1] = pd.NaT res = df.resample("2D").first()["time"] tm.assert_series_equal(res, exp) res = df["time"].resample("2D").first() tm.assert_series_equal(res, exp) @pytest.mark.parametrize( "start, end, freq, resample_freq", [ ("8H", "21h59min50s", "10S", "3H"), # GH 30353 example ("3H", "22H", "1H", "5H"), ("527D", "5006D", "3D", "10D"), ("1D", "10D", "1D", "2D"), # GH 13022 example # tests that worked before GH 33498: ("8H", "21h59min50s", "10S", "2H"), ("0H", "21h59min50s", "10S", "3H"), ("10D", "85D", "D", "2D"), ], ) def test_resample_timedelta_edge_case(start, end, freq, resample_freq): # GH 33498 # check that the timedelta bins does not contains an extra bin idx = pd.timedelta_range(start=start, end=end, freq=freq) s = Series(np.arange(len(idx)), index=idx) result = s.resample(resample_freq).min() expected_index = pd.timedelta_range(freq=resample_freq, start=start, end=end) tm.assert_index_equal(result.index, expected_index) assert result.index.freq == expected_index.freq assert not np.isnan(result[-1]) def test_resample_with_timedelta_yields_no_empty_groups(): # GH 10603 df = DataFrame( np.random.normal(size=(10000, 4)), index=pd.timedelta_range(start="0s", periods=10000, freq="3906250n"), ) result = df.loc["1s":, :].resample("3s").apply(lambda x: len(x)) expected = DataFrame( [[768.0] * 4] * 12 + [[528.0] * 4], index=pd.timedelta_range(start="1s", periods=13, freq="3s"), ) tm.assert_frame_equal(result, expected) def test_resample_quantile_timedelta(): # GH: 29485 df = DataFrame( {"value": pd.to_timedelta(np.arange(4), unit="s")}, index=pd.date_range("20200101", periods=4, tz="UTC"), ) result = df.resample("2D").quantile(0.99) expected = DataFrame( { "value": [ pd.Timedelta("0 days 00:00:00.990000"), pd.Timedelta("0 days 00:00:02.990000"), ] }, index=pd.date_range("20200101", periods=2, tz="UTC", freq="2D"), ) tm.assert_frame_equal(result, expected)
33.080214
88
0.631911
from datetime import timedelta import numpy as np import pytest import pandas as pd from pandas import DataFrame, Series import pandas._testing as tm from pandas.core.indexes.timedeltas import timedelta_range def test_asfreq_bug(): df = DataFrame(data=[1, 3], index=[timedelta(), timedelta(minutes=3)]) result = df.resample("1T").asfreq() expected = DataFrame( data=[1, np.nan, np.nan, 3], index=timedelta_range("0 day", periods=4, freq="1T"), ) tm.assert_frame_equal(result, expected) def test_resample_with_nat(): index = pd.to_timedelta(["0s", pd.NaT, "2s"]) result = DataFrame({"value": [2, 3, 5]}, index).resample("1s").mean() expected = DataFrame( {"value": [2.5, np.nan, 5.0]}, index=timedelta_range("0 day", periods=3, freq="1S"), ) tm.assert_frame_equal(result, expected) def test_resample_as_freq_with_subperiod(): index = timedelta_range("00:00:00", "00:10:00", freq="5T") df = DataFrame(data={"value": [1, 5, 10]}, index=index) result = df.resample("2T").asfreq() expected_data = {"value": [1, np.nan, np.nan, np.nan, np.nan, 10]} expected = DataFrame( data=expected_data, index=timedelta_range("00:00:00", "00:10:00", freq="2T") ) tm.assert_frame_equal(result, expected) def test_resample_with_timedeltas(): expected = DataFrame({"A": np.arange(1480)}) expected = expected.groupby(expected.index // 30).sum() expected.index = pd.timedelta_range("0 days", freq="30T", periods=50) df = DataFrame( {"A": np.arange(1480)}, index=pd.to_timedelta(np.arange(1480), unit="T") ) result = df.resample("30T").sum() tm.assert_frame_equal(result, expected) s = df["A"] result = s.resample("30T").sum() tm.assert_series_equal(result, expected["A"]) def test_resample_single_period_timedelta(): s = Series(list(range(5)), index=pd.timedelta_range("1 day", freq="s", periods=5)) result = s.resample("2s").sum() expected = Series( [1, 5, 4], index=pd.timedelta_range("1 day", freq="2s", periods=3) ) tm.assert_series_equal(result, expected) def test_resample_timedelta_idempotency(): index = pd.timedelta_range("0", periods=9, freq="10L") series = Series(range(9), index=index) result = series.resample("10L").mean() expected = series tm.assert_series_equal(result, expected) def test_resample_offset_with_timedeltaindex(): rng = timedelta_range(start="0s", periods=25, freq="s") ts = Series(np.random.randn(len(rng)), index=rng) with_base = ts.resample("2s", offset="5s").mean() without_base = ts.resample("2s").mean() exp_without_base = timedelta_range(start="0s", end="25s", freq="2s") exp_with_base = timedelta_range(start="5s", end="29s", freq="2s") tm.assert_index_equal(without_base.index, exp_without_base) tm.assert_index_equal(with_base.index, exp_with_base) def test_resample_categorical_data_with_timedeltaindex(): f = DataFrame({"Group_obj": "A"}, index=pd.to_timedelta(list(range(20)), unit="s")) df["Group"] = df["Group_obj"].astype("category") result = df.resample("10s").agg(lambda x: (x.value_counts().index[0])) expected = DataFrame( {"Group_obj": ["A", "A"], "Group": ["A", "A"]}, index=pd.TimedeltaIndex([0, 10], unit="s", freq="10s"), ) expected = expected.reindex(["Group_obj", "Group"], axis=1) expected["Group"] = expected["Group_obj"] tm.assert_frame_equal(result, expected) def test_resample_timedelta_values(): times = timedelta_range("1 day", "6 day", freq="4D") df = DataFrame({"time": times}, index=times) times2 = timedelta_range("1 day", "6 day", freq="2D") exp = Series(times2, index=times2, name="time") exp.iloc[1] = pd.NaT res = df.resample("2D").first()["time"] tm.assert_series_equal(res, exp) res = df["time"].resample("2D").first() tm.assert_series_equal(res, exp) @pytest.mark.parametrize( "start, end, freq, resample_freq", [ ("8H", "21h59min50s", "10S", "3H"), ("3H", "22H", "1H", "5H"), ("527D", "5006D", "3D", "10D"), ("1D", "10D", "1D", "2D"), ("8H", "21h59min50s", "10S", "2H"), ("0H", "21h59min50s", "10S", "3H"), ("10D", "85D", "D", "2D"), ], ) def test_resample_timedelta_edge_case(start, end, freq, resample_freq): idx = pd.timedelta_range(start=start, end=end, freq=freq) s = Series(np.arange(len(idx)), index=idx) result = s.resample(resample_freq).min() expected_index = pd.timedelta_range(freq=resample_freq, start=start, end=end) tm.assert_index_equal(result.index, expected_index) assert result.index.freq == expected_index.freq assert not np.isnan(result[-1]) def test_resample_with_timedelta_yields_no_empty_groups(): df = DataFrame( np.random.normal(size=(10000, 4)), index=pd.timedelta_range(start="0s", periods=10000, freq="3906250n"), ) result = df.loc["1s":, :].resample("3s").apply(lambda x: len(x)) expected = DataFrame( [[768.0] * 4] * 12 + [[528.0] * 4], index=pd.timedelta_range(start="1s", periods=13, freq="3s"), ) tm.assert_frame_equal(result, expected) def test_resample_quantile_timedelta(): df = DataFrame( {"value": pd.to_timedelta(np.arange(4), unit="s")}, index=pd.date_range("20200101", periods=4, tz="UTC"), ) result = df.resample("2D").quantile(0.99) expected = DataFrame( { "value": [ pd.Timedelta("0 days 00:00:00.990000"), pd.Timedelta("0 days 00:00:02.990000"), ] }, index=pd.date_range("20200101", periods=2, tz="UTC", freq="2D"), ) tm.assert_frame_equal(result, expected)
true
true
1c440bf67138afa263b8887f4363d386e850994f
1,395
py
Python
azure-mgmt-compute/azure/mgmt/compute/models/storage_profile.py
CharaD7/azure-sdk-for-python
9fdf0aac0cec8a15a5bb2a0ea27dd331dbfa2f5c
[ "MIT" ]
null
null
null
azure-mgmt-compute/azure/mgmt/compute/models/storage_profile.py
CharaD7/azure-sdk-for-python
9fdf0aac0cec8a15a5bb2a0ea27dd331dbfa2f5c
[ "MIT" ]
null
null
null
azure-mgmt-compute/azure/mgmt/compute/models/storage_profile.py
CharaD7/azure-sdk-for-python
9fdf0aac0cec8a15a5bb2a0ea27dd331dbfa2f5c
[ "MIT" ]
null
null
null
# 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 msrest.serialization import Model class StorageProfile(Model): """Describes a storage profile. :param image_reference: the image reference. :type image_reference: :class:`ImageReference <azure.mgmt.compute.models.ImageReference>` :param os_disk: the OS disk. :type os_disk: :class:`OSDisk <azure.mgmt.compute.models.OSDisk>` :param data_disks: the data disks. :type data_disks: list of :class:`DataDisk <azure.mgmt.compute.models.DataDisk>` """ _attribute_map = { 'image_reference': {'key': 'imageReference', 'type': 'ImageReference'}, 'os_disk': {'key': 'osDisk', 'type': 'OSDisk'}, 'data_disks': {'key': 'dataDisks', 'type': '[DataDisk]'}, } def __init__(self, image_reference=None, os_disk=None, data_disks=None): self.image_reference = image_reference self.os_disk = os_disk self.data_disks = data_disks
36.710526
79
0.615771
from msrest.serialization import Model class StorageProfile(Model): _attribute_map = { 'image_reference': {'key': 'imageReference', 'type': 'ImageReference'}, 'os_disk': {'key': 'osDisk', 'type': 'OSDisk'}, 'data_disks': {'key': 'dataDisks', 'type': '[DataDisk]'}, } def __init__(self, image_reference=None, os_disk=None, data_disks=None): self.image_reference = image_reference self.os_disk = os_disk self.data_disks = data_disks
true
true
1c440ead8b5d13c3647b3df37feee6ea8b6383e4
492
py
Python
weather-forecast-api/weather_forecast/tasks/receive_weather_forecast_failure.py
dalmarcogd/weather-forecast
f0987009c5691e46d9b8b6ba6f4408688ebec944
[ "Apache-2.0" ]
null
null
null
weather-forecast-api/weather_forecast/tasks/receive_weather_forecast_failure.py
dalmarcogd/weather-forecast
f0987009c5691e46d9b8b6ba6f4408688ebec944
[ "Apache-2.0" ]
null
null
null
weather-forecast-api/weather_forecast/tasks/receive_weather_forecast_failure.py
dalmarcogd/weather-forecast
f0987009c5691e46d9b8b6ba6f4408688ebec944
[ "Apache-2.0" ]
null
null
null
from typing import Dict from celery.task import Task from weather_forecast.database import queries from weather_forecast.database.models.weather_forecast import WeatherForecastStatus class ReceiveWeatherForecastFailureTask(Task): name = "receive-weather-forecast-failure" ignore_result = True def run(self, result: Dict) -> Dict: return queries.update_weather_forecast( {"id": result["weatherForecastId"], **result}, WeatherForecastStatus.error )
28.941176
86
0.754065
from typing import Dict from celery.task import Task from weather_forecast.database import queries from weather_forecast.database.models.weather_forecast import WeatherForecastStatus class ReceiveWeatherForecastFailureTask(Task): name = "receive-weather-forecast-failure" ignore_result = True def run(self, result: Dict) -> Dict: return queries.update_weather_forecast( {"id": result["weatherForecastId"], **result}, WeatherForecastStatus.error )
true
true
1c44110674bac1be1a91e7868849d9425da2b31e
27,746
py
Python
anchore_engine/utils.py
ballad86/anchore-engine
51f784dbb697586083bce023e2e6a708a25f1797
[ "Apache-2.0" ]
1,484
2017-09-11T19:08:42.000Z
2022-03-29T07:47:44.000Z
anchore_engine/utils.py
ballad86/anchore-engine
51f784dbb697586083bce023e2e6a708a25f1797
[ "Apache-2.0" ]
913
2017-09-27T20:37:53.000Z
2022-03-29T17:21:28.000Z
anchore_engine/utils.py
PhoenixRedflash/anchore-engine
4192eba02bb91cf0eebebe32e8134b27b06feefe
[ "Apache-2.0" ]
294
2017-09-12T16:54:03.000Z
2022-03-14T01:28:51.000Z
""" Generic utilities """ import decimal import os import platform import re import shlex import subprocess import threading import time import uuid from contextlib import contextmanager from operator import itemgetter from ijson import common as ijcommon from ijson.backends import python as ijpython from anchore_engine.subsys import logger SANITIZE_CMD_ERROR_MESSAGE = "bad character in shell input" PIPED_CMD_VALUE_ERROR_MESSAGE = "Piped command cannot be None or empty" K_BYTES = 1024 M_BYTES = 1024 * K_BYTES G_BYTES = 1024 * M_BYTES T_BYTES = 1024 * G_BYTES SIZE_UNITS = {"kb": K_BYTES, "mb": M_BYTES, "gb": G_BYTES, "tb": T_BYTES} BYTES_REGEX = re.compile("^([0-9]+)([kmgt]b)?$") def process_cve_status(old_cves_result=None, new_cves_result=None): """ Returns the diff of two cve results. Only compares two valid results, if either is None or empty, will return empty. :param cve_record: :return: dict with diff results: {'added': [], 'updated': [], 'removed': []} """ if not new_cves_result or not old_cves_result: return {} # Nothing to do try: if "multi" in old_cves_result: old_cve_header = old_cves_result["multi"]["result"]["header"] old_cve_rows = old_cves_result["multi"]["result"]["rows"] else: # element 0 is the image id old_cve_header = old_cves_result[0]["result"]["header"] old_cve_rows = old_cves_result[0]["result"]["rows"] except: old_cve_header = None old_cve_rows = None try: if "multi" in new_cves_result: new_cve_header = new_cves_result["multi"]["result"]["header"] new_cve_rows = new_cves_result["multi"]["result"]["rows"] else: # element 0 is the image id new_cve_header = new_cves_result[0]["result"]["header"] new_cve_rows = new_cves_result[0]["result"]["rows"] except: new_cve_header = None new_cve_rows = None summary_elements = [ "CVE_ID", "Severity", "Vulnerable_Package", "Fix_Available", "URL", "Package_Name", "Package_Version", "Package_Type", "Feed", "Feed_Group", ] if new_cve_rows is None or old_cve_rows is None: return {} new_cves = pivot_rows_to_keys( new_cve_header, new_cve_rows, key_names=["CVE_ID", "Vulnerable_Package"], whitelist_headers=summary_elements, ) old_cves = pivot_rows_to_keys( old_cve_header, old_cve_rows, key_names=["CVE_ID", "Vulnerable_Package"], whitelist_headers=summary_elements, ) diff = item_diffs(old_cves, new_cves) return diff def item_diffs(old_items=None, new_items=None): """ Given previous cve-scan output and new cve-scan output for the same image, return a diff as a map. Keys: { 'added': [], 'removed': [], 'updated': [] } :param old_cves: mapped cve results (from map_rows() result) from previous value :param new_cves: mapped cve results (from map_rows() result) from current_value :return: dictionary object with results """ if not old_items: old_items = {} if not new_items: new_items = {} new_ids = set(new_items.keys()) old_ids = set(old_items.keys()) added = [new_items[x] for x in new_ids.difference(old_ids)] removed = [old_items[x] for x in old_ids.difference(new_ids)] intersected_ids = new_ids.intersection(old_ids) updated = [ new_items[x] for x in [x for x in intersected_ids if new_items[x] != old_items[x]] ] return {"added": added, "removed": removed, "updated": updated} def list_to_map(item_list, key_name): """ Given a list of dicts/objects return a dict mapping item[key_name] -> item :param item_list: :param key_name: :return: """ return {x.pop(key_name): x for x in item_list} def map_rows(header_list, row_list): """ :param header_list: list of names ordered to match row data, provides names for each row :param row_list: list of row tuples/lists with each tuple/list in same order as header_list :return: list of dicts with named values instead of tuples """ header_map = {v: header_list.index(v) for v in header_list} mapped = [{key: item[header_map[key]] for key in header_map} for item in row_list] return mapped def pivot_rows_to_keys(header_list, row_list, key_names=[], whitelist_headers=None): """ Slightly more direct converter for header,row combo into a dict of objects :param header_list: :param row_list: :param key_name: :return: """ header_map = { v: header_list.index(v) for v in [ x for x in header_list if not whitelist_headers or x in whitelist_headers or x in key_names ] } key_idxs = [] for key_name in key_names: key_idxs.append(header_map[key_name]) # key_idx = header_map[key_name] # return {"{}{}".format(x[key_idx],x[keya_idx]): {k: x[v] for k, v in list(header_map.items())} for x in row_list} return { ":".join(itemgetter(*key_idxs)(x)): { k: x[v] for k, v in list(header_map.items()) } for x in row_list } def filter_record_keys(record_list, whitelist_keys): """ Filter the list records to remove verbose entries and make it suitable for notification format :param record_dict: dict containing values to process :param whitelist_keys: keys to leave in the record dicts :return: a new list with dicts that only contain the whitelisted elements """ filtered = [ {k: v for k, v in [y for y in list(x.items()) if y[0] in whitelist_keys]} for x in record_list ] return filtered def run_sanitize(cmd_list): def shellcheck(x): if not re.search("[;&<>]", x): return x else: raise Exception(SANITIZE_CMD_ERROR_MESSAGE) return [x for x in cmd_list if shellcheck(x)] def run_command_list_with_piped_input( cmd_list, input_data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, **kwargs ): """ Pipe the input data to the command list and run it with optional environment and return a tuple (rc, stdout_str, stderr_str) :param cmd_list: list of command e.g. ['ls', '/tmp'] :param input_data: string or bytes to be piped to cmd_list :param stdin: :param stdout: :param stderr: :return: tuple (rc_int, stdout_str, stderr_str) """ try: input_data = input_data.encode("utf-8") except AttributeError: # it is a str already, no need to encode pass cmd_list = run_sanitize(cmd_list) pipes = subprocess.Popen( cmd_list, **dict(stdout=stdout, stderr=stderr, stdin=stdin, **kwargs) ) stdout_result, stderr_result = pipes.communicate(input=input_data) return pipes.returncode, stdout_result, stderr_result def run_command_list( cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs ): """ Run a command from a list with optional environment and return a tuple (rc, stdout_str, stderr_str) :param cmd_list: list of command e.g. ['ls', '/tmp'] :param env: dict of env vars for the environment if desired. will replace normal env, not augment :return: tuple (rc_int, stdout_str, stderr_str) """ cmd_list = run_sanitize(cmd_list) pipes = subprocess.Popen(cmd_list, **dict(stdout=stdout, stderr=stderr, **kwargs)) stdout_result, stderr_result = pipes.communicate() return pipes.returncode, stdout_result, stderr_result def run_check(cmd, input_data=None, log_level="debug", **kwargs): """ Run a command (input required to be a list), log the output, and raise an exception if a non-zero exit status code is returned. """ cmd = run_sanitize(cmd) try: if input_data is not None: logger.debug("running cmd: %s with piped input", " ".join(cmd)) code, stdout, stderr = run_command_list_with_piped_input( cmd, input_data, **kwargs ) else: logger.debug("running cmd: %s", " ".join(cmd)) code, stdout, stderr = run_command_list(cmd, **kwargs) except FileNotFoundError: msg = "unable to run command. Executable does not exist or not availabe in path" raise CommandException(cmd, 1, "", "", msg=msg) try: stdout = stdout.decode("utf-8") stderr = stderr.decode("utf-8") except AttributeError: # it is a str already, no need to decode pass stdout_stream = stdout.splitlines() stderr_stream = stderr.splitlines() if log_level == "spew": # Some commands (like grype scanning) will generate enough output here that we # need to try to limit the impact of debug logging on system performance for line in stdout_stream: logger.spew("stdout: %s" % line) # safe formatting not available for spew for line in stderr_stream: logger.spew("stderr: %s" % line) else: # Always log stdout and stderr as debug, unless spew is specified for line in stdout_stream: logger.debug("stdout: %s", line) for line in stderr_stream: logger.debug("stderr: %s", line) if code != 0: # When non-zero exit status returns, log stderr as error, but only when # the log level is higher (lower in Engine's interpretation) than debug. # XXX: engine mangles the logger, so this way of checking the level is # non-standard. This line should be: # if logger.level > logging.debug: if logger.log_level < logger.log_level_map["DEBUG"]: for line in stderr_stream: logger.error(line) raise CommandException(cmd, code, stdout, stderr) return stdout, stderr def run_command(cmdstr, **kwargs): return run_command_list(shlex.split(cmdstr), **kwargs) def get_threadbased_id(guarantee_uniq=False): """ Returns a string for use with acquire() calls optionally. Constructs a consistent id from the platform node, process_id and thread_id :param guarantee_uniq: bool to have the id generate a uuid suffix to guarantee uniqeness between invocations even in the same thread :return: string """ return "{}:{}:{}:{}".format( platform.node(), os.getpid(), str(threading.get_ident()), uuid.uuid4().hex if guarantee_uniq else "", ) class AnchoreException(Exception): def to_dict(self): return { self.__class__.__name__: dict( (key, value) for key, value in vars(self).items() if not key.startswith("_") ) } class CommandException(Exception): """ An exception raised when subprocess.Popen calls have non-zero exit status. Capture useful information as part of the exception raised """ def __init__(self, cmd, code, stdout, stderr, msg=None): self.msg = msg or "Non-zero exit status code when running subprocess" self.cmd = " ".join(cmd) if isinstance(cmd, list) else cmd self.code = code self.stderr = stderr self.stdout = stdout def __repr__(self): return "{}: cmd={}, rc={}".format(self.msg, self.cmd, self.code) def __str__(self): return "{}: cmd={}, rc={}".format(self.msg, self.cmd, self.code) def ensure_bytes(obj): return obj.encode("utf-8") if type(obj) != bytes else obj def ensure_str(obj): return str(obj, "utf-8") if type(obj) != str else obj def convert_bytes_size(size_str): """ Converts a size string to an int. Allows trailing units e.g. "10" -> 10, "1kb" -> 1024, "1gb" -> 1024*1024*1024 :param size_str: :return: """ m = BYTES_REGEX.fullmatch(size_str.lower()) if m: number = int(m.group(1)) if m.group(2) is not None: unit = m.group(2) conversion = SIZE_UNITS.get(unit) if conversion: return conversion * number return number else: raise ValueError("Invalid size string: {}".format(size_str)) CPE_SPECIAL_CHAR_ENCODER = { "!": "%21", '"': "%22", "#": "%23", "$": "%24", "%": "%25", "&": "%26", "'": "%27", "(": "%28", ")": "%29", "*": "%2a", "+": "%2b", ",": "%2c", # '-': '-', # not affected by transformation between formatted string and uri, only impacts wfn # '.': '.', # not affected by transformation between formatted string and uri, only impacts wfn "/": "%2f", ":": "%3a", ";": "%3b", "<": "%3c", "=": "%3d", ">": "%3e", "?": "%3f", "@": "%40", "[": "%5b", "\\": "%5c", "]": "%5d", "^": "%5e", "`": "%60", "{": "%7b", "|": "%7c", "}": "%7d", "~": "%7e", } class CPE(object): """ A helper class for converting CPE 2.3 formatted string into CPE 2.2 URI and matching CPE 2.3 formatted strings """ def __init__( self, part=None, vendor=None, product=None, version=None, update=None, edition=None, language=None, sw_edition=None, target_sw=None, target_hw=None, other=None, ): self.part = part self.vendor = vendor self.product = product self.version = version self.update = update self.edition = edition self.language = language self.sw_edition = sw_edition self.target_sw = target_sw self.target_hw = target_hw self.other = other def __hash__(self): return hash( ( self.part, self.vendor, self.product, self.version, self.update, self.edition, self.language, self.sw_edition, self.target_sw, self.target_hw, self.other, ) ) def __eq__(self, other): return other and self == other def __repr__(self): return "CPE: part={}, vendor={}, product={}, version={}, update={}, edition={}, language={}, sw_edition={}, target_sw={}, target_hw={}, other={}".format( self.part, self.vendor, self.product, self.version, self.update, self.edition, self.language, self.sw_edition, self.target_sw, self.target_hw, self.other, ) def copy(self): return CPE( part=self.part, vendor=self.vendor, product=self.product, version=self.version, update=self.update, edition=self.edition, language=self.language, sw_edition=self.sw_edition, target_sw=self.target_sw, target_hw=self.target_hw, other=self.other, ) @staticmethod def from_cpe23_fs(cpe23_fs): """ Takes a CPE 2.3 formatted string and returns a CPE object. This is the only supported method to create an instance of this class This is not entirely true to the spec, it does not unbind all the elements as wfn representation is not used. All of unbinding logic is concentrated in the conversion from wfn to uri format in as_cpe22_uri() :param cpe23_fs: cpe:2.3:part:vendor:product:version:update:edition:language:sw_edition:target_sw:target_hw:other :return: """ cpe_parts = cpe23_fs.split(":") if cpe_parts and len(cpe_parts) == 13: return CPE( part=cpe_parts[2], vendor=cpe_parts[3], product=cpe_parts[4], version=cpe_parts[5], update=cpe_parts[6], edition=cpe_parts[7], language=cpe_parts[8], sw_edition=cpe_parts[9], target_sw=cpe_parts[10], target_hw=cpe_parts[11], other=cpe_parts[12], ) elif len(cpe_parts) > 13: # logger.debug('{} did not split nicely into 13 parts'.format(cpe23_fs)) adjusted_cpe_parts = [] counter = 1 # start from the third element in the list and iterate through the penultimate element while counter < len(cpe_parts) - 1: counter += 1 part = cpe_parts[counter] # if the element ends with a '\', good chance its an escape for ':', concatenate the elements together if part.endswith("\\"): new_part = part while counter < len(cpe_parts) - 1: counter += 1 part = cpe_parts[counter] new_part += ":" + part if part.endswith("\\"): continue else: break adjusted_cpe_parts.append(new_part) else: adjusted_cpe_parts.append(part) if len(adjusted_cpe_parts) == 11: # logger.debug('Adjusted cpe components: {}'.format(adjusted_cpe_parts)) return CPE( part=adjusted_cpe_parts[0], vendor=adjusted_cpe_parts[1], product=adjusted_cpe_parts[2], version=adjusted_cpe_parts[3], update=adjusted_cpe_parts[4], edition=adjusted_cpe_parts[5], language=adjusted_cpe_parts[6], sw_edition=adjusted_cpe_parts[7], target_sw=adjusted_cpe_parts[8], target_hw=adjusted_cpe_parts[9], other=adjusted_cpe_parts[10], ) else: raise Exception( "Cannot convert cpe 2.3 formatted string {} into wfn".format( cpe23_fs ) ) else: raise Exception( "Invalid cpe 2.3 formatted string {} Splitting with : delimiter resulted in less than 13 elements".format( cpe23_fs ) ) def as_cpe23_fs(self): return "cpe:2.3:{}".format( ":".join( [ self.part, self.vendor, self.product, self.version, self.update, self.edition, self.language, self.sw_edition, self.target_sw, self.target_hw, self.other, ] ) ) def update_version(self, version): """ Helper method for escaping the Ensures that resulting version is CPE 2.3 formatted string compliant, this is necessary for as_cpe22_uri() to do its thing affected version data in nvd json data which is usually unescaped. Converts the supplied version :param version: :return: """ self.version = CPE.escape_for_cpe23_fs(version) @staticmethod def escape_for_cpe23_fs(element): """ Helper method for escaping special characters as per the CPE 2.3 formatted string spec :param element: :return: escaped element string as per CPE 2.3 formatted string spec """ if not isinstance(element, str): raise Exception("Value to be escaped is not a string") if element in ["*", "-", ""]: # let these pass through as they are return element elif any(char in CPE_SPECIAL_CHAR_ENCODER.keys() for char in element): new_element = str() pos = 0 while pos < len(element): char = element[pos] if ( char == "\\" ): # this might be an escape character, check to see if the next character requires escape pos += 1 if pos < len(element): n_char = element[pos] if ( n_char in CPE_SPECIAL_CHAR_ENCODER ): # definitely an escaped sequence, preserve it as it is new_element += char + n_char else: # just a \ that needs to be escaped new_element += "\\" + char + n_char else: # last char is unescaped \, just add an escape new_element += "\\" + char elif char in CPE_SPECIAL_CHAR_ENCODER: new_element += "\\" + char else: new_element += char pos += 1 return new_element else: return element @staticmethod def bind_for_cpe22_uri(element): if not isinstance(element, str): raise Exception("Value to be bound in URI format is not a string") if element == "*": return "" elif element in ["-", ""]: return element else: result = str() pos = -1 while pos < (len(element) - 1): pos += 1 char = element[pos] if char == "\\": # an escaped character, percent encode it if possible if pos != ( len(element) - 1 ): # check the next character and transform into percent encoded string pos += 1 n_char = element[pos] encoded = CPE_SPECIAL_CHAR_ENCODER.get(n_char, None) if encoded: result += encoded else: # no encoding found, let it go through as it is logger.warn( "No encoding found for {}{}".format(char, n_char) ) result += char + n_char else: # this is the last char, nothing to percent encode logger.warn( "{} is the last char, skipping percent encoded transformation".format( char ) ) result += char elif char == "?": # bind the unescaped ? to %01 result += "%01" elif char == "*": # bind the unescaped * to %02 result += "%02" else: result += char return result def as_cpe22_uri(self): """ Transforms this CPE object into a CPE 2.2 URI. Based on the specification in https://nvlpubs.nist.gov/nistpubs/Legacy/IR/nistir7695.pdf :return: CPE 2.2 URI string """ # part:vendor:product:version:update:edition:language:sw_edition:target_sw:target_hw:other # 0 1 2 3 4 5 6 7 8 9 10 # |-------------cpe 2.2 attributes----------- |------------new in cpe 2.3----------| e = CPE.bind_for_cpe22_uri(self.edition) sw_e = CPE.bind_for_cpe22_uri(self.sw_edition) t_sw = CPE.bind_for_cpe22_uri(self.target_sw) t_hw = CPE.bind_for_cpe22_uri(self.target_hw) o = CPE.bind_for_cpe22_uri(self.other) if sw_e or t_sw or t_hw or o: edition = "~{}~{}~{}~{}~{}".format(e, sw_e, t_sw, t_hw, o) else: edition = e uri_parts = [ "cpe", "/" + self.part, CPE.bind_for_cpe22_uri(self.vendor), CPE.bind_for_cpe22_uri(self.product), CPE.bind_for_cpe22_uri(self.version), CPE.bind_for_cpe22_uri(self.update), edition, CPE.bind_for_cpe22_uri(self.language), ] uri = ":".join(uri_parts) uri = uri.strip(":") # remove any trailing : return uri def is_match(self, other_cpe): """ This is a very limited implementation of cpe matching. other_cpe is a wildcard ridden base cpe used by range descriptors other_cpe checked against this cpe for an exact match of part and vendor. For all the remaining components a match is positive if the other cpe is an exact match or contains the wild char :param other_cpe: :return: """ if not isinstance(other_cpe, CPE): return False if self.part == other_cpe.part and self.vendor == other_cpe.vendor: if other_cpe.product not in ["*", self.product]: return False if other_cpe.version not in ["*", self.version]: return False if other_cpe.update not in ["*", self.update]: return False if other_cpe.edition not in ["*", self.edition]: return False if other_cpe.language not in ["*", self.language]: return False if other_cpe.sw_edition not in ["*", self.sw_edition]: return False if other_cpe.target_sw not in ["*", self.target_sw]: return False if other_cpe.target_hw not in ["*", self.target_hw]: return False if other_cpe.other not in ["*", self.other]: return False return True else: return False @contextmanager def timer(label, log_level="debug"): t = time.time() try: yield finally: log_level = log_level.lower() if log_level == "info": logger.info( "Execution of {} took: {} seconds".format(label, time.time() - t) ) elif log_level == "warn": logger.warn( "Execution of {} took: {} seconds".format(label, time.time() - t) ) elif log_level == "spew": logger.spew( "Execution of {} took: {} seconds".format(label, time.time() - t) ) else: logger.debug( "Execution of {} took: {} seconds".format(label, time.time() - t) ) # Generally we're not dealing with high precision floats in feed data, so this shouldn't result in any loss of precision def ijson_decimal_to_float(event): """ Event handler for use with ijson parsers to output floats instead of Decimals for better json serializability downstream. :param event: :return: """ if event[1] == "number" and isinstance(event[2], decimal.Decimal): return event[0], event[1], float(event[2]) else: return event def mapped_parser_item_iterator(input_stream, item_path): """ Boilerplate function to setup the event mapper to ensure floats instead of decimals for use with ijson :param input_stream: :param item_path: :return: """ events = map(ijson_decimal_to_float, ijpython.parse(input_stream)) return ijcommon.items(events, item_path) def bytes_to_mb(value, round_to=None): mb = value / M_BYTES if round_to: mb = round(mb, round_to) return mb
32.225319
161
0.558026
import decimal import os import platform import re import shlex import subprocess import threading import time import uuid from contextlib import contextmanager from operator import itemgetter from ijson import common as ijcommon from ijson.backends import python as ijpython from anchore_engine.subsys import logger SANITIZE_CMD_ERROR_MESSAGE = "bad character in shell input" PIPED_CMD_VALUE_ERROR_MESSAGE = "Piped command cannot be None or empty" K_BYTES = 1024 M_BYTES = 1024 * K_BYTES G_BYTES = 1024 * M_BYTES T_BYTES = 1024 * G_BYTES SIZE_UNITS = {"kb": K_BYTES, "mb": M_BYTES, "gb": G_BYTES, "tb": T_BYTES} BYTES_REGEX = re.compile("^([0-9]+)([kmgt]b)?$") def process_cve_status(old_cves_result=None, new_cves_result=None): if not new_cves_result or not old_cves_result: return {} try: if "multi" in old_cves_result: old_cve_header = old_cves_result["multi"]["result"]["header"] old_cve_rows = old_cves_result["multi"]["result"]["rows"] else: old_cve_header = old_cves_result[0]["result"]["header"] old_cve_rows = old_cves_result[0]["result"]["rows"] except: old_cve_header = None old_cve_rows = None try: if "multi" in new_cves_result: new_cve_header = new_cves_result["multi"]["result"]["header"] new_cve_rows = new_cves_result["multi"]["result"]["rows"] else: new_cve_header = new_cves_result[0]["result"]["header"] new_cve_rows = new_cves_result[0]["result"]["rows"] except: new_cve_header = None new_cve_rows = None summary_elements = [ "CVE_ID", "Severity", "Vulnerable_Package", "Fix_Available", "URL", "Package_Name", "Package_Version", "Package_Type", "Feed", "Feed_Group", ] if new_cve_rows is None or old_cve_rows is None: return {} new_cves = pivot_rows_to_keys( new_cve_header, new_cve_rows, key_names=["CVE_ID", "Vulnerable_Package"], whitelist_headers=summary_elements, ) old_cves = pivot_rows_to_keys( old_cve_header, old_cve_rows, key_names=["CVE_ID", "Vulnerable_Package"], whitelist_headers=summary_elements, ) diff = item_diffs(old_cves, new_cves) return diff def item_diffs(old_items=None, new_items=None): if not old_items: old_items = {} if not new_items: new_items = {} new_ids = set(new_items.keys()) old_ids = set(old_items.keys()) added = [new_items[x] for x in new_ids.difference(old_ids)] removed = [old_items[x] for x in old_ids.difference(new_ids)] intersected_ids = new_ids.intersection(old_ids) updated = [ new_items[x] for x in [x for x in intersected_ids if new_items[x] != old_items[x]] ] return {"added": added, "removed": removed, "updated": updated} def list_to_map(item_list, key_name): return {x.pop(key_name): x for x in item_list} def map_rows(header_list, row_list): header_map = {v: header_list.index(v) for v in header_list} mapped = [{key: item[header_map[key]] for key in header_map} for item in row_list] return mapped def pivot_rows_to_keys(header_list, row_list, key_names=[], whitelist_headers=None): header_map = { v: header_list.index(v) for v in [ x for x in header_list if not whitelist_headers or x in whitelist_headers or x in key_names ] } key_idxs = [] for key_name in key_names: key_idxs.append(header_map[key_name]) return { ":".join(itemgetter(*key_idxs)(x)): { k: x[v] for k, v in list(header_map.items()) } for x in row_list } def filter_record_keys(record_list, whitelist_keys): filtered = [ {k: v for k, v in [y for y in list(x.items()) if y[0] in whitelist_keys]} for x in record_list ] return filtered def run_sanitize(cmd_list): def shellcheck(x): if not re.search("[;&<>]", x): return x else: raise Exception(SANITIZE_CMD_ERROR_MESSAGE) return [x for x in cmd_list if shellcheck(x)] def run_command_list_with_piped_input( cmd_list, input_data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, **kwargs ): try: input_data = input_data.encode("utf-8") except AttributeError: pass cmd_list = run_sanitize(cmd_list) pipes = subprocess.Popen( cmd_list, **dict(stdout=stdout, stderr=stderr, stdin=stdin, **kwargs) ) stdout_result, stderr_result = pipes.communicate(input=input_data) return pipes.returncode, stdout_result, stderr_result def run_command_list( cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs ): cmd_list = run_sanitize(cmd_list) pipes = subprocess.Popen(cmd_list, **dict(stdout=stdout, stderr=stderr, **kwargs)) stdout_result, stderr_result = pipes.communicate() return pipes.returncode, stdout_result, stderr_result def run_check(cmd, input_data=None, log_level="debug", **kwargs): cmd = run_sanitize(cmd) try: if input_data is not None: logger.debug("running cmd: %s with piped input", " ".join(cmd)) code, stdout, stderr = run_command_list_with_piped_input( cmd, input_data, **kwargs ) else: logger.debug("running cmd: %s", " ".join(cmd)) code, stdout, stderr = run_command_list(cmd, **kwargs) except FileNotFoundError: msg = "unable to run command. Executable does not exist or not availabe in path" raise CommandException(cmd, 1, "", "", msg=msg) try: stdout = stdout.decode("utf-8") stderr = stderr.decode("utf-8") except AttributeError: pass stdout_stream = stdout.splitlines() stderr_stream = stderr.splitlines() if log_level == "spew": for line in stdout_stream: logger.spew("stdout: %s" % line) for line in stderr_stream: logger.spew("stderr: %s" % line) else: for line in stdout_stream: logger.debug("stdout: %s", line) for line in stderr_stream: logger.debug("stderr: %s", line) if code != 0: # XXX: engine mangles the logger, so this way of checking the level is # non-standard. This line should be: # if logger.level > logging.debug: if logger.log_level < logger.log_level_map["DEBUG"]: for line in stderr_stream: logger.error(line) raise CommandException(cmd, code, stdout, stderr) return stdout, stderr def run_command(cmdstr, **kwargs): return run_command_list(shlex.split(cmdstr), **kwargs) def get_threadbased_id(guarantee_uniq=False): return "{}:{}:{}:{}".format( platform.node(), os.getpid(), str(threading.get_ident()), uuid.uuid4().hex if guarantee_uniq else "", ) class AnchoreException(Exception): def to_dict(self): return { self.__class__.__name__: dict( (key, value) for key, value in vars(self).items() if not key.startswith("_") ) } class CommandException(Exception): def __init__(self, cmd, code, stdout, stderr, msg=None): self.msg = msg or "Non-zero exit status code when running subprocess" self.cmd = " ".join(cmd) if isinstance(cmd, list) else cmd self.code = code self.stderr = stderr self.stdout = stdout def __repr__(self): return "{}: cmd={}, rc={}".format(self.msg, self.cmd, self.code) def __str__(self): return "{}: cmd={}, rc={}".format(self.msg, self.cmd, self.code) def ensure_bytes(obj): return obj.encode("utf-8") if type(obj) != bytes else obj def ensure_str(obj): return str(obj, "utf-8") if type(obj) != str else obj def convert_bytes_size(size_str): m = BYTES_REGEX.fullmatch(size_str.lower()) if m: number = int(m.group(1)) if m.group(2) is not None: unit = m.group(2) conversion = SIZE_UNITS.get(unit) if conversion: return conversion * number return number else: raise ValueError("Invalid size string: {}".format(size_str)) CPE_SPECIAL_CHAR_ENCODER = { "!": "%21", '"': "%22", "#": "%23", "$": "%24", "%": "%25", "&": "%26", "'": "%27", "(": "%28", ")": "%29", "*": "%2a", "+": "%2b", ",": "%2c", # '-': '-', # not affected by transformation between formatted string and uri, only impacts wfn # '.': '.', # not affected by transformation between formatted string and uri, only impacts wfn "/": "%2f", ":": "%3a", ";": "%3b", "<": "%3c", "=": "%3d", ">": "%3e", "?": "%3f", "@": "%40", "[": "%5b", "\\": "%5c", "]": "%5d", "^": "%5e", "`": "%60", "{": "%7b", "|": "%7c", "}": "%7d", "~": "%7e", } class CPE(object): def __init__( self, part=None, vendor=None, product=None, version=None, update=None, edition=None, language=None, sw_edition=None, target_sw=None, target_hw=None, other=None, ): self.part = part self.vendor = vendor self.product = product self.version = version self.update = update self.edition = edition self.language = language self.sw_edition = sw_edition self.target_sw = target_sw self.target_hw = target_hw self.other = other def __hash__(self): return hash( ( self.part, self.vendor, self.product, self.version, self.update, self.edition, self.language, self.sw_edition, self.target_sw, self.target_hw, self.other, ) ) def __eq__(self, other): return other and self == other def __repr__(self): return "CPE: part={}, vendor={}, product={}, version={}, update={}, edition={}, language={}, sw_edition={}, target_sw={}, target_hw={}, other={}".format( self.part, self.vendor, self.product, self.version, self.update, self.edition, self.language, self.sw_edition, self.target_sw, self.target_hw, self.other, ) def copy(self): return CPE( part=self.part, vendor=self.vendor, product=self.product, version=self.version, update=self.update, edition=self.edition, language=self.language, sw_edition=self.sw_edition, target_sw=self.target_sw, target_hw=self.target_hw, other=self.other, ) @staticmethod def from_cpe23_fs(cpe23_fs): cpe_parts = cpe23_fs.split(":") if cpe_parts and len(cpe_parts) == 13: return CPE( part=cpe_parts[2], vendor=cpe_parts[3], product=cpe_parts[4], version=cpe_parts[5], update=cpe_parts[6], edition=cpe_parts[7], language=cpe_parts[8], sw_edition=cpe_parts[9], target_sw=cpe_parts[10], target_hw=cpe_parts[11], other=cpe_parts[12], ) elif len(cpe_parts) > 13: # logger.debug('{} did not split nicely into 13 parts'.format(cpe23_fs)) adjusted_cpe_parts = [] counter = 1 # start from the third element in the list and iterate through the penultimate element while counter < len(cpe_parts) - 1: counter += 1 part = cpe_parts[counter] # if the element ends with a '\', good chance its an escape for ':', concatenate the elements together if part.endswith("\\"): new_part = part while counter < len(cpe_parts) - 1: counter += 1 part = cpe_parts[counter] new_part += ":" + part if part.endswith("\\"): continue else: break adjusted_cpe_parts.append(new_part) else: adjusted_cpe_parts.append(part) if len(adjusted_cpe_parts) == 11: # logger.debug('Adjusted cpe components: {}'.format(adjusted_cpe_parts)) return CPE( part=adjusted_cpe_parts[0], vendor=adjusted_cpe_parts[1], product=adjusted_cpe_parts[2], version=adjusted_cpe_parts[3], update=adjusted_cpe_parts[4], edition=adjusted_cpe_parts[5], language=adjusted_cpe_parts[6], sw_edition=adjusted_cpe_parts[7], target_sw=adjusted_cpe_parts[8], target_hw=adjusted_cpe_parts[9], other=adjusted_cpe_parts[10], ) else: raise Exception( "Cannot convert cpe 2.3 formatted string {} into wfn".format( cpe23_fs ) ) else: raise Exception( "Invalid cpe 2.3 formatted string {} Splitting with : delimiter resulted in less than 13 elements".format( cpe23_fs ) ) def as_cpe23_fs(self): return "cpe:2.3:{}".format( ":".join( [ self.part, self.vendor, self.product, self.version, self.update, self.edition, self.language, self.sw_edition, self.target_sw, self.target_hw, self.other, ] ) ) def update_version(self, version): self.version = CPE.escape_for_cpe23_fs(version) @staticmethod def escape_for_cpe23_fs(element): if not isinstance(element, str): raise Exception("Value to be escaped is not a string") if element in ["*", "-", ""]: # let these pass through as they are return element elif any(char in CPE_SPECIAL_CHAR_ENCODER.keys() for char in element): new_element = str() pos = 0 while pos < len(element): char = element[pos] if ( char == "\\" ): # this might be an escape character, check to see if the next character requires escape pos += 1 if pos < len(element): n_char = element[pos] if ( n_char in CPE_SPECIAL_CHAR_ENCODER ): # definitely an escaped sequence, preserve it as it is new_element += char + n_char else: # just a \ that needs to be escaped new_element += "\\" + char + n_char else: # last char is unescaped \, just add an escape new_element += "\\" + char elif char in CPE_SPECIAL_CHAR_ENCODER: new_element += "\\" + char else: new_element += char pos += 1 return new_element else: return element @staticmethod def bind_for_cpe22_uri(element): if not isinstance(element, str): raise Exception("Value to be bound in URI format is not a string") if element == "*": return "" elif element in ["-", ""]: return element else: result = str() pos = -1 while pos < (len(element) - 1): pos += 1 char = element[pos] if char == "\\": # an escaped character, percent encode it if possible if pos != ( len(element) - 1 ): # check the next character and transform into percent encoded string pos += 1 n_char = element[pos] encoded = CPE_SPECIAL_CHAR_ENCODER.get(n_char, None) if encoded: result += encoded else: # no encoding found, let it go through as it is logger.warn( "No encoding found for {}{}".format(char, n_char) ) result += char + n_char else: # this is the last char, nothing to percent encode logger.warn( "{} is the last char, skipping percent encoded transformation".format( char ) ) result += char elif char == "?": # bind the unescaped ? to %01 result += "%01" elif char == "*": # bind the unescaped * to %02 result += "%02" else: result += char return result def as_cpe22_uri(self): # part:vendor:product:version:update:edition:language:sw_edition:target_sw:target_hw:other # 0 1 2 3 4 5 6 7 8 9 10 # |-------------cpe 2.2 attributes----------- |------------new in cpe 2.3----------| e = CPE.bind_for_cpe22_uri(self.edition) sw_e = CPE.bind_for_cpe22_uri(self.sw_edition) t_sw = CPE.bind_for_cpe22_uri(self.target_sw) t_hw = CPE.bind_for_cpe22_uri(self.target_hw) o = CPE.bind_for_cpe22_uri(self.other) if sw_e or t_sw or t_hw or o: edition = "~{}~{}~{}~{}~{}".format(e, sw_e, t_sw, t_hw, o) else: edition = e uri_parts = [ "cpe", "/" + self.part, CPE.bind_for_cpe22_uri(self.vendor), CPE.bind_for_cpe22_uri(self.product), CPE.bind_for_cpe22_uri(self.version), CPE.bind_for_cpe22_uri(self.update), edition, CPE.bind_for_cpe22_uri(self.language), ] uri = ":".join(uri_parts) uri = uri.strip(":") # remove any trailing : return uri def is_match(self, other_cpe): if not isinstance(other_cpe, CPE): return False if self.part == other_cpe.part and self.vendor == other_cpe.vendor: if other_cpe.product not in ["*", self.product]: return False if other_cpe.version not in ["*", self.version]: return False if other_cpe.update not in ["*", self.update]: return False if other_cpe.edition not in ["*", self.edition]: return False if other_cpe.language not in ["*", self.language]: return False if other_cpe.sw_edition not in ["*", self.sw_edition]: return False if other_cpe.target_sw not in ["*", self.target_sw]: return False if other_cpe.target_hw not in ["*", self.target_hw]: return False if other_cpe.other not in ["*", self.other]: return False return True else: return False @contextmanager def timer(label, log_level="debug"): t = time.time() try: yield finally: log_level = log_level.lower() if log_level == "info": logger.info( "Execution of {} took: {} seconds".format(label, time.time() - t) ) elif log_level == "warn": logger.warn( "Execution of {} took: {} seconds".format(label, time.time() - t) ) elif log_level == "spew": logger.spew( "Execution of {} took: {} seconds".format(label, time.time() - t) ) else: logger.debug( "Execution of {} took: {} seconds".format(label, time.time() - t) ) # Generally we're not dealing with high precision floats in feed data, so this shouldn't result in any loss of precision def ijson_decimal_to_float(event): if event[1] == "number" and isinstance(event[2], decimal.Decimal): return event[0], event[1], float(event[2]) else: return event def mapped_parser_item_iterator(input_stream, item_path): events = map(ijson_decimal_to_float, ijpython.parse(input_stream)) return ijcommon.items(events, item_path) def bytes_to_mb(value, round_to=None): mb = value / M_BYTES if round_to: mb = round(mb, round_to) return mb
true
true
1c44111cc007cf80d7930ed6a4faa8477866dacd
12,036
py
Python
src/docker_code/docker_face_detect_v0.py
yuhaoluo/facenet
d3a3087f52ae1a17a77a1dadb81c53911be97b4b
[ "MIT" ]
null
null
null
src/docker_code/docker_face_detect_v0.py
yuhaoluo/facenet
d3a3087f52ae1a17a77a1dadb81c53911be97b4b
[ "MIT" ]
null
null
null
src/docker_code/docker_face_detect_v0.py
yuhaoluo/facenet
d3a3087f52ae1a17a77a1dadb81c53911be97b4b
[ "MIT" ]
null
null
null
# MIT License # # Copyright (c) 2016 David Sandberg # # 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, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following 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 MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS 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. from __future__ import absolute_import from __future__ import division from __future__ import print_function from scipy import misc import sys import os import argparse import tensorflow as tf import numpy as np import align.detect_face import time import imageio import requests #import skimage import json os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' minsize = 20 # minimum size of face threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold factor = 0.709 # scale factor ai_type = 'face-detect' config_path = '/data/configure.json' job_path = '/data/job/job.json' log_path = '/data/job/logs.log' log_path = '/home/luoyuhao/Datasets/Docker/logs/logs.log' test_config_path = '/home/luoyuhao/Datasets/Docker/configure.json' test_job_path = '/home/luoyuhao/Datasets/Docker/job.json' def load_mtcnn_model(args): print('Creating networks and loading parameters') with tf.Graph().as_default(): gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)) with sess.as_default(): start_time = time.time(); pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None) print('create and load mtcnn model time: ', (time.time() - start_time)) return pnet,rnet,onet def crop_face(img,bounding_boxes,margin,image_size): nrof_faces = bounding_boxes.shape[0] if nrof_faces>0: det = bounding_boxes[:,0:4] det_arr = [] img_size = np.asarray(img.shape)[0:2] if nrof_faces>1: for i in range(nrof_faces): det_arr.append(np.squeeze(det[i])) else: det_arr.append(np.squeeze(det)) face_res = [] for i, det in enumerate(det_arr): det = np.squeeze(det) bb = np.zeros(4, dtype=np.int32) bb[0] = np.maximum(det[0]-margin/2, 0) bb[1] = np.maximum(det[1]-margin/2, 0) bb[2] = np.minimum(det[2]+margin/2, img_size[1]) bb[3] = np.minimum(det[3]+margin/2, img_size[0]) cropped = img[bb[1]:bb[3],bb[0]:bb[2],:] #scaled = skimage.transform.resize(cropped, (args.image_size, args.image_size), interp='bilinear') scaled = misc.imresize(cropped, (image_size, image_size), interp='bilinear') face_res.append(scaled) return face_res def save_faces(res,output_filename): if(len(res)>0): filename_base, file_extension = os.path.splitext(output_filename) for i in range(len(res)): if (len(res)>1): output_filename_n = "{}_{}{}".format(filename_base, i, file_extension) else: output_filename_n = "{}{}".format(filename_base, file_extension) imageio.imwrite(output_filename_n, res[i]) def img_resize(img,scale): img_resize = misc.imresize(img, (int(img.shape[0]/scale), int(img.shape[1]/scale)), interp='bilinear') return img_resize def detectFace(args,img,pnet,rnet,onet,output_filename=None,isDrawFace=False,isPrintTimeInfo=False): ## reseize img to detect if args.scale>1: img_input = img_resize(img,args.scale) else: img_input = img detect_time_start = time.time() bounding_boxes, _ = align.detect_face.detect_face(img_input, minsize, pnet, rnet, onet, threshold, factor) if args.scale>1: bounding_boxes[:,0:4] = args.scale * bounding_boxes[:,0:4] detect_time = time.time() - detect_time_start if isPrintTimeInfo: print('detect_face_time: ', detect_time) faces = crop_face(img,bounding_boxes,args.margin,args.image_size) if(output_filename is not None): save_time_start = time.time() save_faces(faces,output_filename) if isPrintTimeInfo: print('save_face_time: ', time.time() - save_time_start) if isDrawFace: draw = align.detect_face.drawBoxes(img,bounding_boxes) filename_base, file_extension = os.path.splitext(output_filename) imageio.imwrite(filename_base+'_res'+file_extension,draw) #print(bounding_boxes) return faces,bounding_boxes def read_config(config_path): #TODO try: f = open(config_path,encoding='utf-8') json_read = f.read() dic = json.loads(json_read) f.close() except Exception as e: print(e) input_url = dic["input"] output_url = dic['output'] logs_info = dic['logs'] return input_url,output_url,logs_info def read_state(job_path): #TODO try: f = open(job_path,encoding='utf-8') json_read = f.read() dic = json.loads(json_read) state = dic['run'] f.close() except Exception as e: print(e) if state == 'true': return True else: return False def read_input(input_url): #TODO try: r = requests.get(input_url) res_dic = r.json() #dic except Exception as e: #errorMessage = '{}: {}'.format(input_url, e) print(e) if r.raise_for_status() is None: try: taskJson_dic = res_dic['taskJson'] except Exception as e: print("no face detect job.") taskJson_dic = [] errorCode = res_dic['errorCode'] errorMsg = res_dic['errorMsg'] else: taskJson_dic = [] errorCode = [] errorMsg = [] return taskJson_dic, errorCode, errorMsg def push_output(input_dic,output_url,faces,bounding_boxes): #TODO for i in range(len(faces)): save_path = '/home/luoyuhao/Datasets/Docker/saveface/' save_path = save_path + str(time.time())+".png" #imageio.imwrite(save_path,faces[i]) storage = 1 avatar = save_path box = bounding_boxes[i,0:4] location = [int(box[0]),int(box[1]),int(box[2]),int(box[3])] out_dic = {"storage":storage,"avatar":avatar,'location':str(location),\ "camId":input_dic["camId"],"capTs":input_dic["capTs"]} requests.post(output_url, data=out_dic) def read_img_from_taskJson(task_dic,tsb): storage = task_dic['storage'] img = [] if storage == 1: img_path = task_dic['imagePath'] try: img = imageio.imread(img_path) except Exception as e: msg = 'Face-detect failed. Wrong picture format' write_logs(log_path,ai_type,task_dic,msg,tsb,time.time()) img = [] errorMessage = '{}: {}'.format(img_path, e) print(errorMessage) # ============================================================================= # else if storage == '2': # img = [] # else if storage == '3': # img = [] # # ============================================================================= return img def write_logs(log_path,ai_type,taskJson_dic,msg,tsb,tse): storage = taskJson_dic['storage'] img_path = taskJson_dic['imagePath'] cam_id = taskJson_dic['camId'] cap_ts = taskJson_dic['capTs'] (filepath,tempfilename) = os.path.split(log_path) if not os.path.exists(filepath): os.mkdir(filepath) with open(log_path,'at') as f: f.write('tsb:%s\ttype:%s\tstorage:%d\timagePath:%s\tcamId:%d\tcapTs:%d\tmsg:%s\ttse:%s\n' % (tsb, ai_type,storage, img_path,\ cam_id,cap_ts,msg,tse)) ######################################################################################################## def main(args): # ============================================================================= # output_dir = args.output_dir # if not os.path.exists(output_dir): # os.makedirs(output_dir) # # # image_path = args.image_path # img = imageio.imread(image_path) # filename = os.path.splitext(os.path.split(image_path)[1])[0] # output_filename = os.path.join(output_dir, filename+'.png') # # ============================================================================= input_url,output_url,logs_info = read_config(config_path) pnet,rnet,onet = load_mtcnn_model(args) while(1): time.sleep(2) if read_state(job_path): tsb = time.time() taskJson_dic, errorCode, errorMsg = read_input(input_url) if len(taskJson_dic)!=4: continue img = read_img_from_taskJson(taskJson_dic,tsb) if len(img)>0: try: faces, bounding_boxes = detectFace(args,img,pnet,rnet,onet,None,False,True) if len(faces)>0: nums = len(faces) msg = 'Face-detect success. find {} faces'.format(nums) write_logs(log_path,ai_type,taskJson_dic,msg,tsb,time.time()) print("detect face success.") else: msg = "Face-detect success. find 0 faces." write_logs(log_path,ai_type,taskJson_dic,msg,tsb,time.time()) print("detect no face.") push_output(taskJson_dic,output_url,faces,bounding_boxes) except Exception as e: msg = "Face-detect failed. System exception" write_logs(log_path,ai_type,taskJson_dic,msg,tsb,time.time()) def parse_arguments(argv): parser = argparse.ArgumentParser() parser.add_argument('image_path', type=str, help='Directory with unaligned images.') parser.add_argument('output_dir', type=str, help='Directory with aligned face thumbnails.') parser.add_argument('--image_size', type=int, help='Image size (height, width) in pixels.', default=160) parser.add_argument('--margin', type=int, help='Margin for the crop around the bounding box (height, width) in pixels.', default=44) parser.add_argument('--gpu_memory_fraction', type=float, help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0) parser.add_argument('--detect_multiple_faces', type=bool, help='Detect and align multiple faces per image.', default=True) parser.add_argument('--scale', type=int, help='the height and width will resize to height/scale and width/scale to detect faces.', default=2) return parser.parse_args(argv) if __name__ == '__main__': img_path = '/home/luoyuhao/Datasets/Align/10.jpg' output_dir = '/home/luoyuhao/Datasets/Align/res' args = [img_path,output_dir,'--scale','2'] main(parse_arguments(args)) #main(parse_arguments(sys.argv[1:]))
36.695122
133
0.601196
from __future__ import absolute_import from __future__ import division from __future__ import print_function from scipy import misc import sys import os import argparse import tensorflow as tf import numpy as np import align.detect_face import time import imageio import requests import json os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' minsize = 20 threshold = [ 0.6, 0.7, 0.7 ] factor = 0.709 # scale factor ai_type = 'face-detect' config_path = '/data/configure.json' job_path = '/data/job/job.json' log_path = '/data/job/logs.log' log_path = '/home/luoyuhao/Datasets/Docker/logs/logs.log' test_config_path = '/home/luoyuhao/Datasets/Docker/configure.json' test_job_path = '/home/luoyuhao/Datasets/Docker/job.json' def load_mtcnn_model(args): print('Creating networks and loading parameters') with tf.Graph().as_default(): gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)) with sess.as_default(): start_time = time.time(); pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None) print('create and load mtcnn model time: ', (time.time() - start_time)) return pnet,rnet,onet def crop_face(img,bounding_boxes,margin,image_size): nrof_faces = bounding_boxes.shape[0] if nrof_faces>0: det = bounding_boxes[:,0:4] det_arr = [] img_size = np.asarray(img.shape)[0:2] if nrof_faces>1: for i in range(nrof_faces): det_arr.append(np.squeeze(det[i])) else: det_arr.append(np.squeeze(det)) face_res = [] for i, det in enumerate(det_arr): det = np.squeeze(det) bb = np.zeros(4, dtype=np.int32) bb[0] = np.maximum(det[0]-margin/2, 0) bb[1] = np.maximum(det[1]-margin/2, 0) bb[2] = np.minimum(det[2]+margin/2, img_size[1]) bb[3] = np.minimum(det[3]+margin/2, img_size[0]) cropped = img[bb[1]:bb[3],bb[0]:bb[2],:] #scaled = skimage.transform.resize(cropped, (args.image_size, args.image_size), interp='bilinear') scaled = misc.imresize(cropped, (image_size, image_size), interp='bilinear') face_res.append(scaled) return face_res def save_faces(res,output_filename): if(len(res)>0): filename_base, file_extension = os.path.splitext(output_filename) for i in range(len(res)): if (len(res)>1): output_filename_n = "{}_{}{}".format(filename_base, i, file_extension) else: output_filename_n = "{}{}".format(filename_base, file_extension) imageio.imwrite(output_filename_n, res[i]) def img_resize(img,scale): img_resize = misc.imresize(img, (int(img.shape[0]/scale), int(img.shape[1]/scale)), interp='bilinear') return img_resize def detectFace(args,img,pnet,rnet,onet,output_filename=None,isDrawFace=False,isPrintTimeInfo=False): ## reseize img to detect if args.scale>1: img_input = img_resize(img,args.scale) else: img_input = img detect_time_start = time.time() bounding_boxes, _ = align.detect_face.detect_face(img_input, minsize, pnet, rnet, onet, threshold, factor) if args.scale>1: bounding_boxes[:,0:4] = args.scale * bounding_boxes[:,0:4] detect_time = time.time() - detect_time_start if isPrintTimeInfo: print('detect_face_time: ', detect_time) faces = crop_face(img,bounding_boxes,args.margin,args.image_size) if(output_filename is not None): save_time_start = time.time() save_faces(faces,output_filename) if isPrintTimeInfo: print('save_face_time: ', time.time() - save_time_start) if isDrawFace: draw = align.detect_face.drawBoxes(img,bounding_boxes) filename_base, file_extension = os.path.splitext(output_filename) imageio.imwrite(filename_base+'_res'+file_extension,draw) #print(bounding_boxes) return faces,bounding_boxes def read_config(config_path): #TODO try: f = open(config_path,encoding='utf-8') json_read = f.read() dic = json.loads(json_read) f.close() except Exception as e: print(e) input_url = dic["input"] output_url = dic['output'] logs_info = dic['logs'] return input_url,output_url,logs_info def read_state(job_path): #TODO try: f = open(job_path,encoding='utf-8') json_read = f.read() dic = json.loads(json_read) state = dic['run'] f.close() except Exception as e: print(e) if state == 'true': return True else: return False def read_input(input_url): #TODO try: r = requests.get(input_url) res_dic = r.json() #dic except Exception as e: #errorMessage = '{}: {}'.format(input_url, e) print(e) if r.raise_for_status() is None: try: taskJson_dic = res_dic['taskJson'] except Exception as e: print("no face detect job.") taskJson_dic = [] errorCode = res_dic['errorCode'] errorMsg = res_dic['errorMsg'] else: taskJson_dic = [] errorCode = [] errorMsg = [] return taskJson_dic, errorCode, errorMsg def push_output(input_dic,output_url,faces,bounding_boxes): #TODO for i in range(len(faces)): save_path = '/home/luoyuhao/Datasets/Docker/saveface/' save_path = save_path + str(time.time())+".png" #imageio.imwrite(save_path,faces[i]) storage = 1 avatar = save_path box = bounding_boxes[i,0:4] location = [int(box[0]),int(box[1]),int(box[2]),int(box[3])] out_dic = {"storage":storage,"avatar":avatar,'location':str(location),\ "camId":input_dic["camId"],"capTs":input_dic["capTs"]} requests.post(output_url, data=out_dic) def read_img_from_taskJson(task_dic,tsb): storage = task_dic['storage'] img = [] if storage == 1: img_path = task_dic['imagePath'] try: img = imageio.imread(img_path) except Exception as e: msg = 'Face-detect failed. Wrong picture format' write_logs(log_path,ai_type,task_dic,msg,tsb,time.time()) img = [] errorMessage = '{}: {}'.format(img_path, e) print(errorMessage) # ============================================================================= # else if storage == '2': # img = [] # else if storage == '3': # img = [] # # ============================================================================= return img def write_logs(log_path,ai_type,taskJson_dic,msg,tsb,tse): storage = taskJson_dic['storage'] img_path = taskJson_dic['imagePath'] cam_id = taskJson_dic['camId'] cap_ts = taskJson_dic['capTs'] (filepath,tempfilename) = os.path.split(log_path) if not os.path.exists(filepath): os.mkdir(filepath) with open(log_path,'at') as f: f.write('tsb:%s\ttype:%s\tstorage:%d\timagePath:%s\tcamId:%d\tcapTs:%d\tmsg:%s\ttse:%s\n' % (tsb, ai_type,storage, img_path,\ cam_id,cap_ts,msg,tse)) ######################################################################################################## def main(args): # ============================================================================= # output_dir = args.output_dir # if not os.path.exists(output_dir): # os.makedirs(output_dir) # # # image_path = args.image_path # img = imageio.imread(image_path) # filename = os.path.splitext(os.path.split(image_path)[1])[0] # output_filename = os.path.join(output_dir, filename+'.png') # # ============================================================================= input_url,output_url,logs_info = read_config(config_path) pnet,rnet,onet = load_mtcnn_model(args) while(1): time.sleep(2) if read_state(job_path): tsb = time.time() taskJson_dic, errorCode, errorMsg = read_input(input_url) if len(taskJson_dic)!=4: continue img = read_img_from_taskJson(taskJson_dic,tsb) if len(img)>0: try: faces, bounding_boxes = detectFace(args,img,pnet,rnet,onet,None,False,True) if len(faces)>0: nums = len(faces) msg = 'Face-detect success. find {} faces'.format(nums) write_logs(log_path,ai_type,taskJson_dic,msg,tsb,time.time()) print("detect face success.") else: msg = "Face-detect success. find 0 faces." write_logs(log_path,ai_type,taskJson_dic,msg,tsb,time.time()) print("detect no face.") push_output(taskJson_dic,output_url,faces,bounding_boxes) except Exception as e: msg = "Face-detect failed. System exception" write_logs(log_path,ai_type,taskJson_dic,msg,tsb,time.time()) def parse_arguments(argv): parser = argparse.ArgumentParser() parser.add_argument('image_path', type=str, help='Directory with unaligned images.') parser.add_argument('output_dir', type=str, help='Directory with aligned face thumbnails.') parser.add_argument('--image_size', type=int, help='Image size (height, width) in pixels.', default=160) parser.add_argument('--margin', type=int, help='Margin for the crop around the bounding box (height, width) in pixels.', default=44) parser.add_argument('--gpu_memory_fraction', type=float, help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0) parser.add_argument('--detect_multiple_faces', type=bool, help='Detect and align multiple faces per image.', default=True) parser.add_argument('--scale', type=int, help='the height and width will resize to height/scale and width/scale to detect faces.', default=2) return parser.parse_args(argv) if __name__ == '__main__': img_path = '/home/luoyuhao/Datasets/Align/10.jpg' output_dir = '/home/luoyuhao/Datasets/Align/res' args = [img_path,output_dir,'--scale','2'] main(parse_arguments(args)) #main(parse_arguments(sys.argv[1:]))
true
true
1c4411906a6862cd76a4a9ab8fdaf4a537918ff5
62,520
py
Python
isi_sdk/api/fsa_results_api.py
robzim/isilon_sdk_python
3c2efcae7002f8ad25c0cfcb42a53b4d83e826d7
[ "MIT" ]
null
null
null
isi_sdk/api/fsa_results_api.py
robzim/isilon_sdk_python
3c2efcae7002f8ad25c0cfcb42a53b4d83e826d7
[ "MIT" ]
null
null
null
isi_sdk/api/fsa_results_api.py
robzim/isilon_sdk_python
3c2efcae7002f8ad25c0cfcb42a53b4d83e826d7
[ "MIT" ]
null
null
null
# coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 3 Contact: sdk@isilon.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from isi_sdk_8_0.api_client import ApiClient class FsaResultsApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def get_histogram_stat_by(self, id, stat, **kwargs): # noqa: E501 """get_histogram_stat_by # noqa: E501 This resource retrieves a histogram breakout for an individual FSA result set. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_histogram_stat_by(id, stat, async=True) >>> result = thread.get() :param async bool :param str id: (required) :param str stat: (required) :return: HistogramStatBy If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_histogram_stat_by_with_http_info(id, stat, **kwargs) # noqa: E501 else: (data) = self.get_histogram_stat_by_with_http_info(id, stat, **kwargs) # noqa: E501 return data def get_histogram_stat_by_with_http_info(self, id, stat, **kwargs): # noqa: E501 """get_histogram_stat_by # noqa: E501 This resource retrieves a histogram breakout for an individual FSA result set. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_histogram_stat_by_with_http_info(id, stat, async=True) >>> result = thread.get() :param async bool :param str id: (required) :param str stat: (required) :return: HistogramStatBy If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'stat'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_histogram_stat_by" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_histogram_stat_by`") # noqa: E501 # verify the required parameter 'stat' is set if ('stat' not in params or params['stat'] is None): raise ValueError("Missing the required parameter `stat` when calling `get_histogram_stat_by`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['Id'] = params['id'] # noqa: E501 if 'stat' in params: path_params['Stat'] = params['stat'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['basicAuth'] # noqa: E501 return self.api_client.call_api( '/platform/3/fsa/results/{Id}/histogram/{Stat}/by', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='HistogramStatBy', # noqa: E501 auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_histogram_stat_by_breakout(self, histogram_stat_by_breakout, id, stat, **kwargs): # noqa: E501 """get_histogram_stat_by_breakout # noqa: E501 This resource retrieves a histogram breakout for an individual FSA result set. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_histogram_stat_by_breakout(histogram_stat_by_breakout, id, stat, async=True) >>> result = thread.get() :param async bool :param str histogram_stat_by_breakout: This resource retrieves a histogram breakout for an individual FSA result set. ID in the resource path is the result set ID. (required) :param str id: (required) :param str stat: (required) :param str directory_filter: Filter according to a specific directory, which includes all of its subdirectories. :param str attribute_filter: Filter according to the name of a file user attribute. :param str node_pool_filter: Filter according to the name of a node pool, which is a set of disk pools that belong to nodes of the same equivalence class. :param str disk_pool_filter: Filter according to the name of a disk pool, which is a set of drives that represent an independent failure domain. :param str tier_filter: Filter according to the name of a storage tier, which is a user-created set of node pools. :param int comp_report: Result set identifier for comparison of database results. :param int log_size_filter: Filter according to file logical size, where the filter value specifies the lower bound in bytes to a set of files that have been grouped by logical size. The list of valid log_size filter values may be found by performing a histogram breakout by log_size and viewing the resulting key values. :param int phys_size_filter: Filter according to file physical size, where the filter value specifies the lower bound in bytes to a set of files that have been grouped by physical size. The list of valid phys_size filter values may be found by performing a histogram breakout by phys_size and viewing the resulting key values. :param int limit: Limit the number of breakout results. :param str path_ext_filter: Filter according to the name of a single file extension. :param int ctime_filter: Filter according to file modified time, where the filter value specifies a negative number of seconds representing a time before the begin time of the report. The list of valid ctime filter values may be found by performing a histogram breakout by ctime and viewing the resulting key values. :param int atime_filter: Filter according to file accessed time, where the filter value specifies a negative number of seconds representing a time before the begin time of the report. The list of valid atime filter values may be found by performing a histogram breakout by atime and viewing the resulting key values. :return: HistogramStatBy If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_histogram_stat_by_breakout_with_http_info(histogram_stat_by_breakout, id, stat, **kwargs) # noqa: E501 else: (data) = self.get_histogram_stat_by_breakout_with_http_info(histogram_stat_by_breakout, id, stat, **kwargs) # noqa: E501 return data def get_histogram_stat_by_breakout_with_http_info(self, histogram_stat_by_breakout, id, stat, **kwargs): # noqa: E501 """get_histogram_stat_by_breakout # noqa: E501 This resource retrieves a histogram breakout for an individual FSA result set. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_histogram_stat_by_breakout_with_http_info(histogram_stat_by_breakout, id, stat, async=True) >>> result = thread.get() :param async bool :param str histogram_stat_by_breakout: This resource retrieves a histogram breakout for an individual FSA result set. ID in the resource path is the result set ID. (required) :param str id: (required) :param str stat: (required) :param str directory_filter: Filter according to a specific directory, which includes all of its subdirectories. :param str attribute_filter: Filter according to the name of a file user attribute. :param str node_pool_filter: Filter according to the name of a node pool, which is a set of disk pools that belong to nodes of the same equivalence class. :param str disk_pool_filter: Filter according to the name of a disk pool, which is a set of drives that represent an independent failure domain. :param str tier_filter: Filter according to the name of a storage tier, which is a user-created set of node pools. :param int comp_report: Result set identifier for comparison of database results. :param int log_size_filter: Filter according to file logical size, where the filter value specifies the lower bound in bytes to a set of files that have been grouped by logical size. The list of valid log_size filter values may be found by performing a histogram breakout by log_size and viewing the resulting key values. :param int phys_size_filter: Filter according to file physical size, where the filter value specifies the lower bound in bytes to a set of files that have been grouped by physical size. The list of valid phys_size filter values may be found by performing a histogram breakout by phys_size and viewing the resulting key values. :param int limit: Limit the number of breakout results. :param str path_ext_filter: Filter according to the name of a single file extension. :param int ctime_filter: Filter according to file modified time, where the filter value specifies a negative number of seconds representing a time before the begin time of the report. The list of valid ctime filter values may be found by performing a histogram breakout by ctime and viewing the resulting key values. :param int atime_filter: Filter according to file accessed time, where the filter value specifies a negative number of seconds representing a time before the begin time of the report. The list of valid atime filter values may be found by performing a histogram breakout by atime and viewing the resulting key values. :return: HistogramStatBy If the method is called asynchronously, returns the request thread. """ all_params = ['histogram_stat_by_breakout', 'id', 'stat', 'directory_filter', 'attribute_filter', 'node_pool_filter', 'disk_pool_filter', 'tier_filter', 'comp_report', 'log_size_filter', 'phys_size_filter', 'limit', 'path_ext_filter', 'ctime_filter', 'atime_filter'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_histogram_stat_by_breakout" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'histogram_stat_by_breakout' is set if ('histogram_stat_by_breakout' not in params or params['histogram_stat_by_breakout'] is None): raise ValueError("Missing the required parameter `histogram_stat_by_breakout` when calling `get_histogram_stat_by_breakout`") # noqa: E501 # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_histogram_stat_by_breakout`") # noqa: E501 # verify the required parameter 'stat' is set if ('stat' not in params or params['stat'] is None): raise ValueError("Missing the required parameter `stat` when calling `get_histogram_stat_by_breakout`") # noqa: E501 collection_formats = {} path_params = {} if 'histogram_stat_by_breakout' in params: path_params['HistogramStatByBreakout'] = params['histogram_stat_by_breakout'] # noqa: E501 if 'id' in params: path_params['Id'] = params['id'] # noqa: E501 if 'stat' in params: path_params['Stat'] = params['stat'] # noqa: E501 query_params = [] if 'directory_filter' in params: query_params.append(('directory_filter', params['directory_filter'])) # noqa: E501 if 'attribute_filter' in params: query_params.append(('attribute_filter', params['attribute_filter'])) # noqa: E501 if 'node_pool_filter' in params: query_params.append(('node_pool_filter', params['node_pool_filter'])) # noqa: E501 if 'disk_pool_filter' in params: query_params.append(('disk_pool_filter', params['disk_pool_filter'])) # noqa: E501 if 'tier_filter' in params: query_params.append(('tier_filter', params['tier_filter'])) # noqa: E501 if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) # noqa: E501 if 'log_size_filter' in params: query_params.append(('log_size_filter', params['log_size_filter'])) # noqa: E501 if 'phys_size_filter' in params: query_params.append(('phys_size_filter', params['phys_size_filter'])) # noqa: E501 if 'limit' in params: query_params.append(('limit', params['limit'])) # noqa: E501 if 'path_ext_filter' in params: query_params.append(('path_ext_filter', params['path_ext_filter'])) # noqa: E501 if 'ctime_filter' in params: query_params.append(('ctime_filter', params['ctime_filter'])) # noqa: E501 if 'atime_filter' in params: query_params.append(('atime_filter', params['atime_filter'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['basicAuth'] # noqa: E501 return self.api_client.call_api( '/platform/3/fsa/results/{Id}/histogram/{Stat}/by/{HistogramStatByBreakout}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='HistogramStatBy', # noqa: E501 auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_directories(self, id, **kwargs): # noqa: E501 """get_result_directories # noqa: E501 This resource retrieves directory information. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_directories(id, async=True) >>> result = thread.get() :param async bool :param str id: (required) :param str sort: The field that will be used for sorting. :param str path: Primary directory path to report usage information, which may be specified instead of a LIN. :param int limit: Limit the number of reported subdirectories. :param int comp_report: Result set identifier for comparison of database results. :param str dir: The direction of the sort. :return: ResultDirectories If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_directories_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_result_directories_with_http_info(id, **kwargs) # noqa: E501 return data def get_result_directories_with_http_info(self, id, **kwargs): # noqa: E501 """get_result_directories # noqa: E501 This resource retrieves directory information. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_directories_with_http_info(id, async=True) >>> result = thread.get() :param async bool :param str id: (required) :param str sort: The field that will be used for sorting. :param str path: Primary directory path to report usage information, which may be specified instead of a LIN. :param int limit: Limit the number of reported subdirectories. :param int comp_report: Result set identifier for comparison of database results. :param str dir: The direction of the sort. :return: ResultDirectories If the method is called asynchronously, returns the request thread. """ all_params = ['id', 'sort', 'path', 'limit', 'comp_report', 'dir'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_directories" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_directories`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['Id'] = params['id'] # noqa: E501 query_params = [] if 'sort' in params: query_params.append(('sort', params['sort'])) # noqa: E501 if 'path' in params: query_params.append(('path', params['path'])) # noqa: E501 if 'limit' in params: query_params.append(('limit', params['limit'])) # noqa: E501 if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) # noqa: E501 if 'dir' in params: query_params.append(('dir', params['dir'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['basicAuth'] # noqa: E501 return self.api_client.call_api( '/platform/3/fsa/results/{Id}/directories', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultDirectories', # noqa: E501 auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_directory(self, result_directory_id, id, **kwargs): # noqa: E501 """get_result_directory # noqa: E501 This resource retrieves directory information. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_directory(result_directory_id, id, async=True) >>> result = thread.get() :param async bool :param int result_directory_id: This resource retrieves directory information. ID in the resource path is the result set ID. (required) :param str id: (required) :param str sort: The field that will be used for sorting. :param int limit: Limit the number of reported subdirectories. :param int comp_report: Result set identifier for comparison of database results. :param str dir: The direction of the sort. :return: ResultDirectories If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_directory_with_http_info(result_directory_id, id, **kwargs) # noqa: E501 else: (data) = self.get_result_directory_with_http_info(result_directory_id, id, **kwargs) # noqa: E501 return data def get_result_directory_with_http_info(self, result_directory_id, id, **kwargs): # noqa: E501 """get_result_directory # noqa: E501 This resource retrieves directory information. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_directory_with_http_info(result_directory_id, id, async=True) >>> result = thread.get() :param async bool :param int result_directory_id: This resource retrieves directory information. ID in the resource path is the result set ID. (required) :param str id: (required) :param str sort: The field that will be used for sorting. :param int limit: Limit the number of reported subdirectories. :param int comp_report: Result set identifier for comparison of database results. :param str dir: The direction of the sort. :return: ResultDirectories If the method is called asynchronously, returns the request thread. """ all_params = ['result_directory_id', 'id', 'sort', 'limit', 'comp_report', 'dir'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_directory" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'result_directory_id' is set if ('result_directory_id' not in params or params['result_directory_id'] is None): raise ValueError("Missing the required parameter `result_directory_id` when calling `get_result_directory`") # noqa: E501 # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_directory`") # noqa: E501 collection_formats = {} path_params = {} if 'result_directory_id' in params: path_params['ResultDirectoryId'] = params['result_directory_id'] # noqa: E501 if 'id' in params: path_params['Id'] = params['id'] # noqa: E501 query_params = [] if 'sort' in params: query_params.append(('sort', params['sort'])) # noqa: E501 if 'limit' in params: query_params.append(('limit', params['limit'])) # noqa: E501 if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) # noqa: E501 if 'dir' in params: query_params.append(('dir', params['dir'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['basicAuth'] # noqa: E501 return self.api_client.call_api( '/platform/3/fsa/results/{Id}/directories/{ResultDirectoryId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultDirectories', # noqa: E501 auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_histogram(self, id, **kwargs): # noqa: E501 """get_result_histogram # noqa: E501 This resource retrieves a histogram of file counts for an individual FSA result set. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_histogram(id, async=True) >>> result = thread.get() :param async bool :param str id: (required) :return: ResultHistogram If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_histogram_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_result_histogram_with_http_info(id, **kwargs) # noqa: E501 return data def get_result_histogram_with_http_info(self, id, **kwargs): # noqa: E501 """get_result_histogram # noqa: E501 This resource retrieves a histogram of file counts for an individual FSA result set. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_histogram_with_http_info(id, async=True) >>> result = thread.get() :param async bool :param str id: (required) :return: ResultHistogram If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_histogram" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_histogram`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['Id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['basicAuth'] # noqa: E501 return self.api_client.call_api( '/platform/3/fsa/results/{Id}/histogram', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultHistogram', # noqa: E501 auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_histogram_stat(self, result_histogram_stat, id, **kwargs): # noqa: E501 """get_result_histogram_stat # noqa: E501 This resource retrieves a histogram of file counts for an individual FSA result set. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_histogram_stat(result_histogram_stat, id, async=True) >>> result = thread.get() :param async bool :param str result_histogram_stat: This resource retrieves a histogram of file counts for an individual FSA result set. ID in the resource path is the result set ID. (required) :param str id: (required) :param str directory_filter: Filter according to a specific directory, which includes all of its subdirectories. :param str attribute_filter: Filter according to the name of a file user attribute. :param str node_pool_filter: Filter according to the name of a node pool, which is a set of disk pools that belong to nodes of the same equivalence class. :param str disk_pool_filter: Filter according to the name of a disk pool, which is a set of drives that represent an independent failure domain. :param str tier_filter: Filter according to the name of a storage tier, which is a user-created set of node pools. :param int comp_report: Result set identifier for comparison of database results. :param int log_size_filter: Filter according to file logical size, where the filter value specifies the lower bound in bytes to a set of files that have been grouped by logical size. The list of valid log_size filter values may be found by performing a histogram breakout by log_size and viewing the resulting key values. :param int phys_size_filter: Filter according to file physical size, where the filter value specifies the lower bound in bytes to a set of files that have been grouped by physical size. The list of valid phys_size filter values may be found by performing a histogram breakout by phys_size and viewing the resulting key values. :param str path_ext_filter: Filter according to the name of a single file extension. :param int ctime_filter: Filter according to file modified time, where the filter value specifies a negative number of seconds representing a time before the begin time of the report. The list of valid ctime filter values may be found by performing a histogram breakout by ctime and viewing the resulting key values. :param int atime_filter: Filter according to file accessed time, where the filter value specifies a negative number of seconds representing a time before the begin time of the report. The list of valid atime filter values may be found by performing a histogram breakout by atime and viewing the resulting key values. :return: ResultHistogram If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_histogram_stat_with_http_info(result_histogram_stat, id, **kwargs) # noqa: E501 else: (data) = self.get_result_histogram_stat_with_http_info(result_histogram_stat, id, **kwargs) # noqa: E501 return data def get_result_histogram_stat_with_http_info(self, result_histogram_stat, id, **kwargs): # noqa: E501 """get_result_histogram_stat # noqa: E501 This resource retrieves a histogram of file counts for an individual FSA result set. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_histogram_stat_with_http_info(result_histogram_stat, id, async=True) >>> result = thread.get() :param async bool :param str result_histogram_stat: This resource retrieves a histogram of file counts for an individual FSA result set. ID in the resource path is the result set ID. (required) :param str id: (required) :param str directory_filter: Filter according to a specific directory, which includes all of its subdirectories. :param str attribute_filter: Filter according to the name of a file user attribute. :param str node_pool_filter: Filter according to the name of a node pool, which is a set of disk pools that belong to nodes of the same equivalence class. :param str disk_pool_filter: Filter according to the name of a disk pool, which is a set of drives that represent an independent failure domain. :param str tier_filter: Filter according to the name of a storage tier, which is a user-created set of node pools. :param int comp_report: Result set identifier for comparison of database results. :param int log_size_filter: Filter according to file logical size, where the filter value specifies the lower bound in bytes to a set of files that have been grouped by logical size. The list of valid log_size filter values may be found by performing a histogram breakout by log_size and viewing the resulting key values. :param int phys_size_filter: Filter according to file physical size, where the filter value specifies the lower bound in bytes to a set of files that have been grouped by physical size. The list of valid phys_size filter values may be found by performing a histogram breakout by phys_size and viewing the resulting key values. :param str path_ext_filter: Filter according to the name of a single file extension. :param int ctime_filter: Filter according to file modified time, where the filter value specifies a negative number of seconds representing a time before the begin time of the report. The list of valid ctime filter values may be found by performing a histogram breakout by ctime and viewing the resulting key values. :param int atime_filter: Filter according to file accessed time, where the filter value specifies a negative number of seconds representing a time before the begin time of the report. The list of valid atime filter values may be found by performing a histogram breakout by atime and viewing the resulting key values. :return: ResultHistogram If the method is called asynchronously, returns the request thread. """ all_params = ['result_histogram_stat', 'id', 'directory_filter', 'attribute_filter', 'node_pool_filter', 'disk_pool_filter', 'tier_filter', 'comp_report', 'log_size_filter', 'phys_size_filter', 'path_ext_filter', 'ctime_filter', 'atime_filter'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_histogram_stat" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'result_histogram_stat' is set if ('result_histogram_stat' not in params or params['result_histogram_stat'] is None): raise ValueError("Missing the required parameter `result_histogram_stat` when calling `get_result_histogram_stat`") # noqa: E501 # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_histogram_stat`") # noqa: E501 collection_formats = {} path_params = {} if 'result_histogram_stat' in params: path_params['ResultHistogramStat'] = params['result_histogram_stat'] # noqa: E501 if 'id' in params: path_params['Id'] = params['id'] # noqa: E501 query_params = [] if 'directory_filter' in params: query_params.append(('directory_filter', params['directory_filter'])) # noqa: E501 if 'attribute_filter' in params: query_params.append(('attribute_filter', params['attribute_filter'])) # noqa: E501 if 'node_pool_filter' in params: query_params.append(('node_pool_filter', params['node_pool_filter'])) # noqa: E501 if 'disk_pool_filter' in params: query_params.append(('disk_pool_filter', params['disk_pool_filter'])) # noqa: E501 if 'tier_filter' in params: query_params.append(('tier_filter', params['tier_filter'])) # noqa: E501 if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) # noqa: E501 if 'log_size_filter' in params: query_params.append(('log_size_filter', params['log_size_filter'])) # noqa: E501 if 'phys_size_filter' in params: query_params.append(('phys_size_filter', params['phys_size_filter'])) # noqa: E501 if 'path_ext_filter' in params: query_params.append(('path_ext_filter', params['path_ext_filter'])) # noqa: E501 if 'ctime_filter' in params: query_params.append(('ctime_filter', params['ctime_filter'])) # noqa: E501 if 'atime_filter' in params: query_params.append(('atime_filter', params['atime_filter'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['basicAuth'] # noqa: E501 return self.api_client.call_api( '/platform/3/fsa/results/{Id}/histogram/{ResultHistogramStat}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultHistogram', # noqa: E501 auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_top_dir(self, result_top_dir_id, id, **kwargs): # noqa: E501 """get_result_top_dir # noqa: E501 This resource retrieves the top directories. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_top_dir(result_top_dir_id, id, async=True) >>> result = thread.get() :param async bool :param str result_top_dir_id: This resource retrieves the top directories. ID in the resource path is the result set ID. (required) :param str id: (required) :param str sort: The field that will be used for sorting. :param int start: Starting index for results. Default value of 0. :param int limit: Number of results from start index. Default value of 1000. :param int comp_report: Result set identifier for comparison of database results. :param str dir: The direction of the sort. :return: ResultTopDirs If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_top_dir_with_http_info(result_top_dir_id, id, **kwargs) # noqa: E501 else: (data) = self.get_result_top_dir_with_http_info(result_top_dir_id, id, **kwargs) # noqa: E501 return data def get_result_top_dir_with_http_info(self, result_top_dir_id, id, **kwargs): # noqa: E501 """get_result_top_dir # noqa: E501 This resource retrieves the top directories. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_top_dir_with_http_info(result_top_dir_id, id, async=True) >>> result = thread.get() :param async bool :param str result_top_dir_id: This resource retrieves the top directories. ID in the resource path is the result set ID. (required) :param str id: (required) :param str sort: The field that will be used for sorting. :param int start: Starting index for results. Default value of 0. :param int limit: Number of results from start index. Default value of 1000. :param int comp_report: Result set identifier for comparison of database results. :param str dir: The direction of the sort. :return: ResultTopDirs If the method is called asynchronously, returns the request thread. """ all_params = ['result_top_dir_id', 'id', 'sort', 'start', 'limit', 'comp_report', 'dir'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_top_dir" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'result_top_dir_id' is set if ('result_top_dir_id' not in params or params['result_top_dir_id'] is None): raise ValueError("Missing the required parameter `result_top_dir_id` when calling `get_result_top_dir`") # noqa: E501 # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_top_dir`") # noqa: E501 collection_formats = {} path_params = {} if 'result_top_dir_id' in params: path_params['ResultTopDirId'] = params['result_top_dir_id'] # noqa: E501 if 'id' in params: path_params['Id'] = params['id'] # noqa: E501 query_params = [] if 'sort' in params: query_params.append(('sort', params['sort'])) # noqa: E501 if 'start' in params: query_params.append(('start', params['start'])) # noqa: E501 if 'limit' in params: query_params.append(('limit', params['limit'])) # noqa: E501 if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) # noqa: E501 if 'dir' in params: query_params.append(('dir', params['dir'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['basicAuth'] # noqa: E501 return self.api_client.call_api( '/platform/3/fsa/results/{Id}/top-dirs/{ResultTopDirId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultTopDirs', # noqa: E501 auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_top_dirs(self, id, **kwargs): # noqa: E501 """get_result_top_dirs # noqa: E501 This resource retrieves the top directories. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_top_dirs(id, async=True) >>> result = thread.get() :param async bool :param str id: (required) :return: ResultTopDirs If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_top_dirs_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_result_top_dirs_with_http_info(id, **kwargs) # noqa: E501 return data def get_result_top_dirs_with_http_info(self, id, **kwargs): # noqa: E501 """get_result_top_dirs # noqa: E501 This resource retrieves the top directories. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_top_dirs_with_http_info(id, async=True) >>> result = thread.get() :param async bool :param str id: (required) :return: ResultTopDirs If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_top_dirs" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_top_dirs`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['Id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['basicAuth'] # noqa: E501 return self.api_client.call_api( '/platform/3/fsa/results/{Id}/top-dirs', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultTopDirs', # noqa: E501 auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_top_file(self, result_top_file_id, id, **kwargs): # noqa: E501 """get_result_top_file # noqa: E501 This resource retrieves the top files. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_top_file(result_top_file_id, id, async=True) >>> result = thread.get() :param async bool :param str result_top_file_id: This resource retrieves the top files. ID in the resource path is the result set ID. (required) :param str id: (required) :param str sort: The field that will be used for sorting. :param int start: Starting index for results. Default value of 0. :param int limit: Number of results from start index. Default value of 1000. :param int comp_report: Result set identifier for comparison of database results. :param str dir: The direction of the sort. :return: ResultTopFiles If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_top_file_with_http_info(result_top_file_id, id, **kwargs) # noqa: E501 else: (data) = self.get_result_top_file_with_http_info(result_top_file_id, id, **kwargs) # noqa: E501 return data def get_result_top_file_with_http_info(self, result_top_file_id, id, **kwargs): # noqa: E501 """get_result_top_file # noqa: E501 This resource retrieves the top files. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_top_file_with_http_info(result_top_file_id, id, async=True) >>> result = thread.get() :param async bool :param str result_top_file_id: This resource retrieves the top files. ID in the resource path is the result set ID. (required) :param str id: (required) :param str sort: The field that will be used for sorting. :param int start: Starting index for results. Default value of 0. :param int limit: Number of results from start index. Default value of 1000. :param int comp_report: Result set identifier for comparison of database results. :param str dir: The direction of the sort. :return: ResultTopFiles If the method is called asynchronously, returns the request thread. """ all_params = ['result_top_file_id', 'id', 'sort', 'start', 'limit', 'comp_report', 'dir'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_top_file" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'result_top_file_id' is set if ('result_top_file_id' not in params or params['result_top_file_id'] is None): raise ValueError("Missing the required parameter `result_top_file_id` when calling `get_result_top_file`") # noqa: E501 # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_top_file`") # noqa: E501 collection_formats = {} path_params = {} if 'result_top_file_id' in params: path_params['ResultTopFileId'] = params['result_top_file_id'] # noqa: E501 if 'id' in params: path_params['Id'] = params['id'] # noqa: E501 query_params = [] if 'sort' in params: query_params.append(('sort', params['sort'])) # noqa: E501 if 'start' in params: query_params.append(('start', params['start'])) # noqa: E501 if 'limit' in params: query_params.append(('limit', params['limit'])) # noqa: E501 if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) # noqa: E501 if 'dir' in params: query_params.append(('dir', params['dir'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['basicAuth'] # noqa: E501 return self.api_client.call_api( '/platform/3/fsa/results/{Id}/top-files/{ResultTopFileId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultTopFiles', # noqa: E501 auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_top_files(self, id, **kwargs): # noqa: E501 """get_result_top_files # noqa: E501 This resource retrieves the top files. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_top_files(id, async=True) >>> result = thread.get() :param async bool :param str id: (required) :return: ResultTopFiles If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_top_files_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.get_result_top_files_with_http_info(id, **kwargs) # noqa: E501 return data def get_result_top_files_with_http_info(self, id, **kwargs): # noqa: E501 """get_result_top_files # noqa: E501 This resource retrieves the top files. ID in the resource path is the result set ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_result_top_files_with_http_info(id, async=True) >>> result = thread.get() :param async bool :param str id: (required) :return: ResultTopFiles If the method is called asynchronously, returns the request thread. """ all_params = ['id'] # noqa: E501 all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_top_files" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'id' is set if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_top_files`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in params: path_params['Id'] = params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['basicAuth'] # noqa: E501 return self.api_client.call_api( '/platform/3/fsa/results/{Id}/top-files', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultTopFiles', # noqa: E501 auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
50.056045
334
0.644962
from __future__ import absolute_import import re import six from isi_sdk_8_0.api_client import ApiClient class FsaResultsApi(object): def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def get_histogram_stat_by(self, id, stat, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_histogram_stat_by_with_http_info(id, stat, **kwargs) else: (data) = self.get_histogram_stat_by_with_http_info(id, stat, **kwargs) return data def get_histogram_stat_by_with_http_info(self, id, stat, **kwargs): all_params = ['id', 'stat'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_histogram_stat_by" % key ) params[key] = val del params['kwargs'] if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_histogram_stat_by`") if ('stat' not in params or params['stat'] is None): raise ValueError("Missing the required parameter `stat` when calling `get_histogram_stat_by`") collection_formats = {} path_params = {} if 'id' in params: path_params['Id'] = params['id'] if 'stat' in params: path_params['Stat'] = params['stat'] query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) auth_settings = ['basicAuth'] return self.api_client.call_api( '/platform/3/fsa/results/{Id}/histogram/{Stat}/by', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='HistogramStatBy', auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_histogram_stat_by_breakout(self, histogram_stat_by_breakout, id, stat, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_histogram_stat_by_breakout_with_http_info(histogram_stat_by_breakout, id, stat, **kwargs) else: (data) = self.get_histogram_stat_by_breakout_with_http_info(histogram_stat_by_breakout, id, stat, **kwargs) return data def get_histogram_stat_by_breakout_with_http_info(self, histogram_stat_by_breakout, id, stat, **kwargs): all_params = ['histogram_stat_by_breakout', 'id', 'stat', 'directory_filter', 'attribute_filter', 'node_pool_filter', 'disk_pool_filter', 'tier_filter', 'comp_report', 'log_size_filter', 'phys_size_filter', 'limit', 'path_ext_filter', 'ctime_filter', 'atime_filter'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_histogram_stat_by_breakout" % key ) params[key] = val del params['kwargs'] if ('histogram_stat_by_breakout' not in params or params['histogram_stat_by_breakout'] is None): raise ValueError("Missing the required parameter `histogram_stat_by_breakout` when calling `get_histogram_stat_by_breakout`") if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_histogram_stat_by_breakout`") if ('stat' not in params or params['stat'] is None): raise ValueError("Missing the required parameter `stat` when calling `get_histogram_stat_by_breakout`") collection_formats = {} path_params = {} if 'histogram_stat_by_breakout' in params: path_params['HistogramStatByBreakout'] = params['histogram_stat_by_breakout'] if 'id' in params: path_params['Id'] = params['id'] if 'stat' in params: path_params['Stat'] = params['stat'] query_params = [] if 'directory_filter' in params: query_params.append(('directory_filter', params['directory_filter'])) if 'attribute_filter' in params: query_params.append(('attribute_filter', params['attribute_filter'])) if 'node_pool_filter' in params: query_params.append(('node_pool_filter', params['node_pool_filter'])) if 'disk_pool_filter' in params: query_params.append(('disk_pool_filter', params['disk_pool_filter'])) if 'tier_filter' in params: query_params.append(('tier_filter', params['tier_filter'])) if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) if 'log_size_filter' in params: query_params.append(('log_size_filter', params['log_size_filter'])) if 'phys_size_filter' in params: query_params.append(('phys_size_filter', params['phys_size_filter'])) if 'limit' in params: query_params.append(('limit', params['limit'])) if 'path_ext_filter' in params: query_params.append(('path_ext_filter', params['path_ext_filter'])) if 'ctime_filter' in params: query_params.append(('ctime_filter', params['ctime_filter'])) if 'atime_filter' in params: query_params.append(('atime_filter', params['atime_filter'])) header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) auth_settings = ['basicAuth'] return self.api_client.call_api( '/platform/3/fsa/results/{Id}/histogram/{Stat}/by/{HistogramStatByBreakout}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='HistogramStatBy', auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_directories(self, id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_directories_with_http_info(id, **kwargs) else: (data) = self.get_result_directories_with_http_info(id, **kwargs) return data def get_result_directories_with_http_info(self, id, **kwargs): all_params = ['id', 'sort', 'path', 'limit', 'comp_report', 'dir'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_directories" % key ) params[key] = val del params['kwargs'] if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_directories`") collection_formats = {} path_params = {} if 'id' in params: path_params['Id'] = params['id'] query_params = [] if 'sort' in params: query_params.append(('sort', params['sort'])) if 'path' in params: query_params.append(('path', params['path'])) if 'limit' in params: query_params.append(('limit', params['limit'])) if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) if 'dir' in params: query_params.append(('dir', params['dir'])) header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) auth_settings = ['basicAuth'] return self.api_client.call_api( '/platform/3/fsa/results/{Id}/directories', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultDirectories', auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_directory(self, result_directory_id, id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_directory_with_http_info(result_directory_id, id, **kwargs) else: (data) = self.get_result_directory_with_http_info(result_directory_id, id, **kwargs) return data def get_result_directory_with_http_info(self, result_directory_id, id, **kwargs): all_params = ['result_directory_id', 'id', 'sort', 'limit', 'comp_report', 'dir'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_directory" % key ) params[key] = val del params['kwargs'] if ('result_directory_id' not in params or params['result_directory_id'] is None): raise ValueError("Missing the required parameter `result_directory_id` when calling `get_result_directory`") if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_directory`") collection_formats = {} path_params = {} if 'result_directory_id' in params: path_params['ResultDirectoryId'] = params['result_directory_id'] if 'id' in params: path_params['Id'] = params['id'] query_params = [] if 'sort' in params: query_params.append(('sort', params['sort'])) if 'limit' in params: query_params.append(('limit', params['limit'])) if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) if 'dir' in params: query_params.append(('dir', params['dir'])) header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) auth_settings = ['basicAuth'] return self.api_client.call_api( '/platform/3/fsa/results/{Id}/directories/{ResultDirectoryId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultDirectories', auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_histogram(self, id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_histogram_with_http_info(id, **kwargs) else: (data) = self.get_result_histogram_with_http_info(id, **kwargs) return data def get_result_histogram_with_http_info(self, id, **kwargs): all_params = ['id'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_histogram" % key ) params[key] = val del params['kwargs'] if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_histogram`") collection_formats = {} path_params = {} if 'id' in params: path_params['Id'] = params['id'] query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) auth_settings = ['basicAuth'] return self.api_client.call_api( '/platform/3/fsa/results/{Id}/histogram', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultHistogram', auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_histogram_stat(self, result_histogram_stat, id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_histogram_stat_with_http_info(result_histogram_stat, id, **kwargs) else: (data) = self.get_result_histogram_stat_with_http_info(result_histogram_stat, id, **kwargs) return data def get_result_histogram_stat_with_http_info(self, result_histogram_stat, id, **kwargs): all_params = ['result_histogram_stat', 'id', 'directory_filter', 'attribute_filter', 'node_pool_filter', 'disk_pool_filter', 'tier_filter', 'comp_report', 'log_size_filter', 'phys_size_filter', 'path_ext_filter', 'ctime_filter', 'atime_filter'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_histogram_stat" % key ) params[key] = val del params['kwargs'] if ('result_histogram_stat' not in params or params['result_histogram_stat'] is None): raise ValueError("Missing the required parameter `result_histogram_stat` when calling `get_result_histogram_stat`") if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_histogram_stat`") collection_formats = {} path_params = {} if 'result_histogram_stat' in params: path_params['ResultHistogramStat'] = params['result_histogram_stat'] if 'id' in params: path_params['Id'] = params['id'] query_params = [] if 'directory_filter' in params: query_params.append(('directory_filter', params['directory_filter'])) if 'attribute_filter' in params: query_params.append(('attribute_filter', params['attribute_filter'])) if 'node_pool_filter' in params: query_params.append(('node_pool_filter', params['node_pool_filter'])) if 'disk_pool_filter' in params: query_params.append(('disk_pool_filter', params['disk_pool_filter'])) if 'tier_filter' in params: query_params.append(('tier_filter', params['tier_filter'])) if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) if 'log_size_filter' in params: query_params.append(('log_size_filter', params['log_size_filter'])) if 'phys_size_filter' in params: query_params.append(('phys_size_filter', params['phys_size_filter'])) if 'path_ext_filter' in params: query_params.append(('path_ext_filter', params['path_ext_filter'])) if 'ctime_filter' in params: query_params.append(('ctime_filter', params['ctime_filter'])) if 'atime_filter' in params: query_params.append(('atime_filter', params['atime_filter'])) header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) auth_settings = ['basicAuth'] return self.api_client.call_api( '/platform/3/fsa/results/{Id}/histogram/{ResultHistogramStat}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultHistogram', auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_top_dir(self, result_top_dir_id, id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_top_dir_with_http_info(result_top_dir_id, id, **kwargs) else: (data) = self.get_result_top_dir_with_http_info(result_top_dir_id, id, **kwargs) return data def get_result_top_dir_with_http_info(self, result_top_dir_id, id, **kwargs): all_params = ['result_top_dir_id', 'id', 'sort', 'start', 'limit', 'comp_report', 'dir'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_top_dir" % key ) params[key] = val del params['kwargs'] if ('result_top_dir_id' not in params or params['result_top_dir_id'] is None): raise ValueError("Missing the required parameter `result_top_dir_id` when calling `get_result_top_dir`") if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_top_dir`") collection_formats = {} path_params = {} if 'result_top_dir_id' in params: path_params['ResultTopDirId'] = params['result_top_dir_id'] if 'id' in params: path_params['Id'] = params['id'] query_params = [] if 'sort' in params: query_params.append(('sort', params['sort'])) if 'start' in params: query_params.append(('start', params['start'])) if 'limit' in params: query_params.append(('limit', params['limit'])) if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) if 'dir' in params: query_params.append(('dir', params['dir'])) header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) auth_settings = ['basicAuth'] return self.api_client.call_api( '/platform/3/fsa/results/{Id}/top-dirs/{ResultTopDirId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultTopDirs', auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_top_dirs(self, id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_top_dirs_with_http_info(id, **kwargs) else: (data) = self.get_result_top_dirs_with_http_info(id, **kwargs) return data def get_result_top_dirs_with_http_info(self, id, **kwargs): all_params = ['id'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_top_dirs" % key ) params[key] = val del params['kwargs'] if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_top_dirs`") collection_formats = {} path_params = {} if 'id' in params: path_params['Id'] = params['id'] query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) auth_settings = ['basicAuth'] return self.api_client.call_api( '/platform/3/fsa/results/{Id}/top-dirs', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultTopDirs', auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_top_file(self, result_top_file_id, id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_top_file_with_http_info(result_top_file_id, id, **kwargs) else: (data) = self.get_result_top_file_with_http_info(result_top_file_id, id, **kwargs) return data def get_result_top_file_with_http_info(self, result_top_file_id, id, **kwargs): all_params = ['result_top_file_id', 'id', 'sort', 'start', 'limit', 'comp_report', 'dir'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_top_file" % key ) params[key] = val del params['kwargs'] if ('result_top_file_id' not in params or params['result_top_file_id'] is None): raise ValueError("Missing the required parameter `result_top_file_id` when calling `get_result_top_file`") if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_top_file`") collection_formats = {} path_params = {} if 'result_top_file_id' in params: path_params['ResultTopFileId'] = params['result_top_file_id'] if 'id' in params: path_params['Id'] = params['id'] query_params = [] if 'sort' in params: query_params.append(('sort', params['sort'])) if 'start' in params: query_params.append(('start', params['start'])) if 'limit' in params: query_params.append(('limit', params['limit'])) if 'comp_report' in params: query_params.append(('comp_report', params['comp_report'])) if 'dir' in params: query_params.append(('dir', params['dir'])) header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) auth_settings = ['basicAuth'] return self.api_client.call_api( '/platform/3/fsa/results/{Id}/top-files/{ResultTopFileId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultTopFiles', auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_result_top_files(self, id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_result_top_files_with_http_info(id, **kwargs) else: (data) = self.get_result_top_files_with_http_info(id, **kwargs) return data def get_result_top_files_with_http_info(self, id, **kwargs): all_params = ['id'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_result_top_files" % key ) params[key] = val del params['kwargs'] if ('id' not in params or params['id'] is None): raise ValueError("Missing the required parameter `id` when calling `get_result_top_files`") collection_formats = {} path_params = {} if 'id' in params: path_params['Id'] = params['id'] query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type( ['application/json']) auth_settings = ['basicAuth'] return self.api_client.call_api( '/platform/3/fsa/results/{Id}/top-files', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResultTopFiles', auth_settings=auth_settings, myAsync=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
true
true
1c4412a8c09bdeeffe088f019f7889bfd861cd4d
1,918
py
Python
command/box.py
DrLarck/DragonBotZ
eab773d6e55f7f5f325828fe249800193120abaf
[ "MIT" ]
3
2020-05-01T07:38:38.000Z
2020-06-02T12:03:40.000Z
command/box.py
DrLarck/DragonBotZ
eab773d6e55f7f5f325828fe249800193120abaf
[ "MIT" ]
19
2020-11-01T22:15:57.000Z
2021-09-08T15:28:30.000Z
command/box.py
DrLarck/DragonBotZ
eab773d6e55f7f5f325828fe249800193120abaf
[ "MIT" ]
1
2021-03-05T04:51:21.000Z
2021-03-05T04:51:21.000Z
""" Box command -- Author : Drlarck Last update : 25/12/20 by DrLarck """ from discord.ext import commands # util from utility.command.checker import CommandChecker from utility.entity.player import Player from utility.global_tool import GlobalTool # tool from utility.command.tool.tool_box import ToolBox class CommandBox(commands.Cog): def __init__(self, client): # Public self.client = client @commands.check(CommandChecker.game_ready) @commands.check(CommandChecker.register) @commands.cooldown(1, 10, commands.BucketType.user) @commands.group(invoke_without_command=True) async def box(self, context, rarity: str = None): # Log await self.client.logger.log(context) # Init player = Player(context, self.client, context.message.author) box_tool = ToolBox(self.client, context) global_tool = GlobalTool() # Normal box if rarity is None: await box_tool.box_manager(player) else: # Get the rarity value value = await global_tool.get_rarity_value(rarity) if value is not None: await box_tool.box_manager(player, rarity=value) else: await context.send(f"Sorry, I can't find the rarity `{rarity}`") @commands.check(CommandChecker.game_ready) @commands.check(CommandChecker.register) @commands.cooldown(1, 10, commands.BucketType.user) @box.command(aliases=["u"]) async def unique(self, context, reference: int): # Log await self.client.logger.log(context) # Init player = Player(context, self.client, context.message.author) box_tool = ToolBox(self.client, context) # Display the unique box await box_tool.box_manager(player, unique_reference=reference) def setup(client): client.add_cog(CommandBox(client))
26.273973
80
0.661627
from discord.ext import commands from utility.command.checker import CommandChecker from utility.entity.player import Player from utility.global_tool import GlobalTool from utility.command.tool.tool_box import ToolBox class CommandBox(commands.Cog): def __init__(self, client): self.client = client @commands.check(CommandChecker.game_ready) @commands.check(CommandChecker.register) @commands.cooldown(1, 10, commands.BucketType.user) @commands.group(invoke_without_command=True) async def box(self, context, rarity: str = None): await self.client.logger.log(context) player = Player(context, self.client, context.message.author) box_tool = ToolBox(self.client, context) global_tool = GlobalTool() if rarity is None: await box_tool.box_manager(player) else: value = await global_tool.get_rarity_value(rarity) if value is not None: await box_tool.box_manager(player, rarity=value) else: await context.send(f"Sorry, I can't find the rarity `{rarity}`") @commands.check(CommandChecker.game_ready) @commands.check(CommandChecker.register) @commands.cooldown(1, 10, commands.BucketType.user) @box.command(aliases=["u"]) async def unique(self, context, reference: int): # Log await self.client.logger.log(context) # Init player = Player(context, self.client, context.message.author) box_tool = ToolBox(self.client, context) # Display the unique box await box_tool.box_manager(player, unique_reference=reference) def setup(client): client.add_cog(CommandBox(client))
true
true
1c4412e0c4f9a993f9fd8586877ecb41b54a8605
2,297
py
Python
mlens/parallel/tests/test_a_learner_subset.py
mehrdad-shokri/mlens
6cbc11354b5f9500a33d9cefb700a1bba9d3199a
[ "MIT" ]
760
2017-03-13T10:11:45.000Z
2022-03-30T20:59:20.000Z
mlens/parallel/tests/test_a_learner_subset.py
rahulsaini/mlens
6cbc11354b5f9500a33d9cefb700a1bba9d3199a
[ "MIT" ]
115
2017-01-18T22:10:33.000Z
2022-03-17T12:42:34.000Z
mlens/parallel/tests/test_a_learner_subset.py
rahulsaini/mlens
6cbc11354b5f9500a33d9cefb700a1bba9d3199a
[ "MIT" ]
96
2017-03-13T10:12:48.000Z
2022-02-23T17:12:39.000Z
""""ML-ENSEMBLE Testing suite for Learner and Transformer """ from mlens.testing import Data, EstimatorContainer, get_learner, run_learner def test_fit(): """[Parallel | Learner | Subset | No Proba | No Prep] test fit""" args = get_learner('fit', 'subsemble', False, False) run_learner(*args) def test_predict(): """[Parallel | Learner | Subset | No Proba | No Prep] test predict""" args = get_learner('predict', 'subsemble', False, False) run_learner(*args) def test_transform(): """[Parallel | Learner | Subset | No Proba | No Prep] test transform""" args = get_learner('transform', 'subsemble', False, False) run_learner(*args) def test_fit_prep(): """[Parallel | Learner | Subset | No Proba | Prep] test fit""" args = get_learner('fit', 'subsemble', False, True) run_learner(*args) def test_predict_prep(): """[Parallel | Learner | Subset | No Proba | Prep] test predict""" args = get_learner('predict', 'subsemble', False, True) run_learner(*args) def test_transform_prep(): """[Parallel | Learner | Subset | No Proba | Prep] test transform""" args = get_learner('transform', 'subsemble', False, True) run_learner(*args) def test_fit_proba(): """[Parallel | Learner | Subset | Proba | No Prep] test fit""" args = get_learner('fit', 'subsemble', True, False) run_learner(*args) def test_predict_proba(): """[Parallel | Learner | Subset | Proba | No Prep] test predict""" args = get_learner('predict', 'subsemble', True, False) run_learner(*args) def test_transform_proba(): """[Parallel | Learner | Subset | Proba | No Prep] test transform""" args = get_learner('transform', 'subsemble', True, False) run_learner(*args) def test_fit_prep_proba(): """[Parallel | Learner | Subset | Proba | Prep] test fit""" args = get_learner('fit', 'subsemble', True, True) run_learner(*args) def test_predict_prep_proba(): """[Parallel | Learner | Subset | Proba | No Prep] test predict""" args = get_learner('predict', 'subsemble', True, True) run_learner(*args) def test_transform_prep_proba(): """[Parallel | Learner | Subset | Proba | Prep] test transform""" args = get_learner('transform', 'subsemble', True, True) run_learner(*args)
29.448718
76
0.65825
from mlens.testing import Data, EstimatorContainer, get_learner, run_learner def test_fit(): args = get_learner('fit', 'subsemble', False, False) run_learner(*args) def test_predict(): args = get_learner('predict', 'subsemble', False, False) run_learner(*args) def test_transform(): args = get_learner('transform', 'subsemble', False, False) run_learner(*args) def test_fit_prep(): args = get_learner('fit', 'subsemble', False, True) run_learner(*args) def test_predict_prep(): args = get_learner('predict', 'subsemble', False, True) run_learner(*args) def test_transform_prep(): args = get_learner('transform', 'subsemble', False, True) run_learner(*args) def test_fit_proba(): args = get_learner('fit', 'subsemble', True, False) run_learner(*args) def test_predict_proba(): args = get_learner('predict', 'subsemble', True, False) run_learner(*args) def test_transform_proba(): args = get_learner('transform', 'subsemble', True, False) run_learner(*args) def test_fit_prep_proba(): args = get_learner('fit', 'subsemble', True, True) run_learner(*args) def test_predict_prep_proba(): args = get_learner('predict', 'subsemble', True, True) run_learner(*args) def test_transform_prep_proba(): args = get_learner('transform', 'subsemble', True, True) run_learner(*args)
true
true
1c4413a8fd4db352cd8e11d757e9ebd5c2024042
3,019
py
Python
donations/management/commands/export_translations.py
diffractive/newstream
cf1a1f230e18d01c63b50ab9d360aa44ac5a486f
[ "MIT" ]
1
2020-05-03T12:33:42.000Z
2020-05-03T12:33:42.000Z
donations/management/commands/export_translations.py
diffractive/newstream
cf1a1f230e18d01c63b50ab9d360aa44ac5a486f
[ "MIT" ]
14
2020-07-06T20:05:57.000Z
2022-03-12T00:39:11.000Z
donations/management/commands/export_translations.py
diffractive/newstream
cf1a1f230e18d01c63b50ab9d360aa44ac5a486f
[ "MIT" ]
null
null
null
import csv import os import re from zipfile import ZipFile from django.core.management.base import BaseCommand from django.apps import apps from pages.models import HomePage class Command(BaseCommand): help = 'updates .po files, compiles all i18n fields into a csv file and zips them all into one zip file' def handle(self, *args, **options): # Get all i18nfields values from all models + page content with open('translation_fields.csv', 'w', newline='') as f: writer = csv.writer(f) # header writer.writerow(['Field/Model Name', 'Field Value']) for model in apps.get_models(): i18n_fields = [] for field in model._meta.get_fields(): # relational fields cannot be deconstructed, we don't have translated relational fields anyway if hasattr(field, 'deconstruct'): # more on deconstruct: https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.Field.deconstruct field_info = field.deconstruct() field_name = field_info[0] import_path = field_info[1] if re.search(r'(I18nCharField|I18nTextField|I18nRichTextField)$', import_path): i18n_fields.append(field_name) # loop over all instances to get all english values from the i18n_fields if len(i18n_fields): # First make a row for this model writer.writerow(['[Model] %s' % model.__name__]) for obj in model.objects.all(): for field in i18n_fields: writer.writerow(['[Field] #%i - %s' % (obj.id, field), getattr(obj, field).localize('en')]) # loop over all pages (HomePage) writer.writerow(['[Model] %s' % 'HomePage']) for page in HomePage.objects.all(): # the locale field might still hasn't been set yet if the page wasn't saved after the locales are introduced if str(page.locale) == 'English' or not page.locale: writer.writerow(['[Field] #%i - %s' % (page.id, 'body'), page.body]) # Get all the .po files file_paths = [] for root, directories, files in os.walk('./'): if not re.search(r'^\./(venv|virtualenv|node_modules|\.git)', root): for filename in files: if 'django.po' in filename: # join the two strings in order to form the full filepath. filepath = os.path.join(root, filename) file_paths.append(filepath) # zip all the files together with ZipFile('translation_files.zip', 'w') as zip: for file in file_paths: zip.write(file) zip.write('translation_fields.csv') print('Zip file generated')
47.920635
138
0.561444
import csv import os import re from zipfile import ZipFile from django.core.management.base import BaseCommand from django.apps import apps from pages.models import HomePage class Command(BaseCommand): help = 'updates .po files, compiles all i18n fields into a csv file and zips them all into one zip file' def handle(self, *args, **options): with open('translation_fields.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerow(['Field/Model Name', 'Field Value']) for model in apps.get_models(): i18n_fields = [] for field in model._meta.get_fields(): if hasattr(field, 'deconstruct'): # more on deconstruct: https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.Field.deconstruct field_info = field.deconstruct() field_name = field_info[0] import_path = field_info[1] if re.search(r'(I18nCharField|I18nTextField|I18nRichTextField)$', import_path): i18n_fields.append(field_name) # loop over all instances to get all english values from the i18n_fields if len(i18n_fields): # First make a row for this model writer.writerow(['[Model] %s' % model.__name__]) for obj in model.objects.all(): for field in i18n_fields: writer.writerow(['[Field] # loop over all pages (HomePage) writer.writerow(['[Model] %s' % 'HomePage']) for page in HomePage.objects.all(): # the locale field might still hasn't been set yet if the page wasn't saved after the locales are introduced if str(page.locale) == 'English' or not page.locale: writer.writerow(['[Field] # Get all the .po files file_paths = [] for root, directories, files in os.walk('./'): if not re.search(r'^\./(venv|virtualenv|node_modules|\.git)', root): for filename in files: if 'django.po' in filename: # join the two strings in order to form the full filepath. filepath = os.path.join(root, filename) file_paths.append(filepath) # zip all the files together with ZipFile('translation_files.zip', 'w') as zip: for file in file_paths: zip.write(file) zip.write('translation_fields.csv') print('Zip file generated')
true
true
1c4414e04d2fcbc39108f6767504885c71b48ec0
1,927
py
Python
modules/AIWorker/backend/celery_interface.py
junxnone/aerial_wildlife_detection
0eebed2aaf926ceb212b6a2b7a75bb0a82b28a88
[ "MIT" ]
1
2021-04-26T22:50:52.000Z
2021-04-26T22:50:52.000Z
modules/AIWorker/backend/celery_interface.py
junxnone/aerial_wildlife_detection
0eebed2aaf926ceb212b6a2b7a75bb0a82b28a88
[ "MIT" ]
null
null
null
modules/AIWorker/backend/celery_interface.py
junxnone/aerial_wildlife_detection
0eebed2aaf926ceb212b6a2b7a75bb0a82b28a88
[ "MIT" ]
2
2021-04-15T17:26:40.000Z
2021-04-15T17:26:53.000Z
''' Wrapper for the Celery message broker concerning the AIWorker(s). 2019-20 Benjamin Kellenberger ''' import os from celery import current_app from kombu.common import Broadcast from constants.version import AIDE_VERSION from modules.AIWorker.app import AIWorker from util.configDef import Config # init AIWorker modules = os.environ['AIDE_MODULES'] passiveMode = (os.environ['PASSIVE_MODE']=='1' if 'PASSIVE_MODE' in os.environ else False) or not('aiworker' in modules.lower()) worker = AIWorker(Config(), passiveMode) @current_app.task(name='AIWorker.aide_internal_notify') def aide_internal_notify(message): return worker.aide_internal_notify(message) @current_app.task(name='AIWorker.call_train', rate_limit=1) def call_train(data, index, epoch, numEpochs, project): is_subset = (len(data) > 1) if index < len(data): return worker.call_train(data[index], epoch, numEpochs, project, is_subset) else: # worker not needed print("[{}] Subset {} requested, but only {} chunk(s) provided. Skipping...".format( project, index, len(data) )) return 0 @current_app.task(name='AIWorker.call_average_model_states', rate_limit=1) def call_average_model_states(blank, epoch, numEpochs, project, *args): return worker.call_average_model_states(epoch, numEpochs, project) @current_app.task(name='AIWorker.call_inference') def call_inference(data, index, epoch, numEpochs, project): if index < len(data): return worker.call_inference(data[index], epoch, numEpochs, project) else: # worker not needed print("[{}] Subset {} requested, but only {} chunk(s) provided. Skipping...".format( project, index, len(data) )) return 0 @current_app.task(name='AIWorker.verify_model_state') def verify_model_state(project): return worker.verify_model_state(project)
31.080645
128
0.705241
import os from celery import current_app from kombu.common import Broadcast from constants.version import AIDE_VERSION from modules.AIWorker.app import AIWorker from util.configDef import Config modules = os.environ['AIDE_MODULES'] passiveMode = (os.environ['PASSIVE_MODE']=='1' if 'PASSIVE_MODE' in os.environ else False) or not('aiworker' in modules.lower()) worker = AIWorker(Config(), passiveMode) @current_app.task(name='AIWorker.aide_internal_notify') def aide_internal_notify(message): return worker.aide_internal_notify(message) @current_app.task(name='AIWorker.call_train', rate_limit=1) def call_train(data, index, epoch, numEpochs, project): is_subset = (len(data) > 1) if index < len(data): return worker.call_train(data[index], epoch, numEpochs, project, is_subset) else: print("[{}] Subset {} requested, but only {} chunk(s) provided. Skipping...".format( project, index, len(data) )) return 0 @current_app.task(name='AIWorker.call_average_model_states', rate_limit=1) def call_average_model_states(blank, epoch, numEpochs, project, *args): return worker.call_average_model_states(epoch, numEpochs, project) @current_app.task(name='AIWorker.call_inference') def call_inference(data, index, epoch, numEpochs, project): if index < len(data): return worker.call_inference(data[index], epoch, numEpochs, project) else: print("[{}] Subset {} requested, but only {} chunk(s) provided. Skipping...".format( project, index, len(data) )) return 0 @current_app.task(name='AIWorker.verify_model_state') def verify_model_state(project): return worker.verify_model_state(project)
true
true
1c44168c82761f7500b7377a312882fa34c63c3c
2,479
py
Python
scripts/empirical/generate_hcp_surrogates.py
netneurolab/markello_spatialnulls
06eb614af626791d55be0e1c8fc3694fa0771c67
[ "BSD-3-Clause" ]
8
2020-08-17T13:00:26.000Z
2022-01-09T05:37:44.000Z
scripts/empirical/generate_hcp_surrogates.py
netneurolab/markello_spatialnulls
06eb614af626791d55be0e1c8fc3694fa0771c67
[ "BSD-3-Clause" ]
1
2021-02-24T19:28:37.000Z
2021-02-24T19:28:37.000Z
scripts/empirical/generate_hcp_surrogates.py
netneurolab/markello_spatialnulls
06eb614af626791d55be0e1c8fc3694fa0771c67
[ "BSD-3-Clause" ]
3
2020-08-27T20:00:04.000Z
2021-01-30T01:55:53.000Z
# -*- coding: utf-8 -*- """ Creates surrogate maps for HCP myelin data using Burt 2018 + 2020 methods. In both cases, surrogate maps are stored as resampling arrays of the original maps and are saved to `data/derivatives/surrogates/<atlas>/<method>/hcp`. """ from pathlib import Path from joblib import Parallel, delayed from parspin import surrogates, utils as putils ROIDIR = Path('./data/raw/rois').resolve() HCPDIR = Path('./data/derivatives/hcp').resolve() DISTDIR = Path('./data/derivatives/geodesic').resolve() SURRDIR = Path('./data/derivatives/surrogates').resolve() SEED = 1234 N_PROC = 36 N_PERM = 10000 def burt2018_surrogates(name, scale): """ Generates surrogates according to Burt et al., 2018, Nat Neuro Parameters ---------- atlas : {'atl-cammoun2012', 'atl-schaefer2018'}, str Name of atlas for which to load data scale : str Scale of atlas to use """ fn = SURRDIR / name / 'burt2018' / 'hcp' / f'{scale}_surrogates.csv' if fn.exists(): return # load data + distance matrix for given parcellation lh, rh = surrogates.load_data(HCPDIR, name, scale)[:-1] dlh, drh = surrogates.load_dist(DISTDIR, name, scale) # generate surrogates and save to disk surrogates.burt2018_surrogates(lh, rh, dlh, drh, fname=fn, n_perm=N_PERM) def burt2020_surrogates(name, scale): """ Generates surrogates according to Burt et al., 2020, NeuroImage Parameters ---------- atlas : {'atl-cammoun2012', 'atl-schaefer2018'}, str Name of atlas for which to load data scale : str Scale of atlas to use """ fn = SURRDIR / name / 'burt2020' / 'hcp' / f'{scale}_surrogates.csv' if fn.exists(): return # load data + distance matrix for given parcellation lh, rh = surrogates.load_data(HCPDIR, name, scale)[:-1] dlh, drh = surrogates.load_dist(DISTDIR, name, scale) # generate surrogates and save to disk surrogates.burt2020_surrogates(lh, rh, dlh, drh, fname=fn, n_perm=N_PERM, seed=SEED) if __name__ == '__main__': # get cammoun + schaefer parcellations parcellations = putils.get_cammoun_schaefer(data_dir=ROIDIR) for func in (burt2018_surrogates, burt2020_surrogates): Parallel(n_jobs=N_PROC)( delayed(func)(name, scale) for (name, annotations) in parcellations.items() for (scale, annot) in annotations.items() )
30.231707
79
0.657523
from pathlib import Path from joblib import Parallel, delayed from parspin import surrogates, utils as putils ROIDIR = Path('./data/raw/rois').resolve() HCPDIR = Path('./data/derivatives/hcp').resolve() DISTDIR = Path('./data/derivatives/geodesic').resolve() SURRDIR = Path('./data/derivatives/surrogates').resolve() SEED = 1234 N_PROC = 36 N_PERM = 10000 def burt2018_surrogates(name, scale): fn = SURRDIR / name / 'burt2018' / 'hcp' / f'{scale}_surrogates.csv' if fn.exists(): return lh, rh = surrogates.load_data(HCPDIR, name, scale)[:-1] dlh, drh = surrogates.load_dist(DISTDIR, name, scale) surrogates.burt2018_surrogates(lh, rh, dlh, drh, fname=fn, n_perm=N_PERM) def burt2020_surrogates(name, scale): fn = SURRDIR / name / 'burt2020' / 'hcp' / f'{scale}_surrogates.csv' if fn.exists(): return lh, rh = surrogates.load_data(HCPDIR, name, scale)[:-1] dlh, drh = surrogates.load_dist(DISTDIR, name, scale) surrogates.burt2020_surrogates(lh, rh, dlh, drh, fname=fn, n_perm=N_PERM, seed=SEED) if __name__ == '__main__': parcellations = putils.get_cammoun_schaefer(data_dir=ROIDIR) for func in (burt2018_surrogates, burt2020_surrogates): Parallel(n_jobs=N_PROC)( delayed(func)(name, scale) for (name, annotations) in parcellations.items() for (scale, annot) in annotations.items() )
true
true
1c4416da16e0e24c7acaf69acc78211ad072d992
3,296
py
Python
update_windows_mappings.py
jean/tzlocal
37b49de83103f81c5e3f414eacf265972b85f9af
[ "MIT" ]
null
null
null
update_windows_mappings.py
jean/tzlocal
37b49de83103f81c5e3f414eacf265972b85f9af
[ "MIT" ]
null
null
null
update_windows_mappings.py
jean/tzlocal
37b49de83103f81c5e3f414eacf265972b85f9af
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # This script generates the mapping between MS Windows timezone names and # tzdata/Olsen timezone names, by retrieving a file: # http://unicode.org/cldr/data/common/supplemental/supplementalData.xml # and parsing it, and from this generating the file windows_tz.py. # # It must be run with Python 3. import ftplib import logging from io import BytesIO from pprint import pprint import tarfile from urllib.parse import urlparse from urllib.request import urlopen from xml.dom import minidom WIN_ZONES_URL = 'http://unicode.org/repos/cldr/trunk/common/supplemental/windowsZones.xml' ZONEINFO_URL = 'ftp://ftp.iana.org/tz/tzdata-latest.tar.gz' logging.basicConfig(level=logging.INFO) log = logging.getLogger() def update_old_names(): """Fetches the list of old tz names and returns a mapping""" url = urlparse(ZONEINFO_URL) log.info('Connecting to %s' % url.netloc) ftp = ftplib.FTP(url.netloc) ftp.login() gzfile = BytesIO() log.info('Fetching zoneinfo database') ftp.retrbinary('RETR ' + url.path, gzfile.write) gzfile.seek(0) log.info('Extracting backwards data') archive = tarfile.open(mode="r:gz", fileobj=gzfile) backward = {} for line in archive.extractfile('backward').readlines(): if line[0] == '#': continue if len(line.strip()) == 0: continue parts = line.split() if parts[0] != b'Link': continue backward[parts[2].decode('ascii')] = parts[1].decode('ascii') return backward def update_windows_zones(): backward = update_old_names() log.info('Fetching Windows mapping info from unicode.org') source = urlopen(WIN_ZONES_URL).read() dom = minidom.parseString(source) for element in dom.getElementsByTagName('mapTimezones'): if element.getAttribute('type') == 'windows': break log.info('Making windows mapping') win_tz = {} tz_win = {} for mapping in element.getElementsByTagName('mapZone'): if mapping.getAttribute('territory') == '001': win_tz[mapping.getAttribute('other')] = mapping.getAttribute('type').split(' ')[0] if win_tz[mapping.getAttribute('other')].startswith('Etc'): print (win_tz[mapping.getAttribute('other')], mapping.getAttribute('type').split(' ')[0]) for tz_name in mapping.getAttribute('type').split(' '): tz_win[tz_name] = mapping.getAttribute('other') log.info('Adding backwards data') # Map in the backwards compatible zone names for backward_compat_name, standard_name in backward.items(): win_zone = tz_win.get(standard_name, None) if win_zone: tz_win[backward_compat_name] = win_zone # Etc/UTC is a common but non-standard alias for Etc/GMT: tz_win['Etc/UTC'] = 'UTC' log.info('Writing mapping') with open('tzlocal/windows_tz.py', "wt") as out: out.write("# This file is autogenerated by the update_windows_mapping.py script\n" "# Do not edit.\nwin_tz = ") pprint(win_tz, out) out.write("\n# Old name for the win_tz variable:\ntz_names = win_tz\n\ntz_win = ") pprint(tz_win, out) log.info('Done') if __name__ == '__main__': update_windows_zones()
32.313725
105
0.664138
import ftplib import logging from io import BytesIO from pprint import pprint import tarfile from urllib.parse import urlparse from urllib.request import urlopen from xml.dom import minidom WIN_ZONES_URL = 'http://unicode.org/repos/cldr/trunk/common/supplemental/windowsZones.xml' ZONEINFO_URL = 'ftp://ftp.iana.org/tz/tzdata-latest.tar.gz' logging.basicConfig(level=logging.INFO) log = logging.getLogger() def update_old_names(): url = urlparse(ZONEINFO_URL) log.info('Connecting to %s' % url.netloc) ftp = ftplib.FTP(url.netloc) ftp.login() gzfile = BytesIO() log.info('Fetching zoneinfo database') ftp.retrbinary('RETR ' + url.path, gzfile.write) gzfile.seek(0) log.info('Extracting backwards data') archive = tarfile.open(mode="r:gz", fileobj=gzfile) backward = {} for line in archive.extractfile('backward').readlines(): if line[0] == '#': continue if len(line.strip()) == 0: continue parts = line.split() if parts[0] != b'Link': continue backward[parts[2].decode('ascii')] = parts[1].decode('ascii') return backward def update_windows_zones(): backward = update_old_names() log.info('Fetching Windows mapping info from unicode.org') source = urlopen(WIN_ZONES_URL).read() dom = minidom.parseString(source) for element in dom.getElementsByTagName('mapTimezones'): if element.getAttribute('type') == 'windows': break log.info('Making windows mapping') win_tz = {} tz_win = {} for mapping in element.getElementsByTagName('mapZone'): if mapping.getAttribute('territory') == '001': win_tz[mapping.getAttribute('other')] = mapping.getAttribute('type').split(' ')[0] if win_tz[mapping.getAttribute('other')].startswith('Etc'): print (win_tz[mapping.getAttribute('other')], mapping.getAttribute('type').split(' ')[0]) for tz_name in mapping.getAttribute('type').split(' '): tz_win[tz_name] = mapping.getAttribute('other') log.info('Adding backwards data') for backward_compat_name, standard_name in backward.items(): win_zone = tz_win.get(standard_name, None) if win_zone: tz_win[backward_compat_name] = win_zone tz_win['Etc/UTC'] = 'UTC' log.info('Writing mapping') with open('tzlocal/windows_tz.py', "wt") as out: out.write("# This file is autogenerated by the update_windows_mapping.py script\n" "# Do not edit.\nwin_tz = ") pprint(win_tz, out) out.write("\n# Old name for the win_tz variable:\ntz_names = win_tz\n\ntz_win = ") pprint(tz_win, out) log.info('Done') if __name__ == '__main__': update_windows_zones()
true
true
1c44181b13c6e5605edca9644c493c62871b48d8
900
py
Python
todoism/apis/v1/errors.py
zhaofangfang1991/airsupport-
b2599091dae6105ad7a01444acb9ab53d273675e
[ "MIT" ]
null
null
null
todoism/apis/v1/errors.py
zhaofangfang1991/airsupport-
b2599091dae6105ad7a01444acb9ab53d273675e
[ "MIT" ]
null
null
null
todoism/apis/v1/errors.py
zhaofangfang1991/airsupport-
b2599091dae6105ad7a01444acb9ab53d273675e
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from flask import jsonify from werkzeug.http import HTTP_STATUS_CODES from todoism.apis.v1 import api_v1 def api_abort(code, message=None, **kwargs): if message is None: message = HTTP_STATUS_CODES.get(code, '') response = jsonify(code=code, message=message, **kwargs) response.status_code = code return response # You can also just return (response, code) tuple def invalid_token(): response = api_abort(401, error='invalid_token', error_description='Either the token was expired or invalid.') response.headers['WWW-Authenticate'] = 'Bearer' return response def token_missing(): response = api_abort(401) response.headers['WWW-Authenticate'] = 'Bearer' return response class ValidationError(ValueError): pass @api_v1.errorhandler(ValidationError) def validation_error(e): return api_abort(400, e.args[0])
24.324324
114
0.718889
from flask import jsonify from werkzeug.http import HTTP_STATUS_CODES from todoism.apis.v1 import api_v1 def api_abort(code, message=None, **kwargs): if message is None: message = HTTP_STATUS_CODES.get(code, '') response = jsonify(code=code, message=message, **kwargs) response.status_code = code return response def invalid_token(): response = api_abort(401, error='invalid_token', error_description='Either the token was expired or invalid.') response.headers['WWW-Authenticate'] = 'Bearer' return response def token_missing(): response = api_abort(401) response.headers['WWW-Authenticate'] = 'Bearer' return response class ValidationError(ValueError): pass @api_v1.errorhandler(ValidationError) def validation_error(e): return api_abort(400, e.args[0])
true
true
1c441909547247dc21e1764be21febe8946d6c2e
6,424
py
Python
global_directions/cog_predict.py
bfirsh/StyleCLIP
164fa8497ea91ea184c0488fcc5e3e14f709561a
[ "MIT" ]
null
null
null
global_directions/cog_predict.py
bfirsh/StyleCLIP
164fa8497ea91ea184c0488fcc5e3e14f709561a
[ "MIT" ]
null
null
null
global_directions/cog_predict.py
bfirsh/StyleCLIP
164fa8497ea91ea184c0488fcc5e3e14f709561a
[ "MIT" ]
null
null
null
import tempfile from pathlib import Path import os from argparse import Namespace import time import dlib import os import sys import numpy as np from PIL import Image import torch import torchvision.transforms as transforms import tensorflow as tf import numpy as np import torch import clip from PIL import Image import pickle import copy import matplotlib.pyplot as plt from MapTS import GetFs, GetBoundary, GetDt from manipulate import Manipulator from dnnlib import tflib sys.path.insert(0, "/content") sys.path.insert(0, "/content/encoder4editing") from encoder4editing.utils.common import tensor2im from encoder4editing.utils.alignment import align_face from encoder4editing.models.psp import pSp import cog class Model(cog.Model): def setup(self): print("starting setup") self.device = "cuda" if torch.cuda.is_available() else "cpu" self.model, self.preprocess = clip.load( "ViT-B/32", device=self.device, jit=False ) self.graph = tf.get_default_graph() gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333) self.sess = tf.Session( graph=self.graph, config=tf.ConfigProto(gpu_options=gpu_options) ) experiment_type = "ffhq_encode" self.experiment_args = {"model_path": "e4e_ffhq_encode.pt"} self.experiment_args["transform"] = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), ] ) self.resize_dims = (256, 256) model_path = self.experiment_args["model_path"] ckpt = torch.load(model_path, map_location="cpu") opts = ckpt["opts"] # pprint.pprint(opts) # Display full options used # update the training options opts["checkpoint_path"] = model_path opts = Namespace(**opts) self.net = pSp(opts) self.net.eval() self.net.cuda() self.shape_predictor = dlib.shape_predictor( "/content/shape_predictor_68_face_landmarks.dat" ) with self.graph.as_default(), self.sess.as_default(): #tflib.init_tf() self.M = Manipulator(dataset_name="ffhq", sess=self.sess) self.fs3 = np.load("./npy/ffhq/fs3.npy") np.set_printoptions(suppress=True) print("setup complete") @cog.input("input", type=Path, help="Input image") @cog.input("neutral", type=str, help="Neutral image description") @cog.input("target", type=str, help="Target image description") @cog.input( "manipulation_strength", type=float, min=-10, max=10, default=4.1, help="The higher the manipulation strength, the closer the generated image becomes to the target description. Negative values moves the generated image further from the target description", ) @cog.input( "disentanglement_threshold", type=float, min=0.08, max=0.3, default=0.15, help="The higher the disentanglement threshold, the more specific the changes are to the target attribute. Lower values mean that broader changes are made to the input image", ) def predict( self, input, neutral, target, manipulation_strength, disentanglement_threshold, ): # @title Align image original_image = Image.open(str(input)) original_image = original_image.convert("RGB") input_image = self.run_alignment(str(input)) input_image = original_image input_image.resize(self.resize_dims) img_transforms = self.experiment_args["transform"] transformed_image = img_transforms(input_image) with torch.no_grad(): images, latents = self.run_on_batch(transformed_image.unsqueeze(0)) result_image, latent = images[0], latents[0] print("latents", latents) print(transformed_image.shape, result_image.shape) w_plus = latents.cpu().detach().numpy() with self.graph.as_default(), self.sess.as_default(): dlatents_loaded = self.M.W2S(w_plus) #print("w_plus, dlatents_loaded", w_plus, dlatents_loaded) img_index = 0 w_plus=latents.cpu().detach().numpy() with self.graph.as_default(), self.sess.as_default(): dlatents_loaded=self.M.W2S(w_plus) img_indexs=[img_index] dlatent_tmp=[tmp[img_indexs] for tmp in dlatents_loaded] with self.graph.as_default(), self.sess.as_default(): self.M.num_images = len(img_indexs) self.M.alpha = [0] self.M.manipulate_layers = [0] with self.graph.as_default(), self.sess.as_default(): codes, out = self.M.EditOneC(0, dlatent_tmp) original = Image.fromarray(out[0, 0]).resize((512, 512)) with self.graph.as_default(), self.sess.as_default(): self.M.manipulate_layers = None classnames = [target, neutral] dt = GetDt(classnames, self.model) with self.graph.as_default(), self.sess.as_default(): self.M.alpha = [manipulation_strength] boundary_tmp2, c = GetBoundary( self.fs3, dt, self.M, threshold=disentanglement_threshold ) codes = self.M.MSCode(dlatent_tmp, boundary_tmp2) out = self.M.GenerateImg(codes) generated = Image.fromarray(out[0, 0]) # .resize((512,512)) out_path = Path(tempfile.mkdtemp()) / "out.jpg" generated.save(str(out_path)) return out_path def run_alignment(self, image_path): aligned_image = align_face(filepath=image_path, predictor=self.shape_predictor) print("Aligned image has shape: {}".format(aligned_image.size)) return aligned_image def run_on_batch(self, inputs): images, latents = self.net( inputs.to("cuda").float(), randomize_noise=False, return_latents=True ) return images, latents def concat_images(*images): width = 0 for im in images: width += im.width height = max([im.height for im in images]) concat = Image.new("RGB", (width, height)) offset = 0 for im in images: concat.paste(im, (offset, 0)) offset += im.width return concat
32.444444
197
0.636986
import tempfile from pathlib import Path import os from argparse import Namespace import time import dlib import os import sys import numpy as np from PIL import Image import torch import torchvision.transforms as transforms import tensorflow as tf import numpy as np import torch import clip from PIL import Image import pickle import copy import matplotlib.pyplot as plt from MapTS import GetFs, GetBoundary, GetDt from manipulate import Manipulator from dnnlib import tflib sys.path.insert(0, "/content") sys.path.insert(0, "/content/encoder4editing") from encoder4editing.utils.common import tensor2im from encoder4editing.utils.alignment import align_face from encoder4editing.models.psp import pSp import cog class Model(cog.Model): def setup(self): print("starting setup") self.device = "cuda" if torch.cuda.is_available() else "cpu" self.model, self.preprocess = clip.load( "ViT-B/32", device=self.device, jit=False ) self.graph = tf.get_default_graph() gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333) self.sess = tf.Session( graph=self.graph, config=tf.ConfigProto(gpu_options=gpu_options) ) experiment_type = "ffhq_encode" self.experiment_args = {"model_path": "e4e_ffhq_encode.pt"} self.experiment_args["transform"] = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), ] ) self.resize_dims = (256, 256) model_path = self.experiment_args["model_path"] ckpt = torch.load(model_path, map_location="cpu") opts = ckpt["opts"] ckpoint_path"] = model_path opts = Namespace(**opts) self.net = pSp(opts) self.net.eval() self.net.cuda() self.shape_predictor = dlib.shape_predictor( "/content/shape_predictor_68_face_landmarks.dat" ) with self.graph.as_default(), self.sess.as_default(): self.M = Manipulator(dataset_name="ffhq", sess=self.sess) self.fs3 = np.load("./npy/ffhq/fs3.npy") np.set_printoptions(suppress=True) print("setup complete") @cog.input("input", type=Path, help="Input image") @cog.input("neutral", type=str, help="Neutral image description") @cog.input("target", type=str, help="Target image description") @cog.input( "manipulation_strength", type=float, min=-10, max=10, default=4.1, help="The higher the manipulation strength, the closer the generated image becomes to the target description. Negative values moves the generated image further from the target description", ) @cog.input( "disentanglement_threshold", type=float, min=0.08, max=0.3, default=0.15, help="The higher the disentanglement threshold, the more specific the changes are to the target attribute. Lower values mean that broader changes are made to the input image", ) def predict( self, input, neutral, target, manipulation_strength, disentanglement_threshold, ): original_image = Image.open(str(input)) original_image = original_image.convert("RGB") input_image = self.run_alignment(str(input)) input_image = original_image input_image.resize(self.resize_dims) img_transforms = self.experiment_args["transform"] transformed_image = img_transforms(input_image) with torch.no_grad(): images, latents = self.run_on_batch(transformed_image.unsqueeze(0)) result_image, latent = images[0], latents[0] print("latents", latents) print(transformed_image.shape, result_image.shape) w_plus = latents.cpu().detach().numpy() with self.graph.as_default(), self.sess.as_default(): dlatents_loaded = self.M.W2S(w_plus) img_index = 0 w_plus=latents.cpu().detach().numpy() with self.graph.as_default(), self.sess.as_default(): dlatents_loaded=self.M.W2S(w_plus) img_indexs=[img_index] dlatent_tmp=[tmp[img_indexs] for tmp in dlatents_loaded] with self.graph.as_default(), self.sess.as_default(): self.M.num_images = len(img_indexs) self.M.alpha = [0] self.M.manipulate_layers = [0] with self.graph.as_default(), self.sess.as_default(): codes, out = self.M.EditOneC(0, dlatent_tmp) original = Image.fromarray(out[0, 0]).resize((512, 512)) with self.graph.as_default(), self.sess.as_default(): self.M.manipulate_layers = None classnames = [target, neutral] dt = GetDt(classnames, self.model) with self.graph.as_default(), self.sess.as_default(): self.M.alpha = [manipulation_strength] boundary_tmp2, c = GetBoundary( self.fs3, dt, self.M, threshold=disentanglement_threshold ) codes = self.M.MSCode(dlatent_tmp, boundary_tmp2) out = self.M.GenerateImg(codes) generated = Image.fromarray(out[0, 0]) out_path = Path(tempfile.mkdtemp()) / "out.jpg" generated.save(str(out_path)) return out_path def run_alignment(self, image_path): aligned_image = align_face(filepath=image_path, predictor=self.shape_predictor) print("Aligned image has shape: {}".format(aligned_image.size)) return aligned_image def run_on_batch(self, inputs): images, latents = self.net( inputs.to("cuda").float(), randomize_noise=False, return_latents=True ) return images, latents def concat_images(*images): width = 0 for im in images: width += im.width height = max([im.height for im in images]) concat = Image.new("RGB", (width, height)) offset = 0 for im in images: concat.paste(im, (offset, 0)) offset += im.width return concat
true
true
1c4419cfc5241033119415ac6f09947cc75e8ab2
40,341
py
Python
superset/security/manager.py
GodelTech/superset
da170aa57e94053cf715f7b41b09901c813a149a
[ "Apache-2.0" ]
44
2021-04-14T10:53:36.000Z
2021-09-11T00:29:50.000Z
superset/security/manager.py
GodelTech/superset
da170aa57e94053cf715f7b41b09901c813a149a
[ "Apache-2.0" ]
60
2021-04-09T08:17:13.000Z
2022-03-04T07:41:38.000Z
superset/security/manager.py
GodelTech/superset
da170aa57e94053cf715f7b41b09901c813a149a
[ "Apache-2.0" ]
11
2021-06-09T08:30:57.000Z
2021-11-30T03:16:14.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # pylint: disable=too-few-public-methods """A set of constants and methods to manage permissions and security""" import logging import re from typing import Any, Callable, cast, List, Optional, Set, Tuple, TYPE_CHECKING, Union from flask import current_app, g from flask_appbuilder import Model from flask_appbuilder.security.sqla.manager import SecurityManager from flask_appbuilder.security.sqla.models import ( assoc_permissionview_role, assoc_user_role, PermissionView, Role, User, ) from flask_appbuilder.security.views import ( PermissionModelView, PermissionViewModelView, RoleModelView, UserModelView, ViewMenuModelView, ) from flask_appbuilder.widgets import ListWidget from sqlalchemy import and_, or_ from sqlalchemy.engine.base import Connection from sqlalchemy.orm import Session from sqlalchemy.orm.mapper import Mapper from sqlalchemy.orm.query import Query as SqlaQuery from superset import sql_parse from superset.connectors.connector_registry import ConnectorRegistry from superset.constants import RouteMethod from superset.errors import ErrorLevel, SupersetError, SupersetErrorType from superset.exceptions import SupersetSecurityException from superset.utils.core import DatasourceName, RowLevelSecurityFilterType if TYPE_CHECKING: from superset.common.query_context import QueryContext from superset.connectors.base.models import BaseDatasource from superset.connectors.druid.models import DruidCluster from superset.models.dashboard import Dashboard from superset.models.core import Database from superset.models.sql_lab import Query from superset.sql_parse import Table from superset.viz import BaseViz logger = logging.getLogger(__name__) class SupersetSecurityListWidget(ListWidget): """ Redeclaring to avoid circular imports """ template = "superset/fab_overrides/list.html" class SupersetRoleListWidget(ListWidget): """ Role model view from FAB already uses a custom list widget override So we override the override """ template = "superset/fab_overrides/list_role.html" def __init__(self, **kwargs: Any) -> None: kwargs["appbuilder"] = current_app.appbuilder super().__init__(**kwargs) UserModelView.list_widget = SupersetSecurityListWidget RoleModelView.list_widget = SupersetRoleListWidget PermissionViewModelView.list_widget = SupersetSecurityListWidget PermissionModelView.list_widget = SupersetSecurityListWidget # Limiting routes on FAB model views UserModelView.include_route_methods = RouteMethod.CRUD_SET | { RouteMethod.ACTION, RouteMethod.API_READ, RouteMethod.ACTION_POST, "userinfo", } RoleModelView.include_route_methods = RouteMethod.CRUD_SET PermissionViewModelView.include_route_methods = {RouteMethod.LIST} PermissionModelView.include_route_methods = {RouteMethod.LIST} ViewMenuModelView.include_route_methods = {RouteMethod.LIST} RoleModelView.list_columns = ["name"] RoleModelView.edit_columns = ["name", "permissions", "user"] RoleModelView.related_views = [] class SupersetSecurityManager( # pylint: disable=too-many-public-methods SecurityManager ): userstatschartview = None READ_ONLY_MODEL_VIEWS = {"Database", "DruidClusterModelView", "DynamicPlugin"} USER_MODEL_VIEWS = { "UserDBModelView", "UserLDAPModelView", "UserOAuthModelView", "UserOIDModelView", "UserRemoteUserModelView", } GAMMA_READ_ONLY_MODEL_VIEWS = { "Dataset", "DruidColumnInlineView", "DruidDatasourceModelView", "DruidMetricInlineView", "Datasource", } | READ_ONLY_MODEL_VIEWS ADMIN_ONLY_VIEW_MENUS = { "AccessRequestsModelView", "SQL Lab", "Refresh Druid Metadata", "ResetPasswordView", "RoleModelView", "Log", "Security", "Row Level Security", "Row Level Security Filters", "RowLevelSecurityFiltersModelView", } | USER_MODEL_VIEWS ALPHA_ONLY_VIEW_MENUS = { "Manage", "CSS Templates", "Queries", "Import dashboards", "Upload a CSV", } ADMIN_ONLY_PERMISSIONS = { "can_sql_json", # TODO: move can_sql_json to sql_lab role "can_override_role_permissions", "can_sync_druid_source", "can_override_role_permissions", "can_approve", "can_update_role", "all_query_access", } READ_ONLY_PERMISSION = { "can_show", "can_list", "can_get", "can_external_metadata", "can_read", } ALPHA_ONLY_PERMISSIONS = { "muldelete", "all_database_access", "all_datasource_access", } OBJECT_SPEC_PERMISSIONS = { "database_access", "schema_access", "datasource_access", "metric_access", } ACCESSIBLE_PERMS = {"can_userinfo", "resetmypassword"} data_access_permissions = ( "database_access", "schema_access", "datasource_access", "all_datasource_access", "all_database_access", "all_query_access", ) def get_schema_perm( # pylint: disable=no-self-use self, database: Union["Database", str], schema: Optional[str] = None ) -> Optional[str]: """ Return the database specific schema permission. :param database: The Superset database or database name :param schema: The Superset schema name :return: The database specific schema permission """ if schema: return f"[{database}].[{schema}]" return None def unpack_schema_perm( # pylint: disable=no-self-use self, schema_permission: str ) -> Tuple[str, str]: # [database_name].[schema_name] schema_name = schema_permission.split(".")[1][1:-1] database_name = schema_permission.split(".")[0][1:-1] return database_name, schema_name def can_access(self, permission_name: str, view_name: str) -> bool: """ Return True if the user can access the FAB permission/view, False otherwise. Note this method adds protection from has_access failing from missing permission/view entries. :param permission_name: The FAB permission name :param view_name: The FAB view-menu name :returns: Whether the user can access the FAB permission/view """ user = g.user if user.is_anonymous: return self.is_item_public(permission_name, view_name) return self._has_view_access(user, permission_name, view_name) def can_access_all_queries(self) -> bool: """ Return True if the user can access all SQL Lab queries, False otherwise. :returns: Whether the user can access all queries """ return self.can_access("all_query_access", "all_query_access") def can_access_all_datasources(self) -> bool: """ Return True if the user can fully access all the Superset datasources, False otherwise. :returns: Whether the user can fully access all Superset datasources """ return self.can_access("all_datasource_access", "all_datasource_access") def can_access_all_databases(self) -> bool: """ Return True if the user can fully access all the Superset databases, False otherwise. :returns: Whether the user can fully access all Superset databases """ return self.can_access("all_database_access", "all_database_access") def can_access_database(self, database: Union["Database", "DruidCluster"]) -> bool: """ Return True if the user can fully access the Superset database, False otherwise. Note for Druid the database is akin to the Druid cluster. :param database: The Superset database :returns: Whether the user can fully access the Superset database """ return ( self.can_access_all_datasources() or self.can_access_all_databases() or self.can_access("database_access", database.perm) # type: ignore ) def can_access_schema(self, datasource: "BaseDatasource") -> bool: """ Return True if the user can fully access the schema associated with the Superset datasource, False otherwise. Note for Druid datasources the database and schema are akin to the Druid cluster and datasource name prefix respectively, i.e., [schema.]datasource. :param datasource: The Superset datasource :returns: Whether the user can fully access the datasource's schema """ return ( self.can_access_all_datasources() or self.can_access_database(datasource.database) or self.can_access("schema_access", datasource.schema_perm or "") ) def can_access_datasource(self, datasource: "BaseDatasource") -> bool: """ Return True if the user can fully access of the Superset datasource, False otherwise. :param datasource: The Superset datasource :returns: Whether the user can fully access the Superset datasource """ try: self.raise_for_access(datasource=datasource) except SupersetSecurityException: return False return True @staticmethod def get_datasource_access_error_msg(datasource: "BaseDatasource") -> str: """ Return the error message for the denied Superset datasource. :param datasource: The denied Superset datasource :returns: The error message """ return f"""This endpoint requires the datasource {datasource.name}, database or `all_datasource_access` permission""" @staticmethod def get_datasource_access_link( # pylint: disable=unused-argument datasource: "BaseDatasource", ) -> Optional[str]: """ Return the link for the denied Superset datasource. :param datasource: The denied Superset datasource :returns: The access URL """ from superset import conf return conf.get("PERMISSION_INSTRUCTIONS_LINK") def get_datasource_access_error_object( # pylint: disable=invalid-name self, datasource: "BaseDatasource" ) -> SupersetError: """ Return the error object for the denied Superset datasource. :param datasource: The denied Superset datasource :returns: The error object """ return SupersetError( error_type=SupersetErrorType.DATASOURCE_SECURITY_ACCESS_ERROR, message=self.get_datasource_access_error_msg(datasource), level=ErrorLevel.ERROR, extra={ "link": self.get_datasource_access_link(datasource), "datasource": datasource.name, }, ) def get_table_access_error_msg( # pylint: disable=no-self-use self, tables: Set["Table"] ) -> str: """ Return the error message for the denied SQL tables. :param tables: The set of denied SQL tables :returns: The error message """ quoted_tables = [f"`{table}`" for table in tables] return f"""You need access to the following tables: {", ".join(quoted_tables)}, `all_database_access` or `all_datasource_access` permission""" def get_table_access_error_object(self, tables: Set["Table"]) -> SupersetError: """ Return the error object for the denied SQL tables. :param tables: The set of denied SQL tables :returns: The error object """ return SupersetError( error_type=SupersetErrorType.TABLE_SECURITY_ACCESS_ERROR, message=self.get_table_access_error_msg(tables), level=ErrorLevel.ERROR, extra={ "link": self.get_table_access_link(tables), "tables": [str(table) for table in tables], }, ) def get_table_access_link( # pylint: disable=unused-argument,no-self-use self, tables: Set["Table"] ) -> Optional[str]: """ Return the access link for the denied SQL tables. :param tables: The set of denied SQL tables :returns: The access URL """ from superset import conf return conf.get("PERMISSION_INSTRUCTIONS_LINK") def can_access_table(self, database: "Database", table: "Table") -> bool: """ Return True if the user can access the SQL table, False otherwise. :param database: The SQL database :param table: The SQL table :returns: Whether the user can access the SQL table """ try: self.raise_for_access(database=database, table=table) except SupersetSecurityException: return False return True def user_view_menu_names(self, permission_name: str) -> Set[str]: base_query = ( self.get_session.query(self.viewmenu_model.name) .join(self.permissionview_model) .join(self.permission_model) .join(assoc_permissionview_role) .join(self.role_model) ) if not g.user.is_anonymous: # filter by user id view_menu_names = ( base_query.join(assoc_user_role) .join(self.user_model) .filter(self.user_model.id == g.user.id) .filter(self.permission_model.name == permission_name) ).all() return {s.name for s in view_menu_names} # Properly treat anonymous user public_role = self.get_public_role() if public_role: # filter by public role view_menu_names = ( base_query.filter(self.role_model.id == public_role.id).filter( self.permission_model.name == permission_name ) ).all() return {s.name for s in view_menu_names} return set() def get_schemas_accessible_by_user( self, database: "Database", schemas: List[str], hierarchical: bool = True ) -> List[str]: """ Return the list of SQL schemas accessible by the user. :param database: The SQL database :param schemas: The list of eligible SQL schemas :param hierarchical: Whether to check using the hierarchical permission logic :returns: The list of accessible SQL schemas """ from superset.connectors.sqla.models import SqlaTable if hierarchical and self.can_access_database(database): return schemas # schema_access accessible_schemas = { self.unpack_schema_perm(s)[1] for s in self.user_view_menu_names("schema_access") if s.startswith(f"[{database}].") } # datasource_access perms = self.user_view_menu_names("datasource_access") if perms: tables = ( self.get_session.query(SqlaTable.schema) .filter(SqlaTable.database_id == database.id) .filter(SqlaTable.schema.isnot(None)) .filter(SqlaTable.schema != "") .filter(or_(SqlaTable.perm.in_(perms))) .distinct() ) accessible_schemas.update([table.schema for table in tables]) return [s for s in schemas if s in accessible_schemas] def get_datasources_accessible_by_user( # pylint: disable=invalid-name self, database: "Database", datasource_names: List[DatasourceName], schema: Optional[str] = None, ) -> List[DatasourceName]: """ Return the list of SQL tables accessible by the user. :param database: The SQL database :param datasource_names: The list of eligible SQL tables w/ schema :param schema: The fallback SQL schema if not present in the table name :returns: The list of accessible SQL tables w/ schema """ if self.can_access_database(database): return datasource_names if schema: schema_perm = self.get_schema_perm(database, schema) if schema_perm and self.can_access("schema_access", schema_perm): return datasource_names user_perms = self.user_view_menu_names("datasource_access") schema_perms = self.user_view_menu_names("schema_access") user_datasources = ConnectorRegistry.query_datasources_by_permissions( self.get_session, database, user_perms, schema_perms ) if schema: names = {d.table_name for d in user_datasources if d.schema == schema} return [d for d in datasource_names if d in names] full_names = {d.full_name for d in user_datasources} return [d for d in datasource_names if f"[{database}].[{d}]" in full_names] def merge_perm(self, permission_name: str, view_menu_name: str) -> None: """ Add the FAB permission/view-menu. :param permission_name: The FAB permission name :param view_menu_names: The FAB view-menu name :see: SecurityManager.add_permission_view_menu """ logger.warning( "This method 'merge_perm' is deprecated use add_permission_view_menu" ) self.add_permission_view_menu(permission_name, view_menu_name) def _is_user_defined_permission(self, perm: Model) -> bool: """ Return True if the FAB permission is user defined, False otherwise. :param perm: The FAB permission :returns: Whether the FAB permission is user defined """ return perm.permission.name in self.OBJECT_SPEC_PERMISSIONS def create_custom_permissions(self) -> None: """ Create custom FAB permissions. """ self.add_permission_view_menu("all_datasource_access", "all_datasource_access") self.add_permission_view_menu("all_database_access", "all_database_access") self.add_permission_view_menu("all_query_access", "all_query_access") def create_missing_perms(self) -> None: """ Creates missing FAB permissions for datasources, schemas and metrics. """ from superset.models import core as models logger.info("Fetching a set of all perms to lookup which ones are missing") all_pvs = set() for pv in self.get_session.query(self.permissionview_model).all(): if pv.permission and pv.view_menu: all_pvs.add((pv.permission.name, pv.view_menu.name)) def merge_pv(view_menu: str, perm: str) -> None: """Create permission view menu only if it doesn't exist""" if view_menu and perm and (view_menu, perm) not in all_pvs: self.add_permission_view_menu(view_menu, perm) logger.info("Creating missing datasource permissions.") datasources = ConnectorRegistry.get_all_datasources(self.get_session) for datasource in datasources: merge_pv("datasource_access", datasource.get_perm()) merge_pv("schema_access", datasource.get_schema_perm()) logger.info("Creating missing database permissions.") databases = self.get_session.query(models.Database).all() for database in databases: merge_pv("database_access", database.perm) def clean_perms(self) -> None: """ Clean up the FAB faulty permissions. """ logger.info("Cleaning faulty perms") sesh = self.get_session pvms = sesh.query(PermissionView).filter( or_( PermissionView.permission # pylint: disable=singleton-comparison == None, PermissionView.view_menu # pylint: disable=singleton-comparison == None, ) ) deleted_count = pvms.delete() sesh.commit() if deleted_count: logger.info("Deleted %i faulty permissions", deleted_count) def sync_role_definitions(self) -> None: """ Initialize the Superset application with security roles and such. """ from superset import conf logger.info("Syncing role definition") self.create_custom_permissions() # Creating default roles self.set_role("Admin", self._is_admin_pvm) self.set_role("Alpha", self._is_alpha_pvm) self.set_role("Gamma", self._is_gamma_pvm) self.set_role("granter", self._is_granter_pvm) self.set_role("sql_lab", self._is_sql_lab_pvm) # Configure public role if conf["PUBLIC_ROLE_LIKE"]: self.copy_role(conf["PUBLIC_ROLE_LIKE"], self.auth_role_public, merge=True) if conf.get("PUBLIC_ROLE_LIKE_GAMMA", False): logger.warning( "The config `PUBLIC_ROLE_LIKE_GAMMA` is deprecated and will be removed " "in Superset 1.0. Please use `PUBLIC_ROLE_LIKE` instead." ) self.copy_role("Gamma", self.auth_role_public, merge=True) self.create_missing_perms() # commit role and view menu updates self.get_session.commit() self.clean_perms() def _get_pvms_from_builtin_role(self, role_name: str) -> List[PermissionView]: """ Gets a list of model PermissionView permissions infered from a builtin role definition """ role_from_permissions_names = self.builtin_roles.get(role_name, []) all_pvms = self.get_session.query(PermissionView).all() role_from_permissions = [] for pvm_regex in role_from_permissions_names: view_name_regex = pvm_regex[0] permission_name_regex = pvm_regex[1] for pvm in all_pvms: if re.match(view_name_regex, pvm.view_menu.name) and re.match( permission_name_regex, pvm.permission.name ): if pvm not in role_from_permissions: role_from_permissions.append(pvm) return role_from_permissions def find_roles_by_id(self, role_ids: List[int]) -> List[Role]: """ Find a List of models by a list of ids, if defined applies `base_filter` """ query = self.get_session.query(Role).filter(Role.id.in_(role_ids)) return query.all() def copy_role( self, role_from_name: str, role_to_name: str, merge: bool = True ) -> None: """ Copies permissions from a role to another. Note: Supports regex defined builtin roles :param role_from_name: The FAB role name from where the permissions are taken :param role_to_name: The FAB role name from where the permissions are copied to :param merge: If merge is true, keep data access permissions if they already exist on the target role """ logger.info("Copy/Merge %s to %s", role_from_name, role_to_name) # If it's a builtin role extract permissions from it if role_from_name in self.builtin_roles: role_from_permissions = self._get_pvms_from_builtin_role(role_from_name) else: role_from_permissions = list(self.find_role(role_from_name).permissions) role_to = self.add_role(role_to_name) # If merge, recover existing data access permissions if merge: for permission_view in role_to.permissions: if ( permission_view not in role_from_permissions and permission_view.permission.name in self.data_access_permissions ): role_from_permissions.append(permission_view) role_to.permissions = role_from_permissions self.get_session.merge(role_to) self.get_session.commit() def set_role( self, role_name: str, pvm_check: Callable[[PermissionView], bool] ) -> None: """ Set the FAB permission/views for the role. :param role_name: The FAB role name :param pvm_check: The FAB permission/view check """ logger.info("Syncing %s perms", role_name) pvms = self.get_session.query(PermissionView).all() pvms = [p for p in pvms if p.permission and p.view_menu] role = self.add_role(role_name) role_pvms = [ permission_view for permission_view in pvms if pvm_check(permission_view) ] role.permissions = role_pvms self.get_session.merge(role) self.get_session.commit() def _is_admin_only(self, pvm: PermissionView) -> bool: """ Return True if the FAB permission/view is accessible to only Admin users, False otherwise. Note readonly operations on read only model views are allowed only for admins. :param pvm: The FAB permission/view :returns: Whether the FAB object is accessible to only Admin users """ if ( pvm.view_menu.name in self.READ_ONLY_MODEL_VIEWS and pvm.permission.name not in self.READ_ONLY_PERMISSION ): return True return ( pvm.view_menu.name in self.ADMIN_ONLY_VIEW_MENUS or pvm.permission.name in self.ADMIN_ONLY_PERMISSIONS ) def _is_alpha_only(self, pvm: PermissionView) -> bool: """ Return True if the FAB permission/view is accessible to only Alpha users, False otherwise. :param pvm: The FAB permission/view :returns: Whether the FAB object is accessible to only Alpha users """ if ( pvm.view_menu.name in self.GAMMA_READ_ONLY_MODEL_VIEWS and pvm.permission.name not in self.READ_ONLY_PERMISSION ): return True return ( pvm.view_menu.name in self.ALPHA_ONLY_VIEW_MENUS or pvm.permission.name in self.ALPHA_ONLY_PERMISSIONS ) def _is_accessible_to_all(self, pvm: PermissionView) -> bool: """ Return True if the FAB permission/view is accessible to all, False otherwise. :param pvm: The FAB permission/view :returns: Whether the FAB object is accessible to all users """ return pvm.permission.name in self.ACCESSIBLE_PERMS def _is_admin_pvm(self, pvm: PermissionView) -> bool: """ Return True if the FAB permission/view is Admin user related, False otherwise. :param pvm: The FAB permission/view :returns: Whether the FAB object is Admin related """ return not self._is_user_defined_permission(pvm) def _is_alpha_pvm(self, pvm: PermissionView) -> bool: """ Return True if the FAB permission/view is Alpha user related, False otherwise. :param pvm: The FAB permission/view :returns: Whether the FAB object is Alpha related """ return not ( self._is_user_defined_permission(pvm) or self._is_admin_only(pvm) ) or self._is_accessible_to_all(pvm) def _is_gamma_pvm(self, pvm: PermissionView) -> bool: """ Return True if the FAB permission/view is Gamma user related, False otherwise. :param pvm: The FAB permission/view :returns: Whether the FAB object is Gamma related """ return not ( self._is_user_defined_permission(pvm) or self._is_admin_only(pvm) or self._is_alpha_only(pvm) ) or self._is_accessible_to_all(pvm) def _is_sql_lab_pvm(self, pvm: PermissionView) -> bool: """ Return True if the FAB permission/view is SQL Lab related, False otherwise. :param pvm: The FAB permission/view :returns: Whether the FAB object is SQL Lab related """ return ( pvm.view_menu.name in {"SQL Lab", "SQL Editor", "Query Search", "Saved Queries"} or pvm.permission.name in { "can_sql_json", "can_csv", "can_search_queries", "can_sqllab_viz", "can_sqllab_table_viz", "can_sqllab", } or ( pvm.view_menu.name in self.USER_MODEL_VIEWS and pvm.permission.name == "can_list" ) ) def _is_granter_pvm( # pylint: disable=no-self-use self, pvm: PermissionView ) -> bool: """ Return True if the user can grant the FAB permission/view, False otherwise. :param pvm: The FAB permission/view :returns: Whether the user can grant the FAB permission/view """ return pvm.permission.name in {"can_override_role_permissions", "can_approve"} def set_perm( # pylint: disable=no-self-use,unused-argument self, mapper: Mapper, connection: Connection, target: "BaseDatasource" ) -> None: """ Set the datasource permissions. :param mapper: The table mapper :param connection: The DB-API connection :param target: The mapped instance being persisted """ link_table = target.__table__ # pylint: disable=no-member if target.perm != target.get_perm(): connection.execute( link_table.update() .where(link_table.c.id == target.id) .values(perm=target.get_perm()) ) if ( hasattr(target, "schema_perm") and target.schema_perm != target.get_schema_perm() ): connection.execute( link_table.update() .where(link_table.c.id == target.id) .values(schema_perm=target.get_schema_perm()) ) pvm_names = [] if target.__tablename__ in {"dbs", "clusters"}: pvm_names.append(("database_access", target.get_perm())) else: pvm_names.append(("datasource_access", target.get_perm())) if target.schema: pvm_names.append(("schema_access", target.get_schema_perm())) # TODO(bogdan): modify slice permissions as well. for permission_name, view_menu_name in pvm_names: permission = self.find_permission(permission_name) view_menu = self.find_view_menu(view_menu_name) pv = None if not permission: permission_table = ( self.permission_model.__table__ # pylint: disable=no-member ) connection.execute( permission_table.insert().values(name=permission_name) ) permission = self.find_permission(permission_name) if not view_menu: view_menu_table = ( self.viewmenu_model.__table__ # pylint: disable=no-member ) connection.execute(view_menu_table.insert().values(name=view_menu_name)) view_menu = self.find_view_menu(view_menu_name) if permission and view_menu: pv = ( self.get_session.query(self.permissionview_model) .filter_by(permission=permission, view_menu=view_menu) .first() ) if not pv and permission and view_menu: permission_view_table = ( self.permissionview_model.__table__ # pylint: disable=no-member ) connection.execute( permission_view_table.insert().values( permission_id=permission.id, view_menu_id=view_menu.id ) ) def raise_for_access( # pylint: disable=too-many-arguments,too-many-branches self, database: Optional["Database"] = None, datasource: Optional["BaseDatasource"] = None, query: Optional["Query"] = None, query_context: Optional["QueryContext"] = None, table: Optional["Table"] = None, viz: Optional["BaseViz"] = None, ) -> None: """ Raise an exception if the user cannot access the resource. :param database: The Superset database :param datasource: The Superset datasource :param query: The SQL Lab query :param query_context: The query context :param table: The Superset table (requires database) :param viz: The visualization :raises SupersetSecurityException: If the user cannot access the resource """ from superset.connectors.sqla.models import SqlaTable from superset.sql_parse import Table if database and table or query: if query: database = query.database database = cast("Database", database) if self.can_access_database(database): return if query: tables = { Table(table_.table, table_.schema or query.schema) for table_ in sql_parse.ParsedQuery(query.sql).tables } elif table: tables = {table} denied = set() for table_ in tables: schema_perm = self.get_schema_perm(database, schema=table_.schema) if not (schema_perm and self.can_access("schema_access", schema_perm)): datasources = SqlaTable.query_datasources_by_name( self.get_session, database, table_.table, schema=table_.schema ) # Access to any datasource is suffice. for datasource_ in datasources: if self.can_access("datasource_access", datasource_.perm): break else: denied.add(table_) if denied: raise SupersetSecurityException( self.get_table_access_error_object(denied) ) if datasource or query_context or viz: if query_context: datasource = query_context.datasource elif viz: datasource = viz.datasource assert datasource if not ( self.can_access_schema(datasource) or self.can_access("datasource_access", datasource.perm or "") ): raise SupersetSecurityException( self.get_datasource_access_error_object(datasource) ) def get_user_by_username( self, username: str, session: Session = None ) -> Optional[User]: """ Retrieves a user by it's username case sensitive. Optional session parameter utility method normally useful for celery tasks where the session need to be scoped """ session = session or self.get_session return ( session.query(self.user_model) .filter(self.user_model.username == username) .one_or_none() ) def get_rls_filters(self, table: "BaseDatasource") -> List[SqlaQuery]: """ Retrieves the appropriate row level security filters for the current user and the passed table. :param table: The table to check against :returns: A list of filters """ if hasattr(g, "user") and hasattr(g.user, "id"): from superset.connectors.sqla.models import ( RLSFilterRoles, RLSFilterTables, RowLevelSecurityFilter, ) user_roles = ( self.get_session.query(assoc_user_role.c.role_id) .filter(assoc_user_role.c.user_id == g.user.id) .subquery() ) regular_filter_roles = ( self.get_session.query(RLSFilterRoles.c.rls_filter_id) .join(RowLevelSecurityFilter) .filter( RowLevelSecurityFilter.filter_type == RowLevelSecurityFilterType.REGULAR ) .filter(RLSFilterRoles.c.role_id.in_(user_roles)) .subquery() ) base_filter_roles = ( self.get_session.query(RLSFilterRoles.c.rls_filter_id) .join(RowLevelSecurityFilter) .filter( RowLevelSecurityFilter.filter_type == RowLevelSecurityFilterType.BASE ) .filter(RLSFilterRoles.c.role_id.in_(user_roles)) .subquery() ) filter_tables = ( self.get_session.query(RLSFilterTables.c.rls_filter_id) .filter(RLSFilterTables.c.table_id == table.id) .subquery() ) query = ( self.get_session.query( RowLevelSecurityFilter.id, RowLevelSecurityFilter.group_key, RowLevelSecurityFilter.clause, ) .filter(RowLevelSecurityFilter.id.in_(filter_tables)) .filter( or_( and_( RowLevelSecurityFilter.filter_type == RowLevelSecurityFilterType.REGULAR, RowLevelSecurityFilter.id.in_(regular_filter_roles), ), and_( RowLevelSecurityFilter.filter_type == RowLevelSecurityFilterType.BASE, RowLevelSecurityFilter.id.notin_(base_filter_roles), ), ) ) ) return query.all() return [] def get_rls_ids(self, table: "BaseDatasource") -> List[int]: """ Retrieves the appropriate row level security filters IDs for the current user and the passed table. :param table: The table to check against :returns: A list of IDs """ ids = [f.id for f in self.get_rls_filters(table)] ids.sort() # Combinations rather than permutations return ids # pylint: disable=no-self-use def raise_for_dashboard_access(self, dashboard: "Dashboard") -> None: """ Raise an exception if the user cannot access the dashboard. :param dashboard: Dashboard the user wants access to :raises DashboardAccessDeniedError: If the user cannot access the resource """ from superset.dashboards.commands.exceptions import DashboardAccessDeniedError from superset.views.base import get_user_roles, is_user_admin from superset.views.utils import is_owner from superset import is_feature_enabled if is_feature_enabled("DASHBOARD_RBAC"): has_rbac_access = any( dashboard_role.id in [user_role.id for user_role in get_user_roles()] for dashboard_role in dashboard.roles ) can_access = ( is_user_admin() or is_owner(dashboard, g.user) or (dashboard.published and has_rbac_access) ) if not can_access: raise DashboardAccessDeniedError()
35.763298
88
0.620634
import logging import re from typing import Any, Callable, cast, List, Optional, Set, Tuple, TYPE_CHECKING, Union from flask import current_app, g from flask_appbuilder import Model from flask_appbuilder.security.sqla.manager import SecurityManager from flask_appbuilder.security.sqla.models import ( assoc_permissionview_role, assoc_user_role, PermissionView, Role, User, ) from flask_appbuilder.security.views import ( PermissionModelView, PermissionViewModelView, RoleModelView, UserModelView, ViewMenuModelView, ) from flask_appbuilder.widgets import ListWidget from sqlalchemy import and_, or_ from sqlalchemy.engine.base import Connection from sqlalchemy.orm import Session from sqlalchemy.orm.mapper import Mapper from sqlalchemy.orm.query import Query as SqlaQuery from superset import sql_parse from superset.connectors.connector_registry import ConnectorRegistry from superset.constants import RouteMethod from superset.errors import ErrorLevel, SupersetError, SupersetErrorType from superset.exceptions import SupersetSecurityException from superset.utils.core import DatasourceName, RowLevelSecurityFilterType if TYPE_CHECKING: from superset.common.query_context import QueryContext from superset.connectors.base.models import BaseDatasource from superset.connectors.druid.models import DruidCluster from superset.models.dashboard import Dashboard from superset.models.core import Database from superset.models.sql_lab import Query from superset.sql_parse import Table from superset.viz import BaseViz logger = logging.getLogger(__name__) class SupersetSecurityListWidget(ListWidget): template = "superset/fab_overrides/list.html" class SupersetRoleListWidget(ListWidget): template = "superset/fab_overrides/list_role.html" def __init__(self, **kwargs: Any) -> None: kwargs["appbuilder"] = current_app.appbuilder super().__init__(**kwargs) UserModelView.list_widget = SupersetSecurityListWidget RoleModelView.list_widget = SupersetRoleListWidget PermissionViewModelView.list_widget = SupersetSecurityListWidget PermissionModelView.list_widget = SupersetSecurityListWidget UserModelView.include_route_methods = RouteMethod.CRUD_SET | { RouteMethod.ACTION, RouteMethod.API_READ, RouteMethod.ACTION_POST, "userinfo", } RoleModelView.include_route_methods = RouteMethod.CRUD_SET PermissionViewModelView.include_route_methods = {RouteMethod.LIST} PermissionModelView.include_route_methods = {RouteMethod.LIST} ViewMenuModelView.include_route_methods = {RouteMethod.LIST} RoleModelView.list_columns = ["name"] RoleModelView.edit_columns = ["name", "permissions", "user"] RoleModelView.related_views = [] class SupersetSecurityManager( SecurityManager ): userstatschartview = None READ_ONLY_MODEL_VIEWS = {"Database", "DruidClusterModelView", "DynamicPlugin"} USER_MODEL_VIEWS = { "UserDBModelView", "UserLDAPModelView", "UserOAuthModelView", "UserOIDModelView", "UserRemoteUserModelView", } GAMMA_READ_ONLY_MODEL_VIEWS = { "Dataset", "DruidColumnInlineView", "DruidDatasourceModelView", "DruidMetricInlineView", "Datasource", } | READ_ONLY_MODEL_VIEWS ADMIN_ONLY_VIEW_MENUS = { "AccessRequestsModelView", "SQL Lab", "Refresh Druid Metadata", "ResetPasswordView", "RoleModelView", "Log", "Security", "Row Level Security", "Row Level Security Filters", "RowLevelSecurityFiltersModelView", } | USER_MODEL_VIEWS ALPHA_ONLY_VIEW_MENUS = { "Manage", "CSS Templates", "Queries", "Import dashboards", "Upload a CSV", } ADMIN_ONLY_PERMISSIONS = { "can_sql_json", "can_override_role_permissions", "can_sync_druid_source", "can_override_role_permissions", "can_approve", "can_update_role", "all_query_access", } READ_ONLY_PERMISSION = { "can_show", "can_list", "can_get", "can_external_metadata", "can_read", } ALPHA_ONLY_PERMISSIONS = { "muldelete", "all_database_access", "all_datasource_access", } OBJECT_SPEC_PERMISSIONS = { "database_access", "schema_access", "datasource_access", "metric_access", } ACCESSIBLE_PERMS = {"can_userinfo", "resetmypassword"} data_access_permissions = ( "database_access", "schema_access", "datasource_access", "all_datasource_access", "all_database_access", "all_query_access", ) def get_schema_perm( self, database: Union["Database", str], schema: Optional[str] = None ) -> Optional[str]: if schema: return f"[{database}].[{schema}]" return None def unpack_schema_perm( self, schema_permission: str ) -> Tuple[str, str]: schema_name = schema_permission.split(".")[1][1:-1] database_name = schema_permission.split(".")[0][1:-1] return database_name, schema_name def can_access(self, permission_name: str, view_name: str) -> bool: user = g.user if user.is_anonymous: return self.is_item_public(permission_name, view_name) return self._has_view_access(user, permission_name, view_name) def can_access_all_queries(self) -> bool: return self.can_access("all_query_access", "all_query_access") def can_access_all_datasources(self) -> bool: return self.can_access("all_datasource_access", "all_datasource_access") def can_access_all_databases(self) -> bool: return self.can_access("all_database_access", "all_database_access") def can_access_database(self, database: Union["Database", "DruidCluster"]) -> bool: return ( self.can_access_all_datasources() or self.can_access_all_databases() or self.can_access("database_access", database.perm) ) def can_access_schema(self, datasource: "BaseDatasource") -> bool: return ( self.can_access_all_datasources() or self.can_access_database(datasource.database) or self.can_access("schema_access", datasource.schema_perm or "") ) def can_access_datasource(self, datasource: "BaseDatasource") -> bool: try: self.raise_for_access(datasource=datasource) except SupersetSecurityException: return False return True @staticmethod def get_datasource_access_error_msg(datasource: "BaseDatasource") -> str: return f"""This endpoint requires the datasource {datasource.name}, database or `all_datasource_access` permission""" @staticmethod def get_datasource_access_link( datasource: "BaseDatasource", ) -> Optional[str]: from superset import conf return conf.get("PERMISSION_INSTRUCTIONS_LINK") def get_datasource_access_error_object( self, datasource: "BaseDatasource" ) -> SupersetError: return SupersetError( error_type=SupersetErrorType.DATASOURCE_SECURITY_ACCESS_ERROR, message=self.get_datasource_access_error_msg(datasource), level=ErrorLevel.ERROR, extra={ "link": self.get_datasource_access_link(datasource), "datasource": datasource.name, }, ) def get_table_access_error_msg( self, tables: Set["Table"] ) -> str: quoted_tables = [f"`{table}`" for table in tables] return f"""You need access to the following tables: {", ".join(quoted_tables)}, `all_database_access` or `all_datasource_access` permission""" def get_table_access_error_object(self, tables: Set["Table"]) -> SupersetError: return SupersetError( error_type=SupersetErrorType.TABLE_SECURITY_ACCESS_ERROR, message=self.get_table_access_error_msg(tables), level=ErrorLevel.ERROR, extra={ "link": self.get_table_access_link(tables), "tables": [str(table) for table in tables], }, ) def get_table_access_link( self, tables: Set["Table"] ) -> Optional[str]: from superset import conf return conf.get("PERMISSION_INSTRUCTIONS_LINK") def can_access_table(self, database: "Database", table: "Table") -> bool: try: self.raise_for_access(database=database, table=table) except SupersetSecurityException: return False return True def user_view_menu_names(self, permission_name: str) -> Set[str]: base_query = ( self.get_session.query(self.viewmenu_model.name) .join(self.permissionview_model) .join(self.permission_model) .join(assoc_permissionview_role) .join(self.role_model) ) if not g.user.is_anonymous: view_menu_names = ( base_query.join(assoc_user_role) .join(self.user_model) .filter(self.user_model.id == g.user.id) .filter(self.permission_model.name == permission_name) ).all() return {s.name for s in view_menu_names} public_role = self.get_public_role() if public_role: view_menu_names = ( base_query.filter(self.role_model.id == public_role.id).filter( self.permission_model.name == permission_name ) ).all() return {s.name for s in view_menu_names} return set() def get_schemas_accessible_by_user( self, database: "Database", schemas: List[str], hierarchical: bool = True ) -> List[str]: from superset.connectors.sqla.models import SqlaTable if hierarchical and self.can_access_database(database): return schemas accessible_schemas = { self.unpack_schema_perm(s)[1] for s in self.user_view_menu_names("schema_access") if s.startswith(f"[{database}].") } perms = self.user_view_menu_names("datasource_access") if perms: tables = ( self.get_session.query(SqlaTable.schema) .filter(SqlaTable.database_id == database.id) .filter(SqlaTable.schema.isnot(None)) .filter(SqlaTable.schema != "") .filter(or_(SqlaTable.perm.in_(perms))) .distinct() ) accessible_schemas.update([table.schema for table in tables]) return [s for s in schemas if s in accessible_schemas] def get_datasources_accessible_by_user( self, database: "Database", datasource_names: List[DatasourceName], schema: Optional[str] = None, ) -> List[DatasourceName]: if self.can_access_database(database): return datasource_names if schema: schema_perm = self.get_schema_perm(database, schema) if schema_perm and self.can_access("schema_access", schema_perm): return datasource_names user_perms = self.user_view_menu_names("datasource_access") schema_perms = self.user_view_menu_names("schema_access") user_datasources = ConnectorRegistry.query_datasources_by_permissions( self.get_session, database, user_perms, schema_perms ) if schema: names = {d.table_name for d in user_datasources if d.schema == schema} return [d for d in datasource_names if d in names] full_names = {d.full_name for d in user_datasources} return [d for d in datasource_names if f"[{database}].[{d}]" in full_names] def merge_perm(self, permission_name: str, view_menu_name: str) -> None: logger.warning( "This method 'merge_perm' is deprecated use add_permission_view_menu" ) self.add_permission_view_menu(permission_name, view_menu_name) def _is_user_defined_permission(self, perm: Model) -> bool: return perm.permission.name in self.OBJECT_SPEC_PERMISSIONS def create_custom_permissions(self) -> None: self.add_permission_view_menu("all_datasource_access", "all_datasource_access") self.add_permission_view_menu("all_database_access", "all_database_access") self.add_permission_view_menu("all_query_access", "all_query_access") def create_missing_perms(self) -> None: from superset.models import core as models logger.info("Fetching a set of all perms to lookup which ones are missing") all_pvs = set() for pv in self.get_session.query(self.permissionview_model).all(): if pv.permission and pv.view_menu: all_pvs.add((pv.permission.name, pv.view_menu.name)) def merge_pv(view_menu: str, perm: str) -> None: if view_menu and perm and (view_menu, perm) not in all_pvs: self.add_permission_view_menu(view_menu, perm) logger.info("Creating missing datasource permissions.") datasources = ConnectorRegistry.get_all_datasources(self.get_session) for datasource in datasources: merge_pv("datasource_access", datasource.get_perm()) merge_pv("schema_access", datasource.get_schema_perm()) logger.info("Creating missing database permissions.") databases = self.get_session.query(models.Database).all() for database in databases: merge_pv("database_access", database.perm) def clean_perms(self) -> None: logger.info("Cleaning faulty perms") sesh = self.get_session pvms = sesh.query(PermissionView).filter( or_( PermissionView.permission == None, PermissionView.view_menu == None, ) ) deleted_count = pvms.delete() sesh.commit() if deleted_count: logger.info("Deleted %i faulty permissions", deleted_count) def sync_role_definitions(self) -> None: from superset import conf logger.info("Syncing role definition") self.create_custom_permissions() self.set_role("Admin", self._is_admin_pvm) self.set_role("Alpha", self._is_alpha_pvm) self.set_role("Gamma", self._is_gamma_pvm) self.set_role("granter", self._is_granter_pvm) self.set_role("sql_lab", self._is_sql_lab_pvm) if conf["PUBLIC_ROLE_LIKE"]: self.copy_role(conf["PUBLIC_ROLE_LIKE"], self.auth_role_public, merge=True) if conf.get("PUBLIC_ROLE_LIKE_GAMMA", False): logger.warning( "The config `PUBLIC_ROLE_LIKE_GAMMA` is deprecated and will be removed " "in Superset 1.0. Please use `PUBLIC_ROLE_LIKE` instead." ) self.copy_role("Gamma", self.auth_role_public, merge=True) self.create_missing_perms() self.get_session.commit() self.clean_perms() def _get_pvms_from_builtin_role(self, role_name: str) -> List[PermissionView]: role_from_permissions_names = self.builtin_roles.get(role_name, []) all_pvms = self.get_session.query(PermissionView).all() role_from_permissions = [] for pvm_regex in role_from_permissions_names: view_name_regex = pvm_regex[0] permission_name_regex = pvm_regex[1] for pvm in all_pvms: if re.match(view_name_regex, pvm.view_menu.name) and re.match( permission_name_regex, pvm.permission.name ): if pvm not in role_from_permissions: role_from_permissions.append(pvm) return role_from_permissions def find_roles_by_id(self, role_ids: List[int]) -> List[Role]: query = self.get_session.query(Role).filter(Role.id.in_(role_ids)) return query.all() def copy_role( self, role_from_name: str, role_to_name: str, merge: bool = True ) -> None: logger.info("Copy/Merge %s to %s", role_from_name, role_to_name) if role_from_name in self.builtin_roles: role_from_permissions = self._get_pvms_from_builtin_role(role_from_name) else: role_from_permissions = list(self.find_role(role_from_name).permissions) role_to = self.add_role(role_to_name) # If merge, recover existing data access permissions if merge: for permission_view in role_to.permissions: if ( permission_view not in role_from_permissions and permission_view.permission.name in self.data_access_permissions ): role_from_permissions.append(permission_view) role_to.permissions = role_from_permissions self.get_session.merge(role_to) self.get_session.commit() def set_role( self, role_name: str, pvm_check: Callable[[PermissionView], bool] ) -> None: logger.info("Syncing %s perms", role_name) pvms = self.get_session.query(PermissionView).all() pvms = [p for p in pvms if p.permission and p.view_menu] role = self.add_role(role_name) role_pvms = [ permission_view for permission_view in pvms if pvm_check(permission_view) ] role.permissions = role_pvms self.get_session.merge(role) self.get_session.commit() def _is_admin_only(self, pvm: PermissionView) -> bool: if ( pvm.view_menu.name in self.READ_ONLY_MODEL_VIEWS and pvm.permission.name not in self.READ_ONLY_PERMISSION ): return True return ( pvm.view_menu.name in self.ADMIN_ONLY_VIEW_MENUS or pvm.permission.name in self.ADMIN_ONLY_PERMISSIONS ) def _is_alpha_only(self, pvm: PermissionView) -> bool: if ( pvm.view_menu.name in self.GAMMA_READ_ONLY_MODEL_VIEWS and pvm.permission.name not in self.READ_ONLY_PERMISSION ): return True return ( pvm.view_menu.name in self.ALPHA_ONLY_VIEW_MENUS or pvm.permission.name in self.ALPHA_ONLY_PERMISSIONS ) def _is_accessible_to_all(self, pvm: PermissionView) -> bool: return pvm.permission.name in self.ACCESSIBLE_PERMS def _is_admin_pvm(self, pvm: PermissionView) -> bool: return not self._is_user_defined_permission(pvm) def _is_alpha_pvm(self, pvm: PermissionView) -> bool: return not ( self._is_user_defined_permission(pvm) or self._is_admin_only(pvm) ) or self._is_accessible_to_all(pvm) def _is_gamma_pvm(self, pvm: PermissionView) -> bool: return not ( self._is_user_defined_permission(pvm) or self._is_admin_only(pvm) or self._is_alpha_only(pvm) ) or self._is_accessible_to_all(pvm) def _is_sql_lab_pvm(self, pvm: PermissionView) -> bool: return ( pvm.view_menu.name in {"SQL Lab", "SQL Editor", "Query Search", "Saved Queries"} or pvm.permission.name in { "can_sql_json", "can_csv", "can_search_queries", "can_sqllab_viz", "can_sqllab_table_viz", "can_sqllab", } or ( pvm.view_menu.name in self.USER_MODEL_VIEWS and pvm.permission.name == "can_list" ) ) def _is_granter_pvm( # pylint: disable=no-self-use self, pvm: PermissionView ) -> bool: return pvm.permission.name in {"can_override_role_permissions", "can_approve"} def set_perm( # pylint: disable=no-self-use,unused-argument self, mapper: Mapper, connection: Connection, target: "BaseDatasource" ) -> None: link_table = target.__table__ # pylint: disable=no-member if target.perm != target.get_perm(): connection.execute( link_table.update() .where(link_table.c.id == target.id) .values(perm=target.get_perm()) ) if ( hasattr(target, "schema_perm") and target.schema_perm != target.get_schema_perm() ): connection.execute( link_table.update() .where(link_table.c.id == target.id) .values(schema_perm=target.get_schema_perm()) ) pvm_names = [] if target.__tablename__ in {"dbs", "clusters"}: pvm_names.append(("database_access", target.get_perm())) else: pvm_names.append(("datasource_access", target.get_perm())) if target.schema: pvm_names.append(("schema_access", target.get_schema_perm())) # TODO(bogdan): modify slice permissions as well. for permission_name, view_menu_name in pvm_names: permission = self.find_permission(permission_name) view_menu = self.find_view_menu(view_menu_name) pv = None if not permission: permission_table = ( self.permission_model.__table__ # pylint: disable=no-member ) connection.execute( permission_table.insert().values(name=permission_name) ) permission = self.find_permission(permission_name) if not view_menu: view_menu_table = ( self.viewmenu_model.__table__ # pylint: disable=no-member ) connection.execute(view_menu_table.insert().values(name=view_menu_name)) view_menu = self.find_view_menu(view_menu_name) if permission and view_menu: pv = ( self.get_session.query(self.permissionview_model) .filter_by(permission=permission, view_menu=view_menu) .first() ) if not pv and permission and view_menu: permission_view_table = ( self.permissionview_model.__table__ # pylint: disable=no-member ) connection.execute( permission_view_table.insert().values( permission_id=permission.id, view_menu_id=view_menu.id ) ) def raise_for_access( # pylint: disable=too-many-arguments,too-many-branches self, database: Optional["Database"] = None, datasource: Optional["BaseDatasource"] = None, query: Optional["Query"] = None, query_context: Optional["QueryContext"] = None, table: Optional["Table"] = None, viz: Optional["BaseViz"] = None, ) -> None: from superset.connectors.sqla.models import SqlaTable from superset.sql_parse import Table if database and table or query: if query: database = query.database database = cast("Database", database) if self.can_access_database(database): return if query: tables = { Table(table_.table, table_.schema or query.schema) for table_ in sql_parse.ParsedQuery(query.sql).tables } elif table: tables = {table} denied = set() for table_ in tables: schema_perm = self.get_schema_perm(database, schema=table_.schema) if not (schema_perm and self.can_access("schema_access", schema_perm)): datasources = SqlaTable.query_datasources_by_name( self.get_session, database, table_.table, schema=table_.schema ) # Access to any datasource is suffice. for datasource_ in datasources: if self.can_access("datasource_access", datasource_.perm): break else: denied.add(table_) if denied: raise SupersetSecurityException( self.get_table_access_error_object(denied) ) if datasource or query_context or viz: if query_context: datasource = query_context.datasource elif viz: datasource = viz.datasource assert datasource if not ( self.can_access_schema(datasource) or self.can_access("datasource_access", datasource.perm or "") ): raise SupersetSecurityException( self.get_datasource_access_error_object(datasource) ) def get_user_by_username( self, username: str, session: Session = None ) -> Optional[User]: session = session or self.get_session return ( session.query(self.user_model) .filter(self.user_model.username == username) .one_or_none() ) def get_rls_filters(self, table: "BaseDatasource") -> List[SqlaQuery]: if hasattr(g, "user") and hasattr(g.user, "id"): from superset.connectors.sqla.models import ( RLSFilterRoles, RLSFilterTables, RowLevelSecurityFilter, ) user_roles = ( self.get_session.query(assoc_user_role.c.role_id) .filter(assoc_user_role.c.user_id == g.user.id) .subquery() ) regular_filter_roles = ( self.get_session.query(RLSFilterRoles.c.rls_filter_id) .join(RowLevelSecurityFilter) .filter( RowLevelSecurityFilter.filter_type == RowLevelSecurityFilterType.REGULAR ) .filter(RLSFilterRoles.c.role_id.in_(user_roles)) .subquery() ) base_filter_roles = ( self.get_session.query(RLSFilterRoles.c.rls_filter_id) .join(RowLevelSecurityFilter) .filter( RowLevelSecurityFilter.filter_type == RowLevelSecurityFilterType.BASE ) .filter(RLSFilterRoles.c.role_id.in_(user_roles)) .subquery() ) filter_tables = ( self.get_session.query(RLSFilterTables.c.rls_filter_id) .filter(RLSFilterTables.c.table_id == table.id) .subquery() ) query = ( self.get_session.query( RowLevelSecurityFilter.id, RowLevelSecurityFilter.group_key, RowLevelSecurityFilter.clause, ) .filter(RowLevelSecurityFilter.id.in_(filter_tables)) .filter( or_( and_( RowLevelSecurityFilter.filter_type == RowLevelSecurityFilterType.REGULAR, RowLevelSecurityFilter.id.in_(regular_filter_roles), ), and_( RowLevelSecurityFilter.filter_type == RowLevelSecurityFilterType.BASE, RowLevelSecurityFilter.id.notin_(base_filter_roles), ), ) ) ) return query.all() return [] def get_rls_ids(self, table: "BaseDatasource") -> List[int]: ids = [f.id for f in self.get_rls_filters(table)] ids.sort() # Combinations rather than permutations return ids # pylint: disable=no-self-use def raise_for_dashboard_access(self, dashboard: "Dashboard") -> None: from superset.dashboards.commands.exceptions import DashboardAccessDeniedError from superset.views.base import get_user_roles, is_user_admin from superset.views.utils import is_owner from superset import is_feature_enabled if is_feature_enabled("DASHBOARD_RBAC"): has_rbac_access = any( dashboard_role.id in [user_role.id for user_role in get_user_roles()] for dashboard_role in dashboard.roles ) can_access = ( is_user_admin() or is_owner(dashboard, g.user) or (dashboard.published and has_rbac_access) ) if not can_access: raise DashboardAccessDeniedError()
true
true
1c441a02c742a3dfe6abbfd727f960c9fef4f1d5
552
py
Python
network/migrations/0007_auto_20181013_1141.py
pawangeek/PollsChain
6059796c671d3250f2cd8bb36171bf54013d176e
[ "MIT" ]
null
null
null
network/migrations/0007_auto_20181013_1141.py
pawangeek/PollsChain
6059796c671d3250f2cd8bb36171bf54013d176e
[ "MIT" ]
null
null
null
network/migrations/0007_auto_20181013_1141.py
pawangeek/PollsChain
6059796c671d3250f2cd8bb36171bf54013d176e
[ "MIT" ]
null
null
null
# Generated by Django 2.1 on 2018-10-13 11:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('network', '0006_transaction_transaction_id'), ] operations = [ migrations.RemoveField( model_name='block', name='transaction', ), migrations.AddField( model_name='block', name='transaction_id', field=models.CharField(default=0, max_length=100), preserve_default=False, ), ]
23
62
0.586957
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('network', '0006_transaction_transaction_id'), ] operations = [ migrations.RemoveField( model_name='block', name='transaction', ), migrations.AddField( model_name='block', name='transaction_id', field=models.CharField(default=0, max_length=100), preserve_default=False, ), ]
true
true
1c441a48841857af47bd57c1c28d22667ebaeb0d
542
py
Python
A_mecanica_das_Classes_e_Instancias/09-Instance-Methods.py
nnsdtr/OOP-Python
3b739966c9b35c32a2bd934574f6421b1470eb23
[ "MIT" ]
null
null
null
A_mecanica_das_Classes_e_Instancias/09-Instance-Methods.py
nnsdtr/OOP-Python
3b739966c9b35c32a2bd934574f6421b1470eb23
[ "MIT" ]
null
null
null
A_mecanica_das_Classes_e_Instancias/09-Instance-Methods.py
nnsdtr/OOP-Python
3b739966c9b35c32a2bd934574f6421b1470eb23
[ "MIT" ]
null
null
null
# Exemplo 1: class Person(object): greeting = '\nHello there!' joe = Person() print(joe.greeting) print('\n') # Exemplo 2: # Método interno à classe utiliza self como 1º parâmetro, sempre. class Something(object): def call_this_method(self): print('Verificação de john == john.call_this_method() resulta em:') return self # Criando instância da classe 'Something' john = Something() # Verificação de igualdade print(john == john.call_this_method()) # Logo, a instância 'john' é o próprio parâmetro 'self'!
20.846154
98
0.693727
class Person(object): greeting = '\nHello there!' joe = Person() print(joe.greeting) print('\n') class Something(object): def call_this_method(self): print('Verificação de john == john.call_this_method() resulta em:') return self john = Something() print(john == john.call_this_method())
true
true
1c441b172e4ee117cc58cbc80d255338d7e0f552
2,835
py
Python
tests/test_queries.py
klen/aio-databases
395edcc810598e1639ccd9727aecb4d97cf04df9
[ "MIT" ]
6
2021-08-13T16:17:47.000Z
2022-02-04T01:22:02.000Z
tests/test_queries.py
klen/aio-databases
395edcc810598e1639ccd9727aecb4d97cf04df9
[ "MIT" ]
null
null
null
tests/test_queries.py
klen/aio-databases
395edcc810598e1639ccd9727aecb4d97cf04df9
[ "MIT" ]
null
null
null
import pytest from pypika import Parameter @pytest.fixture async def schema(pool, User, manager): UserManager = manager(User) await pool.execute(UserManager.create_table().if_not_exists()) yield await pool.execute(UserManager.drop_table().if_exists()) async def test_base(db): await db.execute("select %s", '1') res = await db.fetchall("select (2 * %s) res", 2) assert [tuple(r) for r in res] == [(4,)] res = await db.fetchmany(10, "select (2 * %s) res", 2) assert [tuple(r) for r in res] == [(4,)] res = await db.fetchone("select (2 * %s) res", 2) assert tuple(res) == (4,) res = await db.fetchval("select 2 + %s", 2) assert res == 4 async def test_all(db, User, manager, schema): UserManager = manager(User) await db.execute(UserManager.delete()) async with db.transaction() as main_trans: assert main_trans res = await db.execute(UserManager.insert(name='Jim', fullname='Jim Jones')) assert res async with db.transaction() as trans2: assert trans2 res = await db.execute(UserManager.insert(name='Tom', fullname='Tom Smith')) assert res res = await db.fetchall(UserManager.select()) assert res assert len(res) == 2 await trans2.rollback() res = await db.fetchall(UserManager.select()) assert res assert len(res) == 1 [user] = res assert user assert user['id'] assert user['name'] == 'Jim' assert user['fullname'] == 'Jim Jones' res = await db.fetchone(UserManager.select().where(User.id == 100)) assert res is None async def test_execute(db, User, manager, schema): UserManager = manager(User) await db.execute(UserManager.insert(name='Jim', fullname='Tom Smith')) await db.execute(UserManager.insert(name='Jim', fullname='Tom Smith')) updated, lastid = await db.execute(UserManager.update().set(User.name, 'Tom')) assert updated == 2 @pytest.mark.parametrize('backend', ['aiomysql']) async def test_execute_many(db, User, manager, schema): UserManager = manager(User) await db.execute(UserManager.delete()) qs = UserManager.insert(name=Parameter('%s'), fullname=Parameter('%s')) await db.executemany(qs, ('Jim', 'Jim Jones'), ('Tom', 'Tom Smith')) res = await db.fetchall(UserManager.select()) assert res assert len(res) == 2 u1, u2 = res assert u1['name'] == 'Jim' assert u2['name'] == 'Tom' async def test_iterate(db, User, manager, schema): UserManager = manager(User) qs = UserManager.insert(name=Parameter('%s'), fullname=Parameter('%s')) await db.executemany(qs, ('Jim', 'Jim Jones'), ('Tom', 'Tom Smith')) async for rec in db.iterate(UserManager.select()): assert rec['name'] in {'Jim', 'Tom'}
29.842105
88
0.631393
import pytest from pypika import Parameter @pytest.fixture async def schema(pool, User, manager): UserManager = manager(User) await pool.execute(UserManager.create_table().if_not_exists()) yield await pool.execute(UserManager.drop_table().if_exists()) async def test_base(db): await db.execute("select %s", '1') res = await db.fetchall("select (2 * %s) res", 2) assert [tuple(r) for r in res] == [(4,)] res = await db.fetchmany(10, "select (2 * %s) res", 2) assert [tuple(r) for r in res] == [(4,)] res = await db.fetchone("select (2 * %s) res", 2) assert tuple(res) == (4,) res = await db.fetchval("select 2 + %s", 2) assert res == 4 async def test_all(db, User, manager, schema): UserManager = manager(User) await db.execute(UserManager.delete()) async with db.transaction() as main_trans: assert main_trans res = await db.execute(UserManager.insert(name='Jim', fullname='Jim Jones')) assert res async with db.transaction() as trans2: assert trans2 res = await db.execute(UserManager.insert(name='Tom', fullname='Tom Smith')) assert res res = await db.fetchall(UserManager.select()) assert res assert len(res) == 2 await trans2.rollback() res = await db.fetchall(UserManager.select()) assert res assert len(res) == 1 [user] = res assert user assert user['id'] assert user['name'] == 'Jim' assert user['fullname'] == 'Jim Jones' res = await db.fetchone(UserManager.select().where(User.id == 100)) assert res is None async def test_execute(db, User, manager, schema): UserManager = manager(User) await db.execute(UserManager.insert(name='Jim', fullname='Tom Smith')) await db.execute(UserManager.insert(name='Jim', fullname='Tom Smith')) updated, lastid = await db.execute(UserManager.update().set(User.name, 'Tom')) assert updated == 2 @pytest.mark.parametrize('backend', ['aiomysql']) async def test_execute_many(db, User, manager, schema): UserManager = manager(User) await db.execute(UserManager.delete()) qs = UserManager.insert(name=Parameter('%s'), fullname=Parameter('%s')) await db.executemany(qs, ('Jim', 'Jim Jones'), ('Tom', 'Tom Smith')) res = await db.fetchall(UserManager.select()) assert res assert len(res) == 2 u1, u2 = res assert u1['name'] == 'Jim' assert u2['name'] == 'Tom' async def test_iterate(db, User, manager, schema): UserManager = manager(User) qs = UserManager.insert(name=Parameter('%s'), fullname=Parameter('%s')) await db.executemany(qs, ('Jim', 'Jim Jones'), ('Tom', 'Tom Smith')) async for rec in db.iterate(UserManager.select()): assert rec['name'] in {'Jim', 'Tom'}
true
true
1c441ba3d757d278aee135f301e462d85e7c43f4
2,447
py
Python
python/GafferAppleseedUI/AppleseedRenderUI.py
ddesmond/gaffer
4f25df88103b7893df75865ea919fb035f92bac0
[ "BSD-3-Clause" ]
561
2016-10-18T04:30:48.000Z
2022-03-30T06:52:04.000Z
python/GafferAppleseedUI/AppleseedRenderUI.py
ddesmond/gaffer
4f25df88103b7893df75865ea919fb035f92bac0
[ "BSD-3-Clause" ]
1,828
2016-10-14T19:01:46.000Z
2022-03-30T16:07:19.000Z
python/GafferAppleseedUI/AppleseedRenderUI.py
ddesmond/gaffer
4f25df88103b7893df75865ea919fb035f92bac0
[ "BSD-3-Clause" ]
120
2016-10-18T15:19:13.000Z
2021-12-20T16:28:23.000Z
########################################################################## # # Copyright (c) 2014, Esteban Tovagliari. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * 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. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 OWNER OR # CONTRIBUTORS 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. # ########################################################################## import IECore import Gaffer import GafferUI import GafferAppleseed Gaffer.Metadata.registerNode( GafferAppleseed.AppleseedRender, "description", """ Performs offline batch rendering using the appleseed renderer, or optionally generates appleseed projects for later rendering using a SystemCommand node. """, plugs = { "fileName" : [ "description", """ The name of the appleseed project file to be generated. """, "nodule:type", "", "plugValueWidget:type", "GafferUI.FileSystemPathPlugValueWidget", "path:leaf", True, "path:bookmarks", "appleseed", "fileSystemPath:extensions", "appleseed", ], } )
32.626667
77
0.688598
true
true
1c441bb44de6f92ddbdce2bba4858f65eb61b169
3,559
py
Python
bindings/python/ensmallen/datasets/string/coriobacteriumglomerans.py
AnacletoLAB/ensmallen_graph
b2c1b18fb1e5801712852bcc239f239e03076f09
[ "MIT" ]
5
2021-02-17T00:44:45.000Z
2021-08-09T16:41:47.000Z
bindings/python/ensmallen/datasets/string/coriobacteriumglomerans.py
AnacletoLAB/ensmallen_graph
b2c1b18fb1e5801712852bcc239f239e03076f09
[ "MIT" ]
18
2021-01-07T16:47:39.000Z
2021-08-12T21:51:32.000Z
bindings/python/ensmallen/datasets/string/coriobacteriumglomerans.py
AnacletoLAB/ensmallen
b2c1b18fb1e5801712852bcc239f239e03076f09
[ "MIT" ]
3
2021-01-14T02:20:59.000Z
2021-08-04T19:09:52.000Z
""" This file offers the methods to automatically retrieve the graph Coriobacterium glomerans. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets}, author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } ``` """ from typing import Dict from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph from ...ensmallen import Graph # pylint: disable=import-error def CoriobacteriumGlomerans( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/string", version: str = "links.v11.5", **additional_graph_kwargs: Dict ) -> Graph: """Return new instance of the Coriobacterium glomerans graph. The graph is automatically retrieved from the STRING repository. Parameters ------------------- directed: bool = False Wether to load the graph as directed or undirected. By default false. preprocess: bool = True Whether to preprocess the graph to be loaded in optimal time and memory. load_nodes: bool = True, Whether to load the nodes vocabulary or treat the nodes simply as a numeric range. verbose: int = 2, Wether to show loading bars during the retrieval and building of the graph. cache: bool = True Whether to use cache, i.e. download files only once and preprocess them only once. cache_path: str = "graphs" Where to store the downloaded graphs. version: str = "links.v11.5" The version of the graph to retrieve. The available versions are: - homology.v11.0 - homology.v11.5 - physical.links.v11.0 - physical.links.v11.5 - links.v11.0 - links.v11.5 additional_graph_kwargs: Dict Additional graph kwargs. Returns ----------------------- Instace of Coriobacterium glomerans graph. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets}, author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } ``` """ return AutomaticallyRetrievedGraph( graph_name="CoriobacteriumGlomerans", repository="string", version=version, directed=directed, preprocess=preprocess, load_nodes=load_nodes, verbose=verbose, cache=cache, cache_path=cache_path, additional_graph_kwargs=additional_graph_kwargs )()
32.953704
223
0.678561
from typing import Dict from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph from ...ensmallen import Graph def CoriobacteriumGlomerans( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/string", version: str = "links.v11.5", **additional_graph_kwargs: Dict ) -> Graph: return AutomaticallyRetrievedGraph( graph_name="CoriobacteriumGlomerans", repository="string", version=version, directed=directed, preprocess=preprocess, load_nodes=load_nodes, verbose=verbose, cache=cache, cache_path=cache_path, additional_graph_kwargs=additional_graph_kwargs )()
true
true
1c441bde02d7e435b5ed2bc275e134215dc9609b
54,472
py
Python
fmpy/gui/MainWindow.py
CSchulzeTLK/FMPy
fde192346c36eb69dbaca60a96e80cdc8ef37b89
[ "CC-BY-3.0", "CC-BY-4.0" ]
1
2021-03-17T14:24:08.000Z
2021-03-17T14:24:08.000Z
fmpy/gui/MainWindow.py
CSchulzeTLK/FMPy
fde192346c36eb69dbaca60a96e80cdc8ef37b89
[ "CC-BY-3.0", "CC-BY-4.0" ]
null
null
null
fmpy/gui/MainWindow.py
CSchulzeTLK/FMPy
fde192346c36eb69dbaca60a96e80cdc8ef37b89
[ "CC-BY-3.0", "CC-BY-4.0" ]
null
null
null
""" Entry point for the graphical user interface """ try: from . import compile_resources compile_resources() except Exception as e: print("Failed to compiled resources. %s" % e) import os import sys from PyQt5.QtCore import QCoreApplication, QDir, Qt, pyqtSignal, QUrl, QSettings, QPoint, QTimer, QStandardPaths, \ QPointF, QBuffer, QIODevice from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QLineEdit, QComboBox, QFileDialog, QLabel, QVBoxLayout, QMenu, QMessageBox, QProgressDialog, QProgressBar, QDialog, QGraphicsScene, QGraphicsItemGroup, QGraphicsRectItem, QGraphicsTextItem, QGraphicsPathItem from PyQt5.QtGui import QDesktopServices, QPixmap, QIcon, QDoubleValidator, QColor, QFont, QPen, QFontMetricsF, QPolygonF, QPainterPath from fmpy.gui.generated.MainWindow import Ui_MainWindow import fmpy from fmpy import read_model_description, supported_platforms, platform from fmpy.model_description import ScalarVariable from fmpy.util import can_simulate from fmpy.gui.model import VariablesTableModel, VariablesTreeModel, VariablesModel, VariablesFilterModel from fmpy.gui.log import Log, LogMessagesFilterProxyModel QCoreApplication.setApplicationVersion(fmpy.__version__) QCoreApplication.setOrganizationName("CATIA-Systems") QCoreApplication.setApplicationName("FMPy") import pyqtgraph as pg pg.setConfigOptions(background='w', foreground='k', antialias=True) COLLAPSABLE_COLUMNS = ['Type', 'Value Reference', 'Initial', 'Causality', 'Variability', 'Min', 'Max'] class ClickableLabel(QLabel): """ A QLabel that shows a pointing hand cursor and emits a *clicked* event when clicked """ clicked = pyqtSignal() def __init__(self, parent=None): super(ClickableLabel, self).__init__(parent) self.setCursor(Qt.PointingHandCursor) def mousePressEvent(self, ev): self.clicked.emit() super(ClickableLabel, self).mousePressEvent(ev) class AboutDialog(QDialog): def __init__(self, parent=None): super(AboutDialog, self).__init__(parent) from .generated.AboutDialog import Ui_Dialog from .. import __version__, platform, __file__ import sys import os self.ui = Ui_Dialog() self.ui.setupUi(self) # hide the question mark button flags = self.windowFlags() flags &= ~Qt.WindowContextHelpButtonHint flags |= Qt.MSWindowsFixedSizeDialogHint self.setWindowFlags(flags) self.ui.fmpyVersionLabel.setText(__version__) self.ui.fmiPlatformLabel.setText(platform) self.ui.installationPathLabel.setText(os.path.dirname(__file__)) self.ui.pythonInterpreterLabel.setText(sys.executable) self.ui.pythonVersionLabel.setText(sys.version) class MainWindow(QMainWindow): variableSelected = pyqtSignal(ScalarVariable, name='variableSelected') variableDeselected = pyqtSignal(ScalarVariable, name='variableDeselected') windows = [] windowOffset = QPoint() def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # save from garbage collection self.windows.append(self) # state self.filename = None self.result = None self.modelDescription = None self.variables = dict() self.selectedVariables = set() self.startValues = dict() self.simulationThread = None # self.progressDialog = None self.plotUpdateTimer = QTimer(self) self.plotUpdateTimer.timeout.connect(self.updatePlotData) self.curves = [] # UI self.ui = Ui_MainWindow() self.ui.setupUi(self) self.showColumnActions = {} # use a smaller default font size on Mac and Linux if sys.platform in ['darwin', 'linux']: defaultFont = QFont() defaultFont.setPixelSize(11) QApplication.setFont(defaultFont) self.setStyleSheet("QWidget { font-size: 11px; }") self.ui.treeView.setAttribute(Qt.WA_MacShowFocusRect, False) self.ui.tableView.setAttribute(Qt.WA_MacShowFocusRect, False) self.ui.logTreeView.setAttribute(Qt.WA_MacShowFocusRect, False) # set the window size to 85% of the available space geo = QApplication.desktop().availableGeometry() width = min(geo.width() * 0.85, 1100.0) height = min(geo.height() * 0.85, 900.0) self.resize(int(width), int(height)) # hide the variables self.ui.dockWidget.hide() # toolbar self.stopTimeLineEdit = QLineEdit("1") self.stopTimeLineEdit.setToolTip("Stop time") self.stopTimeLineEdit.setFixedWidth(50) self.stopTimeValidator = QDoubleValidator(self) self.stopTimeValidator.setBottom(0) self.stopTimeLineEdit.setValidator(self.stopTimeValidator) self.ui.toolBar.addWidget(self.stopTimeLineEdit) spacer = QWidget(self) spacer.setFixedWidth(10) self.ui.toolBar.addWidget(spacer) self.fmiTypeComboBox = QComboBox(self) self.fmiTypeComboBox.addItem("Co-Simulation") self.fmiTypeComboBox.setToolTip("FMI type") self.fmiTypeComboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.ui.toolBar.addWidget(self.fmiTypeComboBox) # disable widgets self.ui.actionLoadStartValues.setEnabled(False) self.ui.actionReload.setEnabled(False) self.ui.actionSettings.setEnabled(False) self.ui.actionShowLog.setEnabled(False) self.ui.actionShowResults.setEnabled(False) self.ui.actionSimulate.setEnabled(False) self.ui.actionSaveResult.setEnabled(False) self.ui.actionSavePlottedResult.setEnabled(False) self.stopTimeLineEdit.setEnabled(False) self.fmiTypeComboBox.setEnabled(False) # hide the dock's title bar self.ui.dockWidget.setTitleBarWidget(QWidget()) self.ui.dockWidgetContents.setMinimumWidth(500) self.tableModel = VariablesTableModel(self.selectedVariables, self.startValues) self.tableFilterModel = VariablesFilterModel() self.tableFilterModel.setSourceModel(self.tableModel) self.tableFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.ui.tableView.setModel(self.tableFilterModel) self.treeModel = VariablesTreeModel(self.selectedVariables, self.startValues) self.treeFilterModel = VariablesFilterModel() self.treeFilterModel.setSourceModel(self.treeModel) self.treeFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.ui.treeView.setModel(self.treeFilterModel) for i, (w, n) in enumerate(zip(VariablesModel.COLUMN_WIDTHS, VariablesModel.COLUMN_NAMES)): self.ui.treeView.setColumnWidth(i, w) self.ui.tableView.setColumnWidth(i, w) self.hideAllColumns() # populate the recent files list settings = QSettings() recent_files = settings.value("recentFiles", defaultValue=[]) recent_files = self.removeDuplicates(recent_files) vbox = QVBoxLayout() if recent_files: added = set() for file in recent_files[:5]: link = QLabel('<a href="%s" style="text-decoration: none">%s</a>' % (file, os.path.basename(file))) link.setToolTip(file) link.linkActivated.connect(self.load) vbox.addWidget(link) added.add(file) self.ui.recentFilesGroupBox.setLayout(vbox) self.ui.recentFilesGroupBox.setVisible(len(recent_files) > 0) # settings page self.inputFileMenu = QMenu() self.inputFileMenu.addAction("New input file...", self.createInputFile) self.inputFileMenu.addSeparator() self.inputFileMenu.addAction("Show in Explorer", self.showInputFileInExplorer) self.inputFileMenu.addAction("Open in default application", self.openInputFile) self.ui.selectInputButton.setMenu(self.inputFileMenu) # log page self.log = Log(self) self.logFilterModel = LogMessagesFilterProxyModel(self) self.logFilterModel.setSourceModel(self.log) self.logFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.ui.logTreeView.setModel(self.logFilterModel) self.ui.clearLogButton.clicked.connect(self.log.clear) self.log.numberOfDebugMessagesChanged.connect(lambda n: self.ui.showDebugMessagesButton.setText(str(n))) self.log.numberOfInfoMessagesChanged.connect(lambda n: self.ui.showInfoMessagesButton.setText(str(n))) self.log.numberOfWarningMessagesChanged.connect(lambda n: self.ui.showWarningMessagesButton.setText(str(n))) self.log.numberOfErrorMessagesChanged.connect(lambda n: self.ui.showErrorMessagesButton.setText(str(n))) self.ui.logFilterLineEdit.textChanged.connect(self.logFilterModel.setFilterFixedString) self.ui.showDebugMessagesButton.toggled.connect(self.logFilterModel.setShowDebugMessages) self.ui.showInfoMessagesButton.toggled.connect(self.logFilterModel.setShowInfoMessages) self.ui.showWarningMessagesButton.toggled.connect(self.logFilterModel.setShowWarningMessages) self.ui.showErrorMessagesButton.toggled.connect(self.logFilterModel.setShowErrorMessages) # context menu self.contextMenu = QMenu() self.actionExpandAll = self.contextMenu.addAction("Expand all") self.actionExpandAll.triggered.connect(self.ui.treeView.expandAll) self.actionCollapseAll = self.contextMenu.addAction("Collapse all") self.actionCollapseAll.triggered.connect(self.ui.treeView.collapseAll) self.contextMenu.addSeparator() self.actionCopyVariableName = self.contextMenu.addAction("Copy Variable Name", self.copyVariableName) self.actionCopyValueReference = self.contextMenu.addAction("Copy Value Reference", self.copyValueReference) self.contextMenu.addSeparator() self.actionEditTable = self.contextMenu.addAction("Edit Table", self.editTable) self.contextMenu.addSeparator() self.columnsMenu = self.contextMenu.addMenu('Columns') action = self.columnsMenu.addAction('Show All') action.triggered.connect(self.showAllColumns) action = self.columnsMenu.addAction('Hide All') action.triggered.connect(self.hideAllColumns) self.columnsMenu.addSeparator() for column in COLLAPSABLE_COLUMNS: action = self.columnsMenu.addAction(column) action.setCheckable(True) action.toggled.connect(lambda show, col=column: self.showColumn(col, show)) self.showColumnActions[column] = action self.contextMenu.addSeparator() self.actionClearPlots = self.contextMenu.addAction("Clear Plots", self.clearPlots) # file menu self.ui.actionExit.triggered.connect(QApplication.closeAllWindows) self.ui.actionLoadStartValues.triggered.connect(self.loadStartValues) self.ui.actionReload.triggered.connect(lambda: self.load(self.filename)) self.ui.actionSaveChanges.triggered.connect(self.saveChanges) # tools menu self.ui.actionValidateFMU.triggered.connect(self.validateFMU) self.ui.actionCompileDarwinBinary.triggered.connect(lambda: self.compilePlatformBinary('darwin64')) self.ui.actionCompileLinuxBinary.triggered.connect(lambda: self.compilePlatformBinary('linux64')) self.ui.actionCompileWin32Binary.triggered.connect(lambda: self.compilePlatformBinary('win32')) self.ui.actionCompileWin64Binary.triggered.connect(lambda: self.compilePlatformBinary('win64')) self.ui.actionCreateJupyterNotebook.triggered.connect(self.createJupyterNotebook) self.ui.actionCreateCMakeProject.triggered.connect(self.createCMakeProject) self.ui.actionAddWindows32Remoting.triggered.connect(lambda: self.addRemotingBinaries('win64', 'win32')) self.ui.actionAddLinux64Remoting.triggered.connect(lambda: self.addRemotingBinaries('linux64', 'win64')) self.ui.actionAddCoSimulationWrapper.triggered.connect(self.addCoSimulationWrapper) # help menu self.ui.actionOpenFMI1SpecCS.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://fmi-standard.org/assets/releases/FMI_for_CoSimulation_v1.0.1.pdf'))) self.ui.actionOpenFMI1SpecME.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://fmi-standard.org/assets/releases/FMI_for_ModelExchange_v1.0.1.pdf'))) self.ui.actionOpenFMI2Spec.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/modelica/fmi-standard/releases/download/v2.0.3/FMI-Specification-2.0.3.pdf'))) self.ui.actionOpenTestFMUs.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/modelica/fmi-cross-check/tree/master/fmus'))) self.ui.actionOpenWebsite.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/CATIA-Systems/FMPy'))) self.ui.actionShowReleaseNotes.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://fmpy.readthedocs.io/en/latest/changelog/'))) # filter menu self.filterMenu = QMenu() self.filterMenu.addAction(self.ui.actionFilterInputs) self.filterMenu.addAction(self.ui.actionFilterOutputs) self.filterMenu.addAction(self.ui.actionFilterParameters) self.filterMenu.addAction(self.ui.actionFilterCalculatedParameters) self.filterMenu.addAction(self.ui.actionFilterIndependentVariables) self.filterMenu.addAction(self.ui.actionFilterLocalVariables) self.ui.filterToolButton.setMenu(self.filterMenu) # status bar self.statusIconLabel = ClickableLabel(self) self.statusIconLabel.setStyleSheet("QLabel { margin-left: 5px; }") self.statusIconLabel.clicked.connect(lambda: self.setCurrentPage(self.ui.logPage)) self.ui.statusBar.addPermanentWidget(self.statusIconLabel) self.statusTextLabel = ClickableLabel(self) self.statusTextLabel.setMinimumWidth(10) self.statusTextLabel.clicked.connect(lambda: self.setCurrentPage(self.ui.logPage)) self.ui.statusBar.addPermanentWidget(self.statusTextLabel) self.ui.statusBar.addPermanentWidget(QWidget(self), 1) # spacer self.simulationProgressBar = QProgressBar(self) self.simulationProgressBar.setFixedHeight(18) self.ui.statusBar.addPermanentWidget(self.simulationProgressBar) self.simulationProgressBar.setVisible(False) # connect signals and slots self.ui.actionNewWindow.triggered.connect(self.newWindow) self.ui.openButton.clicked.connect(self.open) self.ui.actionOpen.triggered.connect(self.open) self.ui.actionSaveResult.triggered.connect(self.saveResult) self.ui.actionSavePlottedResult.triggered.connect(lambda: self.saveResult(plotted=True)) self.ui.actionSimulate.triggered.connect(self.startSimulation) self.ui.actionSettings.triggered.connect(lambda: self.setCurrentPage(self.ui.settingsPage)) self.ui.actionShowLog.triggered.connect(lambda: self.setCurrentPage(self.ui.logPage)) self.ui.actionShowResults.triggered.connect(lambda: self.setCurrentPage(self.ui.resultPage)) self.fmiTypeComboBox.currentTextChanged.connect(self.updateSimulationSettings) self.ui.solverComboBox.currentTextChanged.connect(self.updateSimulationSettings) self.variableSelected.connect(self.updatePlotLayout) self.variableDeselected.connect(self.updatePlotLayout) self.tableModel.variableSelected.connect(self.selectVariable) self.tableModel.variableDeselected.connect(self.deselectVariable) self.treeModel.variableSelected.connect(self.selectVariable) self.treeModel.variableDeselected.connect(self.deselectVariable) self.ui.filterLineEdit.textChanged.connect(self.treeFilterModel.setFilterFixedString) self.ui.filterLineEdit.textChanged.connect(self.tableFilterModel.setFilterFixedString) self.ui.filterToolButton.toggled.connect(self.treeFilterModel.setFilterByCausality) self.ui.filterToolButton.toggled.connect(self.tableFilterModel.setFilterByCausality) self.log.currentMessageChanged.connect(self.setStatusMessage) self.ui.selectInputButton.clicked.connect(self.selectInputFile) self.ui.actionShowAboutDialog.triggered.connect(self.showAboutDialog) if os.name == 'nt': self.ui.actionCreateDesktopShortcut.triggered.connect(self.createDesktopShortcut) self.ui.actionAddFileAssociation.triggered.connect(self.addFileAssociation) else: self.ui.actionCreateDesktopShortcut.setEnabled(False) self.ui.actionAddFileAssociation.setEnabled(False) self.ui.tableViewToolButton.toggled.connect(lambda show: self.ui.variablesStackedWidget.setCurrentWidget(self.ui.tablePage if show else self.ui.treePage)) for model in [self.treeFilterModel, self.tableFilterModel]: self.ui.actionFilterInputs.triggered.connect(model.setFilterInputs) self.ui.actionFilterOutputs.triggered.connect(model.setFilterOutputs) self.ui.actionFilterParameters.triggered.connect(model.setFilterParameters) self.ui.actionFilterCalculatedParameters.triggered.connect(model.setFilterCalculatedParameters) self.ui.actionFilterIndependentVariables.triggered.connect(model.setFilterIndependentVariables) self.ui.actionFilterLocalVariables.triggered.connect(model.setFilterLocalVariables) self.ui.treeView.customContextMenuRequested.connect(self.showContextMenu) self.ui.tableView.customContextMenuRequested.connect(self.showContextMenu) def newWindow(self): window = MainWindow() window.show() def show(self): super(MainWindow, self).show() self.move(self.frameGeometry().topLeft() + self.windowOffset) self.windowOffset += QPoint(20, 20) def showContextMenu(self, point): """ Update and show the variables context menu """ from .TableDialog import TableDialog if self.ui.variablesStackedWidget.currentWidget() == self.ui.treePage: currentView = self.ui.treeView else: currentView = self.ui.tableView self.actionExpandAll.setEnabled(currentView == self.ui.treeView) self.actionCollapseAll.setEnabled(currentView == self.ui.treeView) selected = self.getSelectedVariables() self.actionEditTable.setEnabled(len(selected) == 1 and TableDialog.canEdit(selected[0])) can_copy = len(selected) > 0 self.actionCopyVariableName.setEnabled(can_copy) self.actionCopyValueReference.setEnabled(can_copy) self.contextMenu.exec_(currentView.mapToGlobal(point)) def load(self, filename): import zipfile if not self.isVisible(): self.show() try: self.modelDescription = md = read_model_description(filename) except Exception as e: QMessageBox.warning(self, "Failed to load FMU", "Failed to load %s. %s" % (filename, e)) return # show model.png try: pixmap = QPixmap() # load the model.png with zipfile.ZipFile(filename, 'r') as zf: pixmap.loadFromData(zf.read('model.png'), format='PNG') # show the unscaled version in tooltip buffer = QBuffer() buffer.open(QIODevice.WriteOnly) pixmap.save(buffer, "PNG", quality=100) image = bytes(buffer.data().toBase64()).decode() html = '<img src="data:image/png;base64,{}">'.format(image) self.ui.modelImageLabel.setToolTip(html) # show a scaled preview in "Model Info" pixmap = pixmap.scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.ui.modelImageLabel.setPixmap(pixmap) except: self.ui.modelImageLabel.setPixmap(QPixmap()) self.ui.modelImageLabel.setToolTip(None) self.filename = filename platforms = supported_platforms(self.filename) self.variables.clear() self.selectedVariables.clear() self.startValues.clear() for v in md.modelVariables: self.variables[v.name] = v if v.causality == 'output' and not v.dimensions: self.selectedVariables.add(v) fmi_types = [] if md.coSimulation: fmi_types.append('Co-Simulation') if md.modelExchange: fmi_types.append('Model Exchange') experiment = md.defaultExperiment # toolbar if experiment is not None and experiment.stopTime is not None: self.stopTimeLineEdit.setText(str(experiment.stopTime)) # actions self.ui.actionValidateFMU.setEnabled(True) can_compile = md.fmiVersion == '2.0' and 'c-code' in platforms self.ui.actionCompileDarwinBinary.setEnabled(can_compile and fmpy.system == 'darwin') self.ui.actionCompileLinuxBinary.setEnabled(can_compile and fmpy.system in ['linux', 'windows']) self.ui.actionCompileWin32Binary.setEnabled(can_compile and fmpy.system == 'windows') self.ui.actionCompileWin64Binary.setEnabled(can_compile and fmpy.system == 'windows') self.ui.actionCreateCMakeProject.setEnabled(can_compile) self.ui.actionCreateJupyterNotebook.setEnabled(True) self.ui.actionAddWindows32Remoting.setEnabled(md.fmiVersion == '2.0' and 'win32' in platforms and 'win64' not in platforms) self.ui.actionAddLinux64Remoting.setEnabled(md.fmiVersion == '2.0' and 'win64' in platforms and 'linux64' not in platforms) can_add_cswrapper = md.fmiVersion == '2.0' and md.coSimulation is None and md.modelExchange is not None self.ui.actionAddCoSimulationWrapper.setEnabled(can_add_cswrapper) # variables view self.treeModel.setModelDescription(md) self.tableModel.setModelDescription(md) self.treeFilterModel.invalidate() self.tableFilterModel.invalidate() self.ui.treeView.reset() self.ui.tableView.reset() # settings page self.ui.fmiVersionLabel.setText(md.fmiVersion) self.ui.fmiTypeLabel.setText(', '.join(fmi_types)) self.ui.platformsLabel.setText(', '.join(platforms)) self.ui.modelNameLabel.setText(md.modelName) self.ui.descriptionLabel.setText(md.description) self.ui.numberOfContinuousStatesLabel.setText(str(md.numberOfContinuousStates)) self.ui.numberOfEventIndicatorsLabel.setText(str(md.numberOfEventIndicators)) self.ui.numberOfVariablesLabel.setText(str(len(md.modelVariables))) self.ui.generationToolLabel.setText(md.generationTool) self.ui.generationDateAndTimeLabel.setText(md.generationDateAndTime) # relative tolerance if experiment is not None and experiment.tolerance is not None: relative_tolerance = experiment.tolerance else: relative_tolerance = 1e-6 self.ui.relativeToleranceLineEdit.setText(str(relative_tolerance)) # output interval if experiment is not None and experiment.stepSize is not None: output_interval = float(experiment.stepSize) while output_interval > 1000: output_interval *= 0.5 else: output_interval = float(self.stopTimeLineEdit.text()) / 500 self.ui.outputIntervalLineEdit.setText(str(output_interval)) self.fmiTypeComboBox.clear() self.fmiTypeComboBox.addItems(fmi_types) self.updateSimulationSettings() self.setCurrentPage(self.ui.settingsPage) self.ui.dockWidget.show() self.ui.actionReload.setEnabled(True) self.ui.actionSettings.setEnabled(True) self.ui.actionShowLog.setEnabled(True) self.ui.actionShowResults.setEnabled(False) can_sim, _ = can_simulate(platforms) self.ui.actionLoadStartValues.setEnabled(can_sim) self.ui.actionSimulate.setEnabled(can_sim) self.stopTimeLineEdit.setEnabled(can_sim) self.fmiTypeComboBox.setEnabled(can_sim and len(fmi_types) > 1) self.ui.settingsGroupBox.setEnabled(can_sim) settings = QSettings() recent_files = settings.value("recentFiles", defaultValue=[]) recent_files = self.removeDuplicates([filename] + recent_files) # save the 10 most recent files settings.setValue('recentFiles', recent_files[:10]) self.setWindowTitle("%s - FMPy" % os.path.normpath(filename)) self.createGraphics() def open(self): start_dir = QDir.homePath() settings = QSettings() recent_files = settings.value("recentFiles", defaultValue=[]) for filename in recent_files: dirname = os.path.dirname(filename) if os.path.isdir(dirname): start_dir = dirname break filename, _ = QFileDialog.getOpenFileName(parent=self, caption="Open File", directory=start_dir, filter="FMUs (*.fmu);;All Files (*.*)") if filename: self.load(filename) def setCurrentPage(self, widget): """ Set the current page and the actions """ # block the signals during the update self.ui.actionSettings.blockSignals(True) self.ui.actionShowLog.blockSignals(True) self.ui.actionShowResults.blockSignals(True) self.ui.stackedWidget.setCurrentWidget(widget) # toggle the actions self.ui.actionSettings.setChecked(widget == self.ui.settingsPage) self.ui.actionShowLog.setChecked(widget == self.ui.logPage) self.ui.actionShowResults.setChecked(widget == self.ui.resultPage) # un-block the signals during the update self.ui.actionSettings.blockSignals(False) self.ui.actionShowLog.blockSignals(False) self.ui.actionShowResults.blockSignals(False) def selectInputFile(self): start_dir = os.path.dirname(self.filename) filename, _ = QFileDialog.getOpenFileName(parent=self, caption="Select Input File", directory=start_dir, filter="FMUs (*.csv);;All Files (*.*)") if filename: self.ui.inputFilenameLineEdit.setText(filename) def createInputFile(self): """ Create an input file based on the input variables in the model description """ input_variables = [] for variable in self.modelDescription.modelVariables: if variable.causality == 'input': input_variables.append(variable) if len(input_variables) == 0: QMessageBox.warning(self, "Cannot create input file", "The input file cannot be created because the model has no input variables") return filename, _ = os.path.splitext(self.filename) filename, _ = QFileDialog.getSaveFileName(parent=self, caption="Save Input File", directory=filename + '_in.csv', filter="Comma Separated Values (*.csv);;All Files (*.*)") if not filename: return with open(filename, 'w') as f: # column names f.write('"time"') for variable in input_variables: f.write(',"%s"' % variable.name) f.write('\n') # example data f.write(','.join(['0'] * (len(input_variables) + 1)) + '\n') self.ui.inputFilenameLineEdit.setText(filename) def showInputFileInExplorer(self): """ Reveal the input file in the file browser """ filename = self.ui.inputFilenameLineEdit.text() if not os.path.isfile(filename): QMessageBox.warning(self, "Cannot show input file", "The input file does not exist") return QDesktopServices.openUrl(QUrl.fromLocalFile(os.path.dirname(filename))) def openInputFile(self): """ Open the input file in the default application """ filename = self.ui.inputFilenameLineEdit.text() if not os.path.isfile(filename): QMessageBox.warning(self, "Cannot open input file", "The input file does not exist") return QDesktopServices.openUrl(QUrl.fromLocalFile(filename)) def updateSimulationSettings(self): if self.fmiTypeComboBox.currentText() == 'Co-Simulation': self.ui.solverComboBox.setEnabled(False) self.ui.stepSizeLineEdit.setEnabled(False) self.ui.relativeToleranceLineEdit.setEnabled(True) else: self.ui.solverComboBox.setEnabled(True) fixed_step = self.ui.solverComboBox.currentText() == 'Fixed-step' self.ui.stepSizeLineEdit.setEnabled(fixed_step) self.ui.relativeToleranceLineEdit.setEnabled(not fixed_step) def selectVariable(self, variable): self.selectedVariables.add(variable) self.variableSelected.emit(variable) def deselectVariable(self, variable): self.selectedVariables.remove(variable) self.variableDeselected.emit(variable) def startSimulation(self): from fmpy.gui.simulation import SimulationThread try: stop_time = float(self.stopTimeLineEdit.text()) step_size = float(self.ui.stepSizeLineEdit.text()) relative_tolerance = float(self.ui.relativeToleranceLineEdit.text()) if self.ui.outputIntervalRadioButton.isChecked(): output_interval = float(self.ui.outputIntervalLineEdit.text()) else: max_samples = float(self.ui.maxSamplesLineEdit.text()) output_interval = stop_time / max_samples except Exception as ex: self.log.log('error', "Failed to start simulation: %s" % ex) self.ui.stackedWidget.setCurrentWidget(self.ui.logPage) return step_size = min(step_size, output_interval) if self.ui.solverComboBox.currentText() == 'Fixed-step': solver = 'Euler' else: solver = 'CVode' if self.ui.inputCheckBox.isChecked(): input_variables = [] for variable in self.modelDescription.modelVariables: if variable.causality == 'input': input_variables.append(variable.name) try: from fmpy.util import read_csv filename = self.ui.inputFilenameLineEdit.text() input = read_csv(filename, variable_names=input_variables) except Exception as e: self.log.log('error', "Failed to load input from '%s'. %s" % (filename, e)) return else: input = None output = [] for variable in self.modelDescription.modelVariables: output.append(variable.name) fmi_type = 'CoSimulation' if self.fmiTypeComboBox.currentText() == 'Co-Simulation' else 'ModelExchange' self.simulationThread = SimulationThread(filename=self.filename, fmiType=fmi_type, stopTime=stop_time, solver=solver, stepSize=step_size, relativeTolerance=relative_tolerance, outputInterval=output_interval, startValues=self.startValues, applyDefaultStartValues=self.ui.applyDefaultStartValuesCheckBox.isChecked(), input=input, output=output, debugLogging=self.ui.debugLoggingCheckBox.isChecked(), fmiLogging=self.ui.logFMICallsCheckBox.isChecked()) self.ui.actionSimulate.setIcon(QIcon(':/icons/stop.png')) self.ui.actionSimulate.setToolTip("Stop simulation") self.ui.actionSimulate.triggered.disconnect(self.startSimulation) self.ui.actionSimulate.triggered.connect(self.simulationThread.stop) self.simulationProgressBar.setVisible(True) self.simulationThread.messageChanged.connect(self.log.log) self.simulationThread.progressChanged.connect(self.simulationProgressBar.setValue) self.simulationThread.finished.connect(self.simulationFinished) if self.ui.clearLogOnStartButton.isChecked(): self.log.clear() self.setCurrentPage(self.ui.resultPage) self.simulationThread.start() self.plotUpdateTimer.start(100) self.updatePlotLayout() def simulationFinished(self): # update UI self.ui.actionSimulate.triggered.disconnect(self.simulationThread.stop) self.ui.actionSimulate.triggered.connect(self.startSimulation) self.ui.actionSimulate.setIcon(QIcon(':/icons/play.png')) self.ui.actionSimulate.setToolTip("Start simulation") self.plotUpdateTimer.stop() self.simulationProgressBar.setVisible(False) self.ui.actionShowResults.setEnabled(True) self.ui.actionSettings.setEnabled(True) self.setCurrentPage(self.ui.resultPage) self.updatePlotLayout() if self.result is None: self.setCurrentPage(self.ui.logPage) else: self.ui.actionSaveResult.setEnabled(True) self.ui.actionSavePlottedResult.setEnabled(True) self.result = self.simulationThread.result self.simulationThread = None self.updatePlotData() def updatePlotData(self): import numpy as np if self.simulationThread is not None and len(self.simulationThread.rows) > 1: # get results from current simulation self.result = np.array(self.simulationThread.rows, dtype=np.dtype(self.simulationThread.cols)) if self.result is None: return # no results available yet time = self.result['time'] for variable, curve in self.curves: if variable.name not in self.result.dtype.names: continue y = self.result[variable.name] if variable.type == 'Real': curve.setData(x=time, y=y) else: curve.setData(x=np.repeat(time, 2)[1:], y=np.repeat(y, 2)[:-1]) def updatePlotLayout(self): self.ui.plotWidget.clear() self.curves[:] = [] if self.simulationThread is not None: stop_time = self.simulationThread.stopTime elif self.result is not None: stop_time = self.result['time'][-1] else: stop_time = 1.0 pen = (0, 0, 255) for variable in self.selectedVariables: self.ui.plotWidget.nextRow() plot = self.ui.plotWidget.addPlot() if variable.type == 'Real': curve = plot.plot(pen=pen) else: if variable.type == 'Boolean': plot.setYRange(0, 1, padding=0.2) plot.getAxis('left').setTicks([[(0, 'false'), (1, 'true')], []]) curve = plot.plot(pen=pen, fillLevel=0, fillBrush=(0, 0, 255, 50), antialias=False) else: curve = plot.plot(pen=pen, antialias=False) plot.setXRange(0, stop_time, padding=0.05) plot.setLabel('left', variable.name) plot.showGrid(x=True, y=True, alpha=0.25) # hide the auto-scale button and disable context menu and mouse interaction plot.hideButtons() plot.setMouseEnabled(False, False) plot.setMenuEnabled(False) self.curves.append((variable, curve)) self.updatePlotData() def showColumn(self, name, show): if name in self.showColumnActions: self.showColumnActions[name].setChecked(show) i = VariablesModel.COLUMN_NAMES.index(name) self.ui.treeView.setColumnHidden(i, not show) self.ui.tableView.setColumnHidden(i, not show) def showAllColumns(self): for name in COLLAPSABLE_COLUMNS: self.showColumn(name, True) def hideAllColumns(self): for name in COLLAPSABLE_COLUMNS: self.showColumn(name, False) def setStatusMessage(self, level, text): if level in ['debug', 'info', 'warning', 'error']: self.statusIconLabel.setPixmap(QPixmap(':/icons/%s-16x16.png' % level)) else: self.statusIconLabel.setPixmap(QPixmap()) self.statusTextLabel.setText(text) def dragEnterEvent(self, event): for url in event.mimeData().urls(): if not url.isLocalFile(): return event.acceptProposedAction() def dropEvent(self, event): urls = event.mimeData().urls() for url in urls: if url == urls[0]: window = self else: window = MainWindow() window.load(url.toLocalFile()) def saveResult(self, plotted=False): filename, _ = os.path.splitext(self.filename) filename, _ = QFileDialog.getSaveFileName(parent=self, caption="Save Result", directory=filename + '_out.csv', filter="Comma Separated Values (*.csv);;All Files (*.*)") if filename: from ..util import write_csv if plotted: columns = [variable.name for variable in self.selectedVariables] else: columns = None try: write_csv(filename=filename, result=self.result, columns=columns) except Exception as e: QMessageBox.critical(self, "Failed to write result", '"Failed to write "%s". %s' % (filename, e)) def createDesktopShortcut(self): """ Create a desktop shortcut to start the GUI """ import os from win32com.client import Dispatch import sys env = os.environ.get('CONDA_DEFAULT_ENV') if env is None: target_path = sys.executable root, ext = os.path.splitext(target_path) pythonw = root + 'w' + ext if os.path.isfile(pythonw): target_path = pythonw arguments = '-m fmpy.gui' else: for path in os.environ["PATH"].split(os.pathsep): activate = os.path.join(path, 'activate.bat') if os.path.isfile(activate): break target_path = r'%windir%\System32\cmd.exe' arguments = '/C ""%s" %s && python -m fmpy.gui"' % (activate, env) file_path = os.path.dirname(__file__) icon = os.path.join(file_path, 'icons', 'app_icon.ico') desktop_locations = QStandardPaths.standardLocations(QStandardPaths.DesktopLocation) shortcut_path = os.path.join(desktop_locations[0], "FMPy GUI.lnk") shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(shortcut_path) shortcut.Targetpath = target_path shortcut.Arguments = arguments # shortcut.WorkingDirectory = ... shortcut.IconLocation = icon shortcut.save() def showAboutDialog(self): dialog = AboutDialog(self) dialog.show() @staticmethod def removeDuplicates(seq): """ Remove duplicates from a sequence """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] def validateFMU(self): from ..validation import validate_fmu problems = validate_fmu(self.filename) if problems: button = QMessageBox.question(self, "Validation failed", "%d problems have been found. Save validation messages?" % len(problems)) if button == QMessageBox.Yes: filename, _ = os.path.splitext(self.filename) filename, _ = QFileDialog.getSaveFileName(parent=self, caption="Save validation messages", directory=filename + '_validation.txt', filter="Text Files (*.txt);;All Files (*.*)") if filename: with open(filename, 'w') as f: f.writelines(problems) else: QMessageBox.information(self, "Validation successful", "No problems have been found.") def addFileAssociation(self): """ Associate *.fmu with the FMPy GUI """ try: from winreg import HKEY_CURRENT_USER, KEY_WRITE, REG_SZ, OpenKey, CreateKey, SetValueEx, CloseKey env = os.environ.get('CONDA_DEFAULT_ENV_') if env is None: python = sys.executable root, ext = os.path.splitext(python) pythonw = root + 'w' + ext if os.path.isfile(pythonw): python = pythonw target = '"%s" -m fmpy.gui "%%1"' % python else: # activate the conda environment for path in os.environ["PATH"].split(os.pathsep): activate = os.path.join(path, 'activate.bat') if os.path.isfile(activate): break windir = os.environ['WINDIR'] cmd = os.path.join(windir, 'System32', 'cmd.exe') target = r'%s /C ""%s" %s && python -m fmpy.gui %%1"' % (cmd, activate, env) key_path = r'Software\Classes\fmpy.gui\shell\open\command' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, target) CloseKey(key) key_path = r'SOFTWARE\Classes\.fmu' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, 'fmpy.gui') CloseKey(key) QMessageBox.information(self, "File association added", "The file association for *.fmu has been added") except Exception as e: QMessageBox.critical(self, "File association failed", "The file association for *.fmu could not be added. %s" % e) def copyValueReference(self): """ Copy the value references of the selected variables to the clipboard """ text = '\n'.join([str(v.valueReference) for v in self.getSelectedVariables()]) QApplication.clipboard().setText(text) def copyVariableName(self): """ Copy the names of the selected variables to the clipboard """ text = '\n'.join([str(v.name) for v in self.getSelectedVariables()]) QApplication.clipboard().setText(text) def getSelectedVariables(self): """ Returns a list of selected variables in the current view """ variables = [] if self.ui.variablesStackedWidget.currentWidget() == self.ui.treePage: for index in self.ui.treeView.selectionModel().selectedRows(): sourceIndex = self.treeFilterModel.mapToSource(index) treeItem = sourceIndex.internalPointer() if treeItem.variable is not None: variables.append(treeItem.variable) else: for index in self.ui.tableView.selectionModel().selectedRows(): sourceIndex = self.tableFilterModel.mapToSource(index) variable = sourceIndex.internalPointer() variables.append(variable) return variables def clearPlots(self): """ Clear all plots """ self.selectedVariables.clear() self.updatePlotLayout() def createGraphics(self): """ Create the graphical representation of the FMU's inputs and outputs """ def variableColor(variable): if variable.type.startswith(('Float', 'Real')): return QColor.fromRgb(26, 77, 179) elif variable.type.startswith(('Enumeration', 'Int', 'UInt')): return QColor.fromRgb(179, 77, 26) elif variable.type == 'Boolean': return QColor.fromRgb(255, 0, 255) elif variable.type == 'String': return QColor.fromRgb(26, 114, 16) elif variable.type == 'Binary': return QColor.fromRgb(81, 81, 81) else: return QColor.fromRgb(0, 0, 0) inputVariables = [] outputVariables = [] maxInputLabelWidth = 0 maxOutputLabelWidth = 0 textItem = QGraphicsTextItem() fontMetrics = QFontMetricsF(textItem.font()) for variable in self.modelDescription.modelVariables: if variable.causality == 'input': inputVariables.append(variable) elif variable.causality == 'output': outputVariables.append(variable) for variable in inputVariables: maxInputLabelWidth = max(maxInputLabelWidth, fontMetrics.width(variable.name)) for variable in outputVariables: maxOutputLabelWidth = max(maxOutputLabelWidth, fontMetrics.width(variable.name)) from math import floor scene = QGraphicsScene() self.ui.graphicsView.setScene(scene) group = QGraphicsItemGroup() scene.addItem(group) group.setPos(200.5, -50.5) lh = 15 # line height w = max(150., maxInputLabelWidth + maxOutputLabelWidth + 20) h = max(50., 10 + lh * max(len(inputVariables), len(outputVariables))) block = QGraphicsRectItem(0, 0, w, h, group) block.setPen(QColor.fromRgb(0, 0, 0)) pen = QPen() pen.setWidthF(1) font = QFont() font.setPixelSize(10) # inputs y = floor((h - len(inputVariables) * lh) / 2 - 2) for variable in inputVariables: text = QGraphicsTextItem(variable.name, group) text.setDefaultTextColor(QColor.fromRgb(0, 0, 0)) text.setFont(font) text.setX(3) text.setY(y) polygon = QPolygonF([QPointF(-8, y + 7.5), QPointF(-1, y + 11), QPointF(-8, y + 14.5)]) path = QPainterPath() path.addPolygon(polygon) path.closeSubpath() contour = QGraphicsPathItem(path, group) contour.setPen(QPen(Qt.NoPen)) contour.setBrush(variableColor(variable)) pen = QPen() pen.setColor(variableColor(variable)) pen.setJoinStyle(Qt.MiterJoin) contour.setPen(pen) y += lh # outputs y = floor((h - len(outputVariables) * lh) / 2 - 2) for variable in outputVariables: text = QGraphicsTextItem(variable.name, group) text.setDefaultTextColor(QColor.fromRgb(0, 0, 0)) text.setFont(font) text.setX(w - 3 - text.boundingRect().width()) text.setY(y) polygon = QPolygonF([QPointF(w + 1, y + 7.5), QPointF(w + 8, y + 11), QPointF(w + 1, y + 14.5)]) path = QPainterPath() path.addPolygon(polygon) path.closeSubpath() contour = QGraphicsPathItem(path, group) contour.setPen(QPen(Qt.NoPen)) contour.setBrush(variableColor(variable)) pen = QPen() pen.setColor(variableColor(variable)) pen.setJoinStyle(Qt.MiterJoin) contour.setPen(pen) y += lh def saveChanges(self): from ..util import change_fmu output_file, _ = QFileDialog.getSaveFileName(parent=self, caption='Save Changed FMU', directory=self.filename, filter='FMUs (*.fmu)') if output_file: change_fmu(input_file=self.filename, output_file=output_file, start_values=self.startValues) def loadStartValues(self): from ..util import get_start_values start_values = get_start_values(self.filename) self.startValues.update(start_values) self.ui.treeView.reset() self.ui.tableView.reset() def editTable(self): """ Open the table dialog """ from .TableDialog import TableDialog variables = self.getSelectedVariables() if len(variables) == 1: start_values = self.startValues.copy() dialog = TableDialog(modelVariables=self.modelDescription.modelVariables, variable=variables[0], startValues=start_values) if dialog.exec_() == QDialog.Accepted: self.startValues.clear() self.startValues.update(start_values) def compilePlatformBinary(self, target_platform): """ Compile the platform binary """ from ..util import compile_platform_binary platforms = supported_platforms(self.filename) if target_platform in platforms: button = QMessageBox.question(self, "Platform binary already exists", f'The FMU already contains a binary for the platform "{target_platform}".' ' Do you want to compile and overwrite the existing binary?') if button == QMessageBox.No: return try: compile_platform_binary(self.filename, target_platform=target_platform) except Exception as e: QMessageBox.critical(self, "Failed to compile platform binaries", str(e)) return self.load(self.filename) def createJupyterNotebook(self): """ Create a Juypyter Notebook to simulate the FMU """ from fmpy.util import create_jupyter_notebook filename, ext = os.path.splitext(self.filename) filename, _ = QFileDialog.getSaveFileName( parent=self, directory=filename + '.ipynb', filter='Jupyter Notebooks (*.ipynb);;All Files (*)' ) if filename: try: create_jupyter_notebook(self.filename, filename) except Exception as e: QMessageBox.critical(self, "Failed to create Jupyter Notebook", str(e)) return if QMessageBox.question(self, "Open Jupyter Notebook?", f"Start Jupyter and open {filename}?") == QMessageBox.Yes: from subprocess import run, CREATE_NEW_CONSOLE try: run(['jupyter', 'notebook', filename], creationflags=CREATE_NEW_CONSOLE) except Exception as e: QMessageBox.critical(self, "Failed to start Jupyter", str(e)) def createCMakeProject(self): """ Create a CMake project from a C code FMU """ from fmpy.util import create_cmake_project project_dir = QFileDialog.getExistingDirectory( parent=self, caption='Select CMake Project Folder', directory=os.path.dirname(self.filename)) if project_dir: create_cmake_project(self.filename, project_dir) def addRemotingBinaries(self, host_platform, remote_platform): from ..util import add_remoting try: add_remoting(self.filename, host_platform, remote_platform) except Exception as e: QMessageBox.warning(self, "Failed to add Remoting Binaries", f"Failed to add remoting binaries to {self.filename}. {e}") self.load(self.filename) def addCoSimulationWrapper(self): """ Add the Co-Simulation Wrapper to the FMU """ from ..cswrapper import add_cswrapper try: add_cswrapper(self.filename) except Exception as e: QMessageBox.warning(self, "Failed to add Co-Simulation Wrapper", "Failed to add Co-Simulation Wrapper %s. %s" % (self.filename, e)) self.load(self.filename)
41.966102
272
0.62265
try: from . import compile_resources compile_resources() except Exception as e: print("Failed to compiled resources. %s" % e) import os import sys from PyQt5.QtCore import QCoreApplication, QDir, Qt, pyqtSignal, QUrl, QSettings, QPoint, QTimer, QStandardPaths, \ QPointF, QBuffer, QIODevice from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QLineEdit, QComboBox, QFileDialog, QLabel, QVBoxLayout, QMenu, QMessageBox, QProgressDialog, QProgressBar, QDialog, QGraphicsScene, QGraphicsItemGroup, QGraphicsRectItem, QGraphicsTextItem, QGraphicsPathItem from PyQt5.QtGui import QDesktopServices, QPixmap, QIcon, QDoubleValidator, QColor, QFont, QPen, QFontMetricsF, QPolygonF, QPainterPath from fmpy.gui.generated.MainWindow import Ui_MainWindow import fmpy from fmpy import read_model_description, supported_platforms, platform from fmpy.model_description import ScalarVariable from fmpy.util import can_simulate from fmpy.gui.model import VariablesTableModel, VariablesTreeModel, VariablesModel, VariablesFilterModel from fmpy.gui.log import Log, LogMessagesFilterProxyModel QCoreApplication.setApplicationVersion(fmpy.__version__) QCoreApplication.setOrganizationName("CATIA-Systems") QCoreApplication.setApplicationName("FMPy") import pyqtgraph as pg pg.setConfigOptions(background='w', foreground='k', antialias=True) COLLAPSABLE_COLUMNS = ['Type', 'Value Reference', 'Initial', 'Causality', 'Variability', 'Min', 'Max'] class ClickableLabel(QLabel): clicked = pyqtSignal() def __init__(self, parent=None): super(ClickableLabel, self).__init__(parent) self.setCursor(Qt.PointingHandCursor) def mousePressEvent(self, ev): self.clicked.emit() super(ClickableLabel, self).mousePressEvent(ev) class AboutDialog(QDialog): def __init__(self, parent=None): super(AboutDialog, self).__init__(parent) from .generated.AboutDialog import Ui_Dialog from .. import __version__, platform, __file__ import sys import os self.ui = Ui_Dialog() self.ui.setupUi(self) flags = self.windowFlags() flags &= ~Qt.WindowContextHelpButtonHint flags |= Qt.MSWindowsFixedSizeDialogHint self.setWindowFlags(flags) self.ui.fmpyVersionLabel.setText(__version__) self.ui.fmiPlatformLabel.setText(platform) self.ui.installationPathLabel.setText(os.path.dirname(__file__)) self.ui.pythonInterpreterLabel.setText(sys.executable) self.ui.pythonVersionLabel.setText(sys.version) class MainWindow(QMainWindow): variableSelected = pyqtSignal(ScalarVariable, name='variableSelected') variableDeselected = pyqtSignal(ScalarVariable, name='variableDeselected') windows = [] windowOffset = QPoint() def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.windows.append(self) self.filename = None self.result = None self.modelDescription = None self.variables = dict() self.selectedVariables = set() self.startValues = dict() self.simulationThread = None self.plotUpdateTimer = QTimer(self) self.plotUpdateTimer.timeout.connect(self.updatePlotData) self.curves = [] self.ui = Ui_MainWindow() self.ui.setupUi(self) self.showColumnActions = {} if sys.platform in ['darwin', 'linux']: defaultFont = QFont() defaultFont.setPixelSize(11) QApplication.setFont(defaultFont) self.setStyleSheet("QWidget { font-size: 11px; }") self.ui.treeView.setAttribute(Qt.WA_MacShowFocusRect, False) self.ui.tableView.setAttribute(Qt.WA_MacShowFocusRect, False) self.ui.logTreeView.setAttribute(Qt.WA_MacShowFocusRect, False) geo = QApplication.desktop().availableGeometry() width = min(geo.width() * 0.85, 1100.0) height = min(geo.height() * 0.85, 900.0) self.resize(int(width), int(height)) self.ui.dockWidget.hide() self.stopTimeLineEdit = QLineEdit("1") self.stopTimeLineEdit.setToolTip("Stop time") self.stopTimeLineEdit.setFixedWidth(50) self.stopTimeValidator = QDoubleValidator(self) self.stopTimeValidator.setBottom(0) self.stopTimeLineEdit.setValidator(self.stopTimeValidator) self.ui.toolBar.addWidget(self.stopTimeLineEdit) spacer = QWidget(self) spacer.setFixedWidth(10) self.ui.toolBar.addWidget(spacer) self.fmiTypeComboBox = QComboBox(self) self.fmiTypeComboBox.addItem("Co-Simulation") self.fmiTypeComboBox.setToolTip("FMI type") self.fmiTypeComboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.ui.toolBar.addWidget(self.fmiTypeComboBox) self.ui.actionLoadStartValues.setEnabled(False) self.ui.actionReload.setEnabled(False) self.ui.actionSettings.setEnabled(False) self.ui.actionShowLog.setEnabled(False) self.ui.actionShowResults.setEnabled(False) self.ui.actionSimulate.setEnabled(False) self.ui.actionSaveResult.setEnabled(False) self.ui.actionSavePlottedResult.setEnabled(False) self.stopTimeLineEdit.setEnabled(False) self.fmiTypeComboBox.setEnabled(False) self.ui.dockWidget.setTitleBarWidget(QWidget()) self.ui.dockWidgetContents.setMinimumWidth(500) self.tableModel = VariablesTableModel(self.selectedVariables, self.startValues) self.tableFilterModel = VariablesFilterModel() self.tableFilterModel.setSourceModel(self.tableModel) self.tableFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.ui.tableView.setModel(self.tableFilterModel) self.treeModel = VariablesTreeModel(self.selectedVariables, self.startValues) self.treeFilterModel = VariablesFilterModel() self.treeFilterModel.setSourceModel(self.treeModel) self.treeFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.ui.treeView.setModel(self.treeFilterModel) for i, (w, n) in enumerate(zip(VariablesModel.COLUMN_WIDTHS, VariablesModel.COLUMN_NAMES)): self.ui.treeView.setColumnWidth(i, w) self.ui.tableView.setColumnWidth(i, w) self.hideAllColumns() # populate the recent files list settings = QSettings() recent_files = settings.value("recentFiles", defaultValue=[]) recent_files = self.removeDuplicates(recent_files) vbox = QVBoxLayout() if recent_files: added = set() for file in recent_files[:5]: link = QLabel('<a href="%s" style="text-decoration: none">%s</a>' % (file, os.path.basename(file))) link.setToolTip(file) link.linkActivated.connect(self.load) vbox.addWidget(link) added.add(file) self.ui.recentFilesGroupBox.setLayout(vbox) self.ui.recentFilesGroupBox.setVisible(len(recent_files) > 0) # settings page self.inputFileMenu = QMenu() self.inputFileMenu.addAction("New input file...", self.createInputFile) self.inputFileMenu.addSeparator() self.inputFileMenu.addAction("Show in Explorer", self.showInputFileInExplorer) self.inputFileMenu.addAction("Open in default application", self.openInputFile) self.ui.selectInputButton.setMenu(self.inputFileMenu) # log page self.log = Log(self) self.logFilterModel = LogMessagesFilterProxyModel(self) self.logFilterModel.setSourceModel(self.log) self.logFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.ui.logTreeView.setModel(self.logFilterModel) self.ui.clearLogButton.clicked.connect(self.log.clear) self.log.numberOfDebugMessagesChanged.connect(lambda n: self.ui.showDebugMessagesButton.setText(str(n))) self.log.numberOfInfoMessagesChanged.connect(lambda n: self.ui.showInfoMessagesButton.setText(str(n))) self.log.numberOfWarningMessagesChanged.connect(lambda n: self.ui.showWarningMessagesButton.setText(str(n))) self.log.numberOfErrorMessagesChanged.connect(lambda n: self.ui.showErrorMessagesButton.setText(str(n))) self.ui.logFilterLineEdit.textChanged.connect(self.logFilterModel.setFilterFixedString) self.ui.showDebugMessagesButton.toggled.connect(self.logFilterModel.setShowDebugMessages) self.ui.showInfoMessagesButton.toggled.connect(self.logFilterModel.setShowInfoMessages) self.ui.showWarningMessagesButton.toggled.connect(self.logFilterModel.setShowWarningMessages) self.ui.showErrorMessagesButton.toggled.connect(self.logFilterModel.setShowErrorMessages) # context menu self.contextMenu = QMenu() self.actionExpandAll = self.contextMenu.addAction("Expand all") self.actionExpandAll.triggered.connect(self.ui.treeView.expandAll) self.actionCollapseAll = self.contextMenu.addAction("Collapse all") self.actionCollapseAll.triggered.connect(self.ui.treeView.collapseAll) self.contextMenu.addSeparator() self.actionCopyVariableName = self.contextMenu.addAction("Copy Variable Name", self.copyVariableName) self.actionCopyValueReference = self.contextMenu.addAction("Copy Value Reference", self.copyValueReference) self.contextMenu.addSeparator() self.actionEditTable = self.contextMenu.addAction("Edit Table", self.editTable) self.contextMenu.addSeparator() self.columnsMenu = self.contextMenu.addMenu('Columns') action = self.columnsMenu.addAction('Show All') action.triggered.connect(self.showAllColumns) action = self.columnsMenu.addAction('Hide All') action.triggered.connect(self.hideAllColumns) self.columnsMenu.addSeparator() for column in COLLAPSABLE_COLUMNS: action = self.columnsMenu.addAction(column) action.setCheckable(True) action.toggled.connect(lambda show, col=column: self.showColumn(col, show)) self.showColumnActions[column] = action self.contextMenu.addSeparator() self.actionClearPlots = self.contextMenu.addAction("Clear Plots", self.clearPlots) # file menu self.ui.actionExit.triggered.connect(QApplication.closeAllWindows) self.ui.actionLoadStartValues.triggered.connect(self.loadStartValues) self.ui.actionReload.triggered.connect(lambda: self.load(self.filename)) self.ui.actionSaveChanges.triggered.connect(self.saveChanges) # tools menu self.ui.actionValidateFMU.triggered.connect(self.validateFMU) self.ui.actionCompileDarwinBinary.triggered.connect(lambda: self.compilePlatformBinary('darwin64')) self.ui.actionCompileLinuxBinary.triggered.connect(lambda: self.compilePlatformBinary('linux64')) self.ui.actionCompileWin32Binary.triggered.connect(lambda: self.compilePlatformBinary('win32')) self.ui.actionCompileWin64Binary.triggered.connect(lambda: self.compilePlatformBinary('win64')) self.ui.actionCreateJupyterNotebook.triggered.connect(self.createJupyterNotebook) self.ui.actionCreateCMakeProject.triggered.connect(self.createCMakeProject) self.ui.actionAddWindows32Remoting.triggered.connect(lambda: self.addRemotingBinaries('win64', 'win32')) self.ui.actionAddLinux64Remoting.triggered.connect(lambda: self.addRemotingBinaries('linux64', 'win64')) self.ui.actionAddCoSimulationWrapper.triggered.connect(self.addCoSimulationWrapper) # help menu self.ui.actionOpenFMI1SpecCS.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://fmi-standard.org/assets/releases/FMI_for_CoSimulation_v1.0.1.pdf'))) self.ui.actionOpenFMI1SpecME.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://fmi-standard.org/assets/releases/FMI_for_ModelExchange_v1.0.1.pdf'))) self.ui.actionOpenFMI2Spec.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/modelica/fmi-standard/releases/download/v2.0.3/FMI-Specification-2.0.3.pdf'))) self.ui.actionOpenTestFMUs.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/modelica/fmi-cross-check/tree/master/fmus'))) self.ui.actionOpenWebsite.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/CATIA-Systems/FMPy'))) self.ui.actionShowReleaseNotes.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://fmpy.readthedocs.io/en/latest/changelog/'))) # filter menu self.filterMenu = QMenu() self.filterMenu.addAction(self.ui.actionFilterInputs) self.filterMenu.addAction(self.ui.actionFilterOutputs) self.filterMenu.addAction(self.ui.actionFilterParameters) self.filterMenu.addAction(self.ui.actionFilterCalculatedParameters) self.filterMenu.addAction(self.ui.actionFilterIndependentVariables) self.filterMenu.addAction(self.ui.actionFilterLocalVariables) self.ui.filterToolButton.setMenu(self.filterMenu) # status bar self.statusIconLabel = ClickableLabel(self) self.statusIconLabel.setStyleSheet("QLabel { margin-left: 5px; }") self.statusIconLabel.clicked.connect(lambda: self.setCurrentPage(self.ui.logPage)) self.ui.statusBar.addPermanentWidget(self.statusIconLabel) self.statusTextLabel = ClickableLabel(self) self.statusTextLabel.setMinimumWidth(10) self.statusTextLabel.clicked.connect(lambda: self.setCurrentPage(self.ui.logPage)) self.ui.statusBar.addPermanentWidget(self.statusTextLabel) self.ui.statusBar.addPermanentWidget(QWidget(self), 1) # spacer self.simulationProgressBar = QProgressBar(self) self.simulationProgressBar.setFixedHeight(18) self.ui.statusBar.addPermanentWidget(self.simulationProgressBar) self.simulationProgressBar.setVisible(False) # connect signals and slots self.ui.actionNewWindow.triggered.connect(self.newWindow) self.ui.openButton.clicked.connect(self.open) self.ui.actionOpen.triggered.connect(self.open) self.ui.actionSaveResult.triggered.connect(self.saveResult) self.ui.actionSavePlottedResult.triggered.connect(lambda: self.saveResult(plotted=True)) self.ui.actionSimulate.triggered.connect(self.startSimulation) self.ui.actionSettings.triggered.connect(lambda: self.setCurrentPage(self.ui.settingsPage)) self.ui.actionShowLog.triggered.connect(lambda: self.setCurrentPage(self.ui.logPage)) self.ui.actionShowResults.triggered.connect(lambda: self.setCurrentPage(self.ui.resultPage)) self.fmiTypeComboBox.currentTextChanged.connect(self.updateSimulationSettings) self.ui.solverComboBox.currentTextChanged.connect(self.updateSimulationSettings) self.variableSelected.connect(self.updatePlotLayout) self.variableDeselected.connect(self.updatePlotLayout) self.tableModel.variableSelected.connect(self.selectVariable) self.tableModel.variableDeselected.connect(self.deselectVariable) self.treeModel.variableSelected.connect(self.selectVariable) self.treeModel.variableDeselected.connect(self.deselectVariable) self.ui.filterLineEdit.textChanged.connect(self.treeFilterModel.setFilterFixedString) self.ui.filterLineEdit.textChanged.connect(self.tableFilterModel.setFilterFixedString) self.ui.filterToolButton.toggled.connect(self.treeFilterModel.setFilterByCausality) self.ui.filterToolButton.toggled.connect(self.tableFilterModel.setFilterByCausality) self.log.currentMessageChanged.connect(self.setStatusMessage) self.ui.selectInputButton.clicked.connect(self.selectInputFile) self.ui.actionShowAboutDialog.triggered.connect(self.showAboutDialog) if os.name == 'nt': self.ui.actionCreateDesktopShortcut.triggered.connect(self.createDesktopShortcut) self.ui.actionAddFileAssociation.triggered.connect(self.addFileAssociation) else: self.ui.actionCreateDesktopShortcut.setEnabled(False) self.ui.actionAddFileAssociation.setEnabled(False) self.ui.tableViewToolButton.toggled.connect(lambda show: self.ui.variablesStackedWidget.setCurrentWidget(self.ui.tablePage if show else self.ui.treePage)) for model in [self.treeFilterModel, self.tableFilterModel]: self.ui.actionFilterInputs.triggered.connect(model.setFilterInputs) self.ui.actionFilterOutputs.triggered.connect(model.setFilterOutputs) self.ui.actionFilterParameters.triggered.connect(model.setFilterParameters) self.ui.actionFilterCalculatedParameters.triggered.connect(model.setFilterCalculatedParameters) self.ui.actionFilterIndependentVariables.triggered.connect(model.setFilterIndependentVariables) self.ui.actionFilterLocalVariables.triggered.connect(model.setFilterLocalVariables) self.ui.treeView.customContextMenuRequested.connect(self.showContextMenu) self.ui.tableView.customContextMenuRequested.connect(self.showContextMenu) def newWindow(self): window = MainWindow() window.show() def show(self): super(MainWindow, self).show() self.move(self.frameGeometry().topLeft() + self.windowOffset) self.windowOffset += QPoint(20, 20) def showContextMenu(self, point): from .TableDialog import TableDialog if self.ui.variablesStackedWidget.currentWidget() == self.ui.treePage: currentView = self.ui.treeView else: currentView = self.ui.tableView self.actionExpandAll.setEnabled(currentView == self.ui.treeView) self.actionCollapseAll.setEnabled(currentView == self.ui.treeView) selected = self.getSelectedVariables() self.actionEditTable.setEnabled(len(selected) == 1 and TableDialog.canEdit(selected[0])) can_copy = len(selected) > 0 self.actionCopyVariableName.setEnabled(can_copy) self.actionCopyValueReference.setEnabled(can_copy) self.contextMenu.exec_(currentView.mapToGlobal(point)) def load(self, filename): import zipfile if not self.isVisible(): self.show() try: self.modelDescription = md = read_model_description(filename) except Exception as e: QMessageBox.warning(self, "Failed to load FMU", "Failed to load %s. %s" % (filename, e)) return # show model.png try: pixmap = QPixmap() # load the model.png with zipfile.ZipFile(filename, 'r') as zf: pixmap.loadFromData(zf.read('model.png'), format='PNG') # show the unscaled version in tooltip buffer = QBuffer() buffer.open(QIODevice.WriteOnly) pixmap.save(buffer, "PNG", quality=100) image = bytes(buffer.data().toBase64()).decode() html = '<img src="data:image/png;base64,{}">'.format(image) self.ui.modelImageLabel.setToolTip(html) # show a scaled preview in "Model Info" pixmap = pixmap.scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.ui.modelImageLabel.setPixmap(pixmap) except: self.ui.modelImageLabel.setPixmap(QPixmap()) self.ui.modelImageLabel.setToolTip(None) self.filename = filename platforms = supported_platforms(self.filename) self.variables.clear() self.selectedVariables.clear() self.startValues.clear() for v in md.modelVariables: self.variables[v.name] = v if v.causality == 'output' and not v.dimensions: self.selectedVariables.add(v) fmi_types = [] if md.coSimulation: fmi_types.append('Co-Simulation') if md.modelExchange: fmi_types.append('Model Exchange') experiment = md.defaultExperiment # toolbar if experiment is not None and experiment.stopTime is not None: self.stopTimeLineEdit.setText(str(experiment.stopTime)) # actions self.ui.actionValidateFMU.setEnabled(True) can_compile = md.fmiVersion == '2.0' and 'c-code' in platforms self.ui.actionCompileDarwinBinary.setEnabled(can_compile and fmpy.system == 'darwin') self.ui.actionCompileLinuxBinary.setEnabled(can_compile and fmpy.system in ['linux', 'windows']) self.ui.actionCompileWin32Binary.setEnabled(can_compile and fmpy.system == 'windows') self.ui.actionCompileWin64Binary.setEnabled(can_compile and fmpy.system == 'windows') self.ui.actionCreateCMakeProject.setEnabled(can_compile) self.ui.actionCreateJupyterNotebook.setEnabled(True) self.ui.actionAddWindows32Remoting.setEnabled(md.fmiVersion == '2.0' and 'win32' in platforms and 'win64' not in platforms) self.ui.actionAddLinux64Remoting.setEnabled(md.fmiVersion == '2.0' and 'win64' in platforms and 'linux64' not in platforms) can_add_cswrapper = md.fmiVersion == '2.0' and md.coSimulation is None and md.modelExchange is not None self.ui.actionAddCoSimulationWrapper.setEnabled(can_add_cswrapper) # variables view self.treeModel.setModelDescription(md) self.tableModel.setModelDescription(md) self.treeFilterModel.invalidate() self.tableFilterModel.invalidate() self.ui.treeView.reset() self.ui.tableView.reset() # settings page self.ui.fmiVersionLabel.setText(md.fmiVersion) self.ui.fmiTypeLabel.setText(', '.join(fmi_types)) self.ui.platformsLabel.setText(', '.join(platforms)) self.ui.modelNameLabel.setText(md.modelName) self.ui.descriptionLabel.setText(md.description) self.ui.numberOfContinuousStatesLabel.setText(str(md.numberOfContinuousStates)) self.ui.numberOfEventIndicatorsLabel.setText(str(md.numberOfEventIndicators)) self.ui.numberOfVariablesLabel.setText(str(len(md.modelVariables))) self.ui.generationToolLabel.setText(md.generationTool) self.ui.generationDateAndTimeLabel.setText(md.generationDateAndTime) # relative tolerance if experiment is not None and experiment.tolerance is not None: relative_tolerance = experiment.tolerance else: relative_tolerance = 1e-6 self.ui.relativeToleranceLineEdit.setText(str(relative_tolerance)) # output interval if experiment is not None and experiment.stepSize is not None: output_interval = float(experiment.stepSize) while output_interval > 1000: output_interval *= 0.5 else: output_interval = float(self.stopTimeLineEdit.text()) / 500 self.ui.outputIntervalLineEdit.setText(str(output_interval)) self.fmiTypeComboBox.clear() self.fmiTypeComboBox.addItems(fmi_types) self.updateSimulationSettings() self.setCurrentPage(self.ui.settingsPage) self.ui.dockWidget.show() self.ui.actionReload.setEnabled(True) self.ui.actionSettings.setEnabled(True) self.ui.actionShowLog.setEnabled(True) self.ui.actionShowResults.setEnabled(False) can_sim, _ = can_simulate(platforms) self.ui.actionLoadStartValues.setEnabled(can_sim) self.ui.actionSimulate.setEnabled(can_sim) self.stopTimeLineEdit.setEnabled(can_sim) self.fmiTypeComboBox.setEnabled(can_sim and len(fmi_types) > 1) self.ui.settingsGroupBox.setEnabled(can_sim) settings = QSettings() recent_files = settings.value("recentFiles", defaultValue=[]) recent_files = self.removeDuplicates([filename] + recent_files) # save the 10 most recent files settings.setValue('recentFiles', recent_files[:10]) self.setWindowTitle("%s - FMPy" % os.path.normpath(filename)) self.createGraphics() def open(self): start_dir = QDir.homePath() settings = QSettings() recent_files = settings.value("recentFiles", defaultValue=[]) for filename in recent_files: dirname = os.path.dirname(filename) if os.path.isdir(dirname): start_dir = dirname break filename, _ = QFileDialog.getOpenFileName(parent=self, caption="Open File", directory=start_dir, filter="FMUs (*.fmu);;All Files (*.*)") if filename: self.load(filename) def setCurrentPage(self, widget): # block the signals during the update self.ui.actionSettings.blockSignals(True) self.ui.actionShowLog.blockSignals(True) self.ui.actionShowResults.blockSignals(True) self.ui.stackedWidget.setCurrentWidget(widget) # toggle the actions self.ui.actionSettings.setChecked(widget == self.ui.settingsPage) self.ui.actionShowLog.setChecked(widget == self.ui.logPage) self.ui.actionShowResults.setChecked(widget == self.ui.resultPage) # un-block the signals during the update self.ui.actionSettings.blockSignals(False) self.ui.actionShowLog.blockSignals(False) self.ui.actionShowResults.blockSignals(False) def selectInputFile(self): start_dir = os.path.dirname(self.filename) filename, _ = QFileDialog.getOpenFileName(parent=self, caption="Select Input File", directory=start_dir, filter="FMUs (*.csv);;All Files (*.*)") if filename: self.ui.inputFilenameLineEdit.setText(filename) def createInputFile(self): input_variables = [] for variable in self.modelDescription.modelVariables: if variable.causality == 'input': input_variables.append(variable) if len(input_variables) == 0: QMessageBox.warning(self, "Cannot create input file", "The input file cannot be created because the model has no input variables") return filename, _ = os.path.splitext(self.filename) filename, _ = QFileDialog.getSaveFileName(parent=self, caption="Save Input File", directory=filename + '_in.csv', filter="Comma Separated Values (*.csv);;All Files (*.*)") if not filename: return with open(filename, 'w') as f: # column names f.write('"time"') for variable in input_variables: f.write(',"%s"' % variable.name) f.write('\n') # example data f.write(','.join(['0'] * (len(input_variables) + 1)) + '\n') self.ui.inputFilenameLineEdit.setText(filename) def showInputFileInExplorer(self): filename = self.ui.inputFilenameLineEdit.text() if not os.path.isfile(filename): QMessageBox.warning(self, "Cannot show input file", "The input file does not exist") return QDesktopServices.openUrl(QUrl.fromLocalFile(os.path.dirname(filename))) def openInputFile(self): filename = self.ui.inputFilenameLineEdit.text() if not os.path.isfile(filename): QMessageBox.warning(self, "Cannot open input file", "The input file does not exist") return QDesktopServices.openUrl(QUrl.fromLocalFile(filename)) def updateSimulationSettings(self): if self.fmiTypeComboBox.currentText() == 'Co-Simulation': self.ui.solverComboBox.setEnabled(False) self.ui.stepSizeLineEdit.setEnabled(False) self.ui.relativeToleranceLineEdit.setEnabled(True) else: self.ui.solverComboBox.setEnabled(True) fixed_step = self.ui.solverComboBox.currentText() == 'Fixed-step' self.ui.stepSizeLineEdit.setEnabled(fixed_step) self.ui.relativeToleranceLineEdit.setEnabled(not fixed_step) def selectVariable(self, variable): self.selectedVariables.add(variable) self.variableSelected.emit(variable) def deselectVariable(self, variable): self.selectedVariables.remove(variable) self.variableDeselected.emit(variable) def startSimulation(self): from fmpy.gui.simulation import SimulationThread try: stop_time = float(self.stopTimeLineEdit.text()) step_size = float(self.ui.stepSizeLineEdit.text()) relative_tolerance = float(self.ui.relativeToleranceLineEdit.text()) if self.ui.outputIntervalRadioButton.isChecked(): output_interval = float(self.ui.outputIntervalLineEdit.text()) else: max_samples = float(self.ui.maxSamplesLineEdit.text()) output_interval = stop_time / max_samples except Exception as ex: self.log.log('error', "Failed to start simulation: %s" % ex) self.ui.stackedWidget.setCurrentWidget(self.ui.logPage) return step_size = min(step_size, output_interval) if self.ui.solverComboBox.currentText() == 'Fixed-step': solver = 'Euler' else: solver = 'CVode' if self.ui.inputCheckBox.isChecked(): input_variables = [] for variable in self.modelDescription.modelVariables: if variable.causality == 'input': input_variables.append(variable.name) try: from fmpy.util import read_csv filename = self.ui.inputFilenameLineEdit.text() input = read_csv(filename, variable_names=input_variables) except Exception as e: self.log.log('error', "Failed to load input from '%s'. %s" % (filename, e)) return else: input = None output = [] for variable in self.modelDescription.modelVariables: output.append(variable.name) fmi_type = 'CoSimulation' if self.fmiTypeComboBox.currentText() == 'Co-Simulation' else 'ModelExchange' self.simulationThread = SimulationThread(filename=self.filename, fmiType=fmi_type, stopTime=stop_time, solver=solver, stepSize=step_size, relativeTolerance=relative_tolerance, outputInterval=output_interval, startValues=self.startValues, applyDefaultStartValues=self.ui.applyDefaultStartValuesCheckBox.isChecked(), input=input, output=output, debugLogging=self.ui.debugLoggingCheckBox.isChecked(), fmiLogging=self.ui.logFMICallsCheckBox.isChecked()) self.ui.actionSimulate.setIcon(QIcon(':/icons/stop.png')) self.ui.actionSimulate.setToolTip("Stop simulation") self.ui.actionSimulate.triggered.disconnect(self.startSimulation) self.ui.actionSimulate.triggered.connect(self.simulationThread.stop) self.simulationProgressBar.setVisible(True) self.simulationThread.messageChanged.connect(self.log.log) self.simulationThread.progressChanged.connect(self.simulationProgressBar.setValue) self.simulationThread.finished.connect(self.simulationFinished) if self.ui.clearLogOnStartButton.isChecked(): self.log.clear() self.setCurrentPage(self.ui.resultPage) self.simulationThread.start() self.plotUpdateTimer.start(100) self.updatePlotLayout() def simulationFinished(self): # update UI self.ui.actionSimulate.triggered.disconnect(self.simulationThread.stop) self.ui.actionSimulate.triggered.connect(self.startSimulation) self.ui.actionSimulate.setIcon(QIcon(':/icons/play.png')) self.ui.actionSimulate.setToolTip("Start simulation") self.plotUpdateTimer.stop() self.simulationProgressBar.setVisible(False) self.ui.actionShowResults.setEnabled(True) self.ui.actionSettings.setEnabled(True) self.setCurrentPage(self.ui.resultPage) self.updatePlotLayout() if self.result is None: self.setCurrentPage(self.ui.logPage) else: self.ui.actionSaveResult.setEnabled(True) self.ui.actionSavePlottedResult.setEnabled(True) self.result = self.simulationThread.result self.simulationThread = None self.updatePlotData() def updatePlotData(self): import numpy as np if self.simulationThread is not None and len(self.simulationThread.rows) > 1: # get results from current simulation self.result = np.array(self.simulationThread.rows, dtype=np.dtype(self.simulationThread.cols)) if self.result is None: return # no results available yet time = self.result['time'] for variable, curve in self.curves: if variable.name not in self.result.dtype.names: continue y = self.result[variable.name] if variable.type == 'Real': curve.setData(x=time, y=y) else: curve.setData(x=np.repeat(time, 2)[1:], y=np.repeat(y, 2)[:-1]) def updatePlotLayout(self): self.ui.plotWidget.clear() self.curves[:] = [] if self.simulationThread is not None: stop_time = self.simulationThread.stopTime elif self.result is not None: stop_time = self.result['time'][-1] else: stop_time = 1.0 pen = (0, 0, 255) for variable in self.selectedVariables: self.ui.plotWidget.nextRow() plot = self.ui.plotWidget.addPlot() if variable.type == 'Real': curve = plot.plot(pen=pen) else: if variable.type == 'Boolean': plot.setYRange(0, 1, padding=0.2) plot.getAxis('left').setTicks([[(0, 'false'), (1, 'true')], []]) curve = plot.plot(pen=pen, fillLevel=0, fillBrush=(0, 0, 255, 50), antialias=False) else: curve = plot.plot(pen=pen, antialias=False) plot.setXRange(0, stop_time, padding=0.05) plot.setLabel('left', variable.name) plot.showGrid(x=True, y=True, alpha=0.25) # hide the auto-scale button and disable context menu and mouse interaction plot.hideButtons() plot.setMouseEnabled(False, False) plot.setMenuEnabled(False) self.curves.append((variable, curve)) self.updatePlotData() def showColumn(self, name, show): if name in self.showColumnActions: self.showColumnActions[name].setChecked(show) i = VariablesModel.COLUMN_NAMES.index(name) self.ui.treeView.setColumnHidden(i, not show) self.ui.tableView.setColumnHidden(i, not show) def showAllColumns(self): for name in COLLAPSABLE_COLUMNS: self.showColumn(name, True) def hideAllColumns(self): for name in COLLAPSABLE_COLUMNS: self.showColumn(name, False) def setStatusMessage(self, level, text): if level in ['debug', 'info', 'warning', 'error']: self.statusIconLabel.setPixmap(QPixmap(':/icons/%s-16x16.png' % level)) else: self.statusIconLabel.setPixmap(QPixmap()) self.statusTextLabel.setText(text) def dragEnterEvent(self, event): for url in event.mimeData().urls(): if not url.isLocalFile(): return event.acceptProposedAction() def dropEvent(self, event): urls = event.mimeData().urls() for url in urls: if url == urls[0]: window = self else: window = MainWindow() window.load(url.toLocalFile()) def saveResult(self, plotted=False): filename, _ = os.path.splitext(self.filename) filename, _ = QFileDialog.getSaveFileName(parent=self, caption="Save Result", directory=filename + '_out.csv', filter="Comma Separated Values (*.csv);;All Files (*.*)") if filename: from ..util import write_csv if plotted: columns = [variable.name for variable in self.selectedVariables] else: columns = None try: write_csv(filename=filename, result=self.result, columns=columns) except Exception as e: QMessageBox.critical(self, "Failed to write result", '"Failed to write "%s". %s' % (filename, e)) def createDesktopShortcut(self): import os from win32com.client import Dispatch import sys env = os.environ.get('CONDA_DEFAULT_ENV') if env is None: target_path = sys.executable root, ext = os.path.splitext(target_path) pythonw = root + 'w' + ext if os.path.isfile(pythonw): target_path = pythonw arguments = '-m fmpy.gui' else: for path in os.environ["PATH"].split(os.pathsep): activate = os.path.join(path, 'activate.bat') if os.path.isfile(activate): break target_path = r'%windir%\System32\cmd.exe' arguments = '/C ""%s" %s && python -m fmpy.gui"' % (activate, env) file_path = os.path.dirname(__file__) icon = os.path.join(file_path, 'icons', 'app_icon.ico') desktop_locations = QStandardPaths.standardLocations(QStandardPaths.DesktopLocation) shortcut_path = os.path.join(desktop_locations[0], "FMPy GUI.lnk") shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(shortcut_path) shortcut.Targetpath = target_path shortcut.Arguments = arguments # shortcut.WorkingDirectory = ... shortcut.IconLocation = icon shortcut.save() def showAboutDialog(self): dialog = AboutDialog(self) dialog.show() @staticmethod def removeDuplicates(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] def validateFMU(self): from ..validation import validate_fmu problems = validate_fmu(self.filename) if problems: button = QMessageBox.question(self, "Validation failed", "%d problems have been found. Save validation messages?" % len(problems)) if button == QMessageBox.Yes: filename, _ = os.path.splitext(self.filename) filename, _ = QFileDialog.getSaveFileName(parent=self, caption="Save validation messages", directory=filename + '_validation.txt', filter="Text Files (*.txt);;All Files (*.*)") if filename: with open(filename, 'w') as f: f.writelines(problems) else: QMessageBox.information(self, "Validation successful", "No problems have been found.") def addFileAssociation(self): try: from winreg import HKEY_CURRENT_USER, KEY_WRITE, REG_SZ, OpenKey, CreateKey, SetValueEx, CloseKey env = os.environ.get('CONDA_DEFAULT_ENV_') if env is None: python = sys.executable root, ext = os.path.splitext(python) pythonw = root + 'w' + ext if os.path.isfile(pythonw): python = pythonw target = '"%s" -m fmpy.gui "%%1"' % python else: # activate the conda environment for path in os.environ["PATH"].split(os.pathsep): activate = os.path.join(path, 'activate.bat') if os.path.isfile(activate): break windir = os.environ['WINDIR'] cmd = os.path.join(windir, 'System32', 'cmd.exe') target = r'%s /C ""%s" %s && python -m fmpy.gui %%1"' % (cmd, activate, env) key_path = r'Software\Classes\fmpy.gui\shell\open\command' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, target) CloseKey(key) key_path = r'SOFTWARE\Classes\.fmu' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, 'fmpy.gui') CloseKey(key) QMessageBox.information(self, "File association added", "The file association for *.fmu has been added") except Exception as e: QMessageBox.critical(self, "File association failed", "The file association for *.fmu could not be added. %s" % e) def copyValueReference(self): text = '\n'.join([str(v.valueReference) for v in self.getSelectedVariables()]) QApplication.clipboard().setText(text) def copyVariableName(self): text = '\n'.join([str(v.name) for v in self.getSelectedVariables()]) QApplication.clipboard().setText(text) def getSelectedVariables(self): variables = [] if self.ui.variablesStackedWidget.currentWidget() == self.ui.treePage: for index in self.ui.treeView.selectionModel().selectedRows(): sourceIndex = self.treeFilterModel.mapToSource(index) treeItem = sourceIndex.internalPointer() if treeItem.variable is not None: variables.append(treeItem.variable) else: for index in self.ui.tableView.selectionModel().selectedRows(): sourceIndex = self.tableFilterModel.mapToSource(index) variable = sourceIndex.internalPointer() variables.append(variable) return variables def clearPlots(self): self.selectedVariables.clear() self.updatePlotLayout() def createGraphics(self): def variableColor(variable): if variable.type.startswith(('Float', 'Real')): return QColor.fromRgb(26, 77, 179) elif variable.type.startswith(('Enumeration', 'Int', 'UInt')): return QColor.fromRgb(179, 77, 26) elif variable.type == 'Boolean': return QColor.fromRgb(255, 0, 255) elif variable.type == 'String': return QColor.fromRgb(26, 114, 16) elif variable.type == 'Binary': return QColor.fromRgb(81, 81, 81) else: return QColor.fromRgb(0, 0, 0) inputVariables = [] outputVariables = [] maxInputLabelWidth = 0 maxOutputLabelWidth = 0 textItem = QGraphicsTextItem() fontMetrics = QFontMetricsF(textItem.font()) for variable in self.modelDescription.modelVariables: if variable.causality == 'input': inputVariables.append(variable) elif variable.causality == 'output': outputVariables.append(variable) for variable in inputVariables: maxInputLabelWidth = max(maxInputLabelWidth, fontMetrics.width(variable.name)) for variable in outputVariables: maxOutputLabelWidth = max(maxOutputLabelWidth, fontMetrics.width(variable.name)) from math import floor scene = QGraphicsScene() self.ui.graphicsView.setScene(scene) group = QGraphicsItemGroup() scene.addItem(group) group.setPos(200.5, -50.5) lh = 15 # line height w = max(150., maxInputLabelWidth + maxOutputLabelWidth + 20) h = max(50., 10 + lh * max(len(inputVariables), len(outputVariables))) block = QGraphicsRectItem(0, 0, w, h, group) block.setPen(QColor.fromRgb(0, 0, 0)) pen = QPen() pen.setWidthF(1) font = QFont() font.setPixelSize(10) # inputs y = floor((h - len(inputVariables) * lh) / 2 - 2) for variable in inputVariables: text = QGraphicsTextItem(variable.name, group) text.setDefaultTextColor(QColor.fromRgb(0, 0, 0)) text.setFont(font) text.setX(3) text.setY(y) polygon = QPolygonF([QPointF(-8, y + 7.5), QPointF(-1, y + 11), QPointF(-8, y + 14.5)]) path = QPainterPath() path.addPolygon(polygon) path.closeSubpath() contour = QGraphicsPathItem(path, group) contour.setPen(QPen(Qt.NoPen)) contour.setBrush(variableColor(variable)) pen = QPen() pen.setColor(variableColor(variable)) pen.setJoinStyle(Qt.MiterJoin) contour.setPen(pen) y += lh # outputs y = floor((h - len(outputVariables) * lh) / 2 - 2) for variable in outputVariables: text = QGraphicsTextItem(variable.name, group) text.setDefaultTextColor(QColor.fromRgb(0, 0, 0)) text.setFont(font) text.setX(w - 3 - text.boundingRect().width()) text.setY(y) polygon = QPolygonF([QPointF(w + 1, y + 7.5), QPointF(w + 8, y + 11), QPointF(w + 1, y + 14.5)]) path = QPainterPath() path.addPolygon(polygon) path.closeSubpath() contour = QGraphicsPathItem(path, group) contour.setPen(QPen(Qt.NoPen)) contour.setBrush(variableColor(variable)) pen = QPen() pen.setColor(variableColor(variable)) pen.setJoinStyle(Qt.MiterJoin) contour.setPen(pen) y += lh def saveChanges(self): from ..util import change_fmu output_file, _ = QFileDialog.getSaveFileName(parent=self, caption='Save Changed FMU', directory=self.filename, filter='FMUs (*.fmu)') if output_file: change_fmu(input_file=self.filename, output_file=output_file, start_values=self.startValues) def loadStartValues(self): from ..util import get_start_values start_values = get_start_values(self.filename) self.startValues.update(start_values) self.ui.treeView.reset() self.ui.tableView.reset() def editTable(self): from .TableDialog import TableDialog variables = self.getSelectedVariables() if len(variables) == 1: start_values = self.startValues.copy() dialog = TableDialog(modelVariables=self.modelDescription.modelVariables, variable=variables[0], startValues=start_values) if dialog.exec_() == QDialog.Accepted: self.startValues.clear() self.startValues.update(start_values) def compilePlatformBinary(self, target_platform): from ..util import compile_platform_binary platforms = supported_platforms(self.filename) if target_platform in platforms: button = QMessageBox.question(self, "Platform binary already exists", f'The FMU already contains a binary for the platform "{target_platform}".' ' Do you want to compile and overwrite the existing binary?') if button == QMessageBox.No: return try: compile_platform_binary(self.filename, target_platform=target_platform) except Exception as e: QMessageBox.critical(self, "Failed to compile platform binaries", str(e)) return self.load(self.filename) def createJupyterNotebook(self): from fmpy.util import create_jupyter_notebook filename, ext = os.path.splitext(self.filename) filename, _ = QFileDialog.getSaveFileName( parent=self, directory=filename + '.ipynb', filter='Jupyter Notebooks (*.ipynb);;All Files (*)' ) if filename: try: create_jupyter_notebook(self.filename, filename) except Exception as e: QMessageBox.critical(self, "Failed to create Jupyter Notebook", str(e)) return if QMessageBox.question(self, "Open Jupyter Notebook?", f"Start Jupyter and open {filename}?") == QMessageBox.Yes: from subprocess import run, CREATE_NEW_CONSOLE try: run(['jupyter', 'notebook', filename], creationflags=CREATE_NEW_CONSOLE) except Exception as e: QMessageBox.critical(self, "Failed to start Jupyter", str(e)) def createCMakeProject(self): from fmpy.util import create_cmake_project project_dir = QFileDialog.getExistingDirectory( parent=self, caption='Select CMake Project Folder', directory=os.path.dirname(self.filename)) if project_dir: create_cmake_project(self.filename, project_dir) def addRemotingBinaries(self, host_platform, remote_platform): from ..util import add_remoting try: add_remoting(self.filename, host_platform, remote_platform) except Exception as e: QMessageBox.warning(self, "Failed to add Remoting Binaries", f"Failed to add remoting binaries to {self.filename}. {e}") self.load(self.filename) def addCoSimulationWrapper(self): from ..cswrapper import add_cswrapper try: add_cswrapper(self.filename) except Exception as e: QMessageBox.warning(self, "Failed to add Co-Simulation Wrapper", "Failed to add Co-Simulation Wrapper %s. %s" % (self.filename, e)) self.load(self.filename)
true
true
1c441c536b6f0ba2ae48a33a2e97137a6527f44f
17,494
py
Python
lib/python2.7/site-packages/matplotlib/tests/test_dates.py
wfehrnstrom/harmonize
e5661d24b2021739e8ac4bf1d3a530eda4e155b3
[ "MIT" ]
1
2017-12-05T15:35:47.000Z
2017-12-05T15:35:47.000Z
lib/python2.7/site-packages/matplotlib/tests/test_dates.py
wfehrnstrom/harmonize
e5661d24b2021739e8ac4bf1d3a530eda4e155b3
[ "MIT" ]
10
2017-07-13T00:24:03.000Z
2017-07-17T07:39:03.000Z
lib/python2.7/site-packages/matplotlib/tests/test_dates.py
wfehrnstrom/harmonize
e5661d24b2021739e8ac4bf1d3a530eda4e155b3
[ "MIT" ]
7
2017-08-01T04:02:07.000Z
2018-10-06T21:07:20.000Z
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import map import datetime import warnings import tempfile import dateutil import pytz try: # mock in python 3.3+ from unittest import mock except ImportError: import mock from nose.tools import assert_raises, assert_equal from nose.plugins.skip import SkipTest from matplotlib.testing.decorators import image_comparison, cleanup import matplotlib.pyplot as plt import matplotlib.dates as mdates @image_comparison(baseline_images=['date_empty'], extensions=['png']) def test_date_empty(): # make sure mpl does the right thing when told to plot dates even # if no date data has been presented, cf # http://sourceforge.net/tracker/?func=detail&aid=2850075&group_id=80706&atid=560720 fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.xaxis_date() @image_comparison(baseline_images=['date_axhspan'], extensions=['png']) def test_date_axhspan(): # test ax hspan with date inputs t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhspan(t0, tf, facecolor="blue", alpha=0.25) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.subplots_adjust(left=0.25) @image_comparison(baseline_images=['date_axvspan'], extensions=['png']) def test_date_axvspan(): # test ax hspan with date inputs t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2010, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axvspan(t0, tf, facecolor="blue", alpha=0.25) ax.set_xlim(t0 - datetime.timedelta(days=720), tf + datetime.timedelta(days=720)) fig.autofmt_xdate() @image_comparison(baseline_images=['date_axhline'], extensions=['png']) def test_date_axhline(): # test ax hline with date inputs t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 31) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhline(t0, color="blue", lw=3) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.subplots_adjust(left=0.25) @image_comparison(baseline_images=['date_axvline'], extensions=['png']) def test_date_axvline(): # test ax hline with date inputs t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2000, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axvline(t0, color="red", lw=3) ax.set_xlim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.autofmt_xdate() @cleanup def test_too_many_date_ticks(): # Attempt to test SF 2715172, see # https://sourceforge.net/tracker/?func=detail&aid=2715172&group_id=80706&atid=560720 # setting equal datetimes triggers and expander call in # transforms.nonsingular which results in too many ticks in the # DayLocator. This should trigger a Locator.MAXTICKS RuntimeError warnings.filterwarnings( 'ignore', 'Attempting to set identical left==right results\\nin singular ' 'transformations; automatically expanding.\\nleft=\d*\.\d*, ' 'right=\d*\.\d*', UserWarning, module='matplotlib.axes') t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2000, 1, 20) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim((t0, tf), auto=True) ax.plot([], []) ax.xaxis.set_major_locator(mdates.DayLocator()) assert_raises(RuntimeError, fig.savefig, 'junk.png') @image_comparison(baseline_images=['RRuleLocator_bounds'], extensions=['png']) def test_RRuleLocator(): import matplotlib.testing.jpl_units as units units.register() # This will cause the RRuleLocator to go out of bounds when it tries # to add padding to the limits, so we make sure it caps at the correct # boundary values. t0 = datetime.datetime(1000, 1, 1) tf = datetime.datetime(6000, 1, 1) fig = plt.figure() ax = plt.subplot(111) ax.set_autoscale_on(True) ax.plot([t0, tf], [0.0, 1.0], marker='o') rrule = mdates.rrulewrapper(dateutil.rrule.YEARLY, interval=500) locator = mdates.RRuleLocator(rrule) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator)) ax.autoscale_view() fig.autofmt_xdate() @image_comparison(baseline_images=['DateFormatter_fractionalSeconds'], extensions=['png']) def test_DateFormatter(): import matplotlib.testing.jpl_units as units units.register() # Lets make sure that DateFormatter will allow us to have tick marks # at intervals of fractional seconds. t0 = datetime.datetime(2001, 1, 1, 0, 0, 0) tf = datetime.datetime(2001, 1, 1, 0, 0, 1) fig = plt.figure() ax = plt.subplot(111) ax.set_autoscale_on(True) ax.plot([t0, tf], [0.0, 1.0], marker='o') # rrule = mpldates.rrulewrapper( dateutil.rrule.YEARLY, interval=500 ) # locator = mpldates.RRuleLocator( rrule ) # ax.xaxis.set_major_locator( locator ) # ax.xaxis.set_major_formatter( mpldates.AutoDateFormatter(locator) ) ax.autoscale_view() fig.autofmt_xdate() def test_date_formatter_strftime(): """ Tests that DateFormatter matches datetime.strftime, check microseconds for years before 1900 for bug #3179 as well as a few related issues for years before 1900. """ def test_strftime_fields(dt): """For datetime object dt, check DateFormatter fields""" # Note: the last couple of %%s are to check multiple %s are handled # properly; %% should get replaced by %. formatter = mdates.DateFormatter("%w %d %m %y %Y %H %I %M %S %%%f %%x") # Compute date fields without using datetime.strftime, # since datetime.strftime does not work before year 1900 formatted_date_str = ( "{weekday} {day:02d} {month:02d} {year:02d} {full_year:04d} " "{hour24:02d} {hour12:02d} {minute:02d} {second:02d} " "%{microsecond:06d} %x" .format( # weeknum=dt.isocalendar()[1], # %U/%W {weeknum:02d} # %w Sunday=0, weekday() Monday=0 weekday=str((dt.weekday() + 1) % 7), day=dt.day, month=dt.month, year=dt.year % 100, full_year=dt.year, hour24=dt.hour, hour12=((dt.hour-1) % 12) + 1, minute=dt.minute, second=dt.second, microsecond=dt.microsecond)) assert_equal(formatter.strftime(dt), formatted_date_str) try: # Test strftime("%x") with the current locale. import locale # Might not exist on some platforms, such as Windows locale_formatter = mdates.DateFormatter("%x") locale_d_fmt = locale.nl_langinfo(locale.D_FMT) expanded_formatter = mdates.DateFormatter(locale_d_fmt) assert_equal(locale_formatter.strftime(dt), expanded_formatter.strftime(dt)) except (ImportError, AttributeError): pass for year in range(1, 3000, 71): # Iterate through random set of years test_strftime_fields(datetime.datetime(year, 1, 1)) test_strftime_fields(datetime.datetime(year, 2, 3, 4, 5, 6, 12345)) def test_date_formatter_callable(): scale = -11 locator = mock.Mock(_get_unit=mock.Mock(return_value=scale)) callable_formatting_function = (lambda dates, _: [dt.strftime('%d-%m//%Y') for dt in dates]) formatter = mdates.AutoDateFormatter(locator) formatter.scaled[-10] = callable_formatting_function assert_equal(formatter([datetime.datetime(2014, 12, 25)]), ['25-12//2014']) def test_drange(): """ This test should check if drange works as expected, and if all the rounding errors are fixed """ start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC) end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC) delta = datetime.timedelta(hours=1) # We expect 24 values in drange(start, end, delta), because drange returns # dates from an half open interval [start, end) assert_equal(24, len(mdates.drange(start, end, delta))) # if end is a little bit later, we expect the range to contain one element # more end = end + datetime.timedelta(microseconds=1) assert_equal(25, len(mdates.drange(start, end, delta))) # reset end end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC) # and tst drange with "complicated" floats: # 4 hours = 1/6 day, this is an "dangerous" float delta = datetime.timedelta(hours=4) daterange = mdates.drange(start, end, delta) assert_equal(6, len(daterange)) assert_equal(mdates.num2date(daterange[-1]), end - delta) @cleanup def test_empty_date_with_year_formatter(): # exposes sf bug 2861426: # https://sourceforge.net/tracker/?func=detail&aid=2861426&group_id=80706&atid=560720 # update: I am no longer believe this is a bug, as I commented on # the tracker. The question is now: what to do with this test import matplotlib.dates as dates fig = plt.figure() ax = fig.add_subplot(111) yearFmt = dates.DateFormatter('%Y') ax.xaxis.set_major_formatter(yearFmt) with tempfile.TemporaryFile() as fh: assert_raises(ValueError, fig.savefig, fh) def test_auto_date_locator(): def _create_auto_date_locator(date1, date2): locator = mdates.AutoDateLocator() locator.create_dummy_axis() locator.set_view_interval(mdates.date2num(date1), mdates.date2num(date2)) return locator d1 = datetime.datetime(1990, 1, 1) results = ([datetime.timedelta(weeks=52 * 200), ['1990-01-01 00:00:00+00:00', '2010-01-01 00:00:00+00:00', '2030-01-01 00:00:00+00:00', '2050-01-01 00:00:00+00:00', '2070-01-01 00:00:00+00:00', '2090-01-01 00:00:00+00:00', '2110-01-01 00:00:00+00:00', '2130-01-01 00:00:00+00:00', '2150-01-01 00:00:00+00:00', '2170-01-01 00:00:00+00:00'] ], [datetime.timedelta(weeks=52), ['1990-01-01 00:00:00+00:00', '1990-02-01 00:00:00+00:00', '1990-03-01 00:00:00+00:00', '1990-04-01 00:00:00+00:00', '1990-05-01 00:00:00+00:00', '1990-06-01 00:00:00+00:00', '1990-07-01 00:00:00+00:00', '1990-08-01 00:00:00+00:00', '1990-09-01 00:00:00+00:00', '1990-10-01 00:00:00+00:00', '1990-11-01 00:00:00+00:00', '1990-12-01 00:00:00+00:00'] ], [datetime.timedelta(days=141), ['1990-01-05 00:00:00+00:00', '1990-01-26 00:00:00+00:00', '1990-02-16 00:00:00+00:00', '1990-03-09 00:00:00+00:00', '1990-03-30 00:00:00+00:00', '1990-04-20 00:00:00+00:00', '1990-05-11 00:00:00+00:00'] ], [datetime.timedelta(days=40), ['1990-01-03 00:00:00+00:00', '1990-01-10 00:00:00+00:00', '1990-01-17 00:00:00+00:00', '1990-01-24 00:00:00+00:00', '1990-01-31 00:00:00+00:00', '1990-02-07 00:00:00+00:00'] ], [datetime.timedelta(hours=40), ['1990-01-01 00:00:00+00:00', '1990-01-01 04:00:00+00:00', '1990-01-01 08:00:00+00:00', '1990-01-01 12:00:00+00:00', '1990-01-01 16:00:00+00:00', '1990-01-01 20:00:00+00:00', '1990-01-02 00:00:00+00:00', '1990-01-02 04:00:00+00:00', '1990-01-02 08:00:00+00:00', '1990-01-02 12:00:00+00:00', '1990-01-02 16:00:00+00:00'] ], [datetime.timedelta(minutes=20), ['1990-01-01 00:00:00+00:00', '1990-01-01 00:05:00+00:00', '1990-01-01 00:10:00+00:00', '1990-01-01 00:15:00+00:00', '1990-01-01 00:20:00+00:00'] ], [datetime.timedelta(seconds=40), ['1990-01-01 00:00:00+00:00', '1990-01-01 00:00:05+00:00', '1990-01-01 00:00:10+00:00', '1990-01-01 00:00:15+00:00', '1990-01-01 00:00:20+00:00', '1990-01-01 00:00:25+00:00', '1990-01-01 00:00:30+00:00', '1990-01-01 00:00:35+00:00', '1990-01-01 00:00:40+00:00'] ], [datetime.timedelta(microseconds=1500), ['1989-12-31 23:59:59.999507+00:00', '1990-01-01 00:00:00+00:00', '1990-01-01 00:00:00.000502+00:00', '1990-01-01 00:00:00.001005+00:00', '1990-01-01 00:00:00.001508+00:00'] ], ) for t_delta, expected in results: d2 = d1 + t_delta locator = _create_auto_date_locator(d1, d2) assert_equal(list(map(str, mdates.num2date(locator()))), expected) @image_comparison(baseline_images=['date_inverted_limit'], extensions=['png']) def test_date_inverted_limit(): # test ax hline with date inputs t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 31) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhline(t0, color="blue", lw=3) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) ax.invert_yaxis() fig.subplots_adjust(left=0.25) def _test_date2num_dst(date_range, tz_convert): # Timezones BRUSSELS = pytz.timezone('Europe/Brussels') UTC = pytz.UTC # Create a list of timezone-aware datetime objects in UTC # Interval is 0b0.0000011 days, to prevent float rounding issues dtstart = datetime.datetime(2014, 3, 30, 0, 0, tzinfo=UTC) interval = datetime.timedelta(minutes=33, seconds=45) interval_days = 0.0234375 # 2025 / 86400 seconds N = 8 dt_utc = date_range(start=dtstart, freq=interval, periods=N) dt_bxl = tz_convert(dt_utc, BRUSSELS) expected_ordinalf = [735322.0 + (i * interval_days) for i in range(N)] actual_ordinalf = list(mdates.date2num(dt_bxl)) assert_equal(actual_ordinalf, expected_ordinalf) def test_date2num_dst(): # Test for github issue #3896, but in date2num around DST transitions # with a timezone-aware pandas date_range object. class dt_tzaware(datetime.datetime): """ This bug specifically occurs because of the normalization behavior of pandas Timestamp objects, so in order to replicate it, we need a datetime-like object that applies timezone normalization after subtraction. """ def __sub__(self, other): r = super(dt_tzaware, self).__sub__(other) tzinfo = getattr(r, 'tzinfo', None) if tzinfo is not None: localizer = getattr(tzinfo, 'normalize', None) if localizer is not None: r = tzinfo.normalize(r) if isinstance(r, datetime.datetime): r = self.mk_tzaware(r) return r def __add__(self, other): return self.mk_tzaware(super(dt_tzaware, self).__add__(other)) def astimezone(self, tzinfo): dt = super(dt_tzaware, self).astimezone(tzinfo) return self.mk_tzaware(dt) @classmethod def mk_tzaware(cls, datetime_obj): kwargs = {} attrs = ('year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond', 'tzinfo') for attr in attrs: val = getattr(datetime_obj, attr, None) if val is not None: kwargs[attr] = val return cls(**kwargs) # Define a date_range function similar to pandas.date_range def date_range(start, freq, periods): dtstart = dt_tzaware.mk_tzaware(start) return [dtstart + (i * freq) for i in range(periods)] # Define a tz_convert function that converts a list to a new time zone. def tz_convert(dt_list, tzinfo): return [d.astimezone(tzinfo) for d in dt_list] _test_date2num_dst(date_range, tz_convert) def test_date2num_dst_pandas(): # Test for github issue #3896, but in date2num around DST transitions # with a timezone-aware pandas date_range object. try: import pandas as pd except ImportError: raise SkipTest('pandas not installed') def tz_convert(*args): return pd.DatetimeIndex.tz_convert(*args).astype(object) _test_date2num_dst(pd.date_range, tz_convert) def test_DayLocator(): assert_raises(ValueError, mdates.DayLocator, interval=-1) assert_raises(ValueError, mdates.DayLocator, interval=-1.5) assert_raises(ValueError, mdates.DayLocator, interval=0) assert_raises(ValueError, mdates.DayLocator, interval=1.3) mdates.DayLocator(interval=1.0) def test_tz_utc(): dt = datetime.datetime(1970, 1, 1, tzinfo=mdates.UTC) dt.tzname() if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
36.752101
89
0.613124
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import map import datetime import warnings import tempfile import dateutil import pytz try: from unittest import mock except ImportError: import mock from nose.tools import assert_raises, assert_equal from nose.plugins.skip import SkipTest from matplotlib.testing.decorators import image_comparison, cleanup import matplotlib.pyplot as plt import matplotlib.dates as mdates @image_comparison(baseline_images=['date_empty'], extensions=['png']) def test_date_empty(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.xaxis_date() @image_comparison(baseline_images=['date_axhspan'], extensions=['png']) def test_date_axhspan(): t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhspan(t0, tf, facecolor="blue", alpha=0.25) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.subplots_adjust(left=0.25) @image_comparison(baseline_images=['date_axvspan'], extensions=['png']) def test_date_axvspan(): t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2010, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axvspan(t0, tf, facecolor="blue", alpha=0.25) ax.set_xlim(t0 - datetime.timedelta(days=720), tf + datetime.timedelta(days=720)) fig.autofmt_xdate() @image_comparison(baseline_images=['date_axhline'], extensions=['png']) def test_date_axhline(): t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 31) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhline(t0, color="blue", lw=3) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.subplots_adjust(left=0.25) @image_comparison(baseline_images=['date_axvline'], extensions=['png']) def test_date_axvline(): t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2000, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axvline(t0, color="red", lw=3) ax.set_xlim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.autofmt_xdate() @cleanup def test_too_many_date_ticks(): warnings.filterwarnings( 'ignore', 'Attempting to set identical left==right results\\nin singular ' 'transformations; automatically expanding.\\nleft=\d*\.\d*, ' 'right=\d*\.\d*', UserWarning, module='matplotlib.axes') t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2000, 1, 20) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim((t0, tf), auto=True) ax.plot([], []) ax.xaxis.set_major_locator(mdates.DayLocator()) assert_raises(RuntimeError, fig.savefig, 'junk.png') @image_comparison(baseline_images=['RRuleLocator_bounds'], extensions=['png']) def test_RRuleLocator(): import matplotlib.testing.jpl_units as units units.register() t0 = datetime.datetime(1000, 1, 1) tf = datetime.datetime(6000, 1, 1) fig = plt.figure() ax = plt.subplot(111) ax.set_autoscale_on(True) ax.plot([t0, tf], [0.0, 1.0], marker='o') rrule = mdates.rrulewrapper(dateutil.rrule.YEARLY, interval=500) locator = mdates.RRuleLocator(rrule) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator)) ax.autoscale_view() fig.autofmt_xdate() @image_comparison(baseline_images=['DateFormatter_fractionalSeconds'], extensions=['png']) def test_DateFormatter(): import matplotlib.testing.jpl_units as units units.register() t0 = datetime.datetime(2001, 1, 1, 0, 0, 0) tf = datetime.datetime(2001, 1, 1, 0, 0, 1) fig = plt.figure() ax = plt.subplot(111) ax.set_autoscale_on(True) ax.plot([t0, tf], [0.0, 1.0], marker='o') ax.autoscale_view() fig.autofmt_xdate() def test_date_formatter_strftime(): def test_strftime_fields(dt): formatter = mdates.DateFormatter("%w %d %m %y %Y %H %I %M %S %%%f %%x") formatted_date_str = ( "{weekday} {day:02d} {month:02d} {year:02d} {full_year:04d} " "{hour24:02d} {hour12:02d} {minute:02d} {second:02d} " "%{microsecond:06d} %x" .format( weekday=str((dt.weekday() + 1) % 7), day=dt.day, month=dt.month, year=dt.year % 100, full_year=dt.year, hour24=dt.hour, hour12=((dt.hour-1) % 12) + 1, minute=dt.minute, second=dt.second, microsecond=dt.microsecond)) assert_equal(formatter.strftime(dt), formatted_date_str) try: import locale locale_formatter = mdates.DateFormatter("%x") locale_d_fmt = locale.nl_langinfo(locale.D_FMT) expanded_formatter = mdates.DateFormatter(locale_d_fmt) assert_equal(locale_formatter.strftime(dt), expanded_formatter.strftime(dt)) except (ImportError, AttributeError): pass for year in range(1, 3000, 71): test_strftime_fields(datetime.datetime(year, 1, 1)) test_strftime_fields(datetime.datetime(year, 2, 3, 4, 5, 6, 12345)) def test_date_formatter_callable(): scale = -11 locator = mock.Mock(_get_unit=mock.Mock(return_value=scale)) callable_formatting_function = (lambda dates, _: [dt.strftime('%d-%m//%Y') for dt in dates]) formatter = mdates.AutoDateFormatter(locator) formatter.scaled[-10] = callable_formatting_function assert_equal(formatter([datetime.datetime(2014, 12, 25)]), ['25-12//2014']) def test_drange(): start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC) end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC) delta = datetime.timedelta(hours=1) assert_equal(24, len(mdates.drange(start, end, delta))) end = end + datetime.timedelta(microseconds=1) assert_equal(25, len(mdates.drange(start, end, delta))) end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC) delta = datetime.timedelta(hours=4) daterange = mdates.drange(start, end, delta) assert_equal(6, len(daterange)) assert_equal(mdates.num2date(daterange[-1]), end - delta) @cleanup def test_empty_date_with_year_formatter(): import matplotlib.dates as dates fig = plt.figure() ax = fig.add_subplot(111) yearFmt = dates.DateFormatter('%Y') ax.xaxis.set_major_formatter(yearFmt) with tempfile.TemporaryFile() as fh: assert_raises(ValueError, fig.savefig, fh) def test_auto_date_locator(): def _create_auto_date_locator(date1, date2): locator = mdates.AutoDateLocator() locator.create_dummy_axis() locator.set_view_interval(mdates.date2num(date1), mdates.date2num(date2)) return locator d1 = datetime.datetime(1990, 1, 1) results = ([datetime.timedelta(weeks=52 * 200), ['1990-01-01 00:00:00+00:00', '2010-01-01 00:00:00+00:00', '2030-01-01 00:00:00+00:00', '2050-01-01 00:00:00+00:00', '2070-01-01 00:00:00+00:00', '2090-01-01 00:00:00+00:00', '2110-01-01 00:00:00+00:00', '2130-01-01 00:00:00+00:00', '2150-01-01 00:00:00+00:00', '2170-01-01 00:00:00+00:00'] ], [datetime.timedelta(weeks=52), ['1990-01-01 00:00:00+00:00', '1990-02-01 00:00:00+00:00', '1990-03-01 00:00:00+00:00', '1990-04-01 00:00:00+00:00', '1990-05-01 00:00:00+00:00', '1990-06-01 00:00:00+00:00', '1990-07-01 00:00:00+00:00', '1990-08-01 00:00:00+00:00', '1990-09-01 00:00:00+00:00', '1990-10-01 00:00:00+00:00', '1990-11-01 00:00:00+00:00', '1990-12-01 00:00:00+00:00'] ], [datetime.timedelta(days=141), ['1990-01-05 00:00:00+00:00', '1990-01-26 00:00:00+00:00', '1990-02-16 00:00:00+00:00', '1990-03-09 00:00:00+00:00', '1990-03-30 00:00:00+00:00', '1990-04-20 00:00:00+00:00', '1990-05-11 00:00:00+00:00'] ], [datetime.timedelta(days=40), ['1990-01-03 00:00:00+00:00', '1990-01-10 00:00:00+00:00', '1990-01-17 00:00:00+00:00', '1990-01-24 00:00:00+00:00', '1990-01-31 00:00:00+00:00', '1990-02-07 00:00:00+00:00'] ], [datetime.timedelta(hours=40), ['1990-01-01 00:00:00+00:00', '1990-01-01 04:00:00+00:00', '1990-01-01 08:00:00+00:00', '1990-01-01 12:00:00+00:00', '1990-01-01 16:00:00+00:00', '1990-01-01 20:00:00+00:00', '1990-01-02 00:00:00+00:00', '1990-01-02 04:00:00+00:00', '1990-01-02 08:00:00+00:00', '1990-01-02 12:00:00+00:00', '1990-01-02 16:00:00+00:00'] ], [datetime.timedelta(minutes=20), ['1990-01-01 00:00:00+00:00', '1990-01-01 00:05:00+00:00', '1990-01-01 00:10:00+00:00', '1990-01-01 00:15:00+00:00', '1990-01-01 00:20:00+00:00'] ], [datetime.timedelta(seconds=40), ['1990-01-01 00:00:00+00:00', '1990-01-01 00:00:05+00:00', '1990-01-01 00:00:10+00:00', '1990-01-01 00:00:15+00:00', '1990-01-01 00:00:20+00:00', '1990-01-01 00:00:25+00:00', '1990-01-01 00:00:30+00:00', '1990-01-01 00:00:35+00:00', '1990-01-01 00:00:40+00:00'] ], [datetime.timedelta(microseconds=1500), ['1989-12-31 23:59:59.999507+00:00', '1990-01-01 00:00:00+00:00', '1990-01-01 00:00:00.000502+00:00', '1990-01-01 00:00:00.001005+00:00', '1990-01-01 00:00:00.001508+00:00'] ], ) for t_delta, expected in results: d2 = d1 + t_delta locator = _create_auto_date_locator(d1, d2) assert_equal(list(map(str, mdates.num2date(locator()))), expected) @image_comparison(baseline_images=['date_inverted_limit'], extensions=['png']) def test_date_inverted_limit(): t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 31) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhline(t0, color="blue", lw=3) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) ax.invert_yaxis() fig.subplots_adjust(left=0.25) def _test_date2num_dst(date_range, tz_convert): BRUSSELS = pytz.timezone('Europe/Brussels') UTC = pytz.UTC dtstart = datetime.datetime(2014, 3, 30, 0, 0, tzinfo=UTC) interval = datetime.timedelta(minutes=33, seconds=45) interval_days = 0.0234375 N = 8 dt_utc = date_range(start=dtstart, freq=interval, periods=N) dt_bxl = tz_convert(dt_utc, BRUSSELS) expected_ordinalf = [735322.0 + (i * interval_days) for i in range(N)] actual_ordinalf = list(mdates.date2num(dt_bxl)) assert_equal(actual_ordinalf, expected_ordinalf) def test_date2num_dst(): ): def __sub__(self, other): r = super(dt_tzaware, self).__sub__(other) tzinfo = getattr(r, 'tzinfo', None) if tzinfo is not None: localizer = getattr(tzinfo, 'normalize', None) if localizer is not None: r = tzinfo.normalize(r) if isinstance(r, datetime.datetime): r = self.mk_tzaware(r) return r def __add__(self, other): return self.mk_tzaware(super(dt_tzaware, self).__add__(other)) def astimezone(self, tzinfo): dt = super(dt_tzaware, self).astimezone(tzinfo) return self.mk_tzaware(dt) @classmethod def mk_tzaware(cls, datetime_obj): kwargs = {} attrs = ('year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond', 'tzinfo') for attr in attrs: val = getattr(datetime_obj, attr, None) if val is not None: kwargs[attr] = val return cls(**kwargs) def date_range(start, freq, periods): dtstart = dt_tzaware.mk_tzaware(start) return [dtstart + (i * freq) for i in range(periods)] def tz_convert(dt_list, tzinfo): return [d.astimezone(tzinfo) for d in dt_list] _test_date2num_dst(date_range, tz_convert) def test_date2num_dst_pandas(): except ImportError: raise SkipTest('pandas not installed') def tz_convert(*args): return pd.DatetimeIndex.tz_convert(*args).astype(object) _test_date2num_dst(pd.date_range, tz_convert) def test_DayLocator(): assert_raises(ValueError, mdates.DayLocator, interval=-1) assert_raises(ValueError, mdates.DayLocator, interval=-1.5) assert_raises(ValueError, mdates.DayLocator, interval=0) assert_raises(ValueError, mdates.DayLocator, interval=1.3) mdates.DayLocator(interval=1.0) def test_tz_utc(): dt = datetime.datetime(1970, 1, 1, tzinfo=mdates.UTC) dt.tzname() if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
true
true
1c441f687a15c8a847fbb5b8238c9fec5fcdeb16
728
py
Python
icekit/plugins/child_pages/migrations/0001_initial.py
ic-labs/django-icekit
c507ea5b1864303732c53ad7c5800571fca5fa94
[ "MIT" ]
52
2016-09-13T03:50:58.000Z
2022-02-23T16:25:08.000Z
icekit/plugins/child_pages/migrations/0001_initial.py
ic-labs/django-icekit
c507ea5b1864303732c53ad7c5800571fca5fa94
[ "MIT" ]
304
2016-08-11T14:17:30.000Z
2020-07-22T13:35:18.000Z
icekit/plugins/child_pages/migrations/0001_initial.py
ic-labs/django-icekit
c507ea5b1864303732c53ad7c5800571fca5fa94
[ "MIT" ]
12
2016-09-21T18:46:35.000Z
2021-02-15T19:37:50.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('fluent_contents', '0001_initial'), ] operations = [ migrations.CreateModel( name='ChildPageItem', fields=[ ('contentitem_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='fluent_contents.ContentItem')), ], options={ 'db_table': 'contentitem_child_pages_childpageitem', 'verbose_name': 'Child Page', }, bases=('fluent_contents.contentitem',), ), ]
28
164
0.593407
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('fluent_contents', '0001_initial'), ] operations = [ migrations.CreateModel( name='ChildPageItem', fields=[ ('contentitem_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='fluent_contents.ContentItem')), ], options={ 'db_table': 'contentitem_child_pages_childpageitem', 'verbose_name': 'Child Page', }, bases=('fluent_contents.contentitem',), ), ]
true
true
1c4421bf3400323db69447583130a58df30bd901
1,811
py
Python
src/embedding/auxiliary/factory.py
chengemily/Distributional-Signatures
7ef96f9cfc8aeb2fb54e117e3968e4390aaad819
[ "MIT" ]
243
2019-08-15T18:34:09.000Z
2022-03-31T11:51:00.000Z
src/embedding/auxiliary/factory.py
phymucs/460d60d2c25a118c67dcbfdd37f27d6c
cd7e4659fc9761a8af046e824853aa338b22f2f6
[ "MIT" ]
34
2019-10-22T08:11:28.000Z
2022-03-19T08:03:30.000Z
src/embedding/auxiliary/factory.py
phymucs/460d60d2c25a118c67dcbfdd37f27d6c
cd7e4659fc9761a8af046e824853aa338b22f2f6
[ "MIT" ]
54
2019-08-19T16:11:49.000Z
2022-03-31T05:36:01.000Z
import datetime import torch import torch.nn as nn import torch.nn.functional as F from embedding.auxiliary.pos import POS def get_embedding(args): ''' @return AUX module with aggregated embeddings or None if args.aux did not provide additional embeddings ''' print("{}, Building augmented embedding".format( datetime.datetime.now().strftime('%02y/%02m/%02d %H:%M:%S'))) aux = [] for ebd in args.auxiliary: if ebd == 'pos': aux.append(POS(args)) else: raise ValueError('Invalid argument for auxiliary ebd') if args.cuda != -1: aux = [a.cuda(args.cuda) for a in aux] model = AUX(aux, args) if args.cuda != -1: return model.cuda(args.cuda) else: return model class AUX(nn.Module): ''' Wrapper around combination of auxiliary embeddings ''' def __init__(self, aux, args): super(AUX, self).__init__() self.args = args # this is a list of nn.Module self.aux = nn.ModuleList(aux) # this is 0 if self.aux is empty self.embedding_dim = sum(a.embedding_dim for a in self.aux) def forward(self, data, weights=None): # torch.cat will discard the empty tensor if len(self.aux) == 0: if self.args.cuda != -1: return torch.FloatTensor().cuda(self.args.cuda) return torch.FloatTensor() # aggregate results from each auxiliary module results = [aux(data, weights) for aux in self.aux] # aux embeddings should only be used with cnn, meta or meta_mlp. # concatenate together with word embeddings assert (self.args.embedding in ['cnn', 'meta', 'meta_mlp', 'lstmatt']) x = torch.cat(results, dim=2) return x
27.861538
78
0.605191
import datetime import torch import torch.nn as nn import torch.nn.functional as F from embedding.auxiliary.pos import POS def get_embedding(args): print("{}, Building augmented embedding".format( datetime.datetime.now().strftime('%02y/%02m/%02d %H:%M:%S'))) aux = [] for ebd in args.auxiliary: if ebd == 'pos': aux.append(POS(args)) else: raise ValueError('Invalid argument for auxiliary ebd') if args.cuda != -1: aux = [a.cuda(args.cuda) for a in aux] model = AUX(aux, args) if args.cuda != -1: return model.cuda(args.cuda) else: return model class AUX(nn.Module): def __init__(self, aux, args): super(AUX, self).__init__() self.args = args self.aux = nn.ModuleList(aux) self.embedding_dim = sum(a.embedding_dim for a in self.aux) def forward(self, data, weights=None): if len(self.aux) == 0: if self.args.cuda != -1: return torch.FloatTensor().cuda(self.args.cuda) return torch.FloatTensor() results = [aux(data, weights) for aux in self.aux] assert (self.args.embedding in ['cnn', 'meta', 'meta_mlp', 'lstmatt']) x = torch.cat(results, dim=2) return x
true
true
1c44232a092f5ad3d514e0826917e96a5a8c0b13
1,278
py
Python
leads/urls.py
tmbyers1102/djcrm
7a2830a3d1867a223a748b5cb9b771fcc45577e4
[ "MIT" ]
null
null
null
leads/urls.py
tmbyers1102/djcrm
7a2830a3d1867a223a748b5cb9b771fcc45577e4
[ "MIT" ]
null
null
null
leads/urls.py
tmbyers1102/djcrm
7a2830a3d1867a223a748b5cb9b771fcc45577e4
[ "MIT" ]
null
null
null
from django.urls import path from .views import ( LeadListView, LeadDetailView, LeadCreateView, LeadUpdateView, LeadDeleteView, AssignAgentView, CategoryListView, CategoryDetailView, LeadCategoryUpdateView, CategoryCreateView, CategoryUpdateView, CategoryDeleteView ) app_name = "leads" urlpatterns = [ path('', LeadListView.as_view(), name='lead-list'), path('<int:pk>/', LeadDetailView.as_view(), name='lead-detail'), path('<int:pk>/update/', LeadUpdateView.as_view(), name='lead-update'), path('<int:pk>/delete/', LeadDeleteView.as_view(), name='lead-delete'), path('<int:pk>/assign-agent/', AssignAgentView.as_view(), name='assign-agent'), path('<int:pk>/category/', LeadCategoryUpdateView.as_view(), name='lead-category-update'), path('create/', LeadCreateView.as_view(), name='lead-create'), path('categories/', CategoryListView.as_view(), name='category-list'), path('categories/<int:pk>/', CategoryDetailView.as_view(), name='category-detail'), path('create-category/', CategoryCreateView.as_view(), name='category-create'), path('categories/<int:pk>/update/', CategoryUpdateView.as_view(), name='category-update'), path('categories/<int:pk>/delete/', CategoryDeleteView.as_view(), name='category-delete'), ]
55.565217
94
0.717527
from django.urls import path from .views import ( LeadListView, LeadDetailView, LeadCreateView, LeadUpdateView, LeadDeleteView, AssignAgentView, CategoryListView, CategoryDetailView, LeadCategoryUpdateView, CategoryCreateView, CategoryUpdateView, CategoryDeleteView ) app_name = "leads" urlpatterns = [ path('', LeadListView.as_view(), name='lead-list'), path('<int:pk>/', LeadDetailView.as_view(), name='lead-detail'), path('<int:pk>/update/', LeadUpdateView.as_view(), name='lead-update'), path('<int:pk>/delete/', LeadDeleteView.as_view(), name='lead-delete'), path('<int:pk>/assign-agent/', AssignAgentView.as_view(), name='assign-agent'), path('<int:pk>/category/', LeadCategoryUpdateView.as_view(), name='lead-category-update'), path('create/', LeadCreateView.as_view(), name='lead-create'), path('categories/', CategoryListView.as_view(), name='category-list'), path('categories/<int:pk>/', CategoryDetailView.as_view(), name='category-detail'), path('create-category/', CategoryCreateView.as_view(), name='category-create'), path('categories/<int:pk>/update/', CategoryUpdateView.as_view(), name='category-update'), path('categories/<int:pk>/delete/', CategoryDeleteView.as_view(), name='category-delete'), ]
true
true
1c4423c0dbd6723411c958372c1c8fc474df25d0
819
py
Python
examples/loading_images.py
FPEPOSHI/PyBoof
00c67c0689be35019b65d5e5dc1a8a5a8e471d9d
[ "Apache-2.0" ]
1
2022-02-10T04:18:28.000Z
2022-02-10T04:18:28.000Z
examples/loading_images.py
yuantailing/PyBoof
a5a0ffba6adfeb8d97c099c2470995553466eeaa
[ "Apache-2.0" ]
null
null
null
examples/loading_images.py
yuantailing/PyBoof
a5a0ffba6adfeb8d97c099c2470995553466eeaa
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 import numpy as np import cv2 import pyboof as pb # Enable use of memory mapped files for MUCH faster conversion of images between java and python pb.init_memmap() image_path = '../data/example/outdoors01.jpg' # Can load an image using OpenCV then convert it into BoofCV ndarray_img = cv2.imread(image_path, 0) boof_cv = pb.ndarray_to_boof(ndarray_img) # Can also use BoofCV to load the image directly boof_gray = pb.load_single_band(image_path, np.uint8) boof_color = pb.load_planar(image_path, np.uint8) # Let's display all 3 of them in Java # display the results in a single window as a list image_list = [(boof_cv, "OpenCV"), (boof_gray, "Gray Scale"), (boof_color, "Color")] pb.swing.show_list(image_list, title="Images") input("Press any key to exit")
26.419355
96
0.73138
import numpy as np import cv2 import pyboof as pb pb.init_memmap() image_path = '../data/example/outdoors01.jpg' ndarray_img = cv2.imread(image_path, 0) boof_cv = pb.ndarray_to_boof(ndarray_img) boof_gray = pb.load_single_band(image_path, np.uint8) boof_color = pb.load_planar(image_path, np.uint8) # display the results in a single window as a list image_list = [(boof_cv, "OpenCV"), (boof_gray, "Gray Scale"), (boof_color, "Color")] pb.swing.show_list(image_list, title="Images") input("Press any key to exit")
true
true
1c4423ccd33c81a933965b4db4ae0ecdcaf8a624
1,563
py
Python
app/urls.py
victoriadrake/django-starter
4fbb423edf79bf4e512a4a6c578072c539d00b9d
[ "MIT" ]
6
2021-08-25T12:06:29.000Z
2022-02-16T12:36:58.000Z
app/urls.py
victoriadrake/django-starter
4fbb423edf79bf4e512a4a6c578072c539d00b9d
[ "MIT" ]
null
null
null
app/urls.py
victoriadrake/django-starter
4fbb423edf79bf4e512a4a6c578072c539d00b9d
[ "MIT" ]
2
2021-08-28T07:50:16.000Z
2022-02-21T09:47:46.000Z
"""URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ import app.views as views from django.conf import settings from django.urls import re_path from django.views.static import serve from django.contrib import admin from django.urls import include, path urlpatterns = [path("admin/", admin.site.urls), path("", views.Welcome.as_view())] if settings.DEBUG: from django.conf.urls.static import static # Will serve files from /media/ in development mode # https://docs.djangoproject.com/en/3.2/ref/views/#serving-files-in-development urlpatterns += [ re_path(r"^media/(?P<path>.*)$", serve, {"document_root": settings.MEDIA_ROOT}) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if "debug_toolbar" in settings.INSTALLED_APPS: # Displays the Debug Toolbar # https://django-debug-toolbar.readthedocs.io/en/latest/index.html import debug_toolbar urlpatterns += [path("__debug__/", include(debug_toolbar.urls))]
39.075
87
0.715291
import app.views as views from django.conf import settings from django.urls import re_path from django.views.static import serve from django.contrib import admin from django.urls import include, path urlpatterns = [path("admin/", admin.site.urls), path("", views.Welcome.as_view())] if settings.DEBUG: from django.conf.urls.static import static re_path(r"^media/(?P<path>.*)$", serve, {"document_root": settings.MEDIA_ROOT}) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if "debug_toolbar" in settings.INSTALLED_APPS: import debug_toolbar urlpatterns += [path("__debug__/", include(debug_toolbar.urls))]
true
true
1c4423e641fedf13db70ea243a100a5ec19fb37b
711
py
Python
dodo.py
Thirty-OneR/Astr496_assignment03
e5c8c842906fa9d6c141fb92a0fc9e134810ec64
[ "BSD-3-Clause" ]
null
null
null
dodo.py
Thirty-OneR/Astr496_assignment03
e5c8c842906fa9d6c141fb92a0fc9e134810ec64
[ "BSD-3-Clause" ]
null
null
null
dodo.py
Thirty-OneR/Astr496_assignment03
e5c8c842906fa9d6c141fb92a0fc9e134810ec64
[ "BSD-3-Clause" ]
null
null
null
from doit.tools import run_once import h5py import numpy as np import matplotlib.pyplot as plt def task_generate_gaussian(): N = 32**3 seed = 0x4d3d3d3 fn = "gaussian.h5" def _generate(): np.random.seed(seed) pos = np.random.normal(loc = [0.5, 0.5, 0.5], scale = 0.2, size = (N, 3)) vel = np.random.random(size = (N, 3)) * 10.0 - 5.0 with h5py.File(fn, "w") as f: f.create_dataset("/particle_positions", data = pos) f.create_dataset("/particle_velocities", data = vel) f.create_dataset("/particle_masses", data = np.ones(N)) return {'actions': [_generate], 'targets': [fn], 'uptodate': [run_once]}
33.857143
81
0.583685
from doit.tools import run_once import h5py import numpy as np import matplotlib.pyplot as plt def task_generate_gaussian(): N = 32**3 seed = 0x4d3d3d3 fn = "gaussian.h5" def _generate(): np.random.seed(seed) pos = np.random.normal(loc = [0.5, 0.5, 0.5], scale = 0.2, size = (N, 3)) vel = np.random.random(size = (N, 3)) * 10.0 - 5.0 with h5py.File(fn, "w") as f: f.create_dataset("/particle_positions", data = pos) f.create_dataset("/particle_velocities", data = vel) f.create_dataset("/particle_masses", data = np.ones(N)) return {'actions': [_generate], 'targets': [fn], 'uptodate': [run_once]}
true
true
1c4423f3e839538adbe798b9a8ec37bc7802b9d8
4,881
py
Python
ciscoisesdk/models/validators/v3_1_0/jsd_df9ab8ff636353279d5c787585dcb6af.py
CiscoISE/ciscoisesdk
860b0fc7cc15d0c2a39c64608195a7ab3d5f4885
[ "MIT" ]
36
2021-05-18T16:24:19.000Z
2022-03-05T13:44:41.000Z
ciscoisesdk/models/validators/v3_0_0/jsd_df9ab8ff636353279d5c787585dcb6af.py
CiscoISE/ciscoisesdk
860b0fc7cc15d0c2a39c64608195a7ab3d5f4885
[ "MIT" ]
15
2021-06-08T19:03:37.000Z
2022-02-25T14:47:33.000Z
ciscoisesdk/models/validators/v3_1_0/jsd_df9ab8ff636353279d5c787585dcb6af.py
CiscoISE/ciscoisesdk
860b0fc7cc15d0c2a39c64608195a7ab3d5f4885
[ "MIT" ]
6
2021-06-10T09:32:01.000Z
2022-01-12T08:34:39.000Z
# -*- coding: utf-8 -*- """Identity Services Engine updateRadiusServerSequenceById data model. Copyright (c) 2021 Cisco and/or its affiliates. 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, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following 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 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. """ from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import fastjsonschema import json from ciscoisesdk.exceptions import MalformedRequest from builtins import * class JSONSchemaValidatorDf9Ab8Ff636353279D5C787585Dcb6Af(object): """updateRadiusServerSequenceById request schema definition.""" def __init__(self): super(JSONSchemaValidatorDf9Ab8Ff636353279D5C787585Dcb6Af, self).__init__() self._validator = fastjsonschema.compile(json.loads( '''{ "$schema": "http://json-schema.org/draft-04/schema#", "properties": { "RadiusServerSequence": { "properties": { "BeforeAcceptAttrManipulatorsList": { "items": { "properties": { "action": { "type": "string" }, "attributeName": { "type": "string" }, "changedVal": { "type": "string" }, "dictionaryName": { "type": "string" }, "value": { "type": "string" } }, "type": "object" }, "type": "array" }, "OnRequestAttrManipulatorList": { "items": { "properties": { "action": { "type": "string" }, "attributeName": { "type": "string" }, "changedVal": { "type": "string" }, "dictionaryName": { "type": "string" }, "value": { "type": "string" } }, "type": "object" }, "type": "array" }, "RadiusServerList": { "items": { "type": "string" }, "type": "array" }, "continueAuthorzPolicy": { "type": "boolean" }, "description": { "type": "string" }, "id": { "type": "string" }, "localAccounting": { "type": "boolean" }, "name": { "type": "string" }, "prefixSeparator": { "type": "string" }, "remoteAccounting": { "type": "boolean" }, "stripPrefix": { "type": "boolean" }, "stripSuffix": { "type": "boolean" }, "suffixSeparator": { "type": "string" }, "useAttrSetBeforeAcc": { "type": "boolean" }, "useAttrSetOnRequest": { "type": "boolean" } }, "type": "object" } }, "type": "object" }'''.replace("\n" + ' ' * 16, '') )) def validate(self, request): try: self._validator(request) except fastjsonschema.exceptions.JsonSchemaException as e: raise MalformedRequest( '{} is invalid. Reason: {}'.format(request, e.message) )
31.694805
83
0.461995
from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import fastjsonschema import json from ciscoisesdk.exceptions import MalformedRequest from builtins import * class JSONSchemaValidatorDf9Ab8Ff636353279D5C787585Dcb6Af(object): def __init__(self): super(JSONSchemaValidatorDf9Ab8Ff636353279D5C787585Dcb6Af, self).__init__() self._validator = fastjsonschema.compile(json.loads( '''{ "$schema": "http://json-schema.org/draft-04/schema#", "properties": { "RadiusServerSequence": { "properties": { "BeforeAcceptAttrManipulatorsList": { "items": { "properties": { "action": { "type": "string" }, "attributeName": { "type": "string" }, "changedVal": { "type": "string" }, "dictionaryName": { "type": "string" }, "value": { "type": "string" } }, "type": "object" }, "type": "array" }, "OnRequestAttrManipulatorList": { "items": { "properties": { "action": { "type": "string" }, "attributeName": { "type": "string" }, "changedVal": { "type": "string" }, "dictionaryName": { "type": "string" }, "value": { "type": "string" } }, "type": "object" }, "type": "array" }, "RadiusServerList": { "items": { "type": "string" }, "type": "array" }, "continueAuthorzPolicy": { "type": "boolean" }, "description": { "type": "string" }, "id": { "type": "string" }, "localAccounting": { "type": "boolean" }, "name": { "type": "string" }, "prefixSeparator": { "type": "string" }, "remoteAccounting": { "type": "boolean" }, "stripPrefix": { "type": "boolean" }, "stripSuffix": { "type": "boolean" }, "suffixSeparator": { "type": "string" }, "useAttrSetBeforeAcc": { "type": "boolean" }, "useAttrSetOnRequest": { "type": "boolean" } }, "type": "object" } }, "type": "object" }'''.replace("\n" + ' ' * 16, '') )) def validate(self, request): try: self._validator(request) except fastjsonschema.exceptions.JsonSchemaException as e: raise MalformedRequest( '{} is invalid. Reason: {}'.format(request, e.message) )
true
true
1c44240d49c67657b76398b4c928871217f7814a
1,365
py
Python
blog/migrations/0001_initial.py
albertmil97/django_AlbertMIliano
9d1c1763e9061083d1cc1e389a77423cfd2e7daf
[ "MIT" ]
null
null
null
blog/migrations/0001_initial.py
albertmil97/django_AlbertMIliano
9d1c1763e9061083d1cc1e389a77423cfd2e7daf
[ "MIT" ]
null
null
null
blog/migrations/0001_initial.py
albertmil97/django_AlbertMIliano
9d1c1763e9061083d1cc1e389a77423cfd2e7daf
[ "MIT" ]
null
null
null
# Generated by Django 3.0.7 on 2020-06-08 04:47 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=250)), ('slug', models.SlugField(max_length=250, unique_for_date='publish')), ('body', models.TextField()), ('publish', models.DateTimeField(default=django.utils.timezone.now)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='draft', max_length=10)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blog_post', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('-publish',), }, ), ]
37.916667
146
0.606593
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=250)), ('slug', models.SlugField(max_length=250, unique_for_date='publish')), ('body', models.TextField()), ('publish', models.DateTimeField(default=django.utils.timezone.now)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='draft', max_length=10)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blog_post', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('-publish',), }, ), ]
true
true
1c4424f6ccb062b4183b7bc73cbbf4c674e6bcfd
25,179
py
Python
hw/vendor/lowrisc_ibex/vendor/google_riscv-dv/pygen/pygen_src/isa/riscv_cov_instr.py
msfschaffner/opentitan-bak
de4cb1bb9e7b707a3ca2a6882d83af7ed2aa1ab8
[ "Apache-2.0" ]
1
2021-12-15T09:23:09.000Z
2021-12-15T09:23:09.000Z
hw/vendor/lowrisc_ibex/vendor/google_riscv-dv/pygen/pygen_src/isa/riscv_cov_instr.py
msfschaffner/opentitan-bak
de4cb1bb9e7b707a3ca2a6882d83af7ed2aa1ab8
[ "Apache-2.0" ]
3
2020-05-29T13:12:25.000Z
2020-06-19T13:07:23.000Z
hw/vendor/lowrisc_ibex/vendor/google_riscv-dv/pygen/pygen_src/isa/riscv_cov_instr.py
msfschaffner/opentitan-bak
de4cb1bb9e7b707a3ca2a6882d83af7ed2aa1ab8
[ "Apache-2.0" ]
1
2021-08-28T16:19:23.000Z
2021-08-28T16:19:23.000Z
"""Copyright 2020 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 vsc import logging from importlib import import_module from enum import IntEnum, auto from pygen_src.riscv_instr_pkg import * from pygen_src.riscv_instr_gen_config import cfg rcs = import_module("pygen_src.target." + cfg.argv.target + ".riscv_core_setting") class operand_sign_e(IntEnum): POSITIVE = 0 NEGATIVE = auto() class div_result_e(IntEnum): DIV_NORMAL = 0 DIV_BY_ZERO = auto() DIV_OVERFLOW = auto() class div_result_ex_overflow_e(IntEnum): DIV_NORMAL = 0 DIV_BY_ZERO = auto() class compare_result_e(IntEnum): EQUAL = 0 LARGER = auto() SMALLER = auto() class logical_similarity_e(IntEnum): IDENTICAL = 0 OPPOSITE = auto() SIMILAR = auto() DIFFERENT = auto() class special_val_e(IntEnum): NORMAL_VAL = 0 MIN_VAL = auto() MAX_VAL = auto() ZERO_VAL = auto() class riscv_cov_instr: """ Class for a riscv instruction in functional coverage phase; data parsed from the CSV file fill different fields of an instruction """ # class attr. to keep track of reg_name:reg_value throughout the program gpr_state = {} def __init__(self): # Program counter (PC) of the instruction self.pc = vsc.bit_t(rcs.XLEN) self.instr = None # self.gpr = None # destination operand of the instruction self.binary = vsc.bit_t(32) # Instruction binary # self.mode = None # Instruction mode self.trace = "None" # String representation of the instruction # self.operands = "None" # Instruction operands (srcss/dests) # self.pad = None # Not used self.rs1_value = vsc.bit_t(rcs.XLEN) self.rs2_value = vsc.bit_t(rcs.XLEN) self.rs3_value = vsc.bit_t(rcs.XLEN) self.rd_value = vsc.bit_t(rcs.XLEN) self.fs1_value = vsc.bit_t(rcs.XLEN) self.fs2_value = vsc.bit_t(rcs.XLEN) self.fs3_value = vsc.bit_t(rcs.XLEN) self.fd_value = vsc.bit_t(rcs.XLEN) self.mem_addr = vsc.int_t(rcs.XLEN) self.unaligned_pc = 0 self.unaligned_mem_access = 0 self.compressed = 0 self.branch_hit = 0 self.div_result = None self.rs1_sign = 0 self.rs2_sign = 0 self.rs3_sign = 0 self.fs1_sign = 0 self.fs2_sign = 0 self.fs3_sign = 0 self.imm_sign = 0 self.rd_sign = 0 self.fd_sign = 0 self.gpr_hazard = hazard_e.NO_HAZARD self.lsu_hazard = hazard_e.NO_HAZARD self.rs1_special_value = 0 self.rs2_special_value = 0 self.rs3_special_value = 0 self.rd_special_value = 0 self.imm_special_value = 0 self.compare_result = 0 self.logical_similarity = 0 self.group = None self.format = None self.category = None self.imm_type = None self.csr = vsc.bit_t(12) ''' TODO: rs2, rs1, rd, group, format, category, imm_type fs1, fs2, fs3, fd will be changed to vsc.enum_t once the issue with set/get_val is fixed ''' self.rs2 = 0 self.rs1 = 0 self.rd = 0 self.imm = vsc.int_t(32) self.has_rs1 = 1 self.has_rs2 = 1 self.has_rd = 1 self.has_imm = 1 self.imm_len = 0 self.has_fs1 = 1 self.has_fs2 = 1 self.has_fs3 = 0 self.has_fd = 1 self.fs1 = 0 self.fs2 = 0 self.fs3 = 0 self.fd = 0 def assign_attributes(self): attr_list = get_attr_list(self.instr) self.format = attr_list[0] self.category = attr_list[1] self.group = attr_list[2] self.imm_type = imm_t.IMM if len(attr_list) > 3: self.imm_type = attr_list[3] self.set_imm_len() self.set_mode() if self.group.name in ["RV32D", "RV32F"]: self.set_fd_mode() def set_imm_len(self): if self.format.name in ["U_FORMAT", "J_FORMAT"]: self.imm_len = 20 elif self.format.name in ["I_FORMAT", "S_FORMAT", "B_FORMAT"]: if self.imm_type.name == "UIMM": self.imm_len = 5 else: self.imm_len = 12 def set_mode(self): # mode setting for Instruction Format if self.format.name == "R_FORMAT": self.has_imm = 0 if self.format.name == "I_FORMAT": self.has_rs2 = 0 if self.format.name in ["S_FORMAT", "B_FORMAT"]: self.has_rd = 0 if self.format.name in ["U_FORMAT", "J_FORMAT"]: self.has_rs1 = 0 self.has_rs2 = 0 # mode setting for Instruction Category if self.category.name == "CSR": self.has_rs2 = 0 if self.format.name == "I_FORMAT": self.has_rs1 = 0 # mode setting for F and D Instruction def set_fd_mode(self): if self.format == riscv_instr_format_t.I_FORMAT: self.has_fs2 = 0 if self.category == riscv_instr_category_t.LOAD: self.has_imm = 1 elif self.instr.name in ['FMV_X_W', 'FMV_X_D', 'FCVT_W_S', 'FCVT_WU_S', 'FCVT_L_S', 'FCVT_LU_S', 'FCVT_L_D', 'FCVT_LU_D', 'FCVT_LU_S', 'FCVT_W_D', 'FCVT_WU_D']: self.has_fd = 0 self.has_rd = 1 elif self.instr.name in ['FMV_W_X', 'FMV_D_X', 'FCVT_S_W', 'FCVT_S_WU', 'FCVT_S_L', 'FCVT_D_L', 'FCVT_S_LU', 'FCVT_D_W', 'FCVT_D_LU', 'FCVT_D_WU']: self.has_rs1 = 1 self.has_fs1 = 0 elif self.format == riscv_instr_format_t.S_FORMAT: self.has_imm = 1 self.has_rs1 = 1 self.has_fs1 = 0 self.has_fs3 = 0 elif self.format == riscv_instr_format_t.R_FORMAT: if self.category == riscv_instr_category_t.COMPARE: self.has_rd = 1 self.has_fd = 0 elif self.instr.name in ['FCLASS_S', 'FCLASS_D']: self.has_rd = 1 self.has_fd = 0 self.has_fs2 = 0 elif self.format == riscv_instr_format_t.R4_FORMAT: self.has_fs3 = 1 elif self.format == riscv_instr_format_t.CL_FORMAT: self.has_imm = 1 self.has_rs1 = 1 self.has_fs1 = 0 self.has_fs2 = 0 elif self.format == riscv_instr_format_t.CS_FORMAT: self.has_imm = 1 self.has_rs1 = 1 self.has_fs1 = 0 self.has_fd = 0 else: logging.info("Unsupported format {}".format(self.format.name)) def pre_sample(self): unaligned_pc = self.pc.get_val() % 4 != 0 self.rs1_sign = self.get_operand_sign(self.rs1_value) self.rs2_sign = self.get_operand_sign(self.rs2_value) self.rs3_sign = self.get_operand_sign(self.rs3_value) self.rd_sign = self.get_operand_sign(self.rd_value) self.fs1_sign = self.get_operand_sign(self.fs1_value) self.fs2_sign = self.get_operand_sign(self.fs2_value) self.fs3_sign = self.get_operand_sign(self.fs3_value) self.fd_sign = self.get_operand_sign(self.fd_value) self.imm_sign = self.get_imm_sign(self.imm) self.rs1_special_value = self.get_operand_special_value(self.rs1_value) self.rd_special_value = self.get_operand_special_value(self.rd_value) self.rs2_special_value = self.get_operand_special_value(self.rs2_value) self.rs3_special_value = self.get_operand_special_value(self.rs3_value) if self.format.name not in ["R_FORMAT", "CR_FORMAT"]: self.imm_special_value = self.get_imm_special_val(self.imm) if self.category.name in ["COMPARE", "BRANCH"]: self.compare_result = self.get_compare_result() if self.category.name in ["LOAD", "STORE"]: self.mem_addr.set_val(self.rs1_value.get_val() + self.imm.get_val()) self.unaligned_mem_access = self.is_unaligned_mem_access() if self.unaligned_mem_access: logging.info("Unaligned: {}, mem_addr: {}".format( self.instr.name, self.mem_addr.get_val())) if self.category.name == "LOGICAL": self.logical_similarity = self.get_logical_similarity() if self.category.name == "BRANCH": self.branch_hit = self.is_branch_hit() if self.instr.name in ["DIV", "DIVU", "REM", "REMU", "DIVW", "DIVUW", "REMW", "REMUW"]: self.div_result = self.get_div_result() @staticmethod def get_operand_sign(operand): # TODO: Currently handled using string formatting as part select # isn't yet supported for global vsc variables operand_bin = format(operand.get_val(), '#0{}b'.format(rcs.XLEN + 2)) # "0b" is the prefix, so operand_bin[2] is the sign bit if operand_bin[2] == "0": return operand_sign_e["POSITIVE"] else: return operand_sign_e["NEGATIVE"] def is_unaligned_mem_access(self): if (self.instr.name in ["LWU", "LD", "SD", "C_LD", "C_SD"] and self.mem_addr.get_val() % 8 != 0): return 1 elif (self.instr.name in ["LW", "SW", "C_LW", "C_SW"] and self.mem_addr.get_val() % 4 != 0): return 1 elif (self.instr.name in ["LH", "LHU", "SH"] and self.mem_addr.get_val() % 2 != 0): return 1 return 0 @staticmethod def get_imm_sign(imm): # TODO: Currently handled using string formatting as part select # isn't yet supported for global vsc variables imm_bin = format(imm.get_val(), '#0{}b'.format(rcs.XLEN + 2)) # "0b" is the prefix, so imm_bin[2] is the sign bit if imm_bin[2] == "0": return operand_sign_e["POSITIVE"] else: return operand_sign_e["NEGATIVE"] def get_div_result(self): if self.rs2_value.get_val() == 0: return div_result_e["DIV_BY_ZERO"] elif (self.rs2_value.get_val() == 1 and self.rs1_value.get_val() == (1 << (rcs.XLEN - 1))): return div_result_e["DIV_OVERFLOW"] else: return div_result_e["DIV_NORMAL"] @staticmethod def get_operand_special_value(operand): if operand.get_val() == 0: return special_val_e["ZERO_VAL"] elif operand.get_val() == 1 << (rcs.XLEN - 1): return special_val_e["MIN_VAL"] elif operand.get_val() == 1 >> 1: return special_val_e["MAX_VAL"] else: return special_val_e["NORMAL_VAL"] def get_imm_special_val(self, imm): if imm.get_val() == 0: return special_val_e["ZERO_VAL"] elif self.format == riscv_instr_format_t.U_FORMAT: # unsigned immediate value max_val = vsc.int_t(32, (1 << self.imm_len) - 1) if imm.get_val() == 0: return special_val_e["MIN_VAL"] if imm.get_val() == max_val.get_val(): return special_val_e["MAX_VAL"] else: # signed immediate value max_val = vsc.int_t(32, (2 ** (self.imm_len - 1)) - 1) min_val = vsc.int_t(32, -2 ** (self.imm_len - 1)) if min_val.get_val() == imm.get_val(): return special_val_e["MIN_VAL"] if max_val.get_val() == imm.get_val(): return special_val_e["MAX_VAL"] return special_val_e["NORMAL_VAL"] def get_compare_result(self): val1 = vsc.int_t(rcs.XLEN, self.rs1_value.get_val()) val2 = vsc.int_t(rcs.XLEN, self.imm.get_val() if ( self.format == riscv_instr_format_t.I_FORMAT) else self.rs2_value.val) if val1.get_val() == val2.get_val(): return compare_result_e["EQUAL"] elif val1.get_val() < val2.get_val(): return compare_result_e["SMALLER"] else: return compare_result_e["LARGER"] def is_branch_hit(self): if self.instr.name == "BEQ": return int(self.rs1_value.get_val() == self.rs2_value.get_val()) elif self.instr.name == "C_BEQZ": return int(self.rs1_value.get_val() == 0) elif self.instr.name == "BNE": return int(self.rs1_value.get_val() != self.rs2_value.get_val()) elif self.instr.name == "C_BNEZ": return int(self.rs1_value.get_val() != 0) elif self.instr.name == "BLT" or self.instr.name == "BLTU": return int(self.rs1_value.get_val() < self.rs2_value.get_val()) elif self.instr.name == "BGE" or self.instr.name == "BGEU": return int(self.rs1_value.get_val() >= self.rs2_value.get_val()) else: logging.error("Unexpected instruction {}".format(self.instr.name)) def get_logical_similarity(self): val1 = vsc.int_t(rcs.XLEN, self.rs1_value.get_val()) val2 = vsc.int_t(rcs.XLEN, (self.imm.get_val() if self.format == riscv_instr_format_t.I_FORMAT else self.rs2_value.val)) temp = bin(val1.get_val() ^ val2.get_val()) bit_difference = len([[ones for ones in temp[2:] if ones == '1']]) if val1.get_val() == val2.get_val(): return logical_similarity_e["IDENTICAL"] elif bit_difference == 32: return logical_similarity_e["OPPOSITE"] elif bit_difference < 5: return logical_similarity_e["SIMILAR"] else: return logical_similarity_e["DIFFERENT"] def check_hazard_condition(self, pre_instr): '''TODO: There are cases where instruction actually has destination but ovpsim doesn't log it because of no change in its value. Hence, the result of the check_hazard_condition won't be accurate. Need to explicitly extract the destination register from the operands ''' if pre_instr.has_rd: if ((self.has_rs1 and (self.rs1 == pre_instr.rd)) or (self.has_rs2 and (self.rs2 == pre_instr.rd))): logging.info("pre_instr {}".format(pre_instr.instr.name)) self.gpr_hazard = hazard_e["RAW_HAZARD"] elif self.has_rd and (self.rd == pre_instr.rd): self.gpr_hazard = hazard_e["WAW_HAZARD"] elif (self.has_rd and ((pre_instr.has_rs1 and (pre_instr.rs1 == self.rd)) or (pre_instr.has_rs2 and (pre_instr.rs2 == self.rd)))): self.gpr_hazard = hazard_e["WAR_HAZARD"] else: self.gpr_hazard = hazard_e["NO_HAZARD"] if self.category == riscv_instr_category_t.LOAD: if (pre_instr.category == riscv_instr_category_t.STORE and (pre_instr.mem_addr.get_val() == self.mem_addr.get_val())): self.lsu_hazard = hazard_e["RAW_HAZARD"] else: self.lsu_hazard = hazard_e["NO_HAZARD"] if self.category == riscv_instr_category_t.STORE: if (pre_instr.category == riscv_instr_category_t.STORE and (pre_instr.mem_addr.get_val() == self.mem_addr.get_val())): self.lsu_hazard = hazard_e["WAW_HAZARD"] elif (pre_instr.category == riscv_instr_category_t.LOAD and (pre_instr.mem_addr.get_val() == self.mem_addr.get_val())): self.lsu_hazard = hazard_e["WAR_HAZARD"] else: self.lsu_hazard = hazard_e["NO_HAZARD"] # Hazard Condition check for RV32D and RV32F instructions if pre_instr.has_fd: if ((self.has_fs1 and (self.fs1 == pre_instr.fd)) or (self.has_fs2 and (self.fs2 == pre_instr.fd)) or (self.has_fs3 and (self.fs3 == pre_instr.fd))): self.gpr_hazard = hazard_e["RAW_HAZARD"] elif (self.has_fd and (self.fd == pre_instr.fd)): self.gpr_hazard = hazard_e["WAW_HAZARD"] elif (self.has_fd and ((pre_instr.has_fs1 and (pre_instr.fs1 == self.fd)) or (pre_instr.has_fs2 and (pre_instr.fs2 == self.fd)) or (pre_instr.has_fs3 and (pre_instr.fs3 == self.fd)))): self.gpr_hazard = hazard_e["WAR_HAZARD"] else: self.gpr_hazard = hazard_e["NO_HAZARD"] logging.debug("Pre PC/name: {}/{}, Cur PC/name: {}/{}, " "Hazard: {}/{}".format(pre_instr.pc.get_val(), pre_instr.instr.name, self.pc.get_val(), self.instr.name, self.gpr_hazard.name, self.lsu_hazard.name)) def get_instr_name(self): get_instr_name = self.instr.name for i in get_instr_name: if i == "_": get_instr_name = get_instr_name.replace(i, ".") return get_instr_name def update_src_regs(self, operands): if self.format.name in ["J_FORMAT", "U_FORMAT"]: # instr rd,imm assert len(operands) == 2 self.imm.set_val(get_val(operands[1])) elif self.format.name == "I_FORMAT": assert len(operands) == 3 if self.category.name == "LOAD": # load rd, imm(rs1) self.rs1 = self.get_gpr(operands[2]) self.rs1_value.set_val(self.get_gpr_state(operands[2])) self.imm.set_val(get_val(operands[1])) elif self.category.name == "CSR": # csrrwi rd, csr, imm self.imm.set_val(get_val(operands[2])) if operands[1].upper() in privileged_reg_t.__members__: self.csr.set_val( privileged_reg_t[operands[1].upper()].value) else: self.csr.set_val(get_val(operands[1])) else: # addi rd, rs1, imm self.rs1 = self.get_gpr(operands[1]) self.rs1_value.set_val(self.get_gpr_state(operands[1])) self.imm.set_val(get_val(operands[2])) elif self.format.name in ["S_FORMAT", "B_FORMAT"]: assert len(operands) == 3 if self.category.name == "STORE": self.rs2 = self.get_gpr(operands[0]) self.rs2_value.set_val(self.get_gpr_state(operands[0])) self.rs1 = self.get_gpr(operands[2]) self.rs1_value.set_val(self.get_gpr_state(operands[2])) self.imm.set_val(get_val(operands[1])) else: # bne rs1, rs2, imm self.rs1 = self.get_gpr(operands[0]) self.rs1_value.set_val(self.get_gpr_state(operands[0])) self.rs2 = self.get_gpr(operands[1]) self.rs2_value.set_val(self.get_gpr_state(operands[1])) self.imm.set_val(get_val(operands[2])) elif self.format.name == "R_FORMAT": if self.has_rs2 or self.category.name == "CSR": assert len(operands) == 3 else: assert len(operands) == 2 if self.category.name == "CSR": # csrrw rd, csr, rs1 if operands[1].upper() in privileged_reg_t.__members__: self.csr.set_val( privileged_reg_t[operands[1].upper()].value) else: self.csr.set_val(get_val(operands[1])) self.rs1 = self.get_gpr(operands[2]) self.rs1_value.set_val(self.get_gpr_state(operands[2])) else: # add rd, rs1, rs2 self.rs1 = self.get_gpr(operands[1]) self.rs1_value.set_val(self.get_gpr_state(operands[1])) if self.has_rs2: self.rs2 = self.get_gpr(operands[2]) self.rs2_value.set_val(self.get_gpr_state(operands[2])) elif self.format.name == "R4_FORMAT": assert len(operands) == 4 self.rs1 = self.get_gpr(operands[1]) self.rs1_value.set_val(self.get_gpr_state(operands[1])) self.rs2 = self.get_gpr(operands[2]) self.rs2_value.set_val(self.get_gpr_state(operands[2])) self.rs2 = self.get_gpr(operands[3]) self.rs2_value.set_val(self.get_gpr_state(operands[3])) elif self.format.name in ["CI_FORMAT", "CIW_FORMAT"]: if self.instr.name == "C_ADDI16SP": self.imm.set_val(get_val(operands[1])) self.rs1 = riscv_reg_t.SP self.rs1_value.set_val(self.get_gpr_state("sp")) elif self.instr.name == "C_ADDI4SPN": self.rs1 = riscv_reg_t.SP self.rs1_value.set_val(self.get_gpr_state("sp")) elif self.instr.name in ["C_LDSP", "C_LWSP", "C_LQSP"]: # c.ldsp rd, imm self.imm.set_val(get_val(operands[1])) self.rs1 = riscv_reg_t.SP self.rs1_value.set_val(self.get_gpr_state("sp")) else: # c.lui rd, imm self.imm.set_val(get_val(operands[1])) elif self.format.name == "CL_FORMAT": # c.lw rd, imm(rs1) self.imm.set_val(get_val(operands[1])) self.rs1 = self.get_gpr(operands[2]) self.rs1_value.set_val(self.get_gpr_state(operands[2])) elif self.format.name == "CS_FORMAT": # c.sw rs2,imm(rs1) self.rs2 = self.get_gpr(operands[0]) self.rs2_value.set_val(self.get_gpr_state(operands[0])) self.rs1 = self.get_gpr(operands[2]) self.rs1_value.set_val(self.get_gpr_state(operands[2])) self.imm.set_val(get_val(operands[1])) elif self.format.name == "CA_FORMAT": # c.and rd, rs2 (rs1 == rd) self.rs2 = self.get_gpr(operands[1]) self.rs2_value.set_val(self.get_gpr_state(operands[1])) self.rs1 = self.get_gpr(operands[0]) self.rs1_value.set_val(self.get_gpr_state(operands[0])) elif self.format.name == "CB_FORMAT": # c.beqz rs1, imm self.rs1 = self.get_gpr(operands[0]) self.rs1_value.set_val(self.get_gpr_state(operands[0])) self.imm.set_val(get_val(operands[1])) elif self.format.name == "CSS_FORMAT": # c.swsp rs2, imm self.rs2 = self.get_gpr(operands[0]) self.rs2_value.set_val(self.get_gpr_state(operands[0])) self.rs1 = riscv_reg_t.SP self.rs1_value.set_val(self.get_gpr_state("sp")) self.imm.set_val(get_val(operands[1])) elif self.format.name == "CR_FORMAT": if self.instr.name in ["C_JR", "C_JALR"]: # c.jalr rs1 self.rs1 = self.get_gpr(operands[0]) self.rs1_value.set_val(self.get_gpr_state(operands[0])) else: # c.add rd, rs2 self.rs2 = self.get_gpr(operands[1]) self.rs2_value.set_val(self.get_gpr_state(operands[1])) elif self.format.name == "CJ_FORMAT": # c.j imm self.imm.set_val(get_val(operands[0])) else: logging.error("Unsupported format {}".format(self.format.name)) def update_dst_regs(self, reg_name, val_str): riscv_cov_instr.gpr_state[reg_name] = get_val(val_str, hexa=1) self.rd = self.get_gpr(reg_name) self.rd_value.set_val(self.get_gpr_state(reg_name)) @staticmethod def get_gpr(reg_name): reg_name = reg_name.upper() if reg_name not in riscv_reg_t.__members__: logging.error("Cannot convert {} to GPR".format(reg_name)) return riscv_reg_t[reg_name] @staticmethod def get_gpr_state(name): if name in ["zero", "x0"]: return 0 elif name in riscv_cov_instr.gpr_state: return riscv_cov_instr.gpr_state[name] else: logging.warning( "Cannot find GPR state: {}; initialize to 0".format(name)) if name.upper() in riscv_reg_t.__members__: riscv_cov_instr.gpr_state[name] = 0 return 0
42.604061
91
0.569959
import vsc import logging from importlib import import_module from enum import IntEnum, auto from pygen_src.riscv_instr_pkg import * from pygen_src.riscv_instr_gen_config import cfg rcs = import_module("pygen_src.target." + cfg.argv.target + ".riscv_core_setting") class operand_sign_e(IntEnum): POSITIVE = 0 NEGATIVE = auto() class div_result_e(IntEnum): DIV_NORMAL = 0 DIV_BY_ZERO = auto() DIV_OVERFLOW = auto() class div_result_ex_overflow_e(IntEnum): DIV_NORMAL = 0 DIV_BY_ZERO = auto() class compare_result_e(IntEnum): EQUAL = 0 LARGER = auto() SMALLER = auto() class logical_similarity_e(IntEnum): IDENTICAL = 0 OPPOSITE = auto() SIMILAR = auto() DIFFERENT = auto() class special_val_e(IntEnum): NORMAL_VAL = 0 MIN_VAL = auto() MAX_VAL = auto() ZERO_VAL = auto() class riscv_cov_instr: gpr_state = {} def __init__(self): self.pc = vsc.bit_t(rcs.XLEN) self.instr = None e = "None" rcs.XLEN) self.rs2_value = vsc.bit_t(rcs.XLEN) self.rs3_value = vsc.bit_t(rcs.XLEN) self.rd_value = vsc.bit_t(rcs.XLEN) self.fs1_value = vsc.bit_t(rcs.XLEN) self.fs2_value = vsc.bit_t(rcs.XLEN) self.fs3_value = vsc.bit_t(rcs.XLEN) self.fd_value = vsc.bit_t(rcs.XLEN) self.mem_addr = vsc.int_t(rcs.XLEN) self.unaligned_pc = 0 self.unaligned_mem_access = 0 self.compressed = 0 self.branch_hit = 0 self.div_result = None self.rs1_sign = 0 self.rs2_sign = 0 self.rs3_sign = 0 self.fs1_sign = 0 self.fs2_sign = 0 self.fs3_sign = 0 self.imm_sign = 0 self.rd_sign = 0 self.fd_sign = 0 self.gpr_hazard = hazard_e.NO_HAZARD self.lsu_hazard = hazard_e.NO_HAZARD self.rs1_special_value = 0 self.rs2_special_value = 0 self.rs3_special_value = 0 self.rd_special_value = 0 self.imm_special_value = 0 self.compare_result = 0 self.logical_similarity = 0 self.group = None self.format = None self.category = None self.imm_type = None self.csr = vsc.bit_t(12) self.rs2 = 0 self.rs1 = 0 self.rd = 0 self.imm = vsc.int_t(32) self.has_rs1 = 1 self.has_rs2 = 1 self.has_rd = 1 self.has_imm = 1 self.imm_len = 0 self.has_fs1 = 1 self.has_fs2 = 1 self.has_fs3 = 0 self.has_fd = 1 self.fs1 = 0 self.fs2 = 0 self.fs3 = 0 self.fd = 0 def assign_attributes(self): attr_list = get_attr_list(self.instr) self.format = attr_list[0] self.category = attr_list[1] self.group = attr_list[2] self.imm_type = imm_t.IMM if len(attr_list) > 3: self.imm_type = attr_list[3] self.set_imm_len() self.set_mode() if self.group.name in ["RV32D", "RV32F"]: self.set_fd_mode() def set_imm_len(self): if self.format.name in ["U_FORMAT", "J_FORMAT"]: self.imm_len = 20 elif self.format.name in ["I_FORMAT", "S_FORMAT", "B_FORMAT"]: if self.imm_type.name == "UIMM": self.imm_len = 5 else: self.imm_len = 12 def set_mode(self): if self.format.name == "R_FORMAT": self.has_imm = 0 if self.format.name == "I_FORMAT": self.has_rs2 = 0 if self.format.name in ["S_FORMAT", "B_FORMAT"]: self.has_rd = 0 if self.format.name in ["U_FORMAT", "J_FORMAT"]: self.has_rs1 = 0 self.has_rs2 = 0 if self.category.name == "CSR": self.has_rs2 = 0 if self.format.name == "I_FORMAT": self.has_rs1 = 0 def set_fd_mode(self): if self.format == riscv_instr_format_t.I_FORMAT: self.has_fs2 = 0 if self.category == riscv_instr_category_t.LOAD: self.has_imm = 1 elif self.instr.name in ['FMV_X_W', 'FMV_X_D', 'FCVT_W_S', 'FCVT_WU_S', 'FCVT_L_S', 'FCVT_LU_S', 'FCVT_L_D', 'FCVT_LU_D', 'FCVT_LU_S', 'FCVT_W_D', 'FCVT_WU_D']: self.has_fd = 0 self.has_rd = 1 elif self.instr.name in ['FMV_W_X', 'FMV_D_X', 'FCVT_S_W', 'FCVT_S_WU', 'FCVT_S_L', 'FCVT_D_L', 'FCVT_S_LU', 'FCVT_D_W', 'FCVT_D_LU', 'FCVT_D_WU']: self.has_rs1 = 1 self.has_fs1 = 0 elif self.format == riscv_instr_format_t.S_FORMAT: self.has_imm = 1 self.has_rs1 = 1 self.has_fs1 = 0 self.has_fs3 = 0 elif self.format == riscv_instr_format_t.R_FORMAT: if self.category == riscv_instr_category_t.COMPARE: self.has_rd = 1 self.has_fd = 0 elif self.instr.name in ['FCLASS_S', 'FCLASS_D']: self.has_rd = 1 self.has_fd = 0 self.has_fs2 = 0 elif self.format == riscv_instr_format_t.R4_FORMAT: self.has_fs3 = 1 elif self.format == riscv_instr_format_t.CL_FORMAT: self.has_imm = 1 self.has_rs1 = 1 self.has_fs1 = 0 self.has_fs2 = 0 elif self.format == riscv_instr_format_t.CS_FORMAT: self.has_imm = 1 self.has_rs1 = 1 self.has_fs1 = 0 self.has_fd = 0 else: logging.info("Unsupported format {}".format(self.format.name)) def pre_sample(self): unaligned_pc = self.pc.get_val() % 4 != 0 self.rs1_sign = self.get_operand_sign(self.rs1_value) self.rs2_sign = self.get_operand_sign(self.rs2_value) self.rs3_sign = self.get_operand_sign(self.rs3_value) self.rd_sign = self.get_operand_sign(self.rd_value) self.fs1_sign = self.get_operand_sign(self.fs1_value) self.fs2_sign = self.get_operand_sign(self.fs2_value) self.fs3_sign = self.get_operand_sign(self.fs3_value) self.fd_sign = self.get_operand_sign(self.fd_value) self.imm_sign = self.get_imm_sign(self.imm) self.rs1_special_value = self.get_operand_special_value(self.rs1_value) self.rd_special_value = self.get_operand_special_value(self.rd_value) self.rs2_special_value = self.get_operand_special_value(self.rs2_value) self.rs3_special_value = self.get_operand_special_value(self.rs3_value) if self.format.name not in ["R_FORMAT", "CR_FORMAT"]: self.imm_special_value = self.get_imm_special_val(self.imm) if self.category.name in ["COMPARE", "BRANCH"]: self.compare_result = self.get_compare_result() if self.category.name in ["LOAD", "STORE"]: self.mem_addr.set_val(self.rs1_value.get_val() + self.imm.get_val()) self.unaligned_mem_access = self.is_unaligned_mem_access() if self.unaligned_mem_access: logging.info("Unaligned: {}, mem_addr: {}".format( self.instr.name, self.mem_addr.get_val())) if self.category.name == "LOGICAL": self.logical_similarity = self.get_logical_similarity() if self.category.name == "BRANCH": self.branch_hit = self.is_branch_hit() if self.instr.name in ["DIV", "DIVU", "REM", "REMU", "DIVW", "DIVUW", "REMW", "REMUW"]: self.div_result = self.get_div_result() @staticmethod def get_operand_sign(operand): operand_bin = format(operand.get_val(), ' # "0b" is the prefix, so operand_bin[2] is the sign bit if operand_bin[2] == "0": return operand_sign_e["POSITIVE"] else: return operand_sign_e["NEGATIVE"] def is_unaligned_mem_access(self): if (self.instr.name in ["LWU", "LD", "SD", "C_LD", "C_SD"] and self.mem_addr.get_val() % 8 != 0): return 1 elif (self.instr.name in ["LW", "SW", "C_LW", "C_SW"] and self.mem_addr.get_val() % 4 != 0): return 1 elif (self.instr.name in ["LH", "LHU", "SH"] and self.mem_addr.get_val() % 2 != 0): return 1 return 0 @staticmethod def get_imm_sign(imm): # TODO: Currently handled using string formatting as part select # isn't yet supported for global vsc variables imm_bin = format(imm.get_val(), '#0{}b'.format(rcs.XLEN + 2)) if imm_bin[2] == "0": return operand_sign_e["POSITIVE"] else: return operand_sign_e["NEGATIVE"] def get_div_result(self): if self.rs2_value.get_val() == 0: return div_result_e["DIV_BY_ZERO"] elif (self.rs2_value.get_val() == 1 and self.rs1_value.get_val() == (1 << (rcs.XLEN - 1))): return div_result_e["DIV_OVERFLOW"] else: return div_result_e["DIV_NORMAL"] @staticmethod def get_operand_special_value(operand): if operand.get_val() == 0: return special_val_e["ZERO_VAL"] elif operand.get_val() == 1 << (rcs.XLEN - 1): return special_val_e["MIN_VAL"] elif operand.get_val() == 1 >> 1: return special_val_e["MAX_VAL"] else: return special_val_e["NORMAL_VAL"] def get_imm_special_val(self, imm): if imm.get_val() == 0: return special_val_e["ZERO_VAL"] elif self.format == riscv_instr_format_t.U_FORMAT: max_val = vsc.int_t(32, (1 << self.imm_len) - 1) if imm.get_val() == 0: return special_val_e["MIN_VAL"] if imm.get_val() == max_val.get_val(): return special_val_e["MAX_VAL"] else: max_val = vsc.int_t(32, (2 ** (self.imm_len - 1)) - 1) min_val = vsc.int_t(32, -2 ** (self.imm_len - 1)) if min_val.get_val() == imm.get_val(): return special_val_e["MIN_VAL"] if max_val.get_val() == imm.get_val(): return special_val_e["MAX_VAL"] return special_val_e["NORMAL_VAL"] def get_compare_result(self): val1 = vsc.int_t(rcs.XLEN, self.rs1_value.get_val()) val2 = vsc.int_t(rcs.XLEN, self.imm.get_val() if ( self.format == riscv_instr_format_t.I_FORMAT) else self.rs2_value.val) if val1.get_val() == val2.get_val(): return compare_result_e["EQUAL"] elif val1.get_val() < val2.get_val(): return compare_result_e["SMALLER"] else: return compare_result_e["LARGER"] def is_branch_hit(self): if self.instr.name == "BEQ": return int(self.rs1_value.get_val() == self.rs2_value.get_val()) elif self.instr.name == "C_BEQZ": return int(self.rs1_value.get_val() == 0) elif self.instr.name == "BNE": return int(self.rs1_value.get_val() != self.rs2_value.get_val()) elif self.instr.name == "C_BNEZ": return int(self.rs1_value.get_val() != 0) elif self.instr.name == "BLT" or self.instr.name == "BLTU": return int(self.rs1_value.get_val() < self.rs2_value.get_val()) elif self.instr.name == "BGE" or self.instr.name == "BGEU": return int(self.rs1_value.get_val() >= self.rs2_value.get_val()) else: logging.error("Unexpected instruction {}".format(self.instr.name)) def get_logical_similarity(self): val1 = vsc.int_t(rcs.XLEN, self.rs1_value.get_val()) val2 = vsc.int_t(rcs.XLEN, (self.imm.get_val() if self.format == riscv_instr_format_t.I_FORMAT else self.rs2_value.val)) temp = bin(val1.get_val() ^ val2.get_val()) bit_difference = len([[ones for ones in temp[2:] if ones == '1']]) if val1.get_val() == val2.get_val(): return logical_similarity_e["IDENTICAL"] elif bit_difference == 32: return logical_similarity_e["OPPOSITE"] elif bit_difference < 5: return logical_similarity_e["SIMILAR"] else: return logical_similarity_e["DIFFERENT"] def check_hazard_condition(self, pre_instr): if pre_instr.has_rd: if ((self.has_rs1 and (self.rs1 == pre_instr.rd)) or (self.has_rs2 and (self.rs2 == pre_instr.rd))): logging.info("pre_instr {}".format(pre_instr.instr.name)) self.gpr_hazard = hazard_e["RAW_HAZARD"] elif self.has_rd and (self.rd == pre_instr.rd): self.gpr_hazard = hazard_e["WAW_HAZARD"] elif (self.has_rd and ((pre_instr.has_rs1 and (pre_instr.rs1 == self.rd)) or (pre_instr.has_rs2 and (pre_instr.rs2 == self.rd)))): self.gpr_hazard = hazard_e["WAR_HAZARD"] else: self.gpr_hazard = hazard_e["NO_HAZARD"] if self.category == riscv_instr_category_t.LOAD: if (pre_instr.category == riscv_instr_category_t.STORE and (pre_instr.mem_addr.get_val() == self.mem_addr.get_val())): self.lsu_hazard = hazard_e["RAW_HAZARD"] else: self.lsu_hazard = hazard_e["NO_HAZARD"] if self.category == riscv_instr_category_t.STORE: if (pre_instr.category == riscv_instr_category_t.STORE and (pre_instr.mem_addr.get_val() == self.mem_addr.get_val())): self.lsu_hazard = hazard_e["WAW_HAZARD"] elif (pre_instr.category == riscv_instr_category_t.LOAD and (pre_instr.mem_addr.get_val() == self.mem_addr.get_val())): self.lsu_hazard = hazard_e["WAR_HAZARD"] else: self.lsu_hazard = hazard_e["NO_HAZARD"] if pre_instr.has_fd: if ((self.has_fs1 and (self.fs1 == pre_instr.fd)) or (self.has_fs2 and (self.fs2 == pre_instr.fd)) or (self.has_fs3 and (self.fs3 == pre_instr.fd))): self.gpr_hazard = hazard_e["RAW_HAZARD"] elif (self.has_fd and (self.fd == pre_instr.fd)): self.gpr_hazard = hazard_e["WAW_HAZARD"] elif (self.has_fd and ((pre_instr.has_fs1 and (pre_instr.fs1 == self.fd)) or (pre_instr.has_fs2 and (pre_instr.fs2 == self.fd)) or (pre_instr.has_fs3 and (pre_instr.fs3 == self.fd)))): self.gpr_hazard = hazard_e["WAR_HAZARD"] else: self.gpr_hazard = hazard_e["NO_HAZARD"] logging.debug("Pre PC/name: {}/{}, Cur PC/name: {}/{}, " "Hazard: {}/{}".format(pre_instr.pc.get_val(), pre_instr.instr.name, self.pc.get_val(), self.instr.name, self.gpr_hazard.name, self.lsu_hazard.name)) def get_instr_name(self): get_instr_name = self.instr.name for i in get_instr_name: if i == "_": get_instr_name = get_instr_name.replace(i, ".") return get_instr_name def update_src_regs(self, operands): if self.format.name in ["J_FORMAT", "U_FORMAT"]: assert len(operands) == 2 self.imm.set_val(get_val(operands[1])) elif self.format.name == "I_FORMAT": assert len(operands) == 3 if self.category.name == "LOAD": self.rs1 = self.get_gpr(operands[2]) self.rs1_value.set_val(self.get_gpr_state(operands[2])) self.imm.set_val(get_val(operands[1])) elif self.category.name == "CSR": self.imm.set_val(get_val(operands[2])) if operands[1].upper() in privileged_reg_t.__members__: self.csr.set_val( privileged_reg_t[operands[1].upper()].value) else: self.csr.set_val(get_val(operands[1])) else: self.rs1 = self.get_gpr(operands[1]) self.rs1_value.set_val(self.get_gpr_state(operands[1])) self.imm.set_val(get_val(operands[2])) elif self.format.name in ["S_FORMAT", "B_FORMAT"]: assert len(operands) == 3 if self.category.name == "STORE": self.rs2 = self.get_gpr(operands[0]) self.rs2_value.set_val(self.get_gpr_state(operands[0])) self.rs1 = self.get_gpr(operands[2]) self.rs1_value.set_val(self.get_gpr_state(operands[2])) self.imm.set_val(get_val(operands[1])) else: self.rs1 = self.get_gpr(operands[0]) self.rs1_value.set_val(self.get_gpr_state(operands[0])) self.rs2 = self.get_gpr(operands[1]) self.rs2_value.set_val(self.get_gpr_state(operands[1])) self.imm.set_val(get_val(operands[2])) elif self.format.name == "R_FORMAT": if self.has_rs2 or self.category.name == "CSR": assert len(operands) == 3 else: assert len(operands) == 2 if self.category.name == "CSR": if operands[1].upper() in privileged_reg_t.__members__: self.csr.set_val( privileged_reg_t[operands[1].upper()].value) else: self.csr.set_val(get_val(operands[1])) self.rs1 = self.get_gpr(operands[2]) self.rs1_value.set_val(self.get_gpr_state(operands[2])) else: self.rs1 = self.get_gpr(operands[1]) self.rs1_value.set_val(self.get_gpr_state(operands[1])) if self.has_rs2: self.rs2 = self.get_gpr(operands[2]) self.rs2_value.set_val(self.get_gpr_state(operands[2])) elif self.format.name == "R4_FORMAT": assert len(operands) == 4 self.rs1 = self.get_gpr(operands[1]) self.rs1_value.set_val(self.get_gpr_state(operands[1])) self.rs2 = self.get_gpr(operands[2]) self.rs2_value.set_val(self.get_gpr_state(operands[2])) self.rs2 = self.get_gpr(operands[3]) self.rs2_value.set_val(self.get_gpr_state(operands[3])) elif self.format.name in ["CI_FORMAT", "CIW_FORMAT"]: if self.instr.name == "C_ADDI16SP": self.imm.set_val(get_val(operands[1])) self.rs1 = riscv_reg_t.SP self.rs1_value.set_val(self.get_gpr_state("sp")) elif self.instr.name == "C_ADDI4SPN": self.rs1 = riscv_reg_t.SP self.rs1_value.set_val(self.get_gpr_state("sp")) elif self.instr.name in ["C_LDSP", "C_LWSP", "C_LQSP"]: self.imm.set_val(get_val(operands[1])) self.rs1 = riscv_reg_t.SP self.rs1_value.set_val(self.get_gpr_state("sp")) else: self.imm.set_val(get_val(operands[1])) elif self.format.name == "CL_FORMAT": self.imm.set_val(get_val(operands[1])) self.rs1 = self.get_gpr(operands[2]) self.rs1_value.set_val(self.get_gpr_state(operands[2])) elif self.format.name == "CS_FORMAT": self.rs2 = self.get_gpr(operands[0]) self.rs2_value.set_val(self.get_gpr_state(operands[0])) self.rs1 = self.get_gpr(operands[2]) self.rs1_value.set_val(self.get_gpr_state(operands[2])) self.imm.set_val(get_val(operands[1])) elif self.format.name == "CA_FORMAT": self.rs2 = self.get_gpr(operands[1]) self.rs2_value.set_val(self.get_gpr_state(operands[1])) self.rs1 = self.get_gpr(operands[0]) self.rs1_value.set_val(self.get_gpr_state(operands[0])) elif self.format.name == "CB_FORMAT": self.rs1 = self.get_gpr(operands[0]) self.rs1_value.set_val(self.get_gpr_state(operands[0])) self.imm.set_val(get_val(operands[1])) elif self.format.name == "CSS_FORMAT": self.rs2 = self.get_gpr(operands[0]) self.rs2_value.set_val(self.get_gpr_state(operands[0])) self.rs1 = riscv_reg_t.SP self.rs1_value.set_val(self.get_gpr_state("sp")) self.imm.set_val(get_val(operands[1])) elif self.format.name == "CR_FORMAT": if self.instr.name in ["C_JR", "C_JALR"]: self.rs1 = self.get_gpr(operands[0]) self.rs1_value.set_val(self.get_gpr_state(operands[0])) else: self.rs2 = self.get_gpr(operands[1]) self.rs2_value.set_val(self.get_gpr_state(operands[1])) elif self.format.name == "CJ_FORMAT": self.imm.set_val(get_val(operands[0])) else: logging.error("Unsupported format {}".format(self.format.name)) def update_dst_regs(self, reg_name, val_str): riscv_cov_instr.gpr_state[reg_name] = get_val(val_str, hexa=1) self.rd = self.get_gpr(reg_name) self.rd_value.set_val(self.get_gpr_state(reg_name)) @staticmethod def get_gpr(reg_name): reg_name = reg_name.upper() if reg_name not in riscv_reg_t.__members__: logging.error("Cannot convert {} to GPR".format(reg_name)) return riscv_reg_t[reg_name] @staticmethod def get_gpr_state(name): if name in ["zero", "x0"]: return 0 elif name in riscv_cov_instr.gpr_state: return riscv_cov_instr.gpr_state[name] else: logging.warning( "Cannot find GPR state: {}; initialize to 0".format(name)) if name.upper() in riscv_reg_t.__members__: riscv_cov_instr.gpr_state[name] = 0 return 0
true
true
1c4425361079a914aa13fb002ab4d66acd3e4a30
104
py
Python
poetry/__main__.py
uda/poetry
30e3d7e33c20cbe2af8eda06e0db4888275caaa1
[ "MIT" ]
12,347
2019-12-12T07:07:32.000Z
2022-03-31T21:08:50.000Z
poetry/__main__.py
uda/poetry
30e3d7e33c20cbe2af8eda06e0db4888275caaa1
[ "MIT" ]
3,483
2019-12-11T20:20:20.000Z
2022-03-31T23:18:18.000Z
poetry/__main__.py
uda/poetry
30e3d7e33c20cbe2af8eda06e0db4888275caaa1
[ "MIT" ]
1,399
2019-12-12T12:27:46.000Z
2022-03-31T09:12:53.000Z
import sys if __name__ == "__main__": from .console.application import main sys.exit(main())
13
41
0.673077
import sys if __name__ == "__main__": from .console.application import main sys.exit(main())
true
true
1c44263ae8800ae610a0ea2b221f9c8a0ffd43f6
911
py
Python
handlers/InputHandler.py
sachio222/socketchat_v3
cd62b892842f6708055359fa2384269038f425dc
[ "MIT" ]
1
2020-11-30T03:54:35.000Z
2020-11-30T03:54:35.000Z
handlers/InputHandler.py
sachio222/socketchat_v3
cd62b892842f6708055359fa2384269038f425dc
[ "MIT" ]
null
null
null
handlers/InputHandler.py
sachio222/socketchat_v3
cd62b892842f6708055359fa2384269038f425dc
[ "MIT" ]
null
null
null
import socket from sys import prefix from chatutils import utils import config.filepaths as paths from handlers import EncryptionHandler, ClientMsgHandler prefixes = utils.JSONLoader(paths.prefix_path) def dispatch(sock: socket, msg: str) -> bytes: """Splits input data between commands and transmissions. Message type - (prefix) 1. Input command - ("/") for control, not messaging. 2. Default - Sent as encrypted message. """ if len(msg): if msg[0] == '/': # Check for command msg = ClientMsgHandler.command_router(sock=sock, msg=msg) msg_type = None else: msg = EncryptionHandler.message_router(msg) msg_type = prefixes.dict["client"]["chat"]["msg"] else: # Send new line on enter press. msg = b"\n" msg_type = prefixes.dict["client"]["chat"]["newLine"] return msg, msg_type
30.366667
69
0.637761
import socket from sys import prefix from chatutils import utils import config.filepaths as paths from handlers import EncryptionHandler, ClientMsgHandler prefixes = utils.JSONLoader(paths.prefix_path) def dispatch(sock: socket, msg: str) -> bytes: if len(msg): if msg[0] == '/': msg = ClientMsgHandler.command_router(sock=sock, msg=msg) msg_type = None else: msg = EncryptionHandler.message_router(msg) msg_type = prefixes.dict["client"]["chat"]["msg"] else: msg = b"\n" msg_type = prefixes.dict["client"]["chat"]["newLine"] return msg, msg_type
true
true
1c4427a91f89d5195c34bc012f9a3d3cfc65f9b3
3,355
py
Python
Octopus/app/__init__.py
zhnlk/octopus
4deb502eebc655ed512273a330b885d77bb8e32a
[ "MIT" ]
null
null
null
Octopus/app/__init__.py
zhnlk/octopus
4deb502eebc655ed512273a330b885d77bb8e32a
[ "MIT" ]
null
null
null
Octopus/app/__init__.py
zhnlk/octopus
4deb502eebc655ed512273a330b885d77bb8e32a
[ "MIT" ]
null
null
null
# Import flask and template operators import logging import traceback import apscheduler from apscheduler.schedulers.background import BackgroundScheduler from flask import Flask from flask import jsonify from flask_basicauth import BasicAuth from flask_restful import Api from flask_restful_swagger import swagger from flask_sqlalchemy import SQLAlchemy from werkzeug.exceptions import HTTPException import Octopus from Octopus import config # Define the WSGI application object app = Flask(__name__) # Configurations app.config.from_object(config) # Logging log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) app.logger.setLevel(app.config.get('LOG_LEVEL', "INFO")) app.logger.addHandler(handler) # swagger api = swagger.docs(Api(app), apiVersion=Octopus.__version__, api_spec_url="/api", description='Octopus') # Define the database object which is imported # by modules and controllers db = SQLAlchemy(app, session_options=dict(autocommit=False, autoflush=True)) @app.teardown_request def teardown_request(exception): if exception: db.session.rollback() db.session.remove() db.session.remove() # Define apscheduler scheduler = BackgroundScheduler() class Base(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) date_created = db.Column(db.DateTime, default=db.func.current_timestamp()) date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp()) # Sample HTTP error handling # @app.errorhandler(404) # def not_found(error): # abort(404) @app.errorhandler(Exception) def handle_error(e): code = 500 if isinstance(e, HTTPException): code = e.code app.logger.error(traceback.print_exc()) return jsonify({ 'code': code, 'success': False, 'msg': str(e), 'data': None }) # Build the database: from Octopus.app.spider.model import * def init_database(): db.init_app(app) db.create_all() # regist spider service proxy from Octopus.app.proxy.spiderctrl import SpiderAgent from Octopus.app.proxy.contrib.scrapy import ScrapydProxy agent = SpiderAgent() def regist_server(): if app.config.get('SERVER_TYPE') == 'scrapyd': for server in app.config.get("SERVERS"): agent.regist(ScrapydProxy(server)) from Octopus.app.spider.controller import api_spider_bp # Register blueprint(s) app.register_blueprint(api_spider_bp) # start sync job status scheduler from Octopus.app.schedulers.common import sync_job_execution_status_job, sync_spiders, \ reload_runnable_spider_job_execution scheduler.add_job(sync_job_execution_status_job, 'interval', seconds=5, id='sys_sync_status') scheduler.add_job(sync_spiders, 'interval', seconds=10, id='sys_sync_spiders') scheduler.add_job(reload_runnable_spider_job_execution, 'interval', seconds=30, id='sys_reload_job') def start_scheduler(): scheduler.start() def init_basic_auth(): if not app.config.get('NO_AUTH'): basic_auth = BasicAuth(app) def initialize(): init_database() regist_server() start_scheduler() init_basic_auth()
25.807692
100
0.739493
import logging import traceback import apscheduler from apscheduler.schedulers.background import BackgroundScheduler from flask import Flask from flask import jsonify from flask_basicauth import BasicAuth from flask_restful import Api from flask_restful_swagger import swagger from flask_sqlalchemy import SQLAlchemy from werkzeug.exceptions import HTTPException import Octopus from Octopus import config app = Flask(__name__) app.config.from_object(config) log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) app.logger.setLevel(app.config.get('LOG_LEVEL', "INFO")) app.logger.addHandler(handler) api = swagger.docs(Api(app), apiVersion=Octopus.__version__, api_spec_url="/api", description='Octopus') db = SQLAlchemy(app, session_options=dict(autocommit=False, autoflush=True)) @app.teardown_request def teardown_request(exception): if exception: db.session.rollback() db.session.remove() db.session.remove() scheduler = BackgroundScheduler() class Base(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) date_created = db.Column(db.DateTime, default=db.func.current_timestamp()) date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp()) @app.errorhandler(Exception) def handle_error(e): code = 500 if isinstance(e, HTTPException): code = e.code app.logger.error(traceback.print_exc()) return jsonify({ 'code': code, 'success': False, 'msg': str(e), 'data': None }) from Octopus.app.spider.model import * def init_database(): db.init_app(app) db.create_all() from Octopus.app.proxy.spiderctrl import SpiderAgent from Octopus.app.proxy.contrib.scrapy import ScrapydProxy agent = SpiderAgent() def regist_server(): if app.config.get('SERVER_TYPE') == 'scrapyd': for server in app.config.get("SERVERS"): agent.regist(ScrapydProxy(server)) from Octopus.app.spider.controller import api_spider_bp app.register_blueprint(api_spider_bp) from Octopus.app.schedulers.common import sync_job_execution_status_job, sync_spiders, \ reload_runnable_spider_job_execution scheduler.add_job(sync_job_execution_status_job, 'interval', seconds=5, id='sys_sync_status') scheduler.add_job(sync_spiders, 'interval', seconds=10, id='sys_sync_spiders') scheduler.add_job(reload_runnable_spider_job_execution, 'interval', seconds=30, id='sys_reload_job') def start_scheduler(): scheduler.start() def init_basic_auth(): if not app.config.get('NO_AUTH'): basic_auth = BasicAuth(app) def initialize(): init_database() regist_server() start_scheduler() init_basic_auth()
true
true
1c4427b25aca05f214bd3202fd7bba4c40a1e7a0
87,751
py
Python
typhon/plots/cm/_cmocean.py
tmieslinger/typhon
588539e5c4831ee18753d7ead5b2f2736e922bb1
[ "MIT" ]
53
2017-09-19T06:40:37.000Z
2022-03-21T07:59:30.000Z
typhon/plots/cm/_cmocean.py
tmieslinger/typhon
588539e5c4831ee18753d7ead5b2f2736e922bb1
[ "MIT" ]
96
2017-09-18T12:01:42.000Z
2021-12-17T13:54:45.000Z
typhon/plots/cm/_cmocean.py
tmieslinger/typhon
588539e5c4831ee18753d7ead5b2f2736e922bb1
[ "MIT" ]
32
2017-09-07T09:09:21.000Z
2021-10-01T03:54:23.000Z
# -*- coding: utf-8 -*- """ It is a subset of the cmocean package [0] provided by Kristen M. Thyng. The MIT License (MIT) Copyright (c) 2015 Kristen M. Thyng 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, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following 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 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. [0] http://matplotlib.org/cmocean/ """ _density_data = [ [0.90220216, 0.94417980, 0.94380273], [0.89544454, 0.94095789, 0.94106488], [0.88868558, 0.93774038, 0.93840987], [0.88192751, 0.93452625, 0.93583728], [0.87517248, 0.93131455, 0.93334654], [0.86842255, 0.92810438, 0.93093690], [0.86167970, 0.92489490, 0.92860749], [0.85494584, 0.92168533, 0.92635732], [0.84822279, 0.91847494, 0.92418529], [0.84151229, 0.91526306, 0.92209023], [0.83481598, 0.91204906, 0.92007088], [0.82813543, 0.90883237, 0.91812595], [0.82147215, 0.90561245, 0.91625407], [0.81482754, 0.90238881, 0.91445386], [0.80820295, 0.89916100, 0.91272391], [0.80159965, 0.89592859, 0.91106281], [0.79501887, 0.89269119, 0.90946910], [0.78846179, 0.88944845, 0.90794134], [0.78192947, 0.88620003, 0.90647814], [0.77542295, 0.88294564, 0.90507810], [0.76894320, 0.87968498, 0.90373988], [0.76249117, 0.87641781, 0.90246212], [0.75606778, 0.87314387, 0.90124351], [0.74967389, 0.86986292, 0.90008279], [0.74331039, 0.86657473, 0.89897869], [0.73697811, 0.86327910, 0.89793000], [0.73067788, 0.85997580, 0.89693553], [0.72441053, 0.85666464, 0.89599414], [0.71817690, 0.85334541, 0.89510469], [0.71197782, 0.85001791, 0.89426610], [0.70581423, 0.84668191, 0.89347718], [0.69968688, 0.84333724, 0.89273702], [0.69359663, 0.83998369, 0.89204464], [0.68754438, 0.83662105, 0.89139904], [0.68153106, 0.83324911, 0.89079928], [0.67555762, 0.82986764, 0.89024441], [0.66962506, 0.82647642, 0.88973352], [0.66373440, 0.82307522, 0.88926568], [0.65788673, 0.81966379, 0.88884001], [0.65208315, 0.81624189, 0.88845562], [0.64632485, 0.81280925, 0.88811162], [0.64061303, 0.80936562, 0.88780715], [0.63494897, 0.80591071, 0.88754133], [0.62933401, 0.80244424, 0.88731328], [0.62376953, 0.79896592, 0.88712212], [0.61825699, 0.79547544, 0.88696697], [0.61279785, 0.79197249, 0.88684700], [0.60739371, 0.78845676, 0.88676131], [0.60204624, 0.78492789, 0.88670892], [0.59675713, 0.78138555, 0.88668891], [0.59152819, 0.77782940, 0.88670031], [0.58636126, 0.77425906, 0.88674212], [0.58125826, 0.77067417, 0.88681333], [0.57622118, 0.76707435, 0.88691290], [0.57125208, 0.76345922, 0.88703974], [0.56635309, 0.75982839, 0.88719273], [0.56152638, 0.75618144, 0.88737072], [0.55677422, 0.75251799, 0.88757251], [0.55209890, 0.74883762, 0.88779685], [0.54750281, 0.74513991, 0.88804246], [0.54298830, 0.74142444, 0.88830811], [0.53855780, 0.73769077, 0.88859267], [0.53421391, 0.73393850, 0.88889434], [0.52995915, 0.73016720, 0.88921160], [0.52579610, 0.72637645, 0.88954287], [0.52172732, 0.72256583, 0.88988650], [0.51775541, 0.71873493, 0.89024078], [0.51388294, 0.71488334, 0.89060393], [0.51011248, 0.71101066, 0.89097410], [0.50644655, 0.70711649, 0.89134936], [0.50288765, 0.70320047, 0.89172772], [0.49943822, 0.69926217, 0.89210744], [0.49610063, 0.69530122, 0.89248647], [0.49287720, 0.69131735, 0.89286215], [0.48977007, 0.68731025, 0.89323218], [0.48678129, 0.68327963, 0.89359417], [0.48391278, 0.67922522, 0.89394566], [0.48116628, 0.67514678, 0.89428415], [0.47854335, 0.67104413, 0.89460702], [0.47604536, 0.66691708, 0.89491161], [0.47367364, 0.66276538, 0.89519579], [0.47142903, 0.65858902, 0.89545627], [0.46931216, 0.65438798, 0.89569008], [0.46732345, 0.65016224, 0.89589433], [0.46546305, 0.64591186, 0.89606608], [0.46373081, 0.64163690, 0.89620239], [0.46212629, 0.63733750, 0.89630027], [0.46064879, 0.63301382, 0.89635684], [0.45929732, 0.62866605, 0.89636919], [0.45807033, 0.62429458, 0.89633399], [0.45696613, 0.61989976, 0.89624827], [0.45598269, 0.61548199, 0.89610905], [0.45511768, 0.61104174, 0.89591342], [0.45436847, 0.60657953, 0.89565850], [0.45373211, 0.60209592, 0.89534144], [0.45320531, 0.59759159, 0.89495941], [0.45278458, 0.59306722, 0.89450974], [0.45246621, 0.58852353, 0.89398987], [0.45224622, 0.58396130, 0.89339735], [0.45212047, 0.57938135, 0.89272981], [0.45208461, 0.57478456, 0.89198505], [0.45213406, 0.57017185, 0.89116092], [0.45226366, 0.56554440, 0.89025507], [0.45246908, 0.56090297, 0.88926607], [0.45274551, 0.55624857, 0.88819230], [0.45308803, 0.55158223, 0.88703226], [0.45349173, 0.54690499, 0.88578463], [0.45395166, 0.54221790, 0.88444824], [0.45446291, 0.53752203, 0.88302210], [0.45502044, 0.53281852, 0.88150529], [0.45561856, 0.52810881, 0.87989676], [0.45625342, 0.52339359, 0.87819649], [0.45692037, 0.51867392, 0.87640412], [0.45761487, 0.51395086, 0.87451947], [0.45833250, 0.50922545, 0.87254251], [0.45906898, 0.50449872, 0.87047333], [0.45982017, 0.49977167, 0.86831217], [0.46058208, 0.49504528, 0.86605942], [0.46135090, 0.49032052, 0.86371555], [0.46212297, 0.48559831, 0.86128120], [0.46289481, 0.48087955, 0.85875708], [0.46366216, 0.47616550, 0.85614385], [0.46442285, 0.47145661, 0.85344263], [0.46517394, 0.46675366, 0.85065444], [0.46591265, 0.46205743, 0.84778034], [0.46663636, 0.45736864, 0.84482148], [0.46734263, 0.45268799, 0.84177905], [0.46802917, 0.44801616, 0.83865432], [0.46869383, 0.44335376, 0.83544858], [0.46933466, 0.43870139, 0.83216318], [0.46994980, 0.43405962, 0.82879947], [0.47053758, 0.42942898, 0.82535887], [0.47109642, 0.42480997, 0.82184277], [0.47162490, 0.42020304, 0.81825263], [0.47212171, 0.41560865, 0.81458986], [0.47258566, 0.41102721, 0.81085591], [0.47301567, 0.40645908, 0.80705223], [0.47341074, 0.40190463, 0.80318024], [0.47376999, 0.39736419, 0.79924139], [0.47409263, 0.39283807, 0.79523708], [0.47437795, 0.38832654, 0.79116870], [0.47462530, 0.38382989, 0.78703766], [0.47483412, 0.37934834, 0.78284530], [0.47500393, 0.37488213, 0.77859297], [0.47513427, 0.37043147, 0.77428199], [0.47522479, 0.36599656, 0.76991363], [0.47527514, 0.36157758, 0.76548918], [0.47528466, 0.35717487, 0.76101004], [0.47525316, 0.35278857, 0.75647742], [0.47518080, 0.34841867, 0.75189235], [0.47506742, 0.34406531, 0.74725597], [0.47491290, 0.33972863, 0.74256938], [0.47471715, 0.33540873, 0.73783366], [0.47448009, 0.33110575, 0.73304987], [0.47420168, 0.32681981, 0.72821900], [0.47388188, 0.32255100, 0.72334205], [0.47352067, 0.31829946, 0.71841996], [0.47311806, 0.31406530, 0.71345366], [0.47267406, 0.30984863, 0.70844403], [0.47218867, 0.30564956, 0.70339194], [0.47166137, 0.30146848, 0.69829868], [0.47109270, 0.29730529, 0.69316468], [0.47048281, 0.29316004, 0.68799058], [0.46983176, 0.28903289, 0.68277713], [0.46913959, 0.28492398, 0.67752502], [0.46840632, 0.28083345, 0.67223496], [0.46763200, 0.27676148, 0.66690758], [0.46681665, 0.27270825, 0.66154354], [0.46596031, 0.26867393, 0.65614343], [0.46506286, 0.26465880, 0.65070800], [0.46412426, 0.26066310, 0.64523790], [0.46314479, 0.25668693, 0.63973335], [0.46212445, 0.25273054, 0.63419487], [0.46106323, 0.24879421, 0.62862296], [0.45996110, 0.24487823, 0.62301809], [0.45881803, 0.24098289, 0.61738074], [0.45763398, 0.23710854, 0.61171135], [0.45640887, 0.23325554, 0.60601037], [0.45514261, 0.22942427, 0.60027826], [0.45383521, 0.22561510, 0.59451528], [0.45248658, 0.22182847, 0.58872183], [0.45109659, 0.21806485, 0.58289828], [0.44966511, 0.21432473, 0.57704502], [0.44819199, 0.21060865, 0.57116243], [0.44667705, 0.20691717, 0.56525088], [0.44512012, 0.20325090, 0.55931077], [0.44352106, 0.19961045, 0.55334230], [0.44187976, 0.19599648, 0.54734563], [0.44019583, 0.19240976, 0.54132138], [0.43846903, 0.18885105, 0.53526994], [0.43669905, 0.18532117, 0.52919170], [0.43488561, 0.18182099, 0.52308708], [0.43302838, 0.17835141, 0.51695650], [0.43112700, 0.17491341, 0.51080040], [0.42918111, 0.17150798, 0.50461925], [0.42719043, 0.16813620, 0.49841321], [0.42515465, 0.16479918, 0.49218247], [0.42307313, 0.16149814, 0.48592814], [0.42094540, 0.15823432, 0.47965080], [0.41877098, 0.15500903, 0.47335108], [0.41654936, 0.15182361, 0.46702967], [0.41428002, 0.14867950, 0.46068730], [0.41196239, 0.14557814, 0.45432475], [0.40959590, 0.14252107, 0.44794287], [0.40717995, 0.13950986, 0.44154258], [0.40471394, 0.13654614, 0.43512488], [0.40219729, 0.13363161, 0.42869038], [0.39962936, 0.13076802, 0.42224018], [0.39700936, 0.12795703, 0.41577611], [0.39433660, 0.12520039, 0.40929955], [0.39161037, 0.12249987, 0.40281200], [0.38882999, 0.11985720, 0.39631510], [0.38599472, 0.11727411, 0.38981058], [0.38310387, 0.11475229, 0.38330035], [0.38015674, 0.11229336, 0.37678646], [0.37715263, 0.10989888, 0.37027108], [0.37409088, 0.10757029, 0.36375657], [0.37097085, 0.10530889, 0.35724546], [0.36779195, 0.10311585, 0.35074041], [0.36455362, 0.10099212, 0.34424427], [0.36125536, 0.09893846, 0.33776007], [0.35789677, 0.09695535, 0.33129096], [0.35447749, 0.09504303, 0.32484029], [0.35099729, 0.09320140, 0.31841152], [0.34745604, 0.09143006, 0.31200825], [0.34385372, 0.08972821, 0.30563417], [0.34019047, 0.08809468, 0.29929318], [0.33646657, 0.08652789, 0.29298920], [0.33268245, 0.08502593, 0.28672608], [0.32883870, 0.08358647, 0.28050768], [0.32493609, 0.08220684, 0.27433782], [0.32097556, 0.08088399, 0.26822019], [0.31695820, 0.07961456, 0.26215837], [0.31288529, 0.07839490, 0.25615575], [0.30875826, 0.07722111, 0.25021549], [0.30457867, 0.07608911, 0.24434046], [0.30034822, 0.07499465, 0.23853326], [0.29606871, 0.07393344, 0.23279613], [0.29174204, 0.07290112, 0.22713094], [0.28737014, 0.07189340, 0.22153921], [0.28295501, 0.07090603, 0.21602205], [0.27849993, 0.06993211, 0.21058327], [0.27400681, 0.06896804, 0.20522255], [0.26947709, 0.06801140, 0.19993831], [0.26491272, 0.06705861, 0.19473015], [0.26031556, 0.06610638, 0.18959733], [0.25568737, 0.06515168, 0.18453880], [0.25103114, 0.06418929, 0.17955550], [0.24635153, 0.06321115, 0.17465056], [0.24164654, 0.06222163, 0.16981600], [0.23691745, 0.06121879, 0.16504980], [0.23216536, 0.06020099, 0.16034977], [0.22739756, 0.05915624, 0.15572185], [0.22261214, 0.05808842, 0.15115908], [0.21780744, 0.05700050, 0.14665582], [0.21298394, 0.05589169, 0.14220951]] _phase_data = [ [0.56724332, 0.41001824, 0.07083093], [0.57369533, 0.40631385, 0.06763640], [0.57994810, 0.40262767, 0.06473393], [0.58621727, 0.39883307, 0.06205459], [0.59231449, 0.39504395, 0.05971206], [0.59841114, 0.39115403, 0.05767412], [0.60434243, 0.38726851, 0.05602886], [0.61027304, 0.38327951, 0.05476297], [0.61602853, 0.37930459, 0.05394142], [0.62179468, 0.37521528, 0.05356325], [0.62739819, 0.37113394, 0.05366089], [0.63296349, 0.36697069, 0.05424569], [0.63841081, 0.36278458, 0.05531731], [0.64376271, 0.35855932, 0.05687403], [0.64904584, 0.35427327, 0.05891871], [0.65418902, 0.34998499, 0.06140802], [0.65927887, 0.34562236, 0.06436753], [0.66424610, 0.34124422, 0.06774175], [0.66908200, 0.33686041, 0.07149836], [0.67385549, 0.33240821, 0.07567487], [0.67849057, 0.32795839, 0.08019026], [0.68299052, 0.32351058, 0.08502570], [0.68739738, 0.31902389, 0.09021504], [0.69166679, 0.31454412, 0.09569861], [0.69579223, 0.31008093, 0.10145681], [0.69977763, 0.30563295, 0.10748756], [0.70363574, 0.30118776, 0.11380990], [0.70733660, 0.29678243, 0.12037554], [0.71087774, 0.29242414, 0.12717830], [0.71425607, 0.28812113, 0.13421258], [0.71747399, 0.28387470, 0.14148683], [0.72052428, 0.27969884, 0.14899031], [0.72339728, 0.27561226, 0.15670273], [0.72609023, 0.27162524, 0.16461824], [0.72860058, 0.26774828, 0.17273041], [0.73092616, 0.26399183, 0.18103219], [0.73306539, 0.26036590, 0.18951638], [0.73501868, 0.25687739, 0.19818207], [0.73678279, 0.25354020, 0.20700886], [0.73835819, 0.25036227, 0.21598766], [0.73974597, 0.24735064, 0.22510891], [0.74094777, 0.24451140, 0.23436265], [0.74196578, 0.24184955, 0.24373863], [0.74280272, 0.23936901, 0.25322643], [0.74346173, 0.23707255, 0.26281551], [0.74394637, 0.23496186, 0.27249532], [0.74426050, 0.23303771, 0.28225449], [0.74440831, 0.23129966, 0.29208237], [0.74439423, 0.22974621, 0.30196906], [0.74422282, 0.22837499, 0.31190490], [0.74389873, 0.22718285, 0.32188048], [0.74342664, 0.22616596, 0.33188669], [0.74281127, 0.22531985, 0.34191474], [0.74205730, 0.22463956, 0.35195616], [0.74116936, 0.22411969, 0.36200283], [0.74015240, 0.22375458, 0.37204357], [0.73901072, 0.22353801, 0.38207355], [0.73774860, 0.22346375, 0.39208656], [0.73637028, 0.22352544, 0.40207607], [0.73487988, 0.22371668, 0.41203587], [0.73328139, 0.22403107, 0.42196011], [0.73157865, 0.22446223, 0.43184326], [0.72977536, 0.22500389, 0.44168013], [0.72787579, 0.22564963, 0.45146241], [0.72588267, 0.22639364, 0.46118937], [0.72379920, 0.22723013, 0.47085716], [0.72162847, 0.22815351, 0.48046197], [0.71937343, 0.22915837, 0.49000029], [0.71703688, 0.23023956, 0.49946892], [0.71462148, 0.23139217, 0.50886493], [0.71213007, 0.23261136, 0.51818447], [0.70956452, 0.23389296, 0.52742703], [0.70692691, 0.23523289, 0.53659083], [0.70421925, 0.23662728, 0.54567406], [0.70144339, 0.23807254, 0.55467513], [0.69860103, 0.23956532, 0.56359267], [0.69569369, 0.24110255, 0.57242556], [0.69272221, 0.24268169, 0.58117426], [0.68968792, 0.24430011, 0.58983750], [0.68659180, 0.24595554, 0.59841463], [0.68343465, 0.24764596, 0.60690513], [0.68021707, 0.24936960, 0.61530861], [0.67693948, 0.25112494, 0.62362475], [0.67360205, 0.25291077, 0.63185346], [0.67020323, 0.25472691, 0.63999820], [0.66674402, 0.25657195, 0.64805568], [0.66322400, 0.25844541, 0.65602563], [0.65964254, 0.26034702, 0.66390773], [0.65599875, 0.26227679, 0.67170157], [0.65229153, 0.26423496, 0.67940663], [0.64851954, 0.26622203, 0.68702221], [0.64468060, 0.26823904, 0.69454851], [0.64077120, 0.27028786, 0.70198747], [0.63679115, 0.27236872, 0.70933383], [0.63273808, 0.27448309, 0.71658581], [0.62860936, 0.27663269, 0.72374126], [0.62440210, 0.27881949, 0.73079761], [0.62011309, 0.28104566, 0.73775186], [0.61573889, 0.28331365, 0.74460048], [0.61127572, 0.28562609, 0.75133940], [0.60671957, 0.28798585, 0.75796392], [0.60206609, 0.29039601, 0.76446868], [0.59731069, 0.29285981, 0.77084761], [0.59244787, 0.29538100, 0.77709461], [0.58747183, 0.29796350, 0.78320265], [0.58237864, 0.30061025, 0.78916126], [0.57716272, 0.30332502, 0.79496090], [0.57181826, 0.30611163, 0.80059103], [0.56633926, 0.30897393, 0.80604014], [0.56071959, 0.31191571, 0.81129563], [0.55495299, 0.31494071, 0.81634387], [0.54903314, 0.31805247, 0.82117010], [0.54295376, 0.32125431, 0.82575850], [0.53670817, 0.32454950, 0.83009251], [0.53028763, 0.32794207, 0.83415578], [0.52368879, 0.33143287, 0.83792761], [0.51690635, 0.33502336, 0.84138818], [0.50993559, 0.33871427, 0.84451696], [0.50277257, 0.34250546, 0.84729293], [0.49541426, 0.34639582, 0.84969480], [0.48785876, 0.35038314, 0.85170127], [0.48010551, 0.35446399, 0.85329141], [0.47215549, 0.35863367, 0.85444501], [0.46400447, 0.36288976, 0.85514340], [0.45566227, 0.36722210, 0.85536788], [0.44713833, 0.37162047, 0.85510290], [0.43844227, 0.37607441, 0.85433577], [0.42958621, 0.38057218, 0.85305689], [0.42058177, 0.38510239, 0.85125950], [0.41144690, 0.38965075, 0.84894112], [0.40220605, 0.39420025, 0.84610490], [0.39288171, 0.39873559, 0.84275762], [0.38349855, 0.40324130, 0.83891048], [0.37408360, 0.40770177, 0.83457920], [0.36466722, 0.41210102, 0.82978465], [0.35527868, 0.41642482, 0.82455055], [0.34594787, 0.42066002, 0.81890378], [0.33670810, 0.42479323, 0.81287608], [0.32759084, 0.42881325, 0.80650068], [0.31862215, 0.43271248, 0.79980883], [0.30982983, 0.43648364, 0.79283433], [0.30124029, 0.44012100, 0.78561114], [0.29288233, 0.44361869, 0.77817660], [0.28477939, 0.44697375, 0.77056484], [0.27694670, 0.45018708, 0.76280283], [0.26940193, 0.45325876, 0.75492020], [0.26216024, 0.45619000, 0.74694475], [0.25523415, 0.45898297, 0.73890234], [0.24863345, 0.46164068, 0.73081674], [0.24236623, 0.46416643, 0.72271109], [0.23643887, 0.46656363, 0.71460825], [0.23084854, 0.46883873, 0.70652028], [0.22559388, 0.47099685, 0.69846259], [0.22067083, 0.47304334, 0.69044868], [0.21607267, 0.47498376, 0.68249026], [0.21179018, 0.47682377, 0.67459735], [0.20781175, 0.47856909, 0.66677840], [0.20412355, 0.48022546, 0.65904036], [0.20070972, 0.48179858, 0.65138879], [0.19755260, 0.48329407, 0.64382798], [0.19463299, 0.48471751, 0.63636101], [0.19193036, 0.48607431, 0.62898985], [0.18942316, 0.48736979, 0.62171541], [0.18708905, 0.48860912, 0.61453762], [0.18490519, 0.48979730, 0.60745550], [0.18284850, 0.49093918, 0.60046718], [0.18089588, 0.49203942, 0.59356996], [0.17902444, 0.49310250, 0.58676036], [0.17721176, 0.49413269, 0.58003415], [0.17543603, 0.49513408, 0.57338636], [0.17367625, 0.49611052, 0.56681136], [0.17191243, 0.49706564, 0.56030287], [0.17012570, 0.49800282, 0.55385397], [0.16829867, 0.49892510, 0.54745788], [0.16641491, 0.49983547, 0.54110563], [0.16445972, 0.50073657, 0.53478849], [0.16242011, 0.50163068, 0.52849746], [0.16028489, 0.50251981, 0.52222315], [0.15804478, 0.50340563, 0.51595585], [0.15569256, 0.50428951, 0.50968556], [0.15322322, 0.50517248, 0.50340207], [0.15063412, 0.50605524, 0.49709504], [0.14792513, 0.50693812, 0.49075405], [0.14509892, 0.50782117, 0.48436869], [0.14216108, 0.50870404, 0.47792862], [0.13912049, 0.50958610, 0.47142361], [0.13598955, 0.51046638, 0.46484364], [0.13278459, 0.51134360, 0.45817896], [0.12952624, 0.51221616, 0.45142008], [0.12623991, 0.51308221, 0.44455788], [0.12295556, 0.51393979, 0.43758212], [0.11971036, 0.51478631, 0.43048588], [0.11654716, 0.51561909, 0.42326145], [0.11351549, 0.51643524, 0.41590148], [0.11067183, 0.51723164, 0.40839906], [0.10807962, 0.51800494, 0.40074776], [0.10580878, 0.51875159, 0.39294158], [0.10393472, 0.51946783, 0.38497499], [0.10253597, 0.52014993, 0.37683930], [0.10169355, 0.52079357, 0.36853055], [0.10148616, 0.52139416, 0.36004512], [0.10198647, 0.52194694, 0.35137897], [0.10325739, 0.52244679, 0.34252861], [0.10534865, 0.52288829, 0.33349121], [0.10829448, 0.52326557, 0.32426472], [0.11211265, 0.52357234, 0.31484804], [0.11680808, 0.52380192, 0.30523576], [0.12238518, 0.52394702, 0.29540477], [0.12881123, 0.52399876, 0.28538279], [0.13605621, 0.52394820, 0.27517603], [0.14410514, 0.52378513, 0.26476898], [0.15293375, 0.52349780, 0.25416480], [0.16247977, 0.52307494, 0.24341445], [0.17276282, 0.52250055, 0.23248374], [0.18369893, 0.52176275, 0.22146098], [0.19529772, 0.52084321, 0.21034680], [0.20746308, 0.51973103, 0.19925592], [0.22018049, 0.51840885, 0.18823609], [0.23332581, 0.51687146, 0.17744061], [0.24678810, 0.51511657, 0.16701119], [0.26043578, 0.51314954, 0.15710290], [0.27409793, 0.51098848, 0.14788694], [0.28761884, 0.50865777, 0.13950080], [0.30086975, 0.50618505, 0.13203710], [0.31370489, 0.50360866, 0.12556363], [0.32609538, 0.50094907, 0.12005608], [0.33799424, 0.49823249, 0.11547743], [0.34938489, 0.49547991, 0.11175786], [0.36029622, 0.49270114, 0.10880174], [0.37075574, 0.48990462, 0.10651189], [0.38076313, 0.48710519, 0.10479584], [0.39039628, 0.48429421, 0.10355136], [0.39968164, 0.48147509, 0.10269340], [0.40861182, 0.47866075, 0.10214468], [0.41725511, 0.47583919, 0.10183013], [0.42563941, 0.47300913, 0.10168644], [0.43378927, 0.47016919, 0.10165742], [0.44172797, 0.46731733, 0.10169329], [0.44947742, 0.46445100, 0.10174995], [0.45705812, 0.46156726, 0.10178816], [0.46448913, 0.45866282, 0.10177265], [0.47178813, 0.45573417, 0.10167122], [0.47897143, 0.45277762, 0.10145383], [0.48605409, 0.44978932, 0.10109169], [0.49304995, 0.44676536, 0.10055631], [0.49997171, 0.44370173, 0.09981844], [0.50683102, 0.44059441, 0.09884695], [0.51363860, 0.43743936, 0.09760740], [0.52040425, 0.43423253, 0.09606047], [0.52713698, 0.43096991, 0.09415980], [0.53384504, 0.42764756, 0.09184919], [0.54053593, 0.42426164, 0.08905888], [0.54721632, 0.42080854, 0.08570001], [0.55389186, 0.41728505, 0.08165660], [0.56056680, 0.41368870, 0.07677269], [0.56724332, 0.41001824, 0.07083093]] _temperature_data = [ [0.01555601, 0.13824425, 0.20181089], [0.01620184, 0.14105074, 0.20897651], [0.01685649, 0.14382701, 0.21623868], [0.01752640, 0.14657173, 0.22359970], [0.01821872, 0.14928346, 0.23106187], [0.01894138, 0.15196073, 0.23862748], [0.01969968, 0.15460145, 0.24630497], [0.02050332, 0.15720378, 0.25409711], [0.02136721, 0.15976645, 0.26199915], [0.02230341, 0.16228755, 0.27001321], [0.02332520, 0.16476505, 0.27814139], [0.02444728, 0.16719678, 0.28638573], [0.02568582, 0.16958042, 0.29474817], [0.02705867, 0.17191350, 0.30323056], [0.02858553, 0.17419338, 0.31183463], [0.03028808, 0.17641726, 0.32056191], [0.03219022, 0.17858215, 0.32941369], [0.03431826, 0.18068487, 0.33839101], [0.03670118, 0.18272205, 0.34749451], [0.03937082, 0.18469014, 0.35672441], [0.04230474, 0.18658537, 0.36608039], [0.04544128, 0.18840380, 0.37556146], [0.04879889, 0.19014130, 0.38516584], [0.05238565, 0.19179358, 0.39489082], [0.05620897, 0.19335621, 0.40473254], [0.06027561, 0.19482469, 0.41468582], [0.06459519, 0.19618775, 0.42477146], [0.06917294, 0.19744583, 0.43495728], [0.07401398, 0.19859437, 0.44523225], [0.07912633, 0.19962514, 0.45559656], [0.08452075, 0.20052842, 0.46605087], [0.09019392, 0.20130794, 0.47654788], [0.09616431, 0.20194725, 0.48710445], [0.10242540, 0.20245202, 0.49766462], [0.10899443, 0.20280889, 0.50822709], [0.11585974, 0.20302735, 0.51872453], [0.12304243, 0.20309380, 0.52914838], [0.13052767, 0.20302178, 0.53942012], [0.13830991, 0.20281956, 0.54947678], [0.14637971, 0.20250018, 0.55924613], [0.15471863, 0.20208507, 0.56864226], [0.16329705, 0.20160546, 0.57756769], [0.17207282, 0.20110273, 0.58591838], [0.18099176, 0.20062705, 0.59359182], [0.18999022, 0.20023416, 0.60049707], [0.19899974, 0.19998029, 0.60656515], [0.20795298, 0.19991643, 0.61175706], [0.21678952, 0.20008303, 0.61606739], [0.22546043, 0.20050671, 0.61952279], [0.23393063, 0.20119920, 0.62217608], [0.24217907, 0.20215872, 0.62409793], [0.25019713, 0.20337273, 0.62536824], [0.25798611, 0.20482134, 0.62606879], [0.26555442, 0.20648047, 0.62627797], [0.27291504, 0.20832446, 0.62606758], [0.28008339, 0.21032792, 0.62550133], [0.28706751, 0.21246914, 0.62464200], [0.29388514, 0.21472543, 0.62353802], [0.30055772, 0.21707565, 0.62222519], [0.30708438, 0.21950598, 0.62075550], [0.31349163, 0.22199831, 0.61914522], [0.31977984, 0.22454204, 0.61743434], [0.32596955, 0.22712412, 0.61563293], [0.33205791, 0.22973736, 0.61377715], [0.33806601, 0.23237153, 0.61186606], [0.34399174, 0.23502151, 0.60992807], [0.34984607, 0.23768089, 0.60796949], [0.35563846, 0.24034440, 0.60599535], [0.36136863, 0.24300892, 0.60402414], [0.36704345, 0.24567078, 0.60206076], [0.37267088, 0.24832670, 0.60010594], [0.37825480, 0.25097436, 0.59816563], [0.38379608, 0.25361228, 0.59624988], [0.38929883, 0.25623877, 0.59436180], [0.39476910, 0.25885207, 0.59249964], [0.40020989, 0.26145107, 0.59066609], [0.40562409, 0.26403484, 0.58886331], [0.41101442, 0.26660262, 0.58709291], [0.41638322, 0.26915383, 0.58535660], [0.42173132, 0.27168825, 0.58365836], [0.42706343, 0.27420503, 0.58199410], [0.43238181, 0.27670380, 0.58036393], [0.43768862, 0.27918426, 0.57876764], [0.44298597, 0.28164615, 0.57720480], [0.44827587, 0.28408925, 0.57567472], [0.45356026, 0.28651338, 0.57417648], [0.45884104, 0.28891838, 0.57270899], [0.46412001, 0.29130410, 0.57127095], [0.46939893, 0.29367044, 0.56986090], [0.47467951, 0.29601729, 0.56847725], [0.47996336, 0.29834456, 0.56711823], [0.48525207, 0.30065217, 0.56578195], [0.49054716, 0.30294008, 0.56446640], [0.49585007, 0.30520822, 0.56316946], [0.50116221, 0.30745656, 0.56188888], [0.50648491, 0.30968508, 0.56062233], [0.51181943, 0.31189376, 0.55936737], [0.51716699, 0.31408263, 0.55812148], [0.52252871, 0.31625172, 0.55688205], [0.52790567, 0.31840106, 0.55564642], [0.53329886, 0.32053073, 0.55441182], [0.53870920, 0.32264084, 0.55317546], [0.54413753, 0.32473150, 0.55193448], [0.54958461, 0.32680287, 0.55068596], [0.55505113, 0.32885514, 0.54942696], [0.56053768, 0.33088852, 0.54815451], [0.56604476, 0.33290327, 0.54686563], [0.57157236, 0.33489987, 0.54555812], [0.57712131, 0.33687845, 0.54422801], [0.58269186, 0.33883938, 0.54287227], [0.58828416, 0.34078308, 0.54148789], [0.59389827, 0.34271002, 0.54007187], [0.59953415, 0.34462069, 0.53862124], [0.60519167, 0.34651565, 0.53713308], [0.61087061, 0.34839552, 0.53560450], [0.61657065, 0.35026093, 0.53403268], [0.62229138, 0.35211260, 0.53241484], [0.62803229, 0.35395127, 0.53074831], [0.63379279, 0.35577776, 0.52903045], [0.63957219, 0.35759292, 0.52725878], [0.64536975, 0.35939765, 0.52543076], [0.65118470, 0.36119285, 0.52354391], [0.65701610, 0.36297956, 0.52159597], [0.66286293, 0.36475881, 0.51958481], [0.66872410, 0.36653173, 0.51750839], [0.67459845, 0.36829947, 0.51536480], [0.68048472, 0.37006325, 0.51315222], [0.68638162, 0.37182432, 0.51086898], [0.69228775, 0.37358401, 0.50851352], [0.69820166, 0.37534367, 0.50608439], [0.70412186, 0.37710473, 0.50358028], [0.71004688, 0.37886859, 0.50099965], [0.71597525, 0.38063670, 0.49834106], [0.72190503, 0.38241075, 0.49560410], [0.72783443, 0.38419239, 0.49278795], [0.73376164, 0.38598330, 0.48989190], [0.73968475, 0.38778523, 0.48691538], [0.74560180, 0.38960001, 0.48385794], [0.75151077, 0.39142951, 0.48071927], [0.75740957, 0.39327566, 0.47749914], [0.76329604, 0.39514048, 0.47419750], [0.76916794, 0.39702603, 0.47081439], [0.77502298, 0.39893446, 0.46735000], [0.78085877, 0.40086800, 0.46380463], [0.78667286, 0.40282892, 0.46017874], [0.79246271, 0.40481960, 0.45647292], [0.79822569, 0.40684249, 0.45268792], [0.80395908, 0.40890011, 0.44882462], [0.80966007, 0.41099506, 0.44488409], [0.81532584, 0.41313001, 0.44086720], [0.82095338, 0.41530771, 0.43677537], [0.82653946, 0.41753108, 0.43261066], [0.83208085, 0.41980305, 0.42837489], [0.83757423, 0.42212661, 0.42407011], [0.84301618, 0.42450482, 0.41969860], [0.84840316, 0.42694082, 0.41526288], [0.85373155, 0.42943780, 0.41076573], [0.85899760, 0.43199897, 0.40621024], [0.86419750, 0.43462760, 0.40159975], [0.86932733, 0.43732696, 0.39693796], [0.87438311, 0.44010033, 0.39222887], [0.87936081, 0.44295096, 0.38747682], [0.88425632, 0.44588207, 0.38268654], [0.88906554, 0.44889681, 0.37786308], [0.89378437, 0.45199824, 0.37301160], [0.89840867, 0.45518929, 0.36813827], [0.90293439, 0.45847274, 0.36324942], [0.90735756, 0.46185117, 0.35835166], [0.91167433, 0.46532694, 0.35345197], [0.91588100, 0.46890217, 0.34855767], [0.91997406, 0.47257868, 0.34367638], [0.92395023, 0.47635796, 0.33881601], [0.92780648, 0.48024117, 0.33398471], [0.93154008, 0.48422909, 0.32919080], [0.93514863, 0.48832213, 0.32444275], [0.93863008, 0.49252027, 0.31974912], [0.94198274, 0.49682311, 0.31511847], [0.94520535, 0.50122981, 0.31055931], [0.94829701, 0.50573917, 0.30608003], [0.95125725, 0.51034957, 0.30168887], [0.95408600, 0.51505906, 0.29739377], [0.95678355, 0.51986536, 0.29320240], [0.95935057, 0.52476587, 0.28912206], [0.96178805, 0.52975777, 0.28515964], [0.96409730, 0.53483802, 0.28132156], [0.96627986, 0.54000343, 0.27761379], [0.96833750, 0.54525070, 0.27404177], [0.97027215, 0.55057645, 0.27061043], [0.97208896, 0.55597442, 0.26733231], [0.97378824, 0.56144311, 0.26420514], [0.97537225, 0.56697917, 0.26123210], [0.97684333, 0.57257930, 0.25841610], [0.97820376, 0.57824032, 0.25575953], [0.97945570, 0.58395922, 0.25326432], [0.98060120, 0.58973318, 0.25093197], [0.98164451, 0.59555764, 0.24876746], [0.98259580, 0.60142353, 0.24678389], [0.98344841, 0.60733543, 0.24496692], [0.98420378, 0.61329131, 0.24331643], [0.98486309, 0.61928934, 0.24183204], [0.98543359, 0.62532321, 0.24052074], [0.98592661, 0.63138392, 0.23939250], [0.98632908, 0.63748058, 0.23842850], [0.98664126, 0.64361223, 0.23762727], [0.98687430, 0.64977022, 0.23699778], [0.98703872, 0.65594684, 0.23654600], [0.98711602, 0.66215449, 0.23625164], [0.98710548, 0.66839291, 0.23611251], [0.98704522, 0.67463615, 0.23615516], [0.98690081, 0.68090692, 0.23634896], [0.98666929, 0.68720645, 0.23669008], [0.98639295, 0.69350720, 0.23720252], [0.98603581, 0.69983201, 0.23785913], [0.98559369, 0.70618283, 0.23865535], [0.98511668, 0.71252856, 0.23961378], [0.98455154, 0.71890163, 0.24070275], [0.98392192, 0.72528731, 0.24193050], [0.98324116, 0.73167761, 0.24329811], [0.98246864, 0.73809600, 0.24478540], [0.98166755, 0.74450581, 0.24641186], [0.98078113, 0.75093941, 0.24815276], [0.97983772, 0.75738047, 0.25001371], [0.97883927, 0.76382790, 0.25199054], [0.97775747, 0.77029690, 0.25407166], [0.97664794, 0.77675738, 0.25626641], [0.97543570, 0.78324913, 0.25855344], [0.97421070, 0.78972470, 0.26094721], [0.97288357, 0.79623051, 0.26342620], [0.97152974, 0.80272764, 0.26599948], [0.97008613, 0.80924798, 0.26865290], [0.96860571, 0.81576486, 0.27138993], [0.96704307, 0.82230061, 0.27420073], [0.96543772, 0.82883583, 0.27708584], [0.96375242, 0.83538829, 0.28003763], [0.96202315, 0.84194079, 0.28305544], [0.96021049, 0.84851164, 0.28613254], [0.95835763, 0.85508072, 0.28926815], [0.95641175, 0.86167196, 0.29245571], [0.95443484, 0.86825730, 0.29569479], [0.95234871, 0.87487125, 0.29897882], [0.95024646, 0.88147281, 0.30230776], [0.94801413, 0.88811109, 0.30567520], [0.94578198, 0.89473018, 0.30908112], [0.94341986, 0.90138491, 0.31252002], [0.94102862, 0.90803285, 0.31599064], [0.93853313, 0.91470475, 0.31948933], [0.93597111, 0.92138481, 0.32301384], [0.93333760, 0.92807483, 0.32656155], [0.93059157, 0.93479051, 0.33012998], [0.92781425, 0.94149986, 0.33371683], [0.92488992, 0.94824702, 0.33731997], [0.92194114, 0.95498491, 0.34093705], [0.91886139, 0.96175325, 0.34456630], [0.91569318, 0.96853549, 0.34820569], [0.91244907, 0.97532669, 0.35185336], [0.90904184, 0.98215741, 0.35550781]] _velocity_b_data = [ [0.06597739, 0.12386005, 0.24948116], [0.06865758, 0.12663250, 0.25557624], [0.07132312, 0.12939515, 0.26166391], [0.07396584, 0.13214058, 0.26779480], [0.07658629, 0.13486916, 0.27396904], [0.07919242, 0.13758843, 0.28014206], [0.08176925, 0.14028419, 0.28640499], [0.08433407, 0.14297318, 0.29265629], [0.08687299, 0.14564215, 0.29898019], [0.08939564, 0.14830082, 0.30531941], [0.09189721, 0.15094484, 0.31170300], [0.09437767, 0.15357460, 0.31813071], [0.09684032, 0.15619402, 0.32458157], [0.09927797, 0.15879644, 0.33109756], [0.10169939, 0.16139154, 0.33762358], [0.10409298, 0.16396840, 0.34422672], [0.10647003, 0.16653949, 0.35083602], [0.10881765, 0.16909286, 0.35752405], [0.11114624, 0.17164030, 0.36422476], [0.11344526, 0.17417268, 0.37099405], [0.11572015, 0.17669703, 0.37779407], [0.11796711, 0.17921142, 0.38463932], [0.12018172, 0.18171361, 0.39154591], [0.12237222, 0.18421369, 0.39845983], [0.12451836, 0.18669519, 0.40547913], [0.12663654, 0.18917624, 0.41250469], [0.12871435, 0.19164859, 0.41958831], [0.13074695, 0.19411179, 0.42673806], [0.13274084, 0.19657524, 0.43390608], [0.13468282, 0.19903239, 0.44113668], [0.13656674, 0.20148370, 0.44843501], [0.13839602, 0.20393744, 0.45576220], [0.14016368, 0.20639447, 0.46312314], [0.14185409, 0.20885126, 0.47055044], [0.14345986, 0.21131167, 0.47803591], [0.14497642, 0.21378230, 0.48555700], [0.14639100, 0.21626634, 0.49311434], [0.14768864, 0.21876800, 0.50070638], [0.14885173, 0.22129285, 0.50832846], [0.14985965, 0.22384818, 0.51597154], [0.15068840, 0.22644340, 0.52362079], [0.15131023, 0.22909058, 0.53125369], [0.15168425, 0.23180303, 0.53885457], [0.15175702, 0.23459819, 0.54640144], [0.15150762, 0.23750367, 0.55379602], [0.15085272, 0.24054407, 0.56100954], [0.14977800, 0.24375297, 0.56790391], [0.14824130, 0.24715977, 0.57437788], [0.14626774, 0.25078506, 0.58029534], [0.14393556, 0.25462901, 0.58555075], [0.14135408, 0.25866955, 0.59010335], [0.13864079, 0.26286871, 0.59397852], [0.13589174, 0.26718438, 0.59724867], [0.13319563, 0.27157423, 0.60000635], [0.13058114, 0.27601030, 0.60234289], [0.12806719, 0.28047115, 0.60433583], [0.12569199, 0.28493491, 0.60605594], [0.12343537, 0.28939604, 0.60755039], [0.12131237, 0.29384382, 0.60886431], [0.11933140, 0.29827105, 0.61003449], [0.11747335, 0.30267840, 0.61108156], [0.11574105, 0.30706267, 0.61202824], [0.11415261, 0.31141804, 0.61290024], [0.11269166, 0.31574724, 0.61370617], [0.11135538, 0.32005035, 0.61445721], [0.11014377, 0.32432716, 0.61516380], [0.10905648, 0.32857778, 0.61583463], [0.10809281, 0.33280260, 0.61647697], [0.10725185, 0.33700217, 0.61709693], [0.10653241, 0.34117717, 0.61769964], [0.10593314, 0.34532836, 0.61828945], [0.10545250, 0.34945656, 0.61887003], [0.10508879, 0.35356261, 0.61944452], [0.10484013, 0.35764738, 0.62001559], [0.10470452, 0.36171173, 0.62058554], [0.10467981, 0.36575652, 0.62115635], [0.10476371, 0.36978259, 0.62172971], [0.10495382, 0.37379076, 0.62230709], [0.10524762, 0.37778184, 0.62288978], [0.10564252, 0.38175660, 0.62347886], [0.10613580, 0.38571579, 0.62407531], [0.10672471, 0.38966014, 0.62467996], [0.10740642, 0.39359035, 0.62529352], [0.10817806, 0.39750711, 0.62591662], [0.10903675, 0.40141105, 0.62654981], [0.10998202, 0.40530231, 0.62719516], [0.11100819, 0.40918206, 0.62785128], [0.11211222, 0.41305092, 0.62851837], [0.11329127, 0.41690943, 0.62919672], [0.11454253, 0.42075813, 0.62988653], [0.11586327, 0.42459754, 0.63058799], [0.11725083, 0.42842816, 0.63130122], [0.11870260, 0.43225046, 0.63202632], [0.12021702, 0.43606470, 0.63276403], [0.12179033, 0.43987161, 0.63351340], [0.12342020, 0.44367161, 0.63427436], [0.12510445, 0.44746510, 0.63504690], [0.12684102, 0.45125247, 0.63583095], [0.12862799, 0.45503408, 0.63662642], [0.13046351, 0.45881028, 0.63743320], [0.13234563, 0.46258148, 0.63825092], [0.13427263, 0.46634802, 0.63907929], [0.13624311, 0.47011020, 0.63991816], [0.13825578, 0.47386832, 0.64076733], [0.14030945, 0.47762263, 0.64162657], [0.14240307, 0.48137341, 0.64249562], [0.14453572, 0.48512091, 0.64337422], [0.14670608, 0.48886546, 0.64426159], [0.14891319, 0.49260737, 0.64515709], [0.15115711, 0.49634669, 0.64606096], [0.15343746, 0.50008362, 0.64697283], [0.15575396, 0.50381833, 0.64789234], [0.15810648, 0.50755096, 0.64881909], [0.16049500, 0.51128167, 0.64975267], [0.16291965, 0.51501059, 0.65069263], [0.16538066, 0.51873781, 0.65163850], [0.16787709, 0.52246378, 0.65258827], [0.17041079, 0.52618823, 0.65354289], [0.17298246, 0.52991124, 0.65450185], [0.17559291, 0.53363281, 0.65546464], [0.17824310, 0.53735298, 0.65643069], [0.18093416, 0.54107173, 0.65739946], [0.18366735, 0.54478903, 0.65837034], [0.18644408, 0.54850484, 0.65934275], [0.18926596, 0.55221906, 0.66031605], [0.19213472, 0.55593160, 0.66128961], [0.19505228, 0.55964231, 0.66226278], [0.19802076, 0.56335105, 0.66323489], [0.20104242, 0.56705760, 0.66420528], [0.20411976, 0.57076173, 0.66517325], [0.20725543, 0.57446319, 0.66613812], [0.21045232, 0.57816165, 0.66709920], [0.21371350, 0.58185676, 0.66805579], [0.21704227, 0.58554813, 0.66900720], [0.22044214, 0.58923531, 0.66995277], [0.22391686, 0.59291779, 0.67089183], [0.22747037, 0.59659503, 0.67182375], [0.23110686, 0.60026640, 0.67274791], [0.23483073, 0.60393124, 0.67366376], [0.23864660, 0.60758879, 0.67457077], [0.24255928, 0.61123826, 0.67546847], [0.24657379, 0.61487875, 0.67635647], [0.25069532, 0.61850931, 0.67723446], [0.25492963, 0.62212933, 0.67809791], [0.25928228, 0.62573723, 0.67895065], [0.26375886, 0.62933183, 0.67979274], [0.26836502, 0.63291182, 0.68062438], [0.27310635, 0.63647586, 0.68144595], [0.27799067, 0.64002284, 0.68225204], [0.28302187, 0.64355084, 0.68304906], [0.28820489, 0.64705829, 0.68383831], [0.29354581, 0.65054365, 0.68461866], [0.29905039, 0.65400523, 0.68538993], [0.30471967, 0.65744127, 0.68615859], [0.31055832, 0.66085014, 0.68692427], [0.31656915, 0.66423017, 0.68768878], [0.32274951, 0.66757995, 0.68845924], [0.32910283, 0.67089793, 0.68923459], [0.33562308, 0.67418311, 0.69002275], [0.34230732, 0.67743451, 0.69082687], [0.34914976, 0.68065146, 0.69165158], [0.35614127, 0.68383379, 0.69250293], [0.36327369, 0.68698145, 0.69338491], [0.37053484, 0.69009497, 0.69430340], [0.37791226, 0.69317522, 0.69526327], [0.38539385, 0.69622324, 0.69626827], [0.39296332, 0.69924082, 0.69732400], [0.40060940, 0.70222938, 0.69843223], [0.40831594, 0.70519122, 0.69959724], [0.41607015, 0.70812840, 0.70082090], [0.42386201, 0.71104276, 0.70210342], [0.43167256, 0.71393771, 0.70344961], [0.43949947, 0.71681422, 0.70485557], [0.44732849, 0.71967527, 0.70632366], [0.45514951, 0.72252334, 0.70785413], [0.46296115, 0.72535947, 0.70944335], [0.47075349, 0.72818626, 0.71109189], [0.47851694, 0.73100635, 0.71280025], [0.48625412, 0.73382019, 0.71456376], [0.49396102, 0.73662941, 0.71638100], [0.50163106, 0.73943622, 0.71825179], [0.50925965, 0.74224248, 0.72017521], [0.51685029, 0.74504841, 0.72214731], [0.52440134, 0.74785523, 0.72416643], [0.53191155, 0.75066408, 0.72623094], [0.53938005, 0.75347600, 0.72833923], [0.54680444, 0.75629239, 0.73049037], [0.55418394, 0.75911426, 0.73268299], [0.56152150, 0.76194178, 0.73491438], [0.56881727, 0.76477570, 0.73718308], [0.57607152, 0.76761672, 0.73948764], [0.58328469, 0.77046550, 0.74182668], [0.59045730, 0.77332263, 0.74419886], [0.59758995, 0.77618869, 0.74660289], [0.60468333, 0.77906419, 0.74903750], [0.61173817, 0.78194964, 0.75150151], [0.61875522, 0.78484550, 0.75399375], [0.62573528, 0.78775220, 0.75651310], [0.63267915, 0.79067016, 0.75905849], [0.63958763, 0.79359978, 0.76162887], [0.64646151, 0.79654145, 0.76422323], [0.65330160, 0.79949552, 0.76684059], [0.66010867, 0.80246236, 0.76948001], [0.66688348, 0.80544232, 0.77214056], [0.67362676, 0.80843573, 0.77482134], [0.68033922, 0.81144292, 0.77752145], [0.68702155, 0.81446423, 0.78024002], [0.69367439, 0.81749998, 0.78297620], [0.70029750, 0.82055075, 0.78572944], [0.70689165, 0.82361681, 0.78849881], [0.71345823, 0.82669826, 0.79128316], [0.71999780, 0.82979542, 0.79408159], [0.72651088, 0.83290861, 0.79689320], [0.73299796, 0.83603816, 0.79971707], [0.73945951, 0.83918440, 0.80255223], [0.74589598, 0.84234767, 0.80539770], [0.75230780, 0.84552831, 0.80825242], [0.75869517, 0.84872673, 0.81111536], [0.76505775, 0.85194348, 0.81398568], [0.77139709, 0.85517859, 0.81686163], [0.77771359, 0.85843239, 0.81974187], [0.78400765, 0.86170526, 0.82262493], [0.79027967, 0.86499755, 0.82550921], [0.79653012, 0.86830960, 0.82839299], [0.80275950, 0.87164177, 0.83127437], [0.80896806, 0.87499448, 0.83415141], [0.81515670, 0.87836796, 0.83702171], [0.82132643, 0.88176244, 0.83988264], [0.82747812, 0.88517819, 0.84273144], [0.83361281, 0.88861542, 0.84556510], [0.83973174, 0.89207431, 0.84838033], [0.84583638, 0.89555495, 0.85117353], [0.85192854, 0.89905734, 0.85394079], [0.85801043, 0.90258135, 0.85667786], [0.86408444, 0.90612679, 0.85938032], [0.87015339, 0.90969330, 0.86204351], [0.87622047, 0.91328040, 0.86466260], [0.88228934, 0.91688740, 0.86723268], [0.88836402, 0.92051348, 0.86974885], [0.89444909, 0.92415756, 0.87220619], [0.90054949, 0.92781839, 0.87459995], [0.90666975, 0.93149475, 0.87692634], [0.91281478, 0.93518523, 0.87918186], [0.91898934, 0.93888836, 0.88136368], [0.92519787, 0.94260271, 0.88346979], [0.93144429, 0.94632694, 0.88549899], [0.93773184, 0.95005986, 0.88745092], [0.94406341, 0.95380038, 0.88932539], [0.95044015, 0.95754793, 0.89112376], [0.95686223, 0.96130226, 0.89284794], [0.96332900, 0.96506343, 0.89449990], [0.96983887, 0.96883187, 0.89608183], [0.97638938, 0.97260834, 0.89759591], [0.98297732, 0.97639393, 0.89904421], [0.98959887, 0.98019003, 0.90042859], [0.99624974, 0.98399826, 0.90175064]] _velocity_g_data = [ [0.99962532, 0.99137112, 0.80410124], [0.99693130, 0.98658659, 0.79581965], [0.99425336, 0.98181358, 0.78753178], [0.99158968, 0.97705259, 0.77923744], [0.98893848, 0.97230412, 0.77093649], [0.98629803, 0.96756863, 0.76262887], [0.98366662, 0.96284660, 0.75431452], [0.98104259, 0.95813849, 0.74599345], [0.97842373, 0.95344486, 0.73766705], [0.97580917, 0.94876601, 0.72933356], [0.97319768, 0.94410230, 0.72099216], [0.97058766, 0.93945419, 0.71264291], [0.96797753, 0.93482212, 0.70428588], [0.96536576, 0.93020653, 0.69592114], [0.96275088, 0.92560786, 0.68754852], [0.96013179, 0.92102646, 0.67916692], [0.95750683, 0.91646282, 0.67077672], [0.95487445, 0.91191742, 0.66237802], [0.95223308, 0.90739072, 0.65397092], [0.94958118, 0.90288322, 0.64555550], [0.94691718, 0.89839541, 0.63713184], [0.94424022, 0.89392765, 0.62869796], [0.94154864, 0.88948047, 0.62025400], [0.93884038, 0.88505451, 0.61180142], [0.93611377, 0.88065031, 0.60334038], [0.93336714, 0.87626844, 0.59487104], [0.93059881, 0.87190949, 0.58639360], [0.92780705, 0.86757406, 0.57790823], [0.92499010, 0.86326276, 0.56941517], [0.92214698, 0.85897609, 0.56091165], [0.91927530, 0.85471481, 0.55239974], [0.91637286, 0.85047967, 0.54388105], [0.91343769, 0.84627138, 0.53535605], [0.91046780, 0.84209066, 0.52682531], [0.90746117, 0.83793825, 0.51828947], [0.90441569, 0.83381493, 0.50974926], [0.90132924, 0.82972148, 0.50120551], [0.89819963, 0.82565871, 0.49265916], [0.89502462, 0.82162744, 0.48411130], [0.89180194, 0.81762851, 0.47556314], [0.88852927, 0.81366275, 0.46701603], [0.88520428, 0.80973103, 0.45847151], [0.88182459, 0.80583419, 0.44993127], [0.87838781, 0.80197310, 0.44139720], [0.87489155, 0.79814860, 0.43287135], [0.87133343, 0.79436152, 0.42435598], [0.86771108, 0.79061266, 0.41585355], [0.86402220, 0.78690280, 0.40736670], [0.86026452, 0.78323268, 0.39889826], [0.85643585, 0.77960299, 0.39045126], [0.85253410, 0.77601436, 0.38202889], [0.84855731, 0.77246735, 0.37363449], [0.84450364, 0.76896245, 0.36527157], [0.84037142, 0.76550008, 0.35694373], [0.83615916, 0.76208053, 0.34865469], [0.83186554, 0.75870402, 0.34040823], [0.82748950, 0.75537065, 0.33220817], [0.82303017, 0.75208041, 0.32405836], [0.81848682, 0.74883326, 0.31596178], [0.81385901, 0.74562899, 0.30792214], [0.80914682, 0.74246709, 0.29994435], [0.80435041, 0.73934706, 0.29203197], [0.79947022, 0.73626828, 0.28418840], [0.79450691, 0.73323004, 0.27641686], [0.78946140, 0.73023149, 0.26872033], [0.78433484, 0.72727172, 0.26110160], [0.77912853, 0.72434970, 0.25356307], [0.77384408, 0.72146431, 0.24610720], [0.76848332, 0.71861432, 0.23873620], [0.76304813, 0.71579850, 0.23145177], [0.75754052, 0.71301555, 0.22425532], [0.75196261, 0.71026417, 0.21714799], [0.74631660, 0.70754299, 0.21013070], [0.74060474, 0.70485066, 0.20320411], [0.73482974, 0.70218562, 0.19636930], [0.72899368, 0.69954660, 0.18962605], [0.72309885, 0.69693228, 0.18297431], [0.71714753, 0.69434130, 0.17641399], [0.71114201, 0.69177235, 0.16994487], [0.70508453, 0.68922412, 0.16356662], [0.69897728, 0.68669535, 0.15727889], [0.69282238, 0.68418481, 0.15108128], [0.68662205, 0.68169124, 0.14497353], [0.68037867, 0.67921331, 0.13895556], [0.67409362, 0.67675013, 0.13302663], [0.66776872, 0.67430062, 0.12718656], [0.66140573, 0.67186375, 0.12143540], [0.65500629, 0.66943851, 0.11577336], [0.64857199, 0.66702394, 0.11020095], [0.64210433, 0.66461911, 0.10471901], [0.63560473, 0.66222315, 0.09932877], [0.62907452, 0.65983518, 0.09403193], [0.62251497, 0.65745441, 0.08883077], [0.61592727, 0.65508003, 0.08372822], [0.60931267, 0.65271125, 0.07872800], [0.60267232, 0.65034731, 0.07383470], [0.59600693, 0.64798759, 0.06905401], [0.58931743, 0.64563142, 0.06439288], [0.58260468, 0.64327815, 0.05985969], [0.57586950, 0.64092715, 0.05546448], [0.56911267, 0.63857780, 0.05121917], [0.56233489, 0.63622950, 0.04713774], [0.55553684, 0.63388168, 0.04323651], [0.54871918, 0.63153377, 0.03952488], [0.54188249, 0.62918522, 0.03612051], [0.53502735, 0.62683550, 0.03311400], [0.52815431, 0.62448406, 0.03049096], [0.52126388, 0.62213041, 0.02823776], [0.51435656, 0.61977401, 0.02634145], [0.50743284, 0.61741438, 0.02478977], [0.50049318, 0.61505101, 0.02357107], [0.49353805, 0.61268341, 0.02267429], [0.48656773, 0.61031113, 0.02208919], [0.47958278, 0.60793365, 0.02180565], [0.47258366, 0.60555050, 0.02181419], [0.46557081, 0.60316118, 0.02210580], [0.45854471, 0.60076521, 0.02267188], [0.45150585, 0.59836210, 0.02350422], [0.44445471, 0.59595137, 0.02459500], [0.43739183, 0.59353253, 0.02593670], [0.43031775, 0.59110510, 0.02752213], [0.42323306, 0.58866858, 0.02934437], [0.41613836, 0.58622247, 0.03139676], [0.40903431, 0.58376629, 0.03367283], [0.40192160, 0.58129953, 0.03616635], [0.39480098, 0.57882170, 0.03887120], [0.38767326, 0.57633228, 0.04174672], [0.38053866, 0.57383092, 0.04468567], [0.37339864, 0.57131697, 0.04768050], [0.36625424, 0.56878993, 0.05071836], [0.35910650, 0.56624928, 0.05378828], [0.35195658, 0.56369452, 0.05688086], [0.34480568, 0.56112513, 0.05998797], [0.33765509, 0.55854062, 0.06310264], [0.33050620, 0.55594049, 0.06621880], [0.32336047, 0.55332424, 0.06933118], [0.31621948, 0.55069139, 0.07243519], [0.30908460, 0.54804150, 0.07552722], [0.30195743, 0.54537413, 0.07860394], [0.29484032, 0.54268874, 0.08166129], [0.28773525, 0.53998488, 0.08469633], [0.28064430, 0.53726212, 0.08770643], [0.27356965, 0.53452006, 0.09068917], [0.26651361, 0.53175830, 0.09364228], [0.25947856, 0.52897647, 0.09656369], [0.25246703, 0.52617424, 0.09945144], [0.24548136, 0.52335131, 0.10230412], [0.23852458, 0.52050736, 0.10511948], [0.23159967, 0.51764210, 0.10789570], [0.22470961, 0.51475531, 0.11063114], [0.21785748, 0.51184679, 0.11332427], [0.21104652, 0.50891636, 0.11597358], [0.20428009, 0.50596389, 0.11857764], [0.19756167, 0.50298929, 0.12113505], [0.19089503, 0.49999248, 0.12364426], [0.18428396, 0.49697343, 0.12610400], [0.17773240, 0.49393216, 0.12851305], [0.17124448, 0.49086871, 0.13087024], [0.16482456, 0.48778316, 0.13317442], [0.15847719, 0.48467561, 0.13542453], [0.15220721, 0.48154623, 0.13761954], [0.14601973, 0.47839518, 0.13975846], [0.13992049, 0.47522266, 0.14183978], [0.13391510, 0.47202893, 0.14386292], [0.12800964, 0.46881425, 0.14582732], [0.12221076, 0.46557892, 0.14773227], [0.11652565, 0.46232325, 0.14957707], [0.11096207, 0.45904759, 0.15136111], [0.10552844, 0.45575227, 0.15308384], [0.10023389, 0.45243770, 0.15474474], [0.09508832, 0.44910425, 0.15634337], [0.09010251, 0.44575233, 0.15787909], [0.08528802, 0.44238240, 0.15935107], [0.08065728, 0.43899485, 0.16075975], [0.07622371, 0.43559013, 0.16210488], [0.07200158, 0.43216868, 0.16338628], [0.06800589, 0.42873094, 0.16460379], [0.06425218, 0.42527736, 0.16575730], [0.06075626, 0.42180841, 0.16684671], [0.05753382, 0.41832454, 0.16787201], [0.05459993, 0.41482619, 0.16883316], [0.05196846, 0.41131384, 0.16973019], [0.04965139, 0.40778792, 0.17056314], [0.04765813, 0.40424888, 0.17133208], [0.04599481, 0.40069717, 0.17203710], [0.04466372, 0.39713324, 0.17267831], [0.04366274, 0.39355751, 0.17325577], [0.04298497, 0.38997047, 0.17376937], [0.04262018, 0.38637248, 0.17421963], [0.04255352, 0.38276397, 0.17460669], [0.04276673, 0.37914535, 0.17493074], [0.04323878, 0.37551702, 0.17519196], [0.04394675, 0.37187939, 0.17539051], [0.04486662, 0.36823283, 0.17552659], [0.04597406, 0.36457776, 0.17560040], [0.04724506, 0.36091453, 0.17561211], [0.04865644, 0.35724353, 0.17556193], [0.05018627, 0.35356513, 0.17545005], [0.05181408, 0.34987969, 0.17527666], [0.05352104, 0.34618758, 0.17504196], [0.05528998, 0.34248913, 0.17474614], [0.05710539, 0.33878471, 0.17438940], [0.05895335, 0.33507466, 0.17397193], [0.06082143, 0.33135932, 0.17349393], [0.06269859, 0.32763902, 0.17295560], [0.06457505, 0.32391411, 0.17235714], [0.06644218, 0.32018490, 0.17169874], [0.06829236, 0.31645172, 0.17098061], [0.07011887, 0.31271491, 0.17020297], [0.07191583, 0.30897477, 0.16936603], [0.07367740, 0.30523170, 0.16846982], [0.07539909, 0.30148601, 0.16751459], [0.07707731, 0.29773796, 0.16650073], [0.07870853, 0.29398786, 0.16542850], [0.08028966, 0.29023603, 0.16429815], [0.08181798, 0.28648275, 0.16310997], [0.08329110, 0.28272833, 0.16186426], [0.08470696, 0.27897306, 0.16056134], [0.08606372, 0.27521722, 0.15920155], [0.08735983, 0.27146109, 0.15778524], [0.08859393, 0.26770495, 0.15631280], [0.08976486, 0.26394904, 0.15478462], [0.09087165, 0.26019363, 0.15320113], [0.09191348, 0.25643894, 0.15156278], [0.09288704, 0.25268563, 0.14986937], [0.09379283, 0.24893377, 0.14812169], [0.09463164, 0.24518338, 0.14632057], [0.09540319, 0.24143464, 0.14446653], [0.09610733, 0.23768772, 0.14256015], [0.09674403, 0.23394277, 0.14060198], [0.09731337, 0.23019990, 0.13859263], [0.09781527, 0.22645927, 0.13653262], [0.09824359, 0.22272214, 0.13442135], [0.09860476, 0.21898749, 0.13226069], [0.09889926, 0.21525533, 0.13005125], [0.09912769, 0.21152567, 0.12779367], [0.09929071, 0.20779846, 0.12548854], [0.09938537, 0.20407438, 0.12313591], [0.09940988, 0.20035390, 0.12073611], [0.09937074, 0.19663577, 0.11829057], [0.09926900, 0.19291982, 0.11579981], [0.09910575, 0.18920581, 0.11326433], [0.09887273, 0.18549555, 0.11068374], [0.09857703, 0.18178753, 0.10805922], [0.09822270, 0.17808082, 0.10539142], [0.09781114, 0.17437504, 0.10268064], [0.09733238, 0.17067237, 0.09992671], [0.09679537, 0.16697070, 0.09713043], [0.09620477, 0.16326879, 0.09429209], [0.09555840, 0.15956697, 0.09141177], [0.09484852, 0.15586693, 0.08848984], [0.09408911, 0.15216506, 0.08552629], [0.09328192, 0.14846061, 0.08252095], [0.09241015, 0.14475747, 0.07947497], [0.09149314, 0.14105046, 0.07638733], [0.09053276, 0.13733861, 0.07325761]] _velocity_data = _velocity_b_data + _velocity_g_data _speed_data = _velocity_g_data _vorticity_p_data = [ [0.99421147, 0.96494148, 0.95917135], [0.99169155, 0.96006773, 0.95274067], [0.98920738, 0.95520176, 0.94627024], [0.98677194, 0.95033807, 0.93975862], [0.98437391, 0.94547881, 0.93322656], [0.98201829, 0.94062171, 0.92667310], [0.97970195, 0.93576702, 0.92010507], [0.97742080, 0.93091541, 0.91352937], [0.97518156, 0.92606439, 0.90693990], [0.97297049, 0.92121764, 0.90035362], [0.97080349, 0.91636994, 0.89375329], [0.96866357, 0.91152607, 0.88715902], [0.96655947, 0.90668298, 0.88056151], [0.96448728, 0.90184151, 0.87396567], [0.96244207, 0.89700286, 0.86737746], [0.96043456, 0.89216329, 0.86078529], [0.95844981, 0.88732720, 0.85420614], [0.95649898, 0.88249069, 0.84762790], [0.95457496, 0.87765571, 0.84105874], [0.95267455, 0.87282297, 0.83450240], [0.95080878, 0.86798852, 0.82794705], [0.94896310, 0.86315684, 0.82140881], [0.94714576, 0.85832485, 0.81487893], [0.94535503, 0.85349280, 0.80835951], [0.94358303, 0.84866304, 0.80185918], [0.94184257, 0.84383087, 0.79536454], [0.94012241, 0.83899979, 0.78888773], [0.93842059, 0.83417022, 0.78243098], [0.93675010, 0.82933722, 0.77598096], [0.93509628, 0.82450566, 0.76955320], [0.93346107, 0.81967454, 0.76314584], [0.93185391, 0.81484010, 0.75674949], [0.93026226, 0.81000656, 0.75037722], [0.92868761, 0.80517307, 0.74402771], [0.92713958, 0.80033571, 0.73769161], [0.92560593, 0.79549870, 0.73138149], [0.92408634, 0.79066188, 0.72509782], [0.92259257, 0.78582038, 0.71882946], [0.92111262, 0.78097847, 0.71258846], [0.91964557, 0.77613620, 0.70637599], [0.91819790, 0.77129068, 0.70018617], [0.91676720, 0.76644249, 0.69402174], [0.91534816, 0.76159342, 0.68788806], [0.91394046, 0.75674328, 0.68178577], [0.91255393, 0.75188769, 0.67570624], [0.91117810, 0.74703058, 0.66965958], [0.90981225, 0.74217193, 0.66364681], [0.90845631, 0.73731145, 0.65766843], [0.90711857, 0.73244522, 0.65171762], [0.90578934, 0.72757702, 0.64580349], [0.90446821, 0.72270670, 0.63992685], [0.90315480, 0.71783410, 0.63408853], [0.90185363, 0.71295684, 0.62828530], [0.90056181, 0.70807582, 0.62252022], [0.89927597, 0.70319221, 0.61679672], [0.89799564, 0.69830590, 0.61111575], [0.89672032, 0.69341676, 0.60547834], [0.89545267, 0.68852319, 0.59988306], [0.89419156, 0.68362534, 0.59433158], [0.89293342, 0.67872453, 0.58882738], [0.89167767, 0.67382071, 0.58337159], [0.89042371, 0.66891382, 0.57796541], [0.88917090, 0.66400384, 0.57261005], [0.88791872, 0.65909067, 0.56730668], [0.88667005, 0.65417250, 0.56205414], [0.88542008, 0.64925139, 0.55685666], [0.88416808, 0.64432738, 0.55171557], [0.88291328, 0.63940055, 0.54663223], [0.88165490, 0.63447097, 0.54160802], [0.88039211, 0.62953874, 0.53664435], [0.87912408, 0.62460401, 0.53174263], [0.87784992, 0.61966691, 0.52690431], [0.87656874, 0.61472764, 0.52213085], [0.87527962, 0.60978640, 0.51742369], [0.87398160, 0.60484341, 0.51278430], [0.87267379, 0.59989890, 0.50821409], [0.87135575, 0.59495282, 0.50371428], [0.87002561, 0.59000599, 0.49928670], [0.86868234, 0.58505874, 0.49493276], [0.86732494, 0.58011144, 0.49065382], [0.86595233, 0.57516447, 0.48645122], [0.86456348, 0.57021827, 0.48232627], [0.86315731, 0.56527328, 0.47828022], [0.86173275, 0.56032997, 0.47431426], [0.86028873, 0.55538883, 0.47042955], [0.85882442, 0.55045025, 0.46662711], [0.85733888, 0.54551465, 0.46290794], [0.85583071, 0.54058284, 0.45927307], [0.85429886, 0.53565540, 0.45572335], [0.85274227, 0.53073296, 0.45225954], [0.85115991, 0.52581613, 0.44888233], [0.84955078, 0.52090556, 0.44559226], [0.84791390, 0.51600192, 0.44238981], [0.84624832, 0.51110586, 0.43927533], [0.84455311, 0.50621807, 0.43624906], [0.84282741, 0.50133921, 0.43331112], [0.84107035, 0.49646996, 0.43046153], [0.83928115, 0.49161102, 0.42770018], [0.83745936, 0.48676280, 0.42502690], [0.83560431, 0.48192593, 0.42244142], [0.83371489, 0.47710144, 0.41994320], [0.83179047, 0.47228997, 0.41753164], [0.82983048, 0.46749218, 0.41520606], [0.82783443, 0.46270870, 0.41296566], [0.82580183, 0.45794015, 0.41080953], [0.82373229, 0.45318712, 0.40873667], [0.82162569, 0.44844998, 0.40674611], [0.81948157, 0.44372941, 0.40483662], [0.81729951, 0.43902609, 0.40300681], [0.81507930, 0.43434053, 0.40125532], [0.81282080, 0.42967323, 0.39958071], [0.81052390, 0.42502464, 0.39798147], [0.80818855, 0.42039519, 0.39645606], [0.80581485, 0.41578517, 0.39500298], [0.80340270, 0.41119510, 0.39362043], [0.80095214, 0.40662536, 0.39230669], [0.79846329, 0.40207627, 0.39106003], [0.79593630, 0.39754813, 0.38987866], [0.79337135, 0.39304120, 0.38876082], [0.79076866, 0.38855573, 0.38770470], [0.78812845, 0.38409196, 0.38670846], [0.78545100, 0.37965010, 0.38577027], [0.78273660, 0.37523032, 0.38488831], [0.77998556, 0.37083276, 0.38406076], [0.77719822, 0.36645754, 0.38328582], [0.77437495, 0.36210479, 0.38256169], [0.77151605, 0.35777464, 0.38188648], [0.76862195, 0.35346712, 0.38125850], [0.76569305, 0.34918228, 0.38067601], [0.76272975, 0.34492014, 0.38013731], [0.75973246, 0.34068073, 0.37964068], [0.75670159, 0.33646406, 0.37918448], [0.75363755, 0.33227014, 0.37876700], [0.75054072, 0.32809900, 0.37838654], [0.74741157, 0.32395055, 0.37804166], [0.74425052, 0.31982476, 0.37773081], [0.74105798, 0.31572158, 0.37745245], [0.73783435, 0.31164097, 0.37720511], [0.73458005, 0.30758288, 0.37698731], [0.73129546, 0.30354729, 0.37679757], [0.72798098, 0.29953413, 0.37663448], [0.72463700, 0.29554332, 0.37649676], [0.72126390, 0.29157480, 0.37638306], [0.71786206, 0.28762852, 0.37629208], [0.71443181, 0.28370442, 0.37622252], [0.71097352, 0.27980245, 0.37617313], [0.70748750, 0.27592259, 0.37614266], [0.70397409, 0.27206478, 0.37612990], [0.70043360, 0.26822899, 0.37613371], [0.69686632, 0.26441520, 0.37615291], [0.69327254, 0.26062340, 0.37618635], [0.68965253, 0.25685360, 0.37623291], [0.68600655, 0.25310580, 0.37629145], [0.68233484, 0.24938002, 0.37636095], [0.67863762, 0.24567630, 0.37644035], [0.67491512, 0.24199472, 0.37652853], [0.67116753, 0.23833535, 0.37662440], [0.66739504, 0.23469830, 0.37672691], [0.66359781, 0.23108369, 0.37683500], [0.65977600, 0.22749166, 0.37694762], [0.65592975, 0.22392235, 0.37706391], [0.65205918, 0.22037597, 0.37718281], [0.64816439, 0.21685275, 0.37730312], [0.64424550, 0.21335297, 0.37742379], [0.64030257, 0.20987692, 0.37754374], [0.63633567, 0.20642491, 0.37766190], [0.63234486, 0.20299730, 0.37777720], [0.62833011, 0.19959444, 0.37788907], [0.62429150, 0.19621684, 0.37799588], [0.62022902, 0.19286498, 0.37809649], [0.61614266, 0.18953940, 0.37818974], [0.61203242, 0.18624067, 0.37827444], [0.60789824, 0.18296943, 0.37834937], [0.60374000, 0.17972635, 0.37841404], [0.59955770, 0.17651220, 0.37846653], [0.59535127, 0.17332779, 0.37850546], [0.59112064, 0.17017398, 0.37852950], [0.58686572, 0.16705170, 0.37853726], [0.58258634, 0.16396195, 0.37852760], [0.57828232, 0.16090583, 0.37849943], [0.57395365, 0.15788445, 0.37845058], [0.56960020, 0.15489902, 0.37837948], [0.56522185, 0.15195079, 0.37828450], [0.56081843, 0.14904112, 0.37816410], [0.55638960, 0.14617156, 0.37801733], [0.55193545, 0.14334348, 0.37784149], [0.54745584, 0.14055843, 0.37763473], [0.54295065, 0.13781801, 0.37739515], [0.53841965, 0.13512398, 0.37712110], [0.53386261, 0.13247818, 0.37681091], [0.52927965, 0.12988221, 0.37646180], [0.52467068, 0.12733788, 0.37607164], [0.52003564, 0.12484701, 0.37563826], [0.51537424, 0.12241171, 0.37516003], [0.51068666, 0.12003365, 0.37463413], [0.50597299, 0.11771456, 0.37405808], [0.50123327, 0.11545624, 0.37342952], [0.49646750, 0.11326054, 0.37274632], [0.49167582, 0.11112909, 0.37200598], [0.48685856, 0.10906325, 0.37120582], [0.48201596, 0.10706442, 0.37034344], [0.47714828, 0.10513387, 0.36941650], [0.47225593, 0.10327260, 0.36842255], [0.46733939, 0.10148133, 0.36735917], [0.46239915, 0.09976065, 0.36622412], [0.45743580, 0.09811082, 0.36501514], [0.45245022, 0.09653153, 0.36372988], [0.44744296, 0.09502266, 0.36236656], [0.44241480, 0.09358362, 0.36092332], [0.43736661, 0.09221344, 0.35939846], [0.43230001, 0.09090969, 0.35778975], [0.42721549, 0.08967152, 0.35609639], [0.42211410, 0.08849693, 0.35431721], [0.41699698, 0.08738362, 0.35245124], [0.41186583, 0.08632804, 0.35049732], [0.40672217, 0.08532677, 0.34845483], [0.40156669, 0.08437758, 0.34632390], [0.39640071, 0.08347702, 0.34410442], [0.39122561, 0.08262142, 0.34179654], [0.38604309, 0.08180633, 0.33940046], [0.38085553, 0.08102606, 0.33691649], [0.37566316, 0.08027858, 0.33434595], [0.37046736, 0.07955978, 0.33168987], [0.36526951, 0.07886553, 0.32894943], [0.36007097, 0.07819169, 0.32612604], [0.35487306, 0.07753419, 0.32322125], [0.34967708, 0.07688902, 0.32023675], [0.34448536, 0.07625034, 0.31717438], [0.33929826, 0.07561586, 0.31403622], [0.33411661, 0.07498254, 0.31082433], [0.32894146, 0.07434697, 0.30754086], [0.32377380, 0.07370590, 0.30418800], [0.31861455, 0.07305628, 0.30076800], [0.31346457, 0.07239524, 0.29728315], [0.30832464, 0.07172011, 0.29373575], [0.30319545, 0.07102842, 0.29012809], [0.29807765, 0.07031788, 0.28646248], [0.29297177, 0.06958642, 0.28274117], [0.28787829, 0.06883212, 0.27896641], [0.28279763, 0.06805326, 0.27514038], [0.27773011, 0.06724828, 0.27126523], [0.27267598, 0.06641579, 0.26734303], [0.26763544, 0.06555455, 0.26337578], [0.26260976, 0.06466150, 0.25936605], [0.25759927, 0.06373523, 0.25531596], [0.25260288, 0.06277675, 0.25122673], [0.24762052, 0.06178533, 0.24710008], [0.24265208, 0.06076033, 0.24293764], [0.23769737, 0.05970120, 0.23874094], [0.23275618, 0.05860748, 0.23451143], [0.22782852, 0.05747825, 0.23025069], [0.22291807, 0.05630663, 0.22596300], [0.21802045, 0.05509893, 0.22164676], [0.21313526, 0.05385492, 0.21730306], [0.20826202, 0.05257439, 0.21293290], [0.20340025, 0.05125715, 0.20853721]] _vorticity_t_data = [ [0.08225560, 0.11492441, 0.26479017], [0.08312617, 0.11903837, 0.26686289], [0.08400181, 0.12310749, 0.26895267], [0.08487294, 0.12713875, 0.27105417], [0.08574385, 0.13113332, 0.27316912], [0.08661249, 0.13509450, 0.27529614], [0.08747533, 0.13902581, 0.27743329], [0.08833859, 0.14292709, 0.27958315], [0.08919013, 0.14680436, 0.28174002], [0.09004100, 0.15065551, 0.28390867], [0.09088232, 0.15448500, 0.28608501], [0.09171714, 0.15829319, 0.28827028], [0.09254608, 0.16208117, 0.29046458], [0.09336173, 0.16585233, 0.29266480], [0.09417284, 0.16960508, 0.29487442], [0.09496900, 0.17334347, 0.29708922], [0.09575619, 0.17706663, 0.29931153], [0.09653316, 0.18077576, 0.30154079], [0.09729329, 0.18447344, 0.30377451], [0.09804493, 0.18815809, 0.30601574], [0.09877832, 0.19183299, 0.30826092], [0.09949804, 0.19549751, 0.31051168], [0.10020549, 0.19915186, 0.31276843], [0.10089002, 0.20279929, 0.31502756], [0.10156203, 0.20643764, 0.31729251], [0.10221505, 0.21006899, 0.31956112], [0.10284688, 0.21369428, 0.32183267], [0.10346375, 0.21731242, 0.32410904], [0.10405562, 0.22092615, 0.32638711], [0.10462727, 0.22453468, 0.32866827], [0.10518146, 0.22813774, 0.33095325], [0.10570551, 0.23173845, 0.33323831], [0.10620936, 0.23533489, 0.33552622], [0.10669272, 0.23892742, 0.33781678], [0.10714289, 0.24251899, 0.34010639], [0.10757131, 0.24610739, 0.34239809], [0.10797639, 0.24969322, 0.34469128], [0.10834600, 0.25327913, 0.34698268], [0.10869133, 0.25686304, 0.34927505], [0.10901163, 0.26044532, 0.35156802], [0.10929328, 0.26402876, 0.35385806], [0.10954788, 0.26761128, 0.35614786], [0.10977489, 0.27119314, 0.35843709], [0.10996353, 0.27477648, 0.36072299], [0.11011983, 0.27836030, 0.36300681], [0.11024602, 0.28194432, 0.36528883], [0.11033616, 0.28552972, 0.36756748], [0.11038673, 0.28911718, 0.36984175], [0.11040471, 0.29270558, 0.37211295], [0.11038934, 0.29629516, 0.37438064], [0.11032908, 0.29988791, 0.37664208], [0.11023173, 0.30348258, 0.37889869], [0.11009863, 0.30707904, 0.38115045], [0.10992866, 0.31067752, 0.38339682], [0.10970926, 0.31428004, 0.38563492], [0.10945183, 0.31788484, 0.38786678], [0.10915570, 0.32149208, 0.39009193], [0.10882021, 0.32510190, 0.39230988], [0.10843373, 0.32871604, 0.39451799], [0.10800528, 0.33233317, 0.39671769], [0.10753553, 0.33595323, 0.39890871], [0.10702392, 0.33957631, 0.40109056], [0.10646662, 0.34320298, 0.40326210], [0.10585824, 0.34683394, 0.40542188], [0.10520656, 0.35046815, 0.40757096], [0.10451122, 0.35410566, 0.40970881], [0.10377192, 0.35774653, 0.41183489], [0.10298843, 0.36139080, 0.41394866], [0.10215131, 0.36503965, 0.41604787], [0.10126892, 0.36869202, 0.41813352], [0.10034231, 0.37234779, 0.42020525], [0.09937170, 0.37600698, 0.42226250], [0.09835742, 0.37966955, 0.42430469], [0.09729997, 0.38333550, 0.42633126], [0.09620004, 0.38700476, 0.42834163], [0.09505173, 0.39067803, 0.43033399], [0.09386234, 0.39435455, 0.43230887], [0.09263427, 0.39803412, 0.43426586], [0.09136928, 0.40171665, 0.43620437], [0.09006946, 0.40540204, 0.43812379], [0.08873731, 0.40909016, 0.44002354], [0.08737577, 0.41278087, 0.44190300], [0.08598831, 0.41647400, 0.44376159], [0.08457895, 0.42016939, 0.44559868], [0.08315236, 0.42386684, 0.44741369], [0.08171394, 0.42756614, 0.44920601], [0.08026988, 0.43126706, 0.45097504], [0.07882726, 0.43496935, 0.45272018], [0.07739416, 0.43867274, 0.45444085], [0.07597972, 0.44237693, 0.45613645], [0.07459424, 0.44608161, 0.45780643], [0.07324931, 0.44978644, 0.45945021], [0.07195782, 0.45349106, 0.46106724], [0.07073404, 0.45719509, 0.46265700], [0.06959365, 0.46089811, 0.46421897], [0.06855375, 0.46459968, 0.46575265], [0.06763273, 0.46829936, 0.46725759], [0.06685020, 0.47199664, 0.46873333], [0.06622677, 0.47569101, 0.47017948], [0.06577674, 0.47938244, 0.47159416], [0.06552566, 0.48307007, 0.47297774], [0.06549821, 0.48675309, 0.47433054], [0.06571558, 0.49043087, 0.47565232], [0.06619782, 0.49410277, 0.47694291], [0.06696294, 0.49776810, 0.47820211], [0.06801611, 0.50142699, 0.47942671], [0.06938288, 0.50507783, 0.48061980], [0.07107372, 0.50871983, 0.48178149], [0.07309574, 0.51235222, 0.48291199], [0.07544313, 0.51597502, 0.48400767], [0.07812721, 0.51958652, 0.48507257], [0.08114572, 0.52318584, 0.48610736], [0.08448833, 0.52677264, 0.48710972], [0.08815110, 0.53034572, 0.48808171], [0.09212706, 0.53390388, 0.48902580], [0.09640117, 0.53744678, 0.48993927], [0.10096511, 0.54097304, 0.49082601], [0.10580589, 0.54448174, 0.49168732], [0.11090917, 0.54797225, 0.49252203], [0.11626318, 0.55144324, 0.49333556], [0.12185356, 0.55489421, 0.49412566], [0.12766727, 0.55832396, 0.49489786], [0.13369121, 0.56173186, 0.49565192], [0.13991195, 0.56511701, 0.49639184], [0.14631713, 0.56847874, 0.49711902], [0.15289371, 0.57181634, 0.49783712], [0.15963000, 0.57512924, 0.49854817], [0.16651330, 0.57841691, 0.49925615], [0.17353288, 0.58167892, 0.49996313], [0.18067610, 0.58491493, 0.50067365], [0.18793344, 0.58812469, 0.50138963], [0.19529246, 0.59130810, 0.50211590], [0.20274431, 0.59446505, 0.50285464], [0.21027766, 0.59759568, 0.50361022], [0.21788350, 0.60070012, 0.50438554], [0.22555217, 0.60377865, 0.50518416], [0.23327491, 0.60683163, 0.50600926], [0.24104301, 0.60985952, 0.50686415], [0.24884894, 0.61286282, 0.50775157], [0.25668402, 0.61584223, 0.50867505], [0.26454253, 0.61879831, 0.50963658], [0.27241623, 0.62173194, 0.51063959], [0.28030037, 0.62464378, 0.51168577], [0.28818811, 0.62753476, 0.51277795], [0.29607483, 0.63040570, 0.51391788], [0.30395552, 0.63325751, 0.51510756], [0.31182548, 0.63609115, 0.51634887], [0.31968144, 0.63890744, 0.51764306], [0.32751881, 0.64170747, 0.51899197], [0.33533556, 0.64449201, 0.52039636], [0.34312773, 0.64726215, 0.52185776], [0.35089362, 0.65001870, 0.52337683], [0.35863089, 0.65276260, 0.52495444], [0.36633683, 0.65549486, 0.52659157], [0.37401197, 0.65821602, 0.52828804], [0.38165106, 0.66092757, 0.53004568], [0.38925805, 0.66362950, 0.53186311], [0.39682619, 0.66632361, 0.53374255], [0.40435935, 0.66900988, 0.53568268], [0.41185545, 0.67168934, 0.53768413], [0.41931195, 0.67436313, 0.53974757], [0.42673260, 0.67703119, 0.54187183], [0.43411299, 0.67969503, 0.54405806], [0.44145473, 0.68235501, 0.54630566], [0.44875982, 0.68501134, 0.54861400], [0.45602407, 0.68766556, 0.55098397], [0.46324986, 0.69031781, 0.55341478], [0.47043894, 0.69296834, 0.55590587], [0.47758904, 0.69561826, 0.55845753], [0.48469972, 0.69826831, 0.56106956], [0.49177413, 0.70091838, 0.56374112], [0.49881245, 0.70356902, 0.56647195], [0.50581153, 0.70622159, 0.56926226], [0.51277388, 0.70887607, 0.57211131], [0.51970103, 0.71153267, 0.57501859], [0.52659327, 0.71419186, 0.57798374], [0.53344948, 0.71685451, 0.58100655], [0.54026906, 0.71952134, 0.58408665], [0.54705487, 0.72219215, 0.58722338], [0.55380726, 0.72486737, 0.59041634], [0.56052657, 0.72754743, 0.59366511], [0.56721317, 0.73023276, 0.59696926], [0.57386499, 0.73292445, 0.60032836], [0.58048457, 0.73562232, 0.60374187], [0.58707274, 0.73832661, 0.60720930], [0.59362989, 0.74103770, 0.61073019], [0.60015641, 0.74375596, 0.61430405], [0.60665269, 0.74648175, 0.61793039], [0.61311912, 0.74921542, 0.62160871], [0.61955610, 0.75195731, 0.62533849], [0.62596359, 0.75470790, 0.62911918], [0.63234144, 0.75746769, 0.63295016], [0.63869119, 0.76023665, 0.63683100], [0.64501324, 0.76301508, 0.64076119], [0.65130797, 0.76580329, 0.64474018], [0.65757580, 0.76860157, 0.64876743], [0.66381711, 0.77141023, 0.65284240], [0.67003230, 0.77422953, 0.65696453], [0.67622177, 0.77705976, 0.66113327], [0.68238592, 0.77990119, 0.66534806], [0.68852514, 0.78275408, 0.66960833], [0.69463984, 0.78561869, 0.67391352], [0.70073040, 0.78849528, 0.67826307], [0.70679722, 0.79138408, 0.68265641], [0.71284071, 0.79428535, 0.68709296], [0.71886125, 0.79719932, 0.69157216], [0.72485924, 0.80012621, 0.69609343], [0.73083509, 0.80306624, 0.70065621], [0.73678917, 0.80601965, 0.70525992], [0.74272190, 0.80898665, 0.70990399], [0.74863273, 0.81196780, 0.71458740], [0.75452231, 0.81496323, 0.71930966], [0.76039158, 0.81797292, 0.72407043], [0.76624094, 0.82099707, 0.72886914], [0.77207078, 0.82403586, 0.73370523], [0.77788150, 0.82708949, 0.73857810], [0.78367350, 0.83015814, 0.74348721], [0.78944716, 0.83324197, 0.74843197], [0.79520290, 0.83634117, 0.75341183], [0.80094018, 0.83945630, 0.75842558], [0.80665847, 0.84258795, 0.76347196], [0.81235991, 0.84573553, 0.76855153], [0.81804489, 0.84889920, 0.77366371], [0.82371383, 0.85207911, 0.77880793], [0.82936712, 0.85527541, 0.78398361], [0.83500487, 0.85848838, 0.78918994], [0.84062467, 0.86171948, 0.79442393], [0.84622998, 0.86496746, 0.79968738], [0.85182123, 0.86823244, 0.80497972], [0.85739886, 0.87151457, 0.81030033], [0.86296333, 0.87481394, 0.81564861], [0.86851129, 0.87813251, 0.82102020], [0.87404693, 0.88146862, 0.82641787], [0.87957085, 0.88482234, 0.83184102], [0.88508363, 0.88819370, 0.83728899], [0.89058366, 0.89158388, 0.84275871], [0.89607183, 0.89499282, 0.84824952], [0.90155093, 0.89841950, 0.85376285], [0.90702184, 0.90186385, 0.85929802], [0.91248330, 0.90532691, 0.86485172], [0.91793653, 0.90880848, 0.87042326], [0.92338518, 0.91230711, 0.87601483], [0.92883088, 0.91582235, 0.88162632], [0.93427164, 0.91935565, 0.88725314], [0.93971244, 0.92290477, 0.89289983], [0.94515638, 0.92646829, 0.89856977], [0.95060356, 0.93004618, 0.90426466], [0.95605310, 0.93363854, 0.90998868], [0.96150666, 0.93724342, 0.91575606], [0.96695738, 0.94086247, 0.92157953], [0.97238707, 0.94450246, 0.92746703], [0.97777857, 0.94816875, 0.93343649], [0.98310507, 0.95187277, 0.93948603], [0.98834174, 0.95562829, 0.94558363], [0.99349184, 0.95943756, 0.95169832], [0.99857633, 0.96329654, 0.95778950]] _vorticity_data = _vorticity_t_data + _vorticity_p_data _difference_data = [ [0.09317630, 0.11117333, 0.26151239], [0.09697152, 0.11687021, 0.27309631], [0.10096885, 0.12239315, 0.28491036], [0.10499270, 0.12782437, 0.29687381], [0.10898740, 0.13319350, 0.30895384], [0.11292230, 0.13851314, 0.32115284], [0.11677874, 0.14379072, 0.33347631], [0.12054634, 0.14903305, 0.34591927], [0.12421597, 0.15424490, 0.35848249], [0.12777784, 0.15942930, 0.37117372], [0.13122438, 0.16458993, 0.38399390], [0.13454904, 0.16973078, 0.39694025], [0.13774403, 0.17485525, 0.41001322], [0.14079963, 0.17996609, 0.42321738], [0.14370728, 0.18506718, 0.43655022], [0.14645608, 0.19016193, 0.45001310], [0.14903482, 0.19525448, 0.46360362], [0.15143093, 0.20034937, 0.47731853], [0.15362665, 0.20545038, 0.49116235], [0.15560730, 0.21056390, 0.50512420], [0.15735349, 0.21569621, 0.51919772], [0.15884111, 0.22085406, 0.53337810], [0.16003963, 0.22604481, 0.54766269], [0.16092053, 0.23127922, 0.56203080], [0.16144553, 0.23656876, 0.57646619], [0.16156876, 0.24192717, 0.59094728], [0.16123528, 0.24737119, 0.60544468], [0.16037934, 0.25292130, 0.61991794], [0.15891657, 0.25860221, 0.63431839], [0.15673874, 0.26444442, 0.64858326], [0.15374227, 0.27048752, 0.66259429], [0.14975399, 0.27677729, 0.67624289], [0.14461903, 0.28337034, 0.68933032], [0.13815067, 0.29032903, 0.70161667], [0.13019375, 0.29771375, 0.71279281], [0.12070563, 0.30556233, 0.72251014], [0.10982269, 0.31386519, 0.73046944], [0.09795843, 0.32254310, 0.73652716], [0.08570024, 0.33146616, 0.74077181], [0.07367689, 0.34049675, 0.74346934], [0.06252233, 0.34951974, 0.74495630], [0.05283258, 0.35846008, 0.74554518], [0.04520939, 0.36727493, 0.74548891], [0.04023631, 0.37594185, 0.74498414], [0.03831576, 0.38445368, 0.74417463], [0.03948350, 0.39281375, 0.74315813], [0.04345844, 0.40102371, 0.74202430], [0.04962432, 0.40909532, 0.74081668], [0.05739800, 0.41703470, 0.73958775], [0.06626018, 0.42485215, 0.73836501], [0.07582789, 0.43255722, 0.73716979], [0.08583710, 0.44015834, 0.73602068], [0.09611024, 0.44766357, 0.73493125], [0.10653039, 0.45508042, 0.73391177], [0.11702165, 0.46241591, 0.73296937], [0.12753580, 0.46967672, 0.73210750], [0.13804321, 0.47686868, 0.73132951], [0.14852667, 0.48399707, 0.73063745], [0.15897744, 0.49106666, 0.73003226], [0.16939271, 0.49808168, 0.72951410], [0.17977386, 0.50504587, 0.72908242], [0.19012529, 0.51196251, 0.72873614], [0.20045367, 0.51883439, 0.72847377], [0.21076743, 0.52566384, 0.72829343], [0.22107637, 0.53245276, 0.72819301], [0.23139144, 0.53920256, 0.72817020], [0.24172459, 0.54591421, 0.72822258], [0.25208860, 0.55258823, 0.72834769], [0.26249697, 0.55922467, 0.72854317], [0.27296382, 0.56582312, 0.72880681], [0.28350369, 0.57238271, 0.72913673], [0.29413138, 0.57890214, 0.72953149], [0.30486166, 0.58537967, 0.72999025], [0.31570894, 0.59181322, 0.73051298], [0.32668681, 0.59820041, 0.73110060], [0.33780753, 0.60453865, 0.73175521], [0.34908180, 0.61082531, 0.73247968], [0.36051697, 0.61705790, 0.73327922], [0.37211638, 0.62323432, 0.73416123], [0.38387988, 0.62935306, 0.73513375], [0.39580281, 0.63541344, 0.73620602], [0.40787554, 0.64141586, 0.73738846], [0.42008256, 0.64736207, 0.73869308], [0.43240665, 0.65325485, 0.74012945], [0.44482701, 0.65909826, 0.74170693], [0.45732109, 0.66489739, 0.74343353], [0.46986588, 0.67065815, 0.74531538], [0.48243916, 0.67638699, 0.74735656], [0.49502055, 0.68209061, 0.74955890], [0.50759227, 0.68777566, 0.75192214], [0.52013952, 0.69344853, 0.75444409], [0.53265066, 0.69911520, 0.75712102], [0.54511511, 0.70478153, 0.75994930], [0.55751816, 0.71045432, 0.76292914], [0.56986354, 0.71613651, 0.76604883], [0.58214859, 0.72183221, 0.76930236], [0.59436024, 0.72754780, 0.77269163], [0.60650809, 0.73328445, 0.77620411], [0.61858647, 0.73904668, 0.77983837], [0.63059636, 0.74483734, 0.78358922], [0.64254033, 0.75065877, 0.78745106], [0.65441860, 0.75651373, 0.79142043], [0.66623153, 0.76240488, 0.79549418], [0.67798504, 0.76833329, 0.79966600], [0.68967550, 0.77430243, 0.80393610], [0.70131075, 0.78031263, 0.80829755], [0.71288853, 0.78636686, 0.81275022], [0.72441124, 0.79246672, 0.81729113], [0.73588370, 0.79861307, 0.82191590], [0.74730444, 0.80480845, 0.82662434], [0.75867599, 0.81105425, 0.83141375], [0.77000070, 0.81735182, 0.83628157], [0.78127895, 0.82370305, 0.84122655], [0.79251162, 0.83010967, 0.84624710], [0.80369975, 0.83657330, 0.85134141], [0.81484311, 0.84309597, 0.85650845], [0.82594216, 0.84967946, 0.86174654], [0.83699675, 0.85632577, 0.86705416], [0.84800383, 0.86303779, 0.87243156], [0.85896284, 0.86981769, 0.87787684], [0.86987188, 0.87666811, 0.88338843], [0.88072260, 0.88359376, 0.88896898], [0.89151256, 0.89059766, 0.89461579], [0.90223219, 0.89768518, 0.90033034], [0.91286295, 0.90486468, 0.90612019], [0.92339067, 0.91214345, 0.91198727], [0.93376907, 0.91953891, 0.91796043], [0.94387686, 0.92709058, 0.92414784], [0.94502413, 0.92672740, 0.92320173], [0.94017715, 0.91750110, 0.91273530], [0.93577882, 0.90818496, 0.90199590], [0.93161955, 0.89884559, 0.89112473], [0.92763669, 0.88950153, 0.88016251], [0.92379637, 0.88016199, 0.86913066], [0.92007678, 0.87083231, 0.85804265], [0.91646227, 0.86151587, 0.84690792], [0.91294097, 0.85221483, 0.83573351], [0.90950339, 0.84293065, 0.82452495], [0.90614135, 0.83366435, 0.81328703], [0.90284824, 0.82441650, 0.80202350], [0.89961835, 0.81518734, 0.79073759], [0.89644640, 0.80597704, 0.77943233], [0.89332810, 0.79678541, 0.76811006], [0.89025854, 0.78761252, 0.75677380], [0.88723415, 0.77845801, 0.74542553], [0.88425152, 0.76932142, 0.73406721], [0.88130757, 0.76020224, 0.72270059], [0.87839898, 0.75110001, 0.71132772], [0.87552202, 0.74201448, 0.69995114], [0.87267498, 0.73294464, 0.68857164], [0.86985472, 0.72389001, 0.67719140], [0.86705966, 0.71484951, 0.66581120], [0.86428554, 0.70582315, 0.65443443], [0.86153122, 0.69680968, 0.64306165], [0.85879456, 0.68780825, 0.63169442], [0.85607377, 0.67881784, 0.62033401], [0.85336475, 0.66983845, 0.60898403], [0.85066718, 0.66086845, 0.59764454], [0.84798038, 0.65190630, 0.58631596], [0.84529929, 0.64295243, 0.57500309], [0.84262333, 0.63400527, 0.56370649], [0.83995267, 0.62506283, 0.55242594], [0.83728236, 0.61612552, 0.54116651], [0.83461150, 0.60719184, 0.52992929], [0.83194170, 0.59825898, 0.51871286], [0.82926584, 0.58932842, 0.50752486], [0.82658652, 0.58039681, 0.49636308], [0.82390077, 0.57146348, 0.48523112], [0.82120472, 0.56252830, 0.47413374], [0.81850284, 0.55358664, 0.46306700], [0.81578580, 0.54464120, 0.45204172], [0.81305988, 0.53568615, 0.44105231], [0.81031573, 0.52672425, 0.43011000], [0.80756008, 0.51774912, 0.41920905], [0.80478300, 0.50876385, 0.40836176], [0.80199136, 0.49976163, 0.39756263], [0.79917761, 0.49074411, 0.38682195], [0.79634125, 0.48170863, 0.37614268], [0.79348534, 0.47265010, 0.36552429], [0.79060209, 0.46357018, 0.35497832], [0.78769221, 0.45446502, 0.34450752], [0.78475844, 0.44532901, 0.33411300], [0.78179438, 0.43616264, 0.32380621], [0.77879860, 0.42696282, 0.31359382], [0.77577003, 0.41772599, 0.30348288], [0.77270738, 0.40844842, 0.29348145], [0.76960910, 0.39912628, 0.28359883], [0.76647331, 0.38975562, 0.27384573], [0.76329775, 0.38033247, 0.26423455], [0.76007961, 0.37085287, 0.25477962], [0.75681552, 0.36131299, 0.24549744], [0.75350142, 0.35170920, 0.23640702], [0.75013244, 0.34203820, 0.22753009], [0.74670837, 0.33229173, 0.21888681], [0.74322062, 0.32246895, 0.21050730], [0.73966264, 0.31256672, 0.20242263], [0.73602766, 0.30258171, 0.19466697], [0.73230751, 0.29251159, 0.18727887], [0.72848868, 0.28235996, 0.18030258], [0.72455978, 0.27212835, 0.17378304], [0.72050526, 0.26182377, 0.16776811], [0.71630775, 0.25145685, 0.16230504], [0.71194775, 0.24104317, 0.15743769], [0.70740461, 0.23060296, 0.15320278], [0.70265778, 0.22016032, 0.14962642], [0.69768564, 0.20974625, 0.14671934], [0.69247010, 0.19939235, 0.14447576], [0.68699563, 0.18913262, 0.14287203], [0.68125094, 0.17900057, 0.14186849], [0.67522904, 0.16902840, 0.14141262], [0.66892723, 0.15924601, 0.14144362], [0.66234629, 0.14968150, 0.14189670], [0.65548946, 0.14036226, 0.14270608], [0.64836184, 0.13131545, 0.14380938], [0.64096909, 0.12257090, 0.14514666], [0.63331719, 0.11416164, 0.14666355], [0.62541177, 0.10612632, 0.14830833], [0.61725809, 0.09850956, 0.15003428], [0.60886121, 0.09136271, 0.15179467], [0.60022601, 0.08474269, 0.15354719], [0.59135807, 0.07870938, 0.15524760], [0.58226407, 0.07332111, 0.15685285], [0.57295232, 0.06862870, 0.15832095], [0.56343372, 0.06466696, 0.15960971], [0.55372241, 0.06144627, 0.16067796], [0.54383514, 0.05894915, 0.16148955], [0.53379121, 0.05712858, 0.16201381], [0.52361200, 0.05591095, 0.16222653], [0.51332147, 0.05519900, 0.16210827], [0.50294151, 0.05489269, 0.16165212], [0.49249206, 0.05489498, 0.16085946], [0.48199704, 0.05509874, 0.15972947], [0.47146853, 0.05543753, 0.15828036], [0.46092984, 0.05581817, 0.15651615], [0.45038823, 0.05620093, 0.15446036], [0.43985504, 0.05653967, 0.15212964], [0.42933959, 0.05679893, 0.14954130], [0.41884881, 0.05695351, 0.14671310], [0.40838748, 0.05698680, 0.14366262], [0.39795842, 0.05688899, 0.14040679], [0.38756618, 0.05664745, 0.13695962], [0.37721626, 0.05624859, 0.13333329], [0.36690097, 0.05571028, 0.12954563], [0.35662892, 0.05501236, 0.12560413], [0.34639461, 0.05416713, 0.12152211], [0.33620182, 0.05316577, 0.11730740], [0.32604244, 0.05202498, 0.11297139], [0.31592786, 0.05071934, 0.10851752], [0.30584405, 0.04927678, 0.10395692], [0.29579063, 0.04769543, 0.09929501], [0.28577617, 0.04595517, 0.09453470], [0.27578839, 0.04407730, 0.08968329], [0.26582514, 0.04206161, 0.08474472], [0.25588406, 0.03990047, 0.07972236], [0.24596222, 0.03762595, 0.07461914]] datad = { 'density': _density_data, 'phase': _phase_data, 'speed': _speed_data, 'temperature': _temperature_data, 'velocity': _velocity_data, 'vorticity': _vorticity_data, 'difference': _difference_data, }
41.548769
78
0.645337
_density_data = [ [0.90220216, 0.94417980, 0.94380273], [0.89544454, 0.94095789, 0.94106488], [0.88868558, 0.93774038, 0.93840987], [0.88192751, 0.93452625, 0.93583728], [0.87517248, 0.93131455, 0.93334654], [0.86842255, 0.92810438, 0.93093690], [0.86167970, 0.92489490, 0.92860749], [0.85494584, 0.92168533, 0.92635732], [0.84822279, 0.91847494, 0.92418529], [0.84151229, 0.91526306, 0.92209023], [0.83481598, 0.91204906, 0.92007088], [0.82813543, 0.90883237, 0.91812595], [0.82147215, 0.90561245, 0.91625407], [0.81482754, 0.90238881, 0.91445386], [0.80820295, 0.89916100, 0.91272391], [0.80159965, 0.89592859, 0.91106281], [0.79501887, 0.89269119, 0.90946910], [0.78846179, 0.88944845, 0.90794134], [0.78192947, 0.88620003, 0.90647814], [0.77542295, 0.88294564, 0.90507810], [0.76894320, 0.87968498, 0.90373988], [0.76249117, 0.87641781, 0.90246212], [0.75606778, 0.87314387, 0.90124351], [0.74967389, 0.86986292, 0.90008279], [0.74331039, 0.86657473, 0.89897869], [0.73697811, 0.86327910, 0.89793000], [0.73067788, 0.85997580, 0.89693553], [0.72441053, 0.85666464, 0.89599414], [0.71817690, 0.85334541, 0.89510469], [0.71197782, 0.85001791, 0.89426610], [0.70581423, 0.84668191, 0.89347718], [0.69968688, 0.84333724, 0.89273702], [0.69359663, 0.83998369, 0.89204464], [0.68754438, 0.83662105, 0.89139904], [0.68153106, 0.83324911, 0.89079928], [0.67555762, 0.82986764, 0.89024441], [0.66962506, 0.82647642, 0.88973352], [0.66373440, 0.82307522, 0.88926568], [0.65788673, 0.81966379, 0.88884001], [0.65208315, 0.81624189, 0.88845562], [0.64632485, 0.81280925, 0.88811162], [0.64061303, 0.80936562, 0.88780715], [0.63494897, 0.80591071, 0.88754133], [0.62933401, 0.80244424, 0.88731328], [0.62376953, 0.79896592, 0.88712212], [0.61825699, 0.79547544, 0.88696697], [0.61279785, 0.79197249, 0.88684700], [0.60739371, 0.78845676, 0.88676131], [0.60204624, 0.78492789, 0.88670892], [0.59675713, 0.78138555, 0.88668891], [0.59152819, 0.77782940, 0.88670031], [0.58636126, 0.77425906, 0.88674212], [0.58125826, 0.77067417, 0.88681333], [0.57622118, 0.76707435, 0.88691290], [0.57125208, 0.76345922, 0.88703974], [0.56635309, 0.75982839, 0.88719273], [0.56152638, 0.75618144, 0.88737072], [0.55677422, 0.75251799, 0.88757251], [0.55209890, 0.74883762, 0.88779685], [0.54750281, 0.74513991, 0.88804246], [0.54298830, 0.74142444, 0.88830811], [0.53855780, 0.73769077, 0.88859267], [0.53421391, 0.73393850, 0.88889434], [0.52995915, 0.73016720, 0.88921160], [0.52579610, 0.72637645, 0.88954287], [0.52172732, 0.72256583, 0.88988650], [0.51775541, 0.71873493, 0.89024078], [0.51388294, 0.71488334, 0.89060393], [0.51011248, 0.71101066, 0.89097410], [0.50644655, 0.70711649, 0.89134936], [0.50288765, 0.70320047, 0.89172772], [0.49943822, 0.69926217, 0.89210744], [0.49610063, 0.69530122, 0.89248647], [0.49287720, 0.69131735, 0.89286215], [0.48977007, 0.68731025, 0.89323218], [0.48678129, 0.68327963, 0.89359417], [0.48391278, 0.67922522, 0.89394566], [0.48116628, 0.67514678, 0.89428415], [0.47854335, 0.67104413, 0.89460702], [0.47604536, 0.66691708, 0.89491161], [0.47367364, 0.66276538, 0.89519579], [0.47142903, 0.65858902, 0.89545627], [0.46931216, 0.65438798, 0.89569008], [0.46732345, 0.65016224, 0.89589433], [0.46546305, 0.64591186, 0.89606608], [0.46373081, 0.64163690, 0.89620239], [0.46212629, 0.63733750, 0.89630027], [0.46064879, 0.63301382, 0.89635684], [0.45929732, 0.62866605, 0.89636919], [0.45807033, 0.62429458, 0.89633399], [0.45696613, 0.61989976, 0.89624827], [0.45598269, 0.61548199, 0.89610905], [0.45511768, 0.61104174, 0.89591342], [0.45436847, 0.60657953, 0.89565850], [0.45373211, 0.60209592, 0.89534144], [0.45320531, 0.59759159, 0.89495941], [0.45278458, 0.59306722, 0.89450974], [0.45246621, 0.58852353, 0.89398987], [0.45224622, 0.58396130, 0.89339735], [0.45212047, 0.57938135, 0.89272981], [0.45208461, 0.57478456, 0.89198505], [0.45213406, 0.57017185, 0.89116092], [0.45226366, 0.56554440, 0.89025507], [0.45246908, 0.56090297, 0.88926607], [0.45274551, 0.55624857, 0.88819230], [0.45308803, 0.55158223, 0.88703226], [0.45349173, 0.54690499, 0.88578463], [0.45395166, 0.54221790, 0.88444824], [0.45446291, 0.53752203, 0.88302210], [0.45502044, 0.53281852, 0.88150529], [0.45561856, 0.52810881, 0.87989676], [0.45625342, 0.52339359, 0.87819649], [0.45692037, 0.51867392, 0.87640412], [0.45761487, 0.51395086, 0.87451947], [0.45833250, 0.50922545, 0.87254251], [0.45906898, 0.50449872, 0.87047333], [0.45982017, 0.49977167, 0.86831217], [0.46058208, 0.49504528, 0.86605942], [0.46135090, 0.49032052, 0.86371555], [0.46212297, 0.48559831, 0.86128120], [0.46289481, 0.48087955, 0.85875708], [0.46366216, 0.47616550, 0.85614385], [0.46442285, 0.47145661, 0.85344263], [0.46517394, 0.46675366, 0.85065444], [0.46591265, 0.46205743, 0.84778034], [0.46663636, 0.45736864, 0.84482148], [0.46734263, 0.45268799, 0.84177905], [0.46802917, 0.44801616, 0.83865432], [0.46869383, 0.44335376, 0.83544858], [0.46933466, 0.43870139, 0.83216318], [0.46994980, 0.43405962, 0.82879947], [0.47053758, 0.42942898, 0.82535887], [0.47109642, 0.42480997, 0.82184277], [0.47162490, 0.42020304, 0.81825263], [0.47212171, 0.41560865, 0.81458986], [0.47258566, 0.41102721, 0.81085591], [0.47301567, 0.40645908, 0.80705223], [0.47341074, 0.40190463, 0.80318024], [0.47376999, 0.39736419, 0.79924139], [0.47409263, 0.39283807, 0.79523708], [0.47437795, 0.38832654, 0.79116870], [0.47462530, 0.38382989, 0.78703766], [0.47483412, 0.37934834, 0.78284530], [0.47500393, 0.37488213, 0.77859297], [0.47513427, 0.37043147, 0.77428199], [0.47522479, 0.36599656, 0.76991363], [0.47527514, 0.36157758, 0.76548918], [0.47528466, 0.35717487, 0.76101004], [0.47525316, 0.35278857, 0.75647742], [0.47518080, 0.34841867, 0.75189235], [0.47506742, 0.34406531, 0.74725597], [0.47491290, 0.33972863, 0.74256938], [0.47471715, 0.33540873, 0.73783366], [0.47448009, 0.33110575, 0.73304987], [0.47420168, 0.32681981, 0.72821900], [0.47388188, 0.32255100, 0.72334205], [0.47352067, 0.31829946, 0.71841996], [0.47311806, 0.31406530, 0.71345366], [0.47267406, 0.30984863, 0.70844403], [0.47218867, 0.30564956, 0.70339194], [0.47166137, 0.30146848, 0.69829868], [0.47109270, 0.29730529, 0.69316468], [0.47048281, 0.29316004, 0.68799058], [0.46983176, 0.28903289, 0.68277713], [0.46913959, 0.28492398, 0.67752502], [0.46840632, 0.28083345, 0.67223496], [0.46763200, 0.27676148, 0.66690758], [0.46681665, 0.27270825, 0.66154354], [0.46596031, 0.26867393, 0.65614343], [0.46506286, 0.26465880, 0.65070800], [0.46412426, 0.26066310, 0.64523790], [0.46314479, 0.25668693, 0.63973335], [0.46212445, 0.25273054, 0.63419487], [0.46106323, 0.24879421, 0.62862296], [0.45996110, 0.24487823, 0.62301809], [0.45881803, 0.24098289, 0.61738074], [0.45763398, 0.23710854, 0.61171135], [0.45640887, 0.23325554, 0.60601037], [0.45514261, 0.22942427, 0.60027826], [0.45383521, 0.22561510, 0.59451528], [0.45248658, 0.22182847, 0.58872183], [0.45109659, 0.21806485, 0.58289828], [0.44966511, 0.21432473, 0.57704502], [0.44819199, 0.21060865, 0.57116243], [0.44667705, 0.20691717, 0.56525088], [0.44512012, 0.20325090, 0.55931077], [0.44352106, 0.19961045, 0.55334230], [0.44187976, 0.19599648, 0.54734563], [0.44019583, 0.19240976, 0.54132138], [0.43846903, 0.18885105, 0.53526994], [0.43669905, 0.18532117, 0.52919170], [0.43488561, 0.18182099, 0.52308708], [0.43302838, 0.17835141, 0.51695650], [0.43112700, 0.17491341, 0.51080040], [0.42918111, 0.17150798, 0.50461925], [0.42719043, 0.16813620, 0.49841321], [0.42515465, 0.16479918, 0.49218247], [0.42307313, 0.16149814, 0.48592814], [0.42094540, 0.15823432, 0.47965080], [0.41877098, 0.15500903, 0.47335108], [0.41654936, 0.15182361, 0.46702967], [0.41428002, 0.14867950, 0.46068730], [0.41196239, 0.14557814, 0.45432475], [0.40959590, 0.14252107, 0.44794287], [0.40717995, 0.13950986, 0.44154258], [0.40471394, 0.13654614, 0.43512488], [0.40219729, 0.13363161, 0.42869038], [0.39962936, 0.13076802, 0.42224018], [0.39700936, 0.12795703, 0.41577611], [0.39433660, 0.12520039, 0.40929955], [0.39161037, 0.12249987, 0.40281200], [0.38882999, 0.11985720, 0.39631510], [0.38599472, 0.11727411, 0.38981058], [0.38310387, 0.11475229, 0.38330035], [0.38015674, 0.11229336, 0.37678646], [0.37715263, 0.10989888, 0.37027108], [0.37409088, 0.10757029, 0.36375657], [0.37097085, 0.10530889, 0.35724546], [0.36779195, 0.10311585, 0.35074041], [0.36455362, 0.10099212, 0.34424427], [0.36125536, 0.09893846, 0.33776007], [0.35789677, 0.09695535, 0.33129096], [0.35447749, 0.09504303, 0.32484029], [0.35099729, 0.09320140, 0.31841152], [0.34745604, 0.09143006, 0.31200825], [0.34385372, 0.08972821, 0.30563417], [0.34019047, 0.08809468, 0.29929318], [0.33646657, 0.08652789, 0.29298920], [0.33268245, 0.08502593, 0.28672608], [0.32883870, 0.08358647, 0.28050768], [0.32493609, 0.08220684, 0.27433782], [0.32097556, 0.08088399, 0.26822019], [0.31695820, 0.07961456, 0.26215837], [0.31288529, 0.07839490, 0.25615575], [0.30875826, 0.07722111, 0.25021549], [0.30457867, 0.07608911, 0.24434046], [0.30034822, 0.07499465, 0.23853326], [0.29606871, 0.07393344, 0.23279613], [0.29174204, 0.07290112, 0.22713094], [0.28737014, 0.07189340, 0.22153921], [0.28295501, 0.07090603, 0.21602205], [0.27849993, 0.06993211, 0.21058327], [0.27400681, 0.06896804, 0.20522255], [0.26947709, 0.06801140, 0.19993831], [0.26491272, 0.06705861, 0.19473015], [0.26031556, 0.06610638, 0.18959733], [0.25568737, 0.06515168, 0.18453880], [0.25103114, 0.06418929, 0.17955550], [0.24635153, 0.06321115, 0.17465056], [0.24164654, 0.06222163, 0.16981600], [0.23691745, 0.06121879, 0.16504980], [0.23216536, 0.06020099, 0.16034977], [0.22739756, 0.05915624, 0.15572185], [0.22261214, 0.05808842, 0.15115908], [0.21780744, 0.05700050, 0.14665582], [0.21298394, 0.05589169, 0.14220951]] _phase_data = [ [0.56724332, 0.41001824, 0.07083093], [0.57369533, 0.40631385, 0.06763640], [0.57994810, 0.40262767, 0.06473393], [0.58621727, 0.39883307, 0.06205459], [0.59231449, 0.39504395, 0.05971206], [0.59841114, 0.39115403, 0.05767412], [0.60434243, 0.38726851, 0.05602886], [0.61027304, 0.38327951, 0.05476297], [0.61602853, 0.37930459, 0.05394142], [0.62179468, 0.37521528, 0.05356325], [0.62739819, 0.37113394, 0.05366089], [0.63296349, 0.36697069, 0.05424569], [0.63841081, 0.36278458, 0.05531731], [0.64376271, 0.35855932, 0.05687403], [0.64904584, 0.35427327, 0.05891871], [0.65418902, 0.34998499, 0.06140802], [0.65927887, 0.34562236, 0.06436753], [0.66424610, 0.34124422, 0.06774175], [0.66908200, 0.33686041, 0.07149836], [0.67385549, 0.33240821, 0.07567487], [0.67849057, 0.32795839, 0.08019026], [0.68299052, 0.32351058, 0.08502570], [0.68739738, 0.31902389, 0.09021504], [0.69166679, 0.31454412, 0.09569861], [0.69579223, 0.31008093, 0.10145681], [0.69977763, 0.30563295, 0.10748756], [0.70363574, 0.30118776, 0.11380990], [0.70733660, 0.29678243, 0.12037554], [0.71087774, 0.29242414, 0.12717830], [0.71425607, 0.28812113, 0.13421258], [0.71747399, 0.28387470, 0.14148683], [0.72052428, 0.27969884, 0.14899031], [0.72339728, 0.27561226, 0.15670273], [0.72609023, 0.27162524, 0.16461824], [0.72860058, 0.26774828, 0.17273041], [0.73092616, 0.26399183, 0.18103219], [0.73306539, 0.26036590, 0.18951638], [0.73501868, 0.25687739, 0.19818207], [0.73678279, 0.25354020, 0.20700886], [0.73835819, 0.25036227, 0.21598766], [0.73974597, 0.24735064, 0.22510891], [0.74094777, 0.24451140, 0.23436265], [0.74196578, 0.24184955, 0.24373863], [0.74280272, 0.23936901, 0.25322643], [0.74346173, 0.23707255, 0.26281551], [0.74394637, 0.23496186, 0.27249532], [0.74426050, 0.23303771, 0.28225449], [0.74440831, 0.23129966, 0.29208237], [0.74439423, 0.22974621, 0.30196906], [0.74422282, 0.22837499, 0.31190490], [0.74389873, 0.22718285, 0.32188048], [0.74342664, 0.22616596, 0.33188669], [0.74281127, 0.22531985, 0.34191474], [0.74205730, 0.22463956, 0.35195616], [0.74116936, 0.22411969, 0.36200283], [0.74015240, 0.22375458, 0.37204357], [0.73901072, 0.22353801, 0.38207355], [0.73774860, 0.22346375, 0.39208656], [0.73637028, 0.22352544, 0.40207607], [0.73487988, 0.22371668, 0.41203587], [0.73328139, 0.22403107, 0.42196011], [0.73157865, 0.22446223, 0.43184326], [0.72977536, 0.22500389, 0.44168013], [0.72787579, 0.22564963, 0.45146241], [0.72588267, 0.22639364, 0.46118937], [0.72379920, 0.22723013, 0.47085716], [0.72162847, 0.22815351, 0.48046197], [0.71937343, 0.22915837, 0.49000029], [0.71703688, 0.23023956, 0.49946892], [0.71462148, 0.23139217, 0.50886493], [0.71213007, 0.23261136, 0.51818447], [0.70956452, 0.23389296, 0.52742703], [0.70692691, 0.23523289, 0.53659083], [0.70421925, 0.23662728, 0.54567406], [0.70144339, 0.23807254, 0.55467513], [0.69860103, 0.23956532, 0.56359267], [0.69569369, 0.24110255, 0.57242556], [0.69272221, 0.24268169, 0.58117426], [0.68968792, 0.24430011, 0.58983750], [0.68659180, 0.24595554, 0.59841463], [0.68343465, 0.24764596, 0.60690513], [0.68021707, 0.24936960, 0.61530861], [0.67693948, 0.25112494, 0.62362475], [0.67360205, 0.25291077, 0.63185346], [0.67020323, 0.25472691, 0.63999820], [0.66674402, 0.25657195, 0.64805568], [0.66322400, 0.25844541, 0.65602563], [0.65964254, 0.26034702, 0.66390773], [0.65599875, 0.26227679, 0.67170157], [0.65229153, 0.26423496, 0.67940663], [0.64851954, 0.26622203, 0.68702221], [0.64468060, 0.26823904, 0.69454851], [0.64077120, 0.27028786, 0.70198747], [0.63679115, 0.27236872, 0.70933383], [0.63273808, 0.27448309, 0.71658581], [0.62860936, 0.27663269, 0.72374126], [0.62440210, 0.27881949, 0.73079761], [0.62011309, 0.28104566, 0.73775186], [0.61573889, 0.28331365, 0.74460048], [0.61127572, 0.28562609, 0.75133940], [0.60671957, 0.28798585, 0.75796392], [0.60206609, 0.29039601, 0.76446868], [0.59731069, 0.29285981, 0.77084761], [0.59244787, 0.29538100, 0.77709461], [0.58747183, 0.29796350, 0.78320265], [0.58237864, 0.30061025, 0.78916126], [0.57716272, 0.30332502, 0.79496090], [0.57181826, 0.30611163, 0.80059103], [0.56633926, 0.30897393, 0.80604014], [0.56071959, 0.31191571, 0.81129563], [0.55495299, 0.31494071, 0.81634387], [0.54903314, 0.31805247, 0.82117010], [0.54295376, 0.32125431, 0.82575850], [0.53670817, 0.32454950, 0.83009251], [0.53028763, 0.32794207, 0.83415578], [0.52368879, 0.33143287, 0.83792761], [0.51690635, 0.33502336, 0.84138818], [0.50993559, 0.33871427, 0.84451696], [0.50277257, 0.34250546, 0.84729293], [0.49541426, 0.34639582, 0.84969480], [0.48785876, 0.35038314, 0.85170127], [0.48010551, 0.35446399, 0.85329141], [0.47215549, 0.35863367, 0.85444501], [0.46400447, 0.36288976, 0.85514340], [0.45566227, 0.36722210, 0.85536788], [0.44713833, 0.37162047, 0.85510290], [0.43844227, 0.37607441, 0.85433577], [0.42958621, 0.38057218, 0.85305689], [0.42058177, 0.38510239, 0.85125950], [0.41144690, 0.38965075, 0.84894112], [0.40220605, 0.39420025, 0.84610490], [0.39288171, 0.39873559, 0.84275762], [0.38349855, 0.40324130, 0.83891048], [0.37408360, 0.40770177, 0.83457920], [0.36466722, 0.41210102, 0.82978465], [0.35527868, 0.41642482, 0.82455055], [0.34594787, 0.42066002, 0.81890378], [0.33670810, 0.42479323, 0.81287608], [0.32759084, 0.42881325, 0.80650068], [0.31862215, 0.43271248, 0.79980883], [0.30982983, 0.43648364, 0.79283433], [0.30124029, 0.44012100, 0.78561114], [0.29288233, 0.44361869, 0.77817660], [0.28477939, 0.44697375, 0.77056484], [0.27694670, 0.45018708, 0.76280283], [0.26940193, 0.45325876, 0.75492020], [0.26216024, 0.45619000, 0.74694475], [0.25523415, 0.45898297, 0.73890234], [0.24863345, 0.46164068, 0.73081674], [0.24236623, 0.46416643, 0.72271109], [0.23643887, 0.46656363, 0.71460825], [0.23084854, 0.46883873, 0.70652028], [0.22559388, 0.47099685, 0.69846259], [0.22067083, 0.47304334, 0.69044868], [0.21607267, 0.47498376, 0.68249026], [0.21179018, 0.47682377, 0.67459735], [0.20781175, 0.47856909, 0.66677840], [0.20412355, 0.48022546, 0.65904036], [0.20070972, 0.48179858, 0.65138879], [0.19755260, 0.48329407, 0.64382798], [0.19463299, 0.48471751, 0.63636101], [0.19193036, 0.48607431, 0.62898985], [0.18942316, 0.48736979, 0.62171541], [0.18708905, 0.48860912, 0.61453762], [0.18490519, 0.48979730, 0.60745550], [0.18284850, 0.49093918, 0.60046718], [0.18089588, 0.49203942, 0.59356996], [0.17902444, 0.49310250, 0.58676036], [0.17721176, 0.49413269, 0.58003415], [0.17543603, 0.49513408, 0.57338636], [0.17367625, 0.49611052, 0.56681136], [0.17191243, 0.49706564, 0.56030287], [0.17012570, 0.49800282, 0.55385397], [0.16829867, 0.49892510, 0.54745788], [0.16641491, 0.49983547, 0.54110563], [0.16445972, 0.50073657, 0.53478849], [0.16242011, 0.50163068, 0.52849746], [0.16028489, 0.50251981, 0.52222315], [0.15804478, 0.50340563, 0.51595585], [0.15569256, 0.50428951, 0.50968556], [0.15322322, 0.50517248, 0.50340207], [0.15063412, 0.50605524, 0.49709504], [0.14792513, 0.50693812, 0.49075405], [0.14509892, 0.50782117, 0.48436869], [0.14216108, 0.50870404, 0.47792862], [0.13912049, 0.50958610, 0.47142361], [0.13598955, 0.51046638, 0.46484364], [0.13278459, 0.51134360, 0.45817896], [0.12952624, 0.51221616, 0.45142008], [0.12623991, 0.51308221, 0.44455788], [0.12295556, 0.51393979, 0.43758212], [0.11971036, 0.51478631, 0.43048588], [0.11654716, 0.51561909, 0.42326145], [0.11351549, 0.51643524, 0.41590148], [0.11067183, 0.51723164, 0.40839906], [0.10807962, 0.51800494, 0.40074776], [0.10580878, 0.51875159, 0.39294158], [0.10393472, 0.51946783, 0.38497499], [0.10253597, 0.52014993, 0.37683930], [0.10169355, 0.52079357, 0.36853055], [0.10148616, 0.52139416, 0.36004512], [0.10198647, 0.52194694, 0.35137897], [0.10325739, 0.52244679, 0.34252861], [0.10534865, 0.52288829, 0.33349121], [0.10829448, 0.52326557, 0.32426472], [0.11211265, 0.52357234, 0.31484804], [0.11680808, 0.52380192, 0.30523576], [0.12238518, 0.52394702, 0.29540477], [0.12881123, 0.52399876, 0.28538279], [0.13605621, 0.52394820, 0.27517603], [0.14410514, 0.52378513, 0.26476898], [0.15293375, 0.52349780, 0.25416480], [0.16247977, 0.52307494, 0.24341445], [0.17276282, 0.52250055, 0.23248374], [0.18369893, 0.52176275, 0.22146098], [0.19529772, 0.52084321, 0.21034680], [0.20746308, 0.51973103, 0.19925592], [0.22018049, 0.51840885, 0.18823609], [0.23332581, 0.51687146, 0.17744061], [0.24678810, 0.51511657, 0.16701119], [0.26043578, 0.51314954, 0.15710290], [0.27409793, 0.51098848, 0.14788694], [0.28761884, 0.50865777, 0.13950080], [0.30086975, 0.50618505, 0.13203710], [0.31370489, 0.50360866, 0.12556363], [0.32609538, 0.50094907, 0.12005608], [0.33799424, 0.49823249, 0.11547743], [0.34938489, 0.49547991, 0.11175786], [0.36029622, 0.49270114, 0.10880174], [0.37075574, 0.48990462, 0.10651189], [0.38076313, 0.48710519, 0.10479584], [0.39039628, 0.48429421, 0.10355136], [0.39968164, 0.48147509, 0.10269340], [0.40861182, 0.47866075, 0.10214468], [0.41725511, 0.47583919, 0.10183013], [0.42563941, 0.47300913, 0.10168644], [0.43378927, 0.47016919, 0.10165742], [0.44172797, 0.46731733, 0.10169329], [0.44947742, 0.46445100, 0.10174995], [0.45705812, 0.46156726, 0.10178816], [0.46448913, 0.45866282, 0.10177265], [0.47178813, 0.45573417, 0.10167122], [0.47897143, 0.45277762, 0.10145383], [0.48605409, 0.44978932, 0.10109169], [0.49304995, 0.44676536, 0.10055631], [0.49997171, 0.44370173, 0.09981844], [0.50683102, 0.44059441, 0.09884695], [0.51363860, 0.43743936, 0.09760740], [0.52040425, 0.43423253, 0.09606047], [0.52713698, 0.43096991, 0.09415980], [0.53384504, 0.42764756, 0.09184919], [0.54053593, 0.42426164, 0.08905888], [0.54721632, 0.42080854, 0.08570001], [0.55389186, 0.41728505, 0.08165660], [0.56056680, 0.41368870, 0.07677269], [0.56724332, 0.41001824, 0.07083093]] _temperature_data = [ [0.01555601, 0.13824425, 0.20181089], [0.01620184, 0.14105074, 0.20897651], [0.01685649, 0.14382701, 0.21623868], [0.01752640, 0.14657173, 0.22359970], [0.01821872, 0.14928346, 0.23106187], [0.01894138, 0.15196073, 0.23862748], [0.01969968, 0.15460145, 0.24630497], [0.02050332, 0.15720378, 0.25409711], [0.02136721, 0.15976645, 0.26199915], [0.02230341, 0.16228755, 0.27001321], [0.02332520, 0.16476505, 0.27814139], [0.02444728, 0.16719678, 0.28638573], [0.02568582, 0.16958042, 0.29474817], [0.02705867, 0.17191350, 0.30323056], [0.02858553, 0.17419338, 0.31183463], [0.03028808, 0.17641726, 0.32056191], [0.03219022, 0.17858215, 0.32941369], [0.03431826, 0.18068487, 0.33839101], [0.03670118, 0.18272205, 0.34749451], [0.03937082, 0.18469014, 0.35672441], [0.04230474, 0.18658537, 0.36608039], [0.04544128, 0.18840380, 0.37556146], [0.04879889, 0.19014130, 0.38516584], [0.05238565, 0.19179358, 0.39489082], [0.05620897, 0.19335621, 0.40473254], [0.06027561, 0.19482469, 0.41468582], [0.06459519, 0.19618775, 0.42477146], [0.06917294, 0.19744583, 0.43495728], [0.07401398, 0.19859437, 0.44523225], [0.07912633, 0.19962514, 0.45559656], [0.08452075, 0.20052842, 0.46605087], [0.09019392, 0.20130794, 0.47654788], [0.09616431, 0.20194725, 0.48710445], [0.10242540, 0.20245202, 0.49766462], [0.10899443, 0.20280889, 0.50822709], [0.11585974, 0.20302735, 0.51872453], [0.12304243, 0.20309380, 0.52914838], [0.13052767, 0.20302178, 0.53942012], [0.13830991, 0.20281956, 0.54947678], [0.14637971, 0.20250018, 0.55924613], [0.15471863, 0.20208507, 0.56864226], [0.16329705, 0.20160546, 0.57756769], [0.17207282, 0.20110273, 0.58591838], [0.18099176, 0.20062705, 0.59359182], [0.18999022, 0.20023416, 0.60049707], [0.19899974, 0.19998029, 0.60656515], [0.20795298, 0.19991643, 0.61175706], [0.21678952, 0.20008303, 0.61606739], [0.22546043, 0.20050671, 0.61952279], [0.23393063, 0.20119920, 0.62217608], [0.24217907, 0.20215872, 0.62409793], [0.25019713, 0.20337273, 0.62536824], [0.25798611, 0.20482134, 0.62606879], [0.26555442, 0.20648047, 0.62627797], [0.27291504, 0.20832446, 0.62606758], [0.28008339, 0.21032792, 0.62550133], [0.28706751, 0.21246914, 0.62464200], [0.29388514, 0.21472543, 0.62353802], [0.30055772, 0.21707565, 0.62222519], [0.30708438, 0.21950598, 0.62075550], [0.31349163, 0.22199831, 0.61914522], [0.31977984, 0.22454204, 0.61743434], [0.32596955, 0.22712412, 0.61563293], [0.33205791, 0.22973736, 0.61377715], [0.33806601, 0.23237153, 0.61186606], [0.34399174, 0.23502151, 0.60992807], [0.34984607, 0.23768089, 0.60796949], [0.35563846, 0.24034440, 0.60599535], [0.36136863, 0.24300892, 0.60402414], [0.36704345, 0.24567078, 0.60206076], [0.37267088, 0.24832670, 0.60010594], [0.37825480, 0.25097436, 0.59816563], [0.38379608, 0.25361228, 0.59624988], [0.38929883, 0.25623877, 0.59436180], [0.39476910, 0.25885207, 0.59249964], [0.40020989, 0.26145107, 0.59066609], [0.40562409, 0.26403484, 0.58886331], [0.41101442, 0.26660262, 0.58709291], [0.41638322, 0.26915383, 0.58535660], [0.42173132, 0.27168825, 0.58365836], [0.42706343, 0.27420503, 0.58199410], [0.43238181, 0.27670380, 0.58036393], [0.43768862, 0.27918426, 0.57876764], [0.44298597, 0.28164615, 0.57720480], [0.44827587, 0.28408925, 0.57567472], [0.45356026, 0.28651338, 0.57417648], [0.45884104, 0.28891838, 0.57270899], [0.46412001, 0.29130410, 0.57127095], [0.46939893, 0.29367044, 0.56986090], [0.47467951, 0.29601729, 0.56847725], [0.47996336, 0.29834456, 0.56711823], [0.48525207, 0.30065217, 0.56578195], [0.49054716, 0.30294008, 0.56446640], [0.49585007, 0.30520822, 0.56316946], [0.50116221, 0.30745656, 0.56188888], [0.50648491, 0.30968508, 0.56062233], [0.51181943, 0.31189376, 0.55936737], [0.51716699, 0.31408263, 0.55812148], [0.52252871, 0.31625172, 0.55688205], [0.52790567, 0.31840106, 0.55564642], [0.53329886, 0.32053073, 0.55441182], [0.53870920, 0.32264084, 0.55317546], [0.54413753, 0.32473150, 0.55193448], [0.54958461, 0.32680287, 0.55068596], [0.55505113, 0.32885514, 0.54942696], [0.56053768, 0.33088852, 0.54815451], [0.56604476, 0.33290327, 0.54686563], [0.57157236, 0.33489987, 0.54555812], [0.57712131, 0.33687845, 0.54422801], [0.58269186, 0.33883938, 0.54287227], [0.58828416, 0.34078308, 0.54148789], [0.59389827, 0.34271002, 0.54007187], [0.59953415, 0.34462069, 0.53862124], [0.60519167, 0.34651565, 0.53713308], [0.61087061, 0.34839552, 0.53560450], [0.61657065, 0.35026093, 0.53403268], [0.62229138, 0.35211260, 0.53241484], [0.62803229, 0.35395127, 0.53074831], [0.63379279, 0.35577776, 0.52903045], [0.63957219, 0.35759292, 0.52725878], [0.64536975, 0.35939765, 0.52543076], [0.65118470, 0.36119285, 0.52354391], [0.65701610, 0.36297956, 0.52159597], [0.66286293, 0.36475881, 0.51958481], [0.66872410, 0.36653173, 0.51750839], [0.67459845, 0.36829947, 0.51536480], [0.68048472, 0.37006325, 0.51315222], [0.68638162, 0.37182432, 0.51086898], [0.69228775, 0.37358401, 0.50851352], [0.69820166, 0.37534367, 0.50608439], [0.70412186, 0.37710473, 0.50358028], [0.71004688, 0.37886859, 0.50099965], [0.71597525, 0.38063670, 0.49834106], [0.72190503, 0.38241075, 0.49560410], [0.72783443, 0.38419239, 0.49278795], [0.73376164, 0.38598330, 0.48989190], [0.73968475, 0.38778523, 0.48691538], [0.74560180, 0.38960001, 0.48385794], [0.75151077, 0.39142951, 0.48071927], [0.75740957, 0.39327566, 0.47749914], [0.76329604, 0.39514048, 0.47419750], [0.76916794, 0.39702603, 0.47081439], [0.77502298, 0.39893446, 0.46735000], [0.78085877, 0.40086800, 0.46380463], [0.78667286, 0.40282892, 0.46017874], [0.79246271, 0.40481960, 0.45647292], [0.79822569, 0.40684249, 0.45268792], [0.80395908, 0.40890011, 0.44882462], [0.80966007, 0.41099506, 0.44488409], [0.81532584, 0.41313001, 0.44086720], [0.82095338, 0.41530771, 0.43677537], [0.82653946, 0.41753108, 0.43261066], [0.83208085, 0.41980305, 0.42837489], [0.83757423, 0.42212661, 0.42407011], [0.84301618, 0.42450482, 0.41969860], [0.84840316, 0.42694082, 0.41526288], [0.85373155, 0.42943780, 0.41076573], [0.85899760, 0.43199897, 0.40621024], [0.86419750, 0.43462760, 0.40159975], [0.86932733, 0.43732696, 0.39693796], [0.87438311, 0.44010033, 0.39222887], [0.87936081, 0.44295096, 0.38747682], [0.88425632, 0.44588207, 0.38268654], [0.88906554, 0.44889681, 0.37786308], [0.89378437, 0.45199824, 0.37301160], [0.89840867, 0.45518929, 0.36813827], [0.90293439, 0.45847274, 0.36324942], [0.90735756, 0.46185117, 0.35835166], [0.91167433, 0.46532694, 0.35345197], [0.91588100, 0.46890217, 0.34855767], [0.91997406, 0.47257868, 0.34367638], [0.92395023, 0.47635796, 0.33881601], [0.92780648, 0.48024117, 0.33398471], [0.93154008, 0.48422909, 0.32919080], [0.93514863, 0.48832213, 0.32444275], [0.93863008, 0.49252027, 0.31974912], [0.94198274, 0.49682311, 0.31511847], [0.94520535, 0.50122981, 0.31055931], [0.94829701, 0.50573917, 0.30608003], [0.95125725, 0.51034957, 0.30168887], [0.95408600, 0.51505906, 0.29739377], [0.95678355, 0.51986536, 0.29320240], [0.95935057, 0.52476587, 0.28912206], [0.96178805, 0.52975777, 0.28515964], [0.96409730, 0.53483802, 0.28132156], [0.96627986, 0.54000343, 0.27761379], [0.96833750, 0.54525070, 0.27404177], [0.97027215, 0.55057645, 0.27061043], [0.97208896, 0.55597442, 0.26733231], [0.97378824, 0.56144311, 0.26420514], [0.97537225, 0.56697917, 0.26123210], [0.97684333, 0.57257930, 0.25841610], [0.97820376, 0.57824032, 0.25575953], [0.97945570, 0.58395922, 0.25326432], [0.98060120, 0.58973318, 0.25093197], [0.98164451, 0.59555764, 0.24876746], [0.98259580, 0.60142353, 0.24678389], [0.98344841, 0.60733543, 0.24496692], [0.98420378, 0.61329131, 0.24331643], [0.98486309, 0.61928934, 0.24183204], [0.98543359, 0.62532321, 0.24052074], [0.98592661, 0.63138392, 0.23939250], [0.98632908, 0.63748058, 0.23842850], [0.98664126, 0.64361223, 0.23762727], [0.98687430, 0.64977022, 0.23699778], [0.98703872, 0.65594684, 0.23654600], [0.98711602, 0.66215449, 0.23625164], [0.98710548, 0.66839291, 0.23611251], [0.98704522, 0.67463615, 0.23615516], [0.98690081, 0.68090692, 0.23634896], [0.98666929, 0.68720645, 0.23669008], [0.98639295, 0.69350720, 0.23720252], [0.98603581, 0.69983201, 0.23785913], [0.98559369, 0.70618283, 0.23865535], [0.98511668, 0.71252856, 0.23961378], [0.98455154, 0.71890163, 0.24070275], [0.98392192, 0.72528731, 0.24193050], [0.98324116, 0.73167761, 0.24329811], [0.98246864, 0.73809600, 0.24478540], [0.98166755, 0.74450581, 0.24641186], [0.98078113, 0.75093941, 0.24815276], [0.97983772, 0.75738047, 0.25001371], [0.97883927, 0.76382790, 0.25199054], [0.97775747, 0.77029690, 0.25407166], [0.97664794, 0.77675738, 0.25626641], [0.97543570, 0.78324913, 0.25855344], [0.97421070, 0.78972470, 0.26094721], [0.97288357, 0.79623051, 0.26342620], [0.97152974, 0.80272764, 0.26599948], [0.97008613, 0.80924798, 0.26865290], [0.96860571, 0.81576486, 0.27138993], [0.96704307, 0.82230061, 0.27420073], [0.96543772, 0.82883583, 0.27708584], [0.96375242, 0.83538829, 0.28003763], [0.96202315, 0.84194079, 0.28305544], [0.96021049, 0.84851164, 0.28613254], [0.95835763, 0.85508072, 0.28926815], [0.95641175, 0.86167196, 0.29245571], [0.95443484, 0.86825730, 0.29569479], [0.95234871, 0.87487125, 0.29897882], [0.95024646, 0.88147281, 0.30230776], [0.94801413, 0.88811109, 0.30567520], [0.94578198, 0.89473018, 0.30908112], [0.94341986, 0.90138491, 0.31252002], [0.94102862, 0.90803285, 0.31599064], [0.93853313, 0.91470475, 0.31948933], [0.93597111, 0.92138481, 0.32301384], [0.93333760, 0.92807483, 0.32656155], [0.93059157, 0.93479051, 0.33012998], [0.92781425, 0.94149986, 0.33371683], [0.92488992, 0.94824702, 0.33731997], [0.92194114, 0.95498491, 0.34093705], [0.91886139, 0.96175325, 0.34456630], [0.91569318, 0.96853549, 0.34820569], [0.91244907, 0.97532669, 0.35185336], [0.90904184, 0.98215741, 0.35550781]] _velocity_b_data = [ [0.06597739, 0.12386005, 0.24948116], [0.06865758, 0.12663250, 0.25557624], [0.07132312, 0.12939515, 0.26166391], [0.07396584, 0.13214058, 0.26779480], [0.07658629, 0.13486916, 0.27396904], [0.07919242, 0.13758843, 0.28014206], [0.08176925, 0.14028419, 0.28640499], [0.08433407, 0.14297318, 0.29265629], [0.08687299, 0.14564215, 0.29898019], [0.08939564, 0.14830082, 0.30531941], [0.09189721, 0.15094484, 0.31170300], [0.09437767, 0.15357460, 0.31813071], [0.09684032, 0.15619402, 0.32458157], [0.09927797, 0.15879644, 0.33109756], [0.10169939, 0.16139154, 0.33762358], [0.10409298, 0.16396840, 0.34422672], [0.10647003, 0.16653949, 0.35083602], [0.10881765, 0.16909286, 0.35752405], [0.11114624, 0.17164030, 0.36422476], [0.11344526, 0.17417268, 0.37099405], [0.11572015, 0.17669703, 0.37779407], [0.11796711, 0.17921142, 0.38463932], [0.12018172, 0.18171361, 0.39154591], [0.12237222, 0.18421369, 0.39845983], [0.12451836, 0.18669519, 0.40547913], [0.12663654, 0.18917624, 0.41250469], [0.12871435, 0.19164859, 0.41958831], [0.13074695, 0.19411179, 0.42673806], [0.13274084, 0.19657524, 0.43390608], [0.13468282, 0.19903239, 0.44113668], [0.13656674, 0.20148370, 0.44843501], [0.13839602, 0.20393744, 0.45576220], [0.14016368, 0.20639447, 0.46312314], [0.14185409, 0.20885126, 0.47055044], [0.14345986, 0.21131167, 0.47803591], [0.14497642, 0.21378230, 0.48555700], [0.14639100, 0.21626634, 0.49311434], [0.14768864, 0.21876800, 0.50070638], [0.14885173, 0.22129285, 0.50832846], [0.14985965, 0.22384818, 0.51597154], [0.15068840, 0.22644340, 0.52362079], [0.15131023, 0.22909058, 0.53125369], [0.15168425, 0.23180303, 0.53885457], [0.15175702, 0.23459819, 0.54640144], [0.15150762, 0.23750367, 0.55379602], [0.15085272, 0.24054407, 0.56100954], [0.14977800, 0.24375297, 0.56790391], [0.14824130, 0.24715977, 0.57437788], [0.14626774, 0.25078506, 0.58029534], [0.14393556, 0.25462901, 0.58555075], [0.14135408, 0.25866955, 0.59010335], [0.13864079, 0.26286871, 0.59397852], [0.13589174, 0.26718438, 0.59724867], [0.13319563, 0.27157423, 0.60000635], [0.13058114, 0.27601030, 0.60234289], [0.12806719, 0.28047115, 0.60433583], [0.12569199, 0.28493491, 0.60605594], [0.12343537, 0.28939604, 0.60755039], [0.12131237, 0.29384382, 0.60886431], [0.11933140, 0.29827105, 0.61003449], [0.11747335, 0.30267840, 0.61108156], [0.11574105, 0.30706267, 0.61202824], [0.11415261, 0.31141804, 0.61290024], [0.11269166, 0.31574724, 0.61370617], [0.11135538, 0.32005035, 0.61445721], [0.11014377, 0.32432716, 0.61516380], [0.10905648, 0.32857778, 0.61583463], [0.10809281, 0.33280260, 0.61647697], [0.10725185, 0.33700217, 0.61709693], [0.10653241, 0.34117717, 0.61769964], [0.10593314, 0.34532836, 0.61828945], [0.10545250, 0.34945656, 0.61887003], [0.10508879, 0.35356261, 0.61944452], [0.10484013, 0.35764738, 0.62001559], [0.10470452, 0.36171173, 0.62058554], [0.10467981, 0.36575652, 0.62115635], [0.10476371, 0.36978259, 0.62172971], [0.10495382, 0.37379076, 0.62230709], [0.10524762, 0.37778184, 0.62288978], [0.10564252, 0.38175660, 0.62347886], [0.10613580, 0.38571579, 0.62407531], [0.10672471, 0.38966014, 0.62467996], [0.10740642, 0.39359035, 0.62529352], [0.10817806, 0.39750711, 0.62591662], [0.10903675, 0.40141105, 0.62654981], [0.10998202, 0.40530231, 0.62719516], [0.11100819, 0.40918206, 0.62785128], [0.11211222, 0.41305092, 0.62851837], [0.11329127, 0.41690943, 0.62919672], [0.11454253, 0.42075813, 0.62988653], [0.11586327, 0.42459754, 0.63058799], [0.11725083, 0.42842816, 0.63130122], [0.11870260, 0.43225046, 0.63202632], [0.12021702, 0.43606470, 0.63276403], [0.12179033, 0.43987161, 0.63351340], [0.12342020, 0.44367161, 0.63427436], [0.12510445, 0.44746510, 0.63504690], [0.12684102, 0.45125247, 0.63583095], [0.12862799, 0.45503408, 0.63662642], [0.13046351, 0.45881028, 0.63743320], [0.13234563, 0.46258148, 0.63825092], [0.13427263, 0.46634802, 0.63907929], [0.13624311, 0.47011020, 0.63991816], [0.13825578, 0.47386832, 0.64076733], [0.14030945, 0.47762263, 0.64162657], [0.14240307, 0.48137341, 0.64249562], [0.14453572, 0.48512091, 0.64337422], [0.14670608, 0.48886546, 0.64426159], [0.14891319, 0.49260737, 0.64515709], [0.15115711, 0.49634669, 0.64606096], [0.15343746, 0.50008362, 0.64697283], [0.15575396, 0.50381833, 0.64789234], [0.15810648, 0.50755096, 0.64881909], [0.16049500, 0.51128167, 0.64975267], [0.16291965, 0.51501059, 0.65069263], [0.16538066, 0.51873781, 0.65163850], [0.16787709, 0.52246378, 0.65258827], [0.17041079, 0.52618823, 0.65354289], [0.17298246, 0.52991124, 0.65450185], [0.17559291, 0.53363281, 0.65546464], [0.17824310, 0.53735298, 0.65643069], [0.18093416, 0.54107173, 0.65739946], [0.18366735, 0.54478903, 0.65837034], [0.18644408, 0.54850484, 0.65934275], [0.18926596, 0.55221906, 0.66031605], [0.19213472, 0.55593160, 0.66128961], [0.19505228, 0.55964231, 0.66226278], [0.19802076, 0.56335105, 0.66323489], [0.20104242, 0.56705760, 0.66420528], [0.20411976, 0.57076173, 0.66517325], [0.20725543, 0.57446319, 0.66613812], [0.21045232, 0.57816165, 0.66709920], [0.21371350, 0.58185676, 0.66805579], [0.21704227, 0.58554813, 0.66900720], [0.22044214, 0.58923531, 0.66995277], [0.22391686, 0.59291779, 0.67089183], [0.22747037, 0.59659503, 0.67182375], [0.23110686, 0.60026640, 0.67274791], [0.23483073, 0.60393124, 0.67366376], [0.23864660, 0.60758879, 0.67457077], [0.24255928, 0.61123826, 0.67546847], [0.24657379, 0.61487875, 0.67635647], [0.25069532, 0.61850931, 0.67723446], [0.25492963, 0.62212933, 0.67809791], [0.25928228, 0.62573723, 0.67895065], [0.26375886, 0.62933183, 0.67979274], [0.26836502, 0.63291182, 0.68062438], [0.27310635, 0.63647586, 0.68144595], [0.27799067, 0.64002284, 0.68225204], [0.28302187, 0.64355084, 0.68304906], [0.28820489, 0.64705829, 0.68383831], [0.29354581, 0.65054365, 0.68461866], [0.29905039, 0.65400523, 0.68538993], [0.30471967, 0.65744127, 0.68615859], [0.31055832, 0.66085014, 0.68692427], [0.31656915, 0.66423017, 0.68768878], [0.32274951, 0.66757995, 0.68845924], [0.32910283, 0.67089793, 0.68923459], [0.33562308, 0.67418311, 0.69002275], [0.34230732, 0.67743451, 0.69082687], [0.34914976, 0.68065146, 0.69165158], [0.35614127, 0.68383379, 0.69250293], [0.36327369, 0.68698145, 0.69338491], [0.37053484, 0.69009497, 0.69430340], [0.37791226, 0.69317522, 0.69526327], [0.38539385, 0.69622324, 0.69626827], [0.39296332, 0.69924082, 0.69732400], [0.40060940, 0.70222938, 0.69843223], [0.40831594, 0.70519122, 0.69959724], [0.41607015, 0.70812840, 0.70082090], [0.42386201, 0.71104276, 0.70210342], [0.43167256, 0.71393771, 0.70344961], [0.43949947, 0.71681422, 0.70485557], [0.44732849, 0.71967527, 0.70632366], [0.45514951, 0.72252334, 0.70785413], [0.46296115, 0.72535947, 0.70944335], [0.47075349, 0.72818626, 0.71109189], [0.47851694, 0.73100635, 0.71280025], [0.48625412, 0.73382019, 0.71456376], [0.49396102, 0.73662941, 0.71638100], [0.50163106, 0.73943622, 0.71825179], [0.50925965, 0.74224248, 0.72017521], [0.51685029, 0.74504841, 0.72214731], [0.52440134, 0.74785523, 0.72416643], [0.53191155, 0.75066408, 0.72623094], [0.53938005, 0.75347600, 0.72833923], [0.54680444, 0.75629239, 0.73049037], [0.55418394, 0.75911426, 0.73268299], [0.56152150, 0.76194178, 0.73491438], [0.56881727, 0.76477570, 0.73718308], [0.57607152, 0.76761672, 0.73948764], [0.58328469, 0.77046550, 0.74182668], [0.59045730, 0.77332263, 0.74419886], [0.59758995, 0.77618869, 0.74660289], [0.60468333, 0.77906419, 0.74903750], [0.61173817, 0.78194964, 0.75150151], [0.61875522, 0.78484550, 0.75399375], [0.62573528, 0.78775220, 0.75651310], [0.63267915, 0.79067016, 0.75905849], [0.63958763, 0.79359978, 0.76162887], [0.64646151, 0.79654145, 0.76422323], [0.65330160, 0.79949552, 0.76684059], [0.66010867, 0.80246236, 0.76948001], [0.66688348, 0.80544232, 0.77214056], [0.67362676, 0.80843573, 0.77482134], [0.68033922, 0.81144292, 0.77752145], [0.68702155, 0.81446423, 0.78024002], [0.69367439, 0.81749998, 0.78297620], [0.70029750, 0.82055075, 0.78572944], [0.70689165, 0.82361681, 0.78849881], [0.71345823, 0.82669826, 0.79128316], [0.71999780, 0.82979542, 0.79408159], [0.72651088, 0.83290861, 0.79689320], [0.73299796, 0.83603816, 0.79971707], [0.73945951, 0.83918440, 0.80255223], [0.74589598, 0.84234767, 0.80539770], [0.75230780, 0.84552831, 0.80825242], [0.75869517, 0.84872673, 0.81111536], [0.76505775, 0.85194348, 0.81398568], [0.77139709, 0.85517859, 0.81686163], [0.77771359, 0.85843239, 0.81974187], [0.78400765, 0.86170526, 0.82262493], [0.79027967, 0.86499755, 0.82550921], [0.79653012, 0.86830960, 0.82839299], [0.80275950, 0.87164177, 0.83127437], [0.80896806, 0.87499448, 0.83415141], [0.81515670, 0.87836796, 0.83702171], [0.82132643, 0.88176244, 0.83988264], [0.82747812, 0.88517819, 0.84273144], [0.83361281, 0.88861542, 0.84556510], [0.83973174, 0.89207431, 0.84838033], [0.84583638, 0.89555495, 0.85117353], [0.85192854, 0.89905734, 0.85394079], [0.85801043, 0.90258135, 0.85667786], [0.86408444, 0.90612679, 0.85938032], [0.87015339, 0.90969330, 0.86204351], [0.87622047, 0.91328040, 0.86466260], [0.88228934, 0.91688740, 0.86723268], [0.88836402, 0.92051348, 0.86974885], [0.89444909, 0.92415756, 0.87220619], [0.90054949, 0.92781839, 0.87459995], [0.90666975, 0.93149475, 0.87692634], [0.91281478, 0.93518523, 0.87918186], [0.91898934, 0.93888836, 0.88136368], [0.92519787, 0.94260271, 0.88346979], [0.93144429, 0.94632694, 0.88549899], [0.93773184, 0.95005986, 0.88745092], [0.94406341, 0.95380038, 0.88932539], [0.95044015, 0.95754793, 0.89112376], [0.95686223, 0.96130226, 0.89284794], [0.96332900, 0.96506343, 0.89449990], [0.96983887, 0.96883187, 0.89608183], [0.97638938, 0.97260834, 0.89759591], [0.98297732, 0.97639393, 0.89904421], [0.98959887, 0.98019003, 0.90042859], [0.99624974, 0.98399826, 0.90175064]] _velocity_g_data = [ [0.99962532, 0.99137112, 0.80410124], [0.99693130, 0.98658659, 0.79581965], [0.99425336, 0.98181358, 0.78753178], [0.99158968, 0.97705259, 0.77923744], [0.98893848, 0.97230412, 0.77093649], [0.98629803, 0.96756863, 0.76262887], [0.98366662, 0.96284660, 0.75431452], [0.98104259, 0.95813849, 0.74599345], [0.97842373, 0.95344486, 0.73766705], [0.97580917, 0.94876601, 0.72933356], [0.97319768, 0.94410230, 0.72099216], [0.97058766, 0.93945419, 0.71264291], [0.96797753, 0.93482212, 0.70428588], [0.96536576, 0.93020653, 0.69592114], [0.96275088, 0.92560786, 0.68754852], [0.96013179, 0.92102646, 0.67916692], [0.95750683, 0.91646282, 0.67077672], [0.95487445, 0.91191742, 0.66237802], [0.95223308, 0.90739072, 0.65397092], [0.94958118, 0.90288322, 0.64555550], [0.94691718, 0.89839541, 0.63713184], [0.94424022, 0.89392765, 0.62869796], [0.94154864, 0.88948047, 0.62025400], [0.93884038, 0.88505451, 0.61180142], [0.93611377, 0.88065031, 0.60334038], [0.93336714, 0.87626844, 0.59487104], [0.93059881, 0.87190949, 0.58639360], [0.92780705, 0.86757406, 0.57790823], [0.92499010, 0.86326276, 0.56941517], [0.92214698, 0.85897609, 0.56091165], [0.91927530, 0.85471481, 0.55239974], [0.91637286, 0.85047967, 0.54388105], [0.91343769, 0.84627138, 0.53535605], [0.91046780, 0.84209066, 0.52682531], [0.90746117, 0.83793825, 0.51828947], [0.90441569, 0.83381493, 0.50974926], [0.90132924, 0.82972148, 0.50120551], [0.89819963, 0.82565871, 0.49265916], [0.89502462, 0.82162744, 0.48411130], [0.89180194, 0.81762851, 0.47556314], [0.88852927, 0.81366275, 0.46701603], [0.88520428, 0.80973103, 0.45847151], [0.88182459, 0.80583419, 0.44993127], [0.87838781, 0.80197310, 0.44139720], [0.87489155, 0.79814860, 0.43287135], [0.87133343, 0.79436152, 0.42435598], [0.86771108, 0.79061266, 0.41585355], [0.86402220, 0.78690280, 0.40736670], [0.86026452, 0.78323268, 0.39889826], [0.85643585, 0.77960299, 0.39045126], [0.85253410, 0.77601436, 0.38202889], [0.84855731, 0.77246735, 0.37363449], [0.84450364, 0.76896245, 0.36527157], [0.84037142, 0.76550008, 0.35694373], [0.83615916, 0.76208053, 0.34865469], [0.83186554, 0.75870402, 0.34040823], [0.82748950, 0.75537065, 0.33220817], [0.82303017, 0.75208041, 0.32405836], [0.81848682, 0.74883326, 0.31596178], [0.81385901, 0.74562899, 0.30792214], [0.80914682, 0.74246709, 0.29994435], [0.80435041, 0.73934706, 0.29203197], [0.79947022, 0.73626828, 0.28418840], [0.79450691, 0.73323004, 0.27641686], [0.78946140, 0.73023149, 0.26872033], [0.78433484, 0.72727172, 0.26110160], [0.77912853, 0.72434970, 0.25356307], [0.77384408, 0.72146431, 0.24610720], [0.76848332, 0.71861432, 0.23873620], [0.76304813, 0.71579850, 0.23145177], [0.75754052, 0.71301555, 0.22425532], [0.75196261, 0.71026417, 0.21714799], [0.74631660, 0.70754299, 0.21013070], [0.74060474, 0.70485066, 0.20320411], [0.73482974, 0.70218562, 0.19636930], [0.72899368, 0.69954660, 0.18962605], [0.72309885, 0.69693228, 0.18297431], [0.71714753, 0.69434130, 0.17641399], [0.71114201, 0.69177235, 0.16994487], [0.70508453, 0.68922412, 0.16356662], [0.69897728, 0.68669535, 0.15727889], [0.69282238, 0.68418481, 0.15108128], [0.68662205, 0.68169124, 0.14497353], [0.68037867, 0.67921331, 0.13895556], [0.67409362, 0.67675013, 0.13302663], [0.66776872, 0.67430062, 0.12718656], [0.66140573, 0.67186375, 0.12143540], [0.65500629, 0.66943851, 0.11577336], [0.64857199, 0.66702394, 0.11020095], [0.64210433, 0.66461911, 0.10471901], [0.63560473, 0.66222315, 0.09932877], [0.62907452, 0.65983518, 0.09403193], [0.62251497, 0.65745441, 0.08883077], [0.61592727, 0.65508003, 0.08372822], [0.60931267, 0.65271125, 0.07872800], [0.60267232, 0.65034731, 0.07383470], [0.59600693, 0.64798759, 0.06905401], [0.58931743, 0.64563142, 0.06439288], [0.58260468, 0.64327815, 0.05985969], [0.57586950, 0.64092715, 0.05546448], [0.56911267, 0.63857780, 0.05121917], [0.56233489, 0.63622950, 0.04713774], [0.55553684, 0.63388168, 0.04323651], [0.54871918, 0.63153377, 0.03952488], [0.54188249, 0.62918522, 0.03612051], [0.53502735, 0.62683550, 0.03311400], [0.52815431, 0.62448406, 0.03049096], [0.52126388, 0.62213041, 0.02823776], [0.51435656, 0.61977401, 0.02634145], [0.50743284, 0.61741438, 0.02478977], [0.50049318, 0.61505101, 0.02357107], [0.49353805, 0.61268341, 0.02267429], [0.48656773, 0.61031113, 0.02208919], [0.47958278, 0.60793365, 0.02180565], [0.47258366, 0.60555050, 0.02181419], [0.46557081, 0.60316118, 0.02210580], [0.45854471, 0.60076521, 0.02267188], [0.45150585, 0.59836210, 0.02350422], [0.44445471, 0.59595137, 0.02459500], [0.43739183, 0.59353253, 0.02593670], [0.43031775, 0.59110510, 0.02752213], [0.42323306, 0.58866858, 0.02934437], [0.41613836, 0.58622247, 0.03139676], [0.40903431, 0.58376629, 0.03367283], [0.40192160, 0.58129953, 0.03616635], [0.39480098, 0.57882170, 0.03887120], [0.38767326, 0.57633228, 0.04174672], [0.38053866, 0.57383092, 0.04468567], [0.37339864, 0.57131697, 0.04768050], [0.36625424, 0.56878993, 0.05071836], [0.35910650, 0.56624928, 0.05378828], [0.35195658, 0.56369452, 0.05688086], [0.34480568, 0.56112513, 0.05998797], [0.33765509, 0.55854062, 0.06310264], [0.33050620, 0.55594049, 0.06621880], [0.32336047, 0.55332424, 0.06933118], [0.31621948, 0.55069139, 0.07243519], [0.30908460, 0.54804150, 0.07552722], [0.30195743, 0.54537413, 0.07860394], [0.29484032, 0.54268874, 0.08166129], [0.28773525, 0.53998488, 0.08469633], [0.28064430, 0.53726212, 0.08770643], [0.27356965, 0.53452006, 0.09068917], [0.26651361, 0.53175830, 0.09364228], [0.25947856, 0.52897647, 0.09656369], [0.25246703, 0.52617424, 0.09945144], [0.24548136, 0.52335131, 0.10230412], [0.23852458, 0.52050736, 0.10511948], [0.23159967, 0.51764210, 0.10789570], [0.22470961, 0.51475531, 0.11063114], [0.21785748, 0.51184679, 0.11332427], [0.21104652, 0.50891636, 0.11597358], [0.20428009, 0.50596389, 0.11857764], [0.19756167, 0.50298929, 0.12113505], [0.19089503, 0.49999248, 0.12364426], [0.18428396, 0.49697343, 0.12610400], [0.17773240, 0.49393216, 0.12851305], [0.17124448, 0.49086871, 0.13087024], [0.16482456, 0.48778316, 0.13317442], [0.15847719, 0.48467561, 0.13542453], [0.15220721, 0.48154623, 0.13761954], [0.14601973, 0.47839518, 0.13975846], [0.13992049, 0.47522266, 0.14183978], [0.13391510, 0.47202893, 0.14386292], [0.12800964, 0.46881425, 0.14582732], [0.12221076, 0.46557892, 0.14773227], [0.11652565, 0.46232325, 0.14957707], [0.11096207, 0.45904759, 0.15136111], [0.10552844, 0.45575227, 0.15308384], [0.10023389, 0.45243770, 0.15474474], [0.09508832, 0.44910425, 0.15634337], [0.09010251, 0.44575233, 0.15787909], [0.08528802, 0.44238240, 0.15935107], [0.08065728, 0.43899485, 0.16075975], [0.07622371, 0.43559013, 0.16210488], [0.07200158, 0.43216868, 0.16338628], [0.06800589, 0.42873094, 0.16460379], [0.06425218, 0.42527736, 0.16575730], [0.06075626, 0.42180841, 0.16684671], [0.05753382, 0.41832454, 0.16787201], [0.05459993, 0.41482619, 0.16883316], [0.05196846, 0.41131384, 0.16973019], [0.04965139, 0.40778792, 0.17056314], [0.04765813, 0.40424888, 0.17133208], [0.04599481, 0.40069717, 0.17203710], [0.04466372, 0.39713324, 0.17267831], [0.04366274, 0.39355751, 0.17325577], [0.04298497, 0.38997047, 0.17376937], [0.04262018, 0.38637248, 0.17421963], [0.04255352, 0.38276397, 0.17460669], [0.04276673, 0.37914535, 0.17493074], [0.04323878, 0.37551702, 0.17519196], [0.04394675, 0.37187939, 0.17539051], [0.04486662, 0.36823283, 0.17552659], [0.04597406, 0.36457776, 0.17560040], [0.04724506, 0.36091453, 0.17561211], [0.04865644, 0.35724353, 0.17556193], [0.05018627, 0.35356513, 0.17545005], [0.05181408, 0.34987969, 0.17527666], [0.05352104, 0.34618758, 0.17504196], [0.05528998, 0.34248913, 0.17474614], [0.05710539, 0.33878471, 0.17438940], [0.05895335, 0.33507466, 0.17397193], [0.06082143, 0.33135932, 0.17349393], [0.06269859, 0.32763902, 0.17295560], [0.06457505, 0.32391411, 0.17235714], [0.06644218, 0.32018490, 0.17169874], [0.06829236, 0.31645172, 0.17098061], [0.07011887, 0.31271491, 0.17020297], [0.07191583, 0.30897477, 0.16936603], [0.07367740, 0.30523170, 0.16846982], [0.07539909, 0.30148601, 0.16751459], [0.07707731, 0.29773796, 0.16650073], [0.07870853, 0.29398786, 0.16542850], [0.08028966, 0.29023603, 0.16429815], [0.08181798, 0.28648275, 0.16310997], [0.08329110, 0.28272833, 0.16186426], [0.08470696, 0.27897306, 0.16056134], [0.08606372, 0.27521722, 0.15920155], [0.08735983, 0.27146109, 0.15778524], [0.08859393, 0.26770495, 0.15631280], [0.08976486, 0.26394904, 0.15478462], [0.09087165, 0.26019363, 0.15320113], [0.09191348, 0.25643894, 0.15156278], [0.09288704, 0.25268563, 0.14986937], [0.09379283, 0.24893377, 0.14812169], [0.09463164, 0.24518338, 0.14632057], [0.09540319, 0.24143464, 0.14446653], [0.09610733, 0.23768772, 0.14256015], [0.09674403, 0.23394277, 0.14060198], [0.09731337, 0.23019990, 0.13859263], [0.09781527, 0.22645927, 0.13653262], [0.09824359, 0.22272214, 0.13442135], [0.09860476, 0.21898749, 0.13226069], [0.09889926, 0.21525533, 0.13005125], [0.09912769, 0.21152567, 0.12779367], [0.09929071, 0.20779846, 0.12548854], [0.09938537, 0.20407438, 0.12313591], [0.09940988, 0.20035390, 0.12073611], [0.09937074, 0.19663577, 0.11829057], [0.09926900, 0.19291982, 0.11579981], [0.09910575, 0.18920581, 0.11326433], [0.09887273, 0.18549555, 0.11068374], [0.09857703, 0.18178753, 0.10805922], [0.09822270, 0.17808082, 0.10539142], [0.09781114, 0.17437504, 0.10268064], [0.09733238, 0.17067237, 0.09992671], [0.09679537, 0.16697070, 0.09713043], [0.09620477, 0.16326879, 0.09429209], [0.09555840, 0.15956697, 0.09141177], [0.09484852, 0.15586693, 0.08848984], [0.09408911, 0.15216506, 0.08552629], [0.09328192, 0.14846061, 0.08252095], [0.09241015, 0.14475747, 0.07947497], [0.09149314, 0.14105046, 0.07638733], [0.09053276, 0.13733861, 0.07325761]] _velocity_data = _velocity_b_data + _velocity_g_data _speed_data = _velocity_g_data _vorticity_p_data = [ [0.99421147, 0.96494148, 0.95917135], [0.99169155, 0.96006773, 0.95274067], [0.98920738, 0.95520176, 0.94627024], [0.98677194, 0.95033807, 0.93975862], [0.98437391, 0.94547881, 0.93322656], [0.98201829, 0.94062171, 0.92667310], [0.97970195, 0.93576702, 0.92010507], [0.97742080, 0.93091541, 0.91352937], [0.97518156, 0.92606439, 0.90693990], [0.97297049, 0.92121764, 0.90035362], [0.97080349, 0.91636994, 0.89375329], [0.96866357, 0.91152607, 0.88715902], [0.96655947, 0.90668298, 0.88056151], [0.96448728, 0.90184151, 0.87396567], [0.96244207, 0.89700286, 0.86737746], [0.96043456, 0.89216329, 0.86078529], [0.95844981, 0.88732720, 0.85420614], [0.95649898, 0.88249069, 0.84762790], [0.95457496, 0.87765571, 0.84105874], [0.95267455, 0.87282297, 0.83450240], [0.95080878, 0.86798852, 0.82794705], [0.94896310, 0.86315684, 0.82140881], [0.94714576, 0.85832485, 0.81487893], [0.94535503, 0.85349280, 0.80835951], [0.94358303, 0.84866304, 0.80185918], [0.94184257, 0.84383087, 0.79536454], [0.94012241, 0.83899979, 0.78888773], [0.93842059, 0.83417022, 0.78243098], [0.93675010, 0.82933722, 0.77598096], [0.93509628, 0.82450566, 0.76955320], [0.93346107, 0.81967454, 0.76314584], [0.93185391, 0.81484010, 0.75674949], [0.93026226, 0.81000656, 0.75037722], [0.92868761, 0.80517307, 0.74402771], [0.92713958, 0.80033571, 0.73769161], [0.92560593, 0.79549870, 0.73138149], [0.92408634, 0.79066188, 0.72509782], [0.92259257, 0.78582038, 0.71882946], [0.92111262, 0.78097847, 0.71258846], [0.91964557, 0.77613620, 0.70637599], [0.91819790, 0.77129068, 0.70018617], [0.91676720, 0.76644249, 0.69402174], [0.91534816, 0.76159342, 0.68788806], [0.91394046, 0.75674328, 0.68178577], [0.91255393, 0.75188769, 0.67570624], [0.91117810, 0.74703058, 0.66965958], [0.90981225, 0.74217193, 0.66364681], [0.90845631, 0.73731145, 0.65766843], [0.90711857, 0.73244522, 0.65171762], [0.90578934, 0.72757702, 0.64580349], [0.90446821, 0.72270670, 0.63992685], [0.90315480, 0.71783410, 0.63408853], [0.90185363, 0.71295684, 0.62828530], [0.90056181, 0.70807582, 0.62252022], [0.89927597, 0.70319221, 0.61679672], [0.89799564, 0.69830590, 0.61111575], [0.89672032, 0.69341676, 0.60547834], [0.89545267, 0.68852319, 0.59988306], [0.89419156, 0.68362534, 0.59433158], [0.89293342, 0.67872453, 0.58882738], [0.89167767, 0.67382071, 0.58337159], [0.89042371, 0.66891382, 0.57796541], [0.88917090, 0.66400384, 0.57261005], [0.88791872, 0.65909067, 0.56730668], [0.88667005, 0.65417250, 0.56205414], [0.88542008, 0.64925139, 0.55685666], [0.88416808, 0.64432738, 0.55171557], [0.88291328, 0.63940055, 0.54663223], [0.88165490, 0.63447097, 0.54160802], [0.88039211, 0.62953874, 0.53664435], [0.87912408, 0.62460401, 0.53174263], [0.87784992, 0.61966691, 0.52690431], [0.87656874, 0.61472764, 0.52213085], [0.87527962, 0.60978640, 0.51742369], [0.87398160, 0.60484341, 0.51278430], [0.87267379, 0.59989890, 0.50821409], [0.87135575, 0.59495282, 0.50371428], [0.87002561, 0.59000599, 0.49928670], [0.86868234, 0.58505874, 0.49493276], [0.86732494, 0.58011144, 0.49065382], [0.86595233, 0.57516447, 0.48645122], [0.86456348, 0.57021827, 0.48232627], [0.86315731, 0.56527328, 0.47828022], [0.86173275, 0.56032997, 0.47431426], [0.86028873, 0.55538883, 0.47042955], [0.85882442, 0.55045025, 0.46662711], [0.85733888, 0.54551465, 0.46290794], [0.85583071, 0.54058284, 0.45927307], [0.85429886, 0.53565540, 0.45572335], [0.85274227, 0.53073296, 0.45225954], [0.85115991, 0.52581613, 0.44888233], [0.84955078, 0.52090556, 0.44559226], [0.84791390, 0.51600192, 0.44238981], [0.84624832, 0.51110586, 0.43927533], [0.84455311, 0.50621807, 0.43624906], [0.84282741, 0.50133921, 0.43331112], [0.84107035, 0.49646996, 0.43046153], [0.83928115, 0.49161102, 0.42770018], [0.83745936, 0.48676280, 0.42502690], [0.83560431, 0.48192593, 0.42244142], [0.83371489, 0.47710144, 0.41994320], [0.83179047, 0.47228997, 0.41753164], [0.82983048, 0.46749218, 0.41520606], [0.82783443, 0.46270870, 0.41296566], [0.82580183, 0.45794015, 0.41080953], [0.82373229, 0.45318712, 0.40873667], [0.82162569, 0.44844998, 0.40674611], [0.81948157, 0.44372941, 0.40483662], [0.81729951, 0.43902609, 0.40300681], [0.81507930, 0.43434053, 0.40125532], [0.81282080, 0.42967323, 0.39958071], [0.81052390, 0.42502464, 0.39798147], [0.80818855, 0.42039519, 0.39645606], [0.80581485, 0.41578517, 0.39500298], [0.80340270, 0.41119510, 0.39362043], [0.80095214, 0.40662536, 0.39230669], [0.79846329, 0.40207627, 0.39106003], [0.79593630, 0.39754813, 0.38987866], [0.79337135, 0.39304120, 0.38876082], [0.79076866, 0.38855573, 0.38770470], [0.78812845, 0.38409196, 0.38670846], [0.78545100, 0.37965010, 0.38577027], [0.78273660, 0.37523032, 0.38488831], [0.77998556, 0.37083276, 0.38406076], [0.77719822, 0.36645754, 0.38328582], [0.77437495, 0.36210479, 0.38256169], [0.77151605, 0.35777464, 0.38188648], [0.76862195, 0.35346712, 0.38125850], [0.76569305, 0.34918228, 0.38067601], [0.76272975, 0.34492014, 0.38013731], [0.75973246, 0.34068073, 0.37964068], [0.75670159, 0.33646406, 0.37918448], [0.75363755, 0.33227014, 0.37876700], [0.75054072, 0.32809900, 0.37838654], [0.74741157, 0.32395055, 0.37804166], [0.74425052, 0.31982476, 0.37773081], [0.74105798, 0.31572158, 0.37745245], [0.73783435, 0.31164097, 0.37720511], [0.73458005, 0.30758288, 0.37698731], [0.73129546, 0.30354729, 0.37679757], [0.72798098, 0.29953413, 0.37663448], [0.72463700, 0.29554332, 0.37649676], [0.72126390, 0.29157480, 0.37638306], [0.71786206, 0.28762852, 0.37629208], [0.71443181, 0.28370442, 0.37622252], [0.71097352, 0.27980245, 0.37617313], [0.70748750, 0.27592259, 0.37614266], [0.70397409, 0.27206478, 0.37612990], [0.70043360, 0.26822899, 0.37613371], [0.69686632, 0.26441520, 0.37615291], [0.69327254, 0.26062340, 0.37618635], [0.68965253, 0.25685360, 0.37623291], [0.68600655, 0.25310580, 0.37629145], [0.68233484, 0.24938002, 0.37636095], [0.67863762, 0.24567630, 0.37644035], [0.67491512, 0.24199472, 0.37652853], [0.67116753, 0.23833535, 0.37662440], [0.66739504, 0.23469830, 0.37672691], [0.66359781, 0.23108369, 0.37683500], [0.65977600, 0.22749166, 0.37694762], [0.65592975, 0.22392235, 0.37706391], [0.65205918, 0.22037597, 0.37718281], [0.64816439, 0.21685275, 0.37730312], [0.64424550, 0.21335297, 0.37742379], [0.64030257, 0.20987692, 0.37754374], [0.63633567, 0.20642491, 0.37766190], [0.63234486, 0.20299730, 0.37777720], [0.62833011, 0.19959444, 0.37788907], [0.62429150, 0.19621684, 0.37799588], [0.62022902, 0.19286498, 0.37809649], [0.61614266, 0.18953940, 0.37818974], [0.61203242, 0.18624067, 0.37827444], [0.60789824, 0.18296943, 0.37834937], [0.60374000, 0.17972635, 0.37841404], [0.59955770, 0.17651220, 0.37846653], [0.59535127, 0.17332779, 0.37850546], [0.59112064, 0.17017398, 0.37852950], [0.58686572, 0.16705170, 0.37853726], [0.58258634, 0.16396195, 0.37852760], [0.57828232, 0.16090583, 0.37849943], [0.57395365, 0.15788445, 0.37845058], [0.56960020, 0.15489902, 0.37837948], [0.56522185, 0.15195079, 0.37828450], [0.56081843, 0.14904112, 0.37816410], [0.55638960, 0.14617156, 0.37801733], [0.55193545, 0.14334348, 0.37784149], [0.54745584, 0.14055843, 0.37763473], [0.54295065, 0.13781801, 0.37739515], [0.53841965, 0.13512398, 0.37712110], [0.53386261, 0.13247818, 0.37681091], [0.52927965, 0.12988221, 0.37646180], [0.52467068, 0.12733788, 0.37607164], [0.52003564, 0.12484701, 0.37563826], [0.51537424, 0.12241171, 0.37516003], [0.51068666, 0.12003365, 0.37463413], [0.50597299, 0.11771456, 0.37405808], [0.50123327, 0.11545624, 0.37342952], [0.49646750, 0.11326054, 0.37274632], [0.49167582, 0.11112909, 0.37200598], [0.48685856, 0.10906325, 0.37120582], [0.48201596, 0.10706442, 0.37034344], [0.47714828, 0.10513387, 0.36941650], [0.47225593, 0.10327260, 0.36842255], [0.46733939, 0.10148133, 0.36735917], [0.46239915, 0.09976065, 0.36622412], [0.45743580, 0.09811082, 0.36501514], [0.45245022, 0.09653153, 0.36372988], [0.44744296, 0.09502266, 0.36236656], [0.44241480, 0.09358362, 0.36092332], [0.43736661, 0.09221344, 0.35939846], [0.43230001, 0.09090969, 0.35778975], [0.42721549, 0.08967152, 0.35609639], [0.42211410, 0.08849693, 0.35431721], [0.41699698, 0.08738362, 0.35245124], [0.41186583, 0.08632804, 0.35049732], [0.40672217, 0.08532677, 0.34845483], [0.40156669, 0.08437758, 0.34632390], [0.39640071, 0.08347702, 0.34410442], [0.39122561, 0.08262142, 0.34179654], [0.38604309, 0.08180633, 0.33940046], [0.38085553, 0.08102606, 0.33691649], [0.37566316, 0.08027858, 0.33434595], [0.37046736, 0.07955978, 0.33168987], [0.36526951, 0.07886553, 0.32894943], [0.36007097, 0.07819169, 0.32612604], [0.35487306, 0.07753419, 0.32322125], [0.34967708, 0.07688902, 0.32023675], [0.34448536, 0.07625034, 0.31717438], [0.33929826, 0.07561586, 0.31403622], [0.33411661, 0.07498254, 0.31082433], [0.32894146, 0.07434697, 0.30754086], [0.32377380, 0.07370590, 0.30418800], [0.31861455, 0.07305628, 0.30076800], [0.31346457, 0.07239524, 0.29728315], [0.30832464, 0.07172011, 0.29373575], [0.30319545, 0.07102842, 0.29012809], [0.29807765, 0.07031788, 0.28646248], [0.29297177, 0.06958642, 0.28274117], [0.28787829, 0.06883212, 0.27896641], [0.28279763, 0.06805326, 0.27514038], [0.27773011, 0.06724828, 0.27126523], [0.27267598, 0.06641579, 0.26734303], [0.26763544, 0.06555455, 0.26337578], [0.26260976, 0.06466150, 0.25936605], [0.25759927, 0.06373523, 0.25531596], [0.25260288, 0.06277675, 0.25122673], [0.24762052, 0.06178533, 0.24710008], [0.24265208, 0.06076033, 0.24293764], [0.23769737, 0.05970120, 0.23874094], [0.23275618, 0.05860748, 0.23451143], [0.22782852, 0.05747825, 0.23025069], [0.22291807, 0.05630663, 0.22596300], [0.21802045, 0.05509893, 0.22164676], [0.21313526, 0.05385492, 0.21730306], [0.20826202, 0.05257439, 0.21293290], [0.20340025, 0.05125715, 0.20853721]] _vorticity_t_data = [ [0.08225560, 0.11492441, 0.26479017], [0.08312617, 0.11903837, 0.26686289], [0.08400181, 0.12310749, 0.26895267], [0.08487294, 0.12713875, 0.27105417], [0.08574385, 0.13113332, 0.27316912], [0.08661249, 0.13509450, 0.27529614], [0.08747533, 0.13902581, 0.27743329], [0.08833859, 0.14292709, 0.27958315], [0.08919013, 0.14680436, 0.28174002], [0.09004100, 0.15065551, 0.28390867], [0.09088232, 0.15448500, 0.28608501], [0.09171714, 0.15829319, 0.28827028], [0.09254608, 0.16208117, 0.29046458], [0.09336173, 0.16585233, 0.29266480], [0.09417284, 0.16960508, 0.29487442], [0.09496900, 0.17334347, 0.29708922], [0.09575619, 0.17706663, 0.29931153], [0.09653316, 0.18077576, 0.30154079], [0.09729329, 0.18447344, 0.30377451], [0.09804493, 0.18815809, 0.30601574], [0.09877832, 0.19183299, 0.30826092], [0.09949804, 0.19549751, 0.31051168], [0.10020549, 0.19915186, 0.31276843], [0.10089002, 0.20279929, 0.31502756], [0.10156203, 0.20643764, 0.31729251], [0.10221505, 0.21006899, 0.31956112], [0.10284688, 0.21369428, 0.32183267], [0.10346375, 0.21731242, 0.32410904], [0.10405562, 0.22092615, 0.32638711], [0.10462727, 0.22453468, 0.32866827], [0.10518146, 0.22813774, 0.33095325], [0.10570551, 0.23173845, 0.33323831], [0.10620936, 0.23533489, 0.33552622], [0.10669272, 0.23892742, 0.33781678], [0.10714289, 0.24251899, 0.34010639], [0.10757131, 0.24610739, 0.34239809], [0.10797639, 0.24969322, 0.34469128], [0.10834600, 0.25327913, 0.34698268], [0.10869133, 0.25686304, 0.34927505], [0.10901163, 0.26044532, 0.35156802], [0.10929328, 0.26402876, 0.35385806], [0.10954788, 0.26761128, 0.35614786], [0.10977489, 0.27119314, 0.35843709], [0.10996353, 0.27477648, 0.36072299], [0.11011983, 0.27836030, 0.36300681], [0.11024602, 0.28194432, 0.36528883], [0.11033616, 0.28552972, 0.36756748], [0.11038673, 0.28911718, 0.36984175], [0.11040471, 0.29270558, 0.37211295], [0.11038934, 0.29629516, 0.37438064], [0.11032908, 0.29988791, 0.37664208], [0.11023173, 0.30348258, 0.37889869], [0.11009863, 0.30707904, 0.38115045], [0.10992866, 0.31067752, 0.38339682], [0.10970926, 0.31428004, 0.38563492], [0.10945183, 0.31788484, 0.38786678], [0.10915570, 0.32149208, 0.39009193], [0.10882021, 0.32510190, 0.39230988], [0.10843373, 0.32871604, 0.39451799], [0.10800528, 0.33233317, 0.39671769], [0.10753553, 0.33595323, 0.39890871], [0.10702392, 0.33957631, 0.40109056], [0.10646662, 0.34320298, 0.40326210], [0.10585824, 0.34683394, 0.40542188], [0.10520656, 0.35046815, 0.40757096], [0.10451122, 0.35410566, 0.40970881], [0.10377192, 0.35774653, 0.41183489], [0.10298843, 0.36139080, 0.41394866], [0.10215131, 0.36503965, 0.41604787], [0.10126892, 0.36869202, 0.41813352], [0.10034231, 0.37234779, 0.42020525], [0.09937170, 0.37600698, 0.42226250], [0.09835742, 0.37966955, 0.42430469], [0.09729997, 0.38333550, 0.42633126], [0.09620004, 0.38700476, 0.42834163], [0.09505173, 0.39067803, 0.43033399], [0.09386234, 0.39435455, 0.43230887], [0.09263427, 0.39803412, 0.43426586], [0.09136928, 0.40171665, 0.43620437], [0.09006946, 0.40540204, 0.43812379], [0.08873731, 0.40909016, 0.44002354], [0.08737577, 0.41278087, 0.44190300], [0.08598831, 0.41647400, 0.44376159], [0.08457895, 0.42016939, 0.44559868], [0.08315236, 0.42386684, 0.44741369], [0.08171394, 0.42756614, 0.44920601], [0.08026988, 0.43126706, 0.45097504], [0.07882726, 0.43496935, 0.45272018], [0.07739416, 0.43867274, 0.45444085], [0.07597972, 0.44237693, 0.45613645], [0.07459424, 0.44608161, 0.45780643], [0.07324931, 0.44978644, 0.45945021], [0.07195782, 0.45349106, 0.46106724], [0.07073404, 0.45719509, 0.46265700], [0.06959365, 0.46089811, 0.46421897], [0.06855375, 0.46459968, 0.46575265], [0.06763273, 0.46829936, 0.46725759], [0.06685020, 0.47199664, 0.46873333], [0.06622677, 0.47569101, 0.47017948], [0.06577674, 0.47938244, 0.47159416], [0.06552566, 0.48307007, 0.47297774], [0.06549821, 0.48675309, 0.47433054], [0.06571558, 0.49043087, 0.47565232], [0.06619782, 0.49410277, 0.47694291], [0.06696294, 0.49776810, 0.47820211], [0.06801611, 0.50142699, 0.47942671], [0.06938288, 0.50507783, 0.48061980], [0.07107372, 0.50871983, 0.48178149], [0.07309574, 0.51235222, 0.48291199], [0.07544313, 0.51597502, 0.48400767], [0.07812721, 0.51958652, 0.48507257], [0.08114572, 0.52318584, 0.48610736], [0.08448833, 0.52677264, 0.48710972], [0.08815110, 0.53034572, 0.48808171], [0.09212706, 0.53390388, 0.48902580], [0.09640117, 0.53744678, 0.48993927], [0.10096511, 0.54097304, 0.49082601], [0.10580589, 0.54448174, 0.49168732], [0.11090917, 0.54797225, 0.49252203], [0.11626318, 0.55144324, 0.49333556], [0.12185356, 0.55489421, 0.49412566], [0.12766727, 0.55832396, 0.49489786], [0.13369121, 0.56173186, 0.49565192], [0.13991195, 0.56511701, 0.49639184], [0.14631713, 0.56847874, 0.49711902], [0.15289371, 0.57181634, 0.49783712], [0.15963000, 0.57512924, 0.49854817], [0.16651330, 0.57841691, 0.49925615], [0.17353288, 0.58167892, 0.49996313], [0.18067610, 0.58491493, 0.50067365], [0.18793344, 0.58812469, 0.50138963], [0.19529246, 0.59130810, 0.50211590], [0.20274431, 0.59446505, 0.50285464], [0.21027766, 0.59759568, 0.50361022], [0.21788350, 0.60070012, 0.50438554], [0.22555217, 0.60377865, 0.50518416], [0.23327491, 0.60683163, 0.50600926], [0.24104301, 0.60985952, 0.50686415], [0.24884894, 0.61286282, 0.50775157], [0.25668402, 0.61584223, 0.50867505], [0.26454253, 0.61879831, 0.50963658], [0.27241623, 0.62173194, 0.51063959], [0.28030037, 0.62464378, 0.51168577], [0.28818811, 0.62753476, 0.51277795], [0.29607483, 0.63040570, 0.51391788], [0.30395552, 0.63325751, 0.51510756], [0.31182548, 0.63609115, 0.51634887], [0.31968144, 0.63890744, 0.51764306], [0.32751881, 0.64170747, 0.51899197], [0.33533556, 0.64449201, 0.52039636], [0.34312773, 0.64726215, 0.52185776], [0.35089362, 0.65001870, 0.52337683], [0.35863089, 0.65276260, 0.52495444], [0.36633683, 0.65549486, 0.52659157], [0.37401197, 0.65821602, 0.52828804], [0.38165106, 0.66092757, 0.53004568], [0.38925805, 0.66362950, 0.53186311], [0.39682619, 0.66632361, 0.53374255], [0.40435935, 0.66900988, 0.53568268], [0.41185545, 0.67168934, 0.53768413], [0.41931195, 0.67436313, 0.53974757], [0.42673260, 0.67703119, 0.54187183], [0.43411299, 0.67969503, 0.54405806], [0.44145473, 0.68235501, 0.54630566], [0.44875982, 0.68501134, 0.54861400], [0.45602407, 0.68766556, 0.55098397], [0.46324986, 0.69031781, 0.55341478], [0.47043894, 0.69296834, 0.55590587], [0.47758904, 0.69561826, 0.55845753], [0.48469972, 0.69826831, 0.56106956], [0.49177413, 0.70091838, 0.56374112], [0.49881245, 0.70356902, 0.56647195], [0.50581153, 0.70622159, 0.56926226], [0.51277388, 0.70887607, 0.57211131], [0.51970103, 0.71153267, 0.57501859], [0.52659327, 0.71419186, 0.57798374], [0.53344948, 0.71685451, 0.58100655], [0.54026906, 0.71952134, 0.58408665], [0.54705487, 0.72219215, 0.58722338], [0.55380726, 0.72486737, 0.59041634], [0.56052657, 0.72754743, 0.59366511], [0.56721317, 0.73023276, 0.59696926], [0.57386499, 0.73292445, 0.60032836], [0.58048457, 0.73562232, 0.60374187], [0.58707274, 0.73832661, 0.60720930], [0.59362989, 0.74103770, 0.61073019], [0.60015641, 0.74375596, 0.61430405], [0.60665269, 0.74648175, 0.61793039], [0.61311912, 0.74921542, 0.62160871], [0.61955610, 0.75195731, 0.62533849], [0.62596359, 0.75470790, 0.62911918], [0.63234144, 0.75746769, 0.63295016], [0.63869119, 0.76023665, 0.63683100], [0.64501324, 0.76301508, 0.64076119], [0.65130797, 0.76580329, 0.64474018], [0.65757580, 0.76860157, 0.64876743], [0.66381711, 0.77141023, 0.65284240], [0.67003230, 0.77422953, 0.65696453], [0.67622177, 0.77705976, 0.66113327], [0.68238592, 0.77990119, 0.66534806], [0.68852514, 0.78275408, 0.66960833], [0.69463984, 0.78561869, 0.67391352], [0.70073040, 0.78849528, 0.67826307], [0.70679722, 0.79138408, 0.68265641], [0.71284071, 0.79428535, 0.68709296], [0.71886125, 0.79719932, 0.69157216], [0.72485924, 0.80012621, 0.69609343], [0.73083509, 0.80306624, 0.70065621], [0.73678917, 0.80601965, 0.70525992], [0.74272190, 0.80898665, 0.70990399], [0.74863273, 0.81196780, 0.71458740], [0.75452231, 0.81496323, 0.71930966], [0.76039158, 0.81797292, 0.72407043], [0.76624094, 0.82099707, 0.72886914], [0.77207078, 0.82403586, 0.73370523], [0.77788150, 0.82708949, 0.73857810], [0.78367350, 0.83015814, 0.74348721], [0.78944716, 0.83324197, 0.74843197], [0.79520290, 0.83634117, 0.75341183], [0.80094018, 0.83945630, 0.75842558], [0.80665847, 0.84258795, 0.76347196], [0.81235991, 0.84573553, 0.76855153], [0.81804489, 0.84889920, 0.77366371], [0.82371383, 0.85207911, 0.77880793], [0.82936712, 0.85527541, 0.78398361], [0.83500487, 0.85848838, 0.78918994], [0.84062467, 0.86171948, 0.79442393], [0.84622998, 0.86496746, 0.79968738], [0.85182123, 0.86823244, 0.80497972], [0.85739886, 0.87151457, 0.81030033], [0.86296333, 0.87481394, 0.81564861], [0.86851129, 0.87813251, 0.82102020], [0.87404693, 0.88146862, 0.82641787], [0.87957085, 0.88482234, 0.83184102], [0.88508363, 0.88819370, 0.83728899], [0.89058366, 0.89158388, 0.84275871], [0.89607183, 0.89499282, 0.84824952], [0.90155093, 0.89841950, 0.85376285], [0.90702184, 0.90186385, 0.85929802], [0.91248330, 0.90532691, 0.86485172], [0.91793653, 0.90880848, 0.87042326], [0.92338518, 0.91230711, 0.87601483], [0.92883088, 0.91582235, 0.88162632], [0.93427164, 0.91935565, 0.88725314], [0.93971244, 0.92290477, 0.89289983], [0.94515638, 0.92646829, 0.89856977], [0.95060356, 0.93004618, 0.90426466], [0.95605310, 0.93363854, 0.90998868], [0.96150666, 0.93724342, 0.91575606], [0.96695738, 0.94086247, 0.92157953], [0.97238707, 0.94450246, 0.92746703], [0.97777857, 0.94816875, 0.93343649], [0.98310507, 0.95187277, 0.93948603], [0.98834174, 0.95562829, 0.94558363], [0.99349184, 0.95943756, 0.95169832], [0.99857633, 0.96329654, 0.95778950]] _vorticity_data = _vorticity_t_data + _vorticity_p_data _difference_data = [ [0.09317630, 0.11117333, 0.26151239], [0.09697152, 0.11687021, 0.27309631], [0.10096885, 0.12239315, 0.28491036], [0.10499270, 0.12782437, 0.29687381], [0.10898740, 0.13319350, 0.30895384], [0.11292230, 0.13851314, 0.32115284], [0.11677874, 0.14379072, 0.33347631], [0.12054634, 0.14903305, 0.34591927], [0.12421597, 0.15424490, 0.35848249], [0.12777784, 0.15942930, 0.37117372], [0.13122438, 0.16458993, 0.38399390], [0.13454904, 0.16973078, 0.39694025], [0.13774403, 0.17485525, 0.41001322], [0.14079963, 0.17996609, 0.42321738], [0.14370728, 0.18506718, 0.43655022], [0.14645608, 0.19016193, 0.45001310], [0.14903482, 0.19525448, 0.46360362], [0.15143093, 0.20034937, 0.47731853], [0.15362665, 0.20545038, 0.49116235], [0.15560730, 0.21056390, 0.50512420], [0.15735349, 0.21569621, 0.51919772], [0.15884111, 0.22085406, 0.53337810], [0.16003963, 0.22604481, 0.54766269], [0.16092053, 0.23127922, 0.56203080], [0.16144553, 0.23656876, 0.57646619], [0.16156876, 0.24192717, 0.59094728], [0.16123528, 0.24737119, 0.60544468], [0.16037934, 0.25292130, 0.61991794], [0.15891657, 0.25860221, 0.63431839], [0.15673874, 0.26444442, 0.64858326], [0.15374227, 0.27048752, 0.66259429], [0.14975399, 0.27677729, 0.67624289], [0.14461903, 0.28337034, 0.68933032], [0.13815067, 0.29032903, 0.70161667], [0.13019375, 0.29771375, 0.71279281], [0.12070563, 0.30556233, 0.72251014], [0.10982269, 0.31386519, 0.73046944], [0.09795843, 0.32254310, 0.73652716], [0.08570024, 0.33146616, 0.74077181], [0.07367689, 0.34049675, 0.74346934], [0.06252233, 0.34951974, 0.74495630], [0.05283258, 0.35846008, 0.74554518], [0.04520939, 0.36727493, 0.74548891], [0.04023631, 0.37594185, 0.74498414], [0.03831576, 0.38445368, 0.74417463], [0.03948350, 0.39281375, 0.74315813], [0.04345844, 0.40102371, 0.74202430], [0.04962432, 0.40909532, 0.74081668], [0.05739800, 0.41703470, 0.73958775], [0.06626018, 0.42485215, 0.73836501], [0.07582789, 0.43255722, 0.73716979], [0.08583710, 0.44015834, 0.73602068], [0.09611024, 0.44766357, 0.73493125], [0.10653039, 0.45508042, 0.73391177], [0.11702165, 0.46241591, 0.73296937], [0.12753580, 0.46967672, 0.73210750], [0.13804321, 0.47686868, 0.73132951], [0.14852667, 0.48399707, 0.73063745], [0.15897744, 0.49106666, 0.73003226], [0.16939271, 0.49808168, 0.72951410], [0.17977386, 0.50504587, 0.72908242], [0.19012529, 0.51196251, 0.72873614], [0.20045367, 0.51883439, 0.72847377], [0.21076743, 0.52566384, 0.72829343], [0.22107637, 0.53245276, 0.72819301], [0.23139144, 0.53920256, 0.72817020], [0.24172459, 0.54591421, 0.72822258], [0.25208860, 0.55258823, 0.72834769], [0.26249697, 0.55922467, 0.72854317], [0.27296382, 0.56582312, 0.72880681], [0.28350369, 0.57238271, 0.72913673], [0.29413138, 0.57890214, 0.72953149], [0.30486166, 0.58537967, 0.72999025], [0.31570894, 0.59181322, 0.73051298], [0.32668681, 0.59820041, 0.73110060], [0.33780753, 0.60453865, 0.73175521], [0.34908180, 0.61082531, 0.73247968], [0.36051697, 0.61705790, 0.73327922], [0.37211638, 0.62323432, 0.73416123], [0.38387988, 0.62935306, 0.73513375], [0.39580281, 0.63541344, 0.73620602], [0.40787554, 0.64141586, 0.73738846], [0.42008256, 0.64736207, 0.73869308], [0.43240665, 0.65325485, 0.74012945], [0.44482701, 0.65909826, 0.74170693], [0.45732109, 0.66489739, 0.74343353], [0.46986588, 0.67065815, 0.74531538], [0.48243916, 0.67638699, 0.74735656], [0.49502055, 0.68209061, 0.74955890], [0.50759227, 0.68777566, 0.75192214], [0.52013952, 0.69344853, 0.75444409], [0.53265066, 0.69911520, 0.75712102], [0.54511511, 0.70478153, 0.75994930], [0.55751816, 0.71045432, 0.76292914], [0.56986354, 0.71613651, 0.76604883], [0.58214859, 0.72183221, 0.76930236], [0.59436024, 0.72754780, 0.77269163], [0.60650809, 0.73328445, 0.77620411], [0.61858647, 0.73904668, 0.77983837], [0.63059636, 0.74483734, 0.78358922], [0.64254033, 0.75065877, 0.78745106], [0.65441860, 0.75651373, 0.79142043], [0.66623153, 0.76240488, 0.79549418], [0.67798504, 0.76833329, 0.79966600], [0.68967550, 0.77430243, 0.80393610], [0.70131075, 0.78031263, 0.80829755], [0.71288853, 0.78636686, 0.81275022], [0.72441124, 0.79246672, 0.81729113], [0.73588370, 0.79861307, 0.82191590], [0.74730444, 0.80480845, 0.82662434], [0.75867599, 0.81105425, 0.83141375], [0.77000070, 0.81735182, 0.83628157], [0.78127895, 0.82370305, 0.84122655], [0.79251162, 0.83010967, 0.84624710], [0.80369975, 0.83657330, 0.85134141], [0.81484311, 0.84309597, 0.85650845], [0.82594216, 0.84967946, 0.86174654], [0.83699675, 0.85632577, 0.86705416], [0.84800383, 0.86303779, 0.87243156], [0.85896284, 0.86981769, 0.87787684], [0.86987188, 0.87666811, 0.88338843], [0.88072260, 0.88359376, 0.88896898], [0.89151256, 0.89059766, 0.89461579], [0.90223219, 0.89768518, 0.90033034], [0.91286295, 0.90486468, 0.90612019], [0.92339067, 0.91214345, 0.91198727], [0.93376907, 0.91953891, 0.91796043], [0.94387686, 0.92709058, 0.92414784], [0.94502413, 0.92672740, 0.92320173], [0.94017715, 0.91750110, 0.91273530], [0.93577882, 0.90818496, 0.90199590], [0.93161955, 0.89884559, 0.89112473], [0.92763669, 0.88950153, 0.88016251], [0.92379637, 0.88016199, 0.86913066], [0.92007678, 0.87083231, 0.85804265], [0.91646227, 0.86151587, 0.84690792], [0.91294097, 0.85221483, 0.83573351], [0.90950339, 0.84293065, 0.82452495], [0.90614135, 0.83366435, 0.81328703], [0.90284824, 0.82441650, 0.80202350], [0.89961835, 0.81518734, 0.79073759], [0.89644640, 0.80597704, 0.77943233], [0.89332810, 0.79678541, 0.76811006], [0.89025854, 0.78761252, 0.75677380], [0.88723415, 0.77845801, 0.74542553], [0.88425152, 0.76932142, 0.73406721], [0.88130757, 0.76020224, 0.72270059], [0.87839898, 0.75110001, 0.71132772], [0.87552202, 0.74201448, 0.69995114], [0.87267498, 0.73294464, 0.68857164], [0.86985472, 0.72389001, 0.67719140], [0.86705966, 0.71484951, 0.66581120], [0.86428554, 0.70582315, 0.65443443], [0.86153122, 0.69680968, 0.64306165], [0.85879456, 0.68780825, 0.63169442], [0.85607377, 0.67881784, 0.62033401], [0.85336475, 0.66983845, 0.60898403], [0.85066718, 0.66086845, 0.59764454], [0.84798038, 0.65190630, 0.58631596], [0.84529929, 0.64295243, 0.57500309], [0.84262333, 0.63400527, 0.56370649], [0.83995267, 0.62506283, 0.55242594], [0.83728236, 0.61612552, 0.54116651], [0.83461150, 0.60719184, 0.52992929], [0.83194170, 0.59825898, 0.51871286], [0.82926584, 0.58932842, 0.50752486], [0.82658652, 0.58039681, 0.49636308], [0.82390077, 0.57146348, 0.48523112], [0.82120472, 0.56252830, 0.47413374], [0.81850284, 0.55358664, 0.46306700], [0.81578580, 0.54464120, 0.45204172], [0.81305988, 0.53568615, 0.44105231], [0.81031573, 0.52672425, 0.43011000], [0.80756008, 0.51774912, 0.41920905], [0.80478300, 0.50876385, 0.40836176], [0.80199136, 0.49976163, 0.39756263], [0.79917761, 0.49074411, 0.38682195], [0.79634125, 0.48170863, 0.37614268], [0.79348534, 0.47265010, 0.36552429], [0.79060209, 0.46357018, 0.35497832], [0.78769221, 0.45446502, 0.34450752], [0.78475844, 0.44532901, 0.33411300], [0.78179438, 0.43616264, 0.32380621], [0.77879860, 0.42696282, 0.31359382], [0.77577003, 0.41772599, 0.30348288], [0.77270738, 0.40844842, 0.29348145], [0.76960910, 0.39912628, 0.28359883], [0.76647331, 0.38975562, 0.27384573], [0.76329775, 0.38033247, 0.26423455], [0.76007961, 0.37085287, 0.25477962], [0.75681552, 0.36131299, 0.24549744], [0.75350142, 0.35170920, 0.23640702], [0.75013244, 0.34203820, 0.22753009], [0.74670837, 0.33229173, 0.21888681], [0.74322062, 0.32246895, 0.21050730], [0.73966264, 0.31256672, 0.20242263], [0.73602766, 0.30258171, 0.19466697], [0.73230751, 0.29251159, 0.18727887], [0.72848868, 0.28235996, 0.18030258], [0.72455978, 0.27212835, 0.17378304], [0.72050526, 0.26182377, 0.16776811], [0.71630775, 0.25145685, 0.16230504], [0.71194775, 0.24104317, 0.15743769], [0.70740461, 0.23060296, 0.15320278], [0.70265778, 0.22016032, 0.14962642], [0.69768564, 0.20974625, 0.14671934], [0.69247010, 0.19939235, 0.14447576], [0.68699563, 0.18913262, 0.14287203], [0.68125094, 0.17900057, 0.14186849], [0.67522904, 0.16902840, 0.14141262], [0.66892723, 0.15924601, 0.14144362], [0.66234629, 0.14968150, 0.14189670], [0.65548946, 0.14036226, 0.14270608], [0.64836184, 0.13131545, 0.14380938], [0.64096909, 0.12257090, 0.14514666], [0.63331719, 0.11416164, 0.14666355], [0.62541177, 0.10612632, 0.14830833], [0.61725809, 0.09850956, 0.15003428], [0.60886121, 0.09136271, 0.15179467], [0.60022601, 0.08474269, 0.15354719], [0.59135807, 0.07870938, 0.15524760], [0.58226407, 0.07332111, 0.15685285], [0.57295232, 0.06862870, 0.15832095], [0.56343372, 0.06466696, 0.15960971], [0.55372241, 0.06144627, 0.16067796], [0.54383514, 0.05894915, 0.16148955], [0.53379121, 0.05712858, 0.16201381], [0.52361200, 0.05591095, 0.16222653], [0.51332147, 0.05519900, 0.16210827], [0.50294151, 0.05489269, 0.16165212], [0.49249206, 0.05489498, 0.16085946], [0.48199704, 0.05509874, 0.15972947], [0.47146853, 0.05543753, 0.15828036], [0.46092984, 0.05581817, 0.15651615], [0.45038823, 0.05620093, 0.15446036], [0.43985504, 0.05653967, 0.15212964], [0.42933959, 0.05679893, 0.14954130], [0.41884881, 0.05695351, 0.14671310], [0.40838748, 0.05698680, 0.14366262], [0.39795842, 0.05688899, 0.14040679], [0.38756618, 0.05664745, 0.13695962], [0.37721626, 0.05624859, 0.13333329], [0.36690097, 0.05571028, 0.12954563], [0.35662892, 0.05501236, 0.12560413], [0.34639461, 0.05416713, 0.12152211], [0.33620182, 0.05316577, 0.11730740], [0.32604244, 0.05202498, 0.11297139], [0.31592786, 0.05071934, 0.10851752], [0.30584405, 0.04927678, 0.10395692], [0.29579063, 0.04769543, 0.09929501], [0.28577617, 0.04595517, 0.09453470], [0.27578839, 0.04407730, 0.08968329], [0.26582514, 0.04206161, 0.08474472], [0.25588406, 0.03990047, 0.07972236], [0.24596222, 0.03762595, 0.07461914]] datad = { 'density': _density_data, 'phase': _phase_data, 'speed': _speed_data, 'temperature': _temperature_data, 'velocity': _velocity_data, 'vorticity': _vorticity_data, 'difference': _difference_data, }
true
true
1c442889a1b7474a639e574b6d8ff896dff9adeb
7,809
py
Python
instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py
stschenk/opentelemetry-python-contrib
28c1331e571d386baab74f5028e3268e4bfda4cd
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-03-17T05:37:21.000Z
2020-03-17T05:37:21.000Z
instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py
stschenk/opentelemetry-python-contrib
28c1331e571d386baab74f5028e3268e4bfda4cd
[ "Apache-2.0", "BSD-3-Clause" ]
3
2019-08-26T13:06:36.000Z
2020-02-21T21:44:02.000Z
instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py
stschenk/opentelemetry-python-contrib
28c1331e571d386baab74f5028e3268e4bfda4cd
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-10-22T20:13:37.000Z
2020-10-22T20:13:37.000Z
# Copyright The OpenTelemetry 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. """ The opentelemetry-instrumentation-asgi package provides an ASGI middleware that can be used on any ASGI framework (such as Django-channels / Quart) to track requests timing through OpenTelemetry. """ import operator import typing import urllib from functools import wraps from typing import Tuple from asgiref.compatibility import guarantee_single_callable from opentelemetry import context, propagators, trace from opentelemetry.instrumentation.asgi.version import __version__ # noqa from opentelemetry.instrumentation.utils import http_status_to_status_code from opentelemetry.trace.propagation.textmap import DictGetter from opentelemetry.trace.status import Status, StatusCode class CarrierGetter(DictGetter): def get(self, carrier: dict, key: str) -> typing.List[str]: """Getter implementation to retrieve a HTTP header value from the ASGI scope. Args: carrier: ASGI scope object key: header name in scope Returns: A list with a single string with the header value if it exists, else an empty list. """ headers = carrier.get("headers") return [ _value.decode("utf8") for (_key, _value) in headers if _key.decode("utf8") == key ] carrier_getter = CarrierGetter() def collect_request_attributes(scope): """Collects HTTP request attributes from the ASGI scope and returns a dictionary to be used as span creation attributes.""" server = scope.get("server") or ["0.0.0.0", 80] port = server[1] server_host = server[0] + (":" + str(port) if port != 80 else "") full_path = scope.get("root_path", "") + scope.get("path", "") http_url = scope.get("scheme", "http") + "://" + server_host + full_path query_string = scope.get("query_string") if query_string and http_url: if isinstance(query_string, bytes): query_string = query_string.decode("utf8") http_url = http_url + ("?" + urllib.parse.unquote(query_string)) result = { "component": scope["type"], "http.scheme": scope.get("scheme"), "http.host": server_host, "host.port": port, "http.flavor": scope.get("http_version"), "http.target": scope.get("path"), "http.url": http_url, } http_method = scope.get("method") if http_method: result["http.method"] = http_method http_host_value = ",".join(carrier_getter.get(scope, "host")) if http_host_value: result["http.server_name"] = http_host_value http_user_agent = carrier_getter.get(scope, "user-agent") if len(http_user_agent) > 0: result["http.user_agent"] = http_user_agent[0] if "client" in scope and scope["client"] is not None: result["net.peer.ip"] = scope.get("client")[0] result["net.peer.port"] = scope.get("client")[1] # remove None values result = {k: v for k, v in result.items() if v is not None} return result def set_status_code(span, status_code): """Adds HTTP response attributes to span using the status_code argument.""" if not span.is_recording(): return try: status_code = int(status_code) except ValueError: span.set_status( Status( StatusCode.ERROR, "Non-integer HTTP status: " + repr(status_code), ) ) else: span.set_attribute("http.status_code", status_code) span.set_status(Status(http_status_to_status_code(status_code))) def get_default_span_details(scope: dict) -> Tuple[str, dict]: """Default implementation for span_details_callback Args: scope: the asgi scope dictionary Returns: a tuple of the span, and any attributes to attach to the span. """ method_or_path = scope.get("method") or scope.get("path") return method_or_path, {} class OpenTelemetryMiddleware: """The ASGI application middleware. This class is an ASGI middleware that starts and annotates spans for any requests it is invoked with. Args: app: The ASGI application callable to forward requests to. span_details_callback: Callback which should return a string and a tuple, representing the desired span name and a dictionary with any additional span attributes to set. Optional: Defaults to get_default_span_details. """ def __init__(self, app, span_details_callback=None): self.app = guarantee_single_callable(app) self.tracer = trace.get_tracer(__name__, __version__) self.span_details_callback = ( span_details_callback or get_default_span_details ) async def __call__(self, scope, receive, send): """The ASGI application Args: scope: A ASGI environment. receive: An awaitable callable yielding dictionaries send: An awaitable callable taking a single dictionary as argument. """ if scope["type"] not in ("http", "websocket"): return await self.app(scope, receive, send) token = context.attach(propagators.extract(carrier_getter, scope)) span_name, additional_attributes = self.span_details_callback(scope) try: with self.tracer.start_as_current_span( span_name + " asgi", kind=trace.SpanKind.SERVER, ) as span: if span.is_recording(): attributes = collect_request_attributes(scope) attributes.update(additional_attributes) for key, value in attributes.items(): span.set_attribute(key, value) @wraps(receive) async def wrapped_receive(): with self.tracer.start_as_current_span( span_name + " asgi." + scope["type"] + ".receive" ) as receive_span: message = await receive() if receive_span.is_recording(): if message["type"] == "websocket.receive": set_status_code(receive_span, 200) receive_span.set_attribute("type", message["type"]) return message @wraps(send) async def wrapped_send(message): with self.tracer.start_as_current_span( span_name + " asgi." + scope["type"] + ".send" ) as send_span: if send_span.is_recording(): if message["type"] == "http.response.start": status_code = message["status"] set_status_code(send_span, status_code) elif message["type"] == "websocket.send": set_status_code(send_span, 200) send_span.set_attribute("type", message["type"]) await send(message) await self.app(scope, wrapped_receive, wrapped_send) finally: context.detach(token)
37.363636
91
0.619029
import operator import typing import urllib from functools import wraps from typing import Tuple from asgiref.compatibility import guarantee_single_callable from opentelemetry import context, propagators, trace from opentelemetry.instrumentation.asgi.version import __version__ from opentelemetry.instrumentation.utils import http_status_to_status_code from opentelemetry.trace.propagation.textmap import DictGetter from opentelemetry.trace.status import Status, StatusCode class CarrierGetter(DictGetter): def get(self, carrier: dict, key: str) -> typing.List[str]: headers = carrier.get("headers") return [ _value.decode("utf8") for (_key, _value) in headers if _key.decode("utf8") == key ] carrier_getter = CarrierGetter() def collect_request_attributes(scope): server = scope.get("server") or ["0.0.0.0", 80] port = server[1] server_host = server[0] + (":" + str(port) if port != 80 else "") full_path = scope.get("root_path", "") + scope.get("path", "") http_url = scope.get("scheme", "http") + "://" + server_host + full_path query_string = scope.get("query_string") if query_string and http_url: if isinstance(query_string, bytes): query_string = query_string.decode("utf8") http_url = http_url + ("?" + urllib.parse.unquote(query_string)) result = { "component": scope["type"], "http.scheme": scope.get("scheme"), "http.host": server_host, "host.port": port, "http.flavor": scope.get("http_version"), "http.target": scope.get("path"), "http.url": http_url, } http_method = scope.get("method") if http_method: result["http.method"] = http_method http_host_value = ",".join(carrier_getter.get(scope, "host")) if http_host_value: result["http.server_name"] = http_host_value http_user_agent = carrier_getter.get(scope, "user-agent") if len(http_user_agent) > 0: result["http.user_agent"] = http_user_agent[0] if "client" in scope and scope["client"] is not None: result["net.peer.ip"] = scope.get("client")[0] result["net.peer.port"] = scope.get("client")[1] result = {k: v for k, v in result.items() if v is not None} return result def set_status_code(span, status_code): if not span.is_recording(): return try: status_code = int(status_code) except ValueError: span.set_status( Status( StatusCode.ERROR, "Non-integer HTTP status: " + repr(status_code), ) ) else: span.set_attribute("http.status_code", status_code) span.set_status(Status(http_status_to_status_code(status_code))) def get_default_span_details(scope: dict) -> Tuple[str, dict]: method_or_path = scope.get("method") or scope.get("path") return method_or_path, {} class OpenTelemetryMiddleware: def __init__(self, app, span_details_callback=None): self.app = guarantee_single_callable(app) self.tracer = trace.get_tracer(__name__, __version__) self.span_details_callback = ( span_details_callback or get_default_span_details ) async def __call__(self, scope, receive, send): if scope["type"] not in ("http", "websocket"): return await self.app(scope, receive, send) token = context.attach(propagators.extract(carrier_getter, scope)) span_name, additional_attributes = self.span_details_callback(scope) try: with self.tracer.start_as_current_span( span_name + " asgi", kind=trace.SpanKind.SERVER, ) as span: if span.is_recording(): attributes = collect_request_attributes(scope) attributes.update(additional_attributes) for key, value in attributes.items(): span.set_attribute(key, value) @wraps(receive) async def wrapped_receive(): with self.tracer.start_as_current_span( span_name + " asgi." + scope["type"] + ".receive" ) as receive_span: message = await receive() if receive_span.is_recording(): if message["type"] == "websocket.receive": set_status_code(receive_span, 200) receive_span.set_attribute("type", message["type"]) return message @wraps(send) async def wrapped_send(message): with self.tracer.start_as_current_span( span_name + " asgi." + scope["type"] + ".send" ) as send_span: if send_span.is_recording(): if message["type"] == "http.response.start": status_code = message["status"] set_status_code(send_span, status_code) elif message["type"] == "websocket.send": set_status_code(send_span, 200) send_span.set_attribute("type", message["type"]) await send(message) await self.app(scope, wrapped_receive, wrapped_send) finally: context.detach(token)
true
true
1c4429efcf1bf8e61716fe3bf3416c05614bb251
6,071
py
Python
tests/falcon_test.py
titaux12/falcon-apispec
2f680622ddfb2af57685903578f9d4dccba72a6b
[ "MIT" ]
null
null
null
tests/falcon_test.py
titaux12/falcon-apispec
2f680622ddfb2af57685903578f9d4dccba72a6b
[ "MIT" ]
null
null
null
tests/falcon_test.py
titaux12/falcon-apispec
2f680622ddfb2af57685903578f9d4dccba72a6b
[ "MIT" ]
1
2021-03-25T17:13:09.000Z
2021-03-25T17:13:09.000Z
import logging import falcon import pytest from apispec import APISpec from apispec.exceptions import APISpecError from falcon_apispec import FalconPlugin logging.basicConfig(level="DEBUG") @pytest.fixture() def spec_factory(): def _spec(app): return APISpec( title="Swagger Petstore", version="1.0.0", openapi_version="3.0.2", description="This is a sample Petstore server. You can find out " 'more about Swagger at <a href="https://swagger.io"> ' "http://swagger.wordnik.com</a> or on irc.freenode.net, #swagger." 'For this sample, you can use the api key "special-key" to test ' "the authorization filters", plugins=[FalconPlugin(app)], ) return _spec @pytest.fixture() def app(): falcon_app = falcon.API() return falcon_app class TestPathHelpers: def test_gettable_resource(self, app, spec_factory): class HelloResource: def on_get(self, req, resp): """A greeting endpoint. --- description: get a greeting responses: 200: description: said hi """ return "dummy" expected = { "description": "get a greeting", "responses": {"200": {"description": "said hi"}}, } hello_resource = HelloResource() app.add_route("/hi", hello_resource) spec = spec_factory(app) spec.path(resource=hello_resource) assert spec._paths["/hi"]["get"] == expected def test_posttable_resource(self, app, spec_factory): class HelloResource: def on_post(self, req, resp): """A greeting endpoint. --- description: get a greeting responses: 201: description: posted something """ return "hi" expected = { "description": "get a greeting", "responses": {"201": {"description": "posted something"}}, } hello_resource = HelloResource() app.add_route("/hi", hello_resource) spec = spec_factory(app) spec.path(resource=hello_resource) assert spec._paths["/hi"]["post"] == expected def test_resource_with_metadata(self, app, spec_factory): class HelloResource: """Greeting API. --- x-extension: global metadata """ hello_resource = HelloResource() app.add_route("/hi", hello_resource) spec = spec_factory(app) spec.path(resource=hello_resource) assert spec._paths["/hi"]["x-extension"] == "global metadata" def test_unredundant_basepath_resource_with_slash(self, app, spec_factory): class HelloResource: def on_get(self, req, resp): """A greeting endpoint. --- description: get a greeting responses: 200: description: said hi """ return "dummy" expected = { "description": "get a greeting", "responses": {"200": {"description": "said hi"}}, } hello_resource = HelloResource() app.add_route("/v1/foo/v1", hello_resource) spec = spec_factory(app) base_path = '/v1' spec.path(resource=hello_resource, base_path=base_path) assert spec._paths["/foo/v1"]["get"] == expected def test_unredundant_basepath_resource_wo_slash(self, app, spec_factory): class HelloResource: def on_get(self, req, resp): """A greeting endpoint. --- description: get a greeting responses: 200: description: said hi """ return "dummy" expected = { "description": "get a greeting", "responses": {"200": {"description": "said hi"}}, } hello_resource = HelloResource() app.add_route("/v1/foo/v1", hello_resource) spec = spec_factory(app) base_path = 'v1' spec.path(resource=hello_resource, base_path=base_path) assert spec._paths["/foo/v1"]["get"] == expected def test_path_with_suffix(self, app, spec_factory): class HelloResource: def on_get_hello(self): """A greeting endpoint. --- description: get a greeting responses: 200: description: said hi """ return "dummy" def on_get(self): """An invalid method. --- description: this should not pass responses: 200: description: said hi """ return "invalid" expected = { "description": "get a greeting", "responses": {"200": {"description": "said hi"}}, } hello_resource_with_suffix = HelloResource() app.add_route("/hi", hello_resource_with_suffix, suffix="hello") spec = spec_factory(app) spec.path(resource=hello_resource_with_suffix) assert spec._paths["/hi"]["get"] == expected def test_resource_without_endpoint(self, app, spec_factory): class HelloResource: def on_get(self, req, resp): """A greeting endpoint. --- description: get a greeting responses: 200: description: said hi """ return "dummy" hello_resource = HelloResource() spec = spec_factory(app) with pytest.raises(APISpecError): spec.path(resource=hello_resource)
30.661616
79
0.51919
import logging import falcon import pytest from apispec import APISpec from apispec.exceptions import APISpecError from falcon_apispec import FalconPlugin logging.basicConfig(level="DEBUG") @pytest.fixture() def spec_factory(): def _spec(app): return APISpec( title="Swagger Petstore", version="1.0.0", openapi_version="3.0.2", description="This is a sample Petstore server. You can find out " 'more about Swagger at <a href="https://swagger.io"> ' "http://swagger.wordnik.com</a> or on irc.freenode.net, #swagger." 'For this sample, you can use the api key "special-key" to test ' "the authorization filters", plugins=[FalconPlugin(app)], ) return _spec @pytest.fixture() def app(): falcon_app = falcon.API() return falcon_app class TestPathHelpers: def test_gettable_resource(self, app, spec_factory): class HelloResource: def on_get(self, req, resp): return "dummy" expected = { "description": "get a greeting", "responses": {"200": {"description": "said hi"}}, } hello_resource = HelloResource() app.add_route("/hi", hello_resource) spec = spec_factory(app) spec.path(resource=hello_resource) assert spec._paths["/hi"]["get"] == expected def test_posttable_resource(self, app, spec_factory): class HelloResource: def on_post(self, req, resp): return "hi" expected = { "description": "get a greeting", "responses": {"201": {"description": "posted something"}}, } hello_resource = HelloResource() app.add_route("/hi", hello_resource) spec = spec_factory(app) spec.path(resource=hello_resource) assert spec._paths["/hi"]["post"] == expected def test_resource_with_metadata(self, app, spec_factory): class HelloResource: hello_resource = HelloResource() app.add_route("/hi", hello_resource) spec = spec_factory(app) spec.path(resource=hello_resource) assert spec._paths["/hi"]["x-extension"] == "global metadata" def test_unredundant_basepath_resource_with_slash(self, app, spec_factory): class HelloResource: def on_get(self, req, resp): return "dummy" expected = { "description": "get a greeting", "responses": {"200": {"description": "said hi"}}, } hello_resource = HelloResource() app.add_route("/v1/foo/v1", hello_resource) spec = spec_factory(app) base_path = '/v1' spec.path(resource=hello_resource, base_path=base_path) assert spec._paths["/foo/v1"]["get"] == expected def test_unredundant_basepath_resource_wo_slash(self, app, spec_factory): class HelloResource: def on_get(self, req, resp): return "dummy" expected = { "description": "get a greeting", "responses": {"200": {"description": "said hi"}}, } hello_resource = HelloResource() app.add_route("/v1/foo/v1", hello_resource) spec = spec_factory(app) base_path = 'v1' spec.path(resource=hello_resource, base_path=base_path) assert spec._paths["/foo/v1"]["get"] == expected def test_path_with_suffix(self, app, spec_factory): class HelloResource: def on_get_hello(self): return "dummy" def on_get(self): return "invalid" expected = { "description": "get a greeting", "responses": {"200": {"description": "said hi"}}, } hello_resource_with_suffix = HelloResource() app.add_route("/hi", hello_resource_with_suffix, suffix="hello") spec = spec_factory(app) spec.path(resource=hello_resource_with_suffix) assert spec._paths["/hi"]["get"] == expected def test_resource_without_endpoint(self, app, spec_factory): class HelloResource: def on_get(self, req, resp): return "dummy" hello_resource = HelloResource() spec = spec_factory(app) with pytest.raises(APISpecError): spec.path(resource=hello_resource)
true
true
1c442aa98df653b95bdf0ffef94696a49f90a158
22,175
py
Python
sdk/python/pulumi_azure_native/network/v20200501/express_route_port.py
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/network/v20200501/express_route_port.py
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/network/v20200501/express_route_port.py
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** 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__ = ['ExpressRoutePortArgs', 'ExpressRoutePort'] @pulumi.input_type class ExpressRoutePortArgs: def __init__(__self__, *, resource_group_name: pulumi.Input[str], bandwidth_in_gbps: Optional[pulumi.Input[int]] = None, encapsulation: Optional[pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']]] = None, express_route_port_name: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, identity: Optional[pulumi.Input['ManagedServiceIdentityArgs']] = None, links: Optional[pulumi.Input[Sequence[pulumi.Input['ExpressRouteLinkArgs']]]] = None, location: Optional[pulumi.Input[str]] = None, peering_location: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None): """ The set of arguments for constructing a ExpressRoutePort resource. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[int] bandwidth_in_gbps: Bandwidth of procured ports in Gbps. :param pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']] encapsulation: Encapsulation method on physical ports. :param pulumi.Input[str] express_route_port_name: The name of the ExpressRoutePort resource. :param pulumi.Input[str] id: Resource ID. :param pulumi.Input['ManagedServiceIdentityArgs'] identity: The identity of ExpressRoutePort, if configured. :param pulumi.Input[Sequence[pulumi.Input['ExpressRouteLinkArgs']]] links: The set of physical links of the ExpressRoutePort resource. :param pulumi.Input[str] location: Resource location. :param pulumi.Input[str] peering_location: The name of the peering location that the ExpressRoutePort is mapped to physically. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags. """ pulumi.set(__self__, "resource_group_name", resource_group_name) if bandwidth_in_gbps is not None: pulumi.set(__self__, "bandwidth_in_gbps", bandwidth_in_gbps) if encapsulation is not None: pulumi.set(__self__, "encapsulation", encapsulation) if express_route_port_name is not None: pulumi.set(__self__, "express_route_port_name", express_route_port_name) if id is not None: pulumi.set(__self__, "id", id) if identity is not None: pulumi.set(__self__, "identity", identity) if links is not None: pulumi.set(__self__, "links", links) if location is not None: pulumi.set(__self__, "location", location) if peering_location is not None: pulumi.set(__self__, "peering_location", peering_location) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: """ The name of the resource group. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="bandwidthInGbps") def bandwidth_in_gbps(self) -> Optional[pulumi.Input[int]]: """ Bandwidth of procured ports in Gbps. """ return pulumi.get(self, "bandwidth_in_gbps") @bandwidth_in_gbps.setter def bandwidth_in_gbps(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "bandwidth_in_gbps", value) @property @pulumi.getter def encapsulation(self) -> Optional[pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']]]: """ Encapsulation method on physical ports. """ return pulumi.get(self, "encapsulation") @encapsulation.setter def encapsulation(self, value: Optional[pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']]]): pulumi.set(self, "encapsulation", value) @property @pulumi.getter(name="expressRoutePortName") def express_route_port_name(self) -> Optional[pulumi.Input[str]]: """ The name of the ExpressRoutePort resource. """ return pulumi.get(self, "express_route_port_name") @express_route_port_name.setter def express_route_port_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "express_route_port_name", value) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ Resource ID. """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter def identity(self) -> Optional[pulumi.Input['ManagedServiceIdentityArgs']]: """ The identity of ExpressRoutePort, if configured. """ return pulumi.get(self, "identity") @identity.setter def identity(self, value: Optional[pulumi.Input['ManagedServiceIdentityArgs']]): pulumi.set(self, "identity", value) @property @pulumi.getter def links(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ExpressRouteLinkArgs']]]]: """ The set of physical links of the ExpressRoutePort resource. """ return pulumi.get(self, "links") @links.setter def links(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ExpressRouteLinkArgs']]]]): pulumi.set(self, "links", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: """ Resource location. """ return pulumi.get(self, "location") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "location", value) @property @pulumi.getter(name="peeringLocation") def peering_location(self) -> Optional[pulumi.Input[str]]: """ The name of the peering location that the ExpressRoutePort is mapped to physically. """ return pulumi.get(self, "peering_location") @peering_location.setter def peering_location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "peering_location", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ Resource tags. """ return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) class ExpressRoutePort(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, bandwidth_in_gbps: Optional[pulumi.Input[int]] = None, encapsulation: Optional[pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']]] = None, express_route_port_name: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, identity: Optional[pulumi.Input[pulumi.InputType['ManagedServiceIdentityArgs']]] = None, links: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ExpressRouteLinkArgs']]]]] = None, location: Optional[pulumi.Input[str]] = None, peering_location: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): """ ExpressRoutePort resource definition. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[int] bandwidth_in_gbps: Bandwidth of procured ports in Gbps. :param pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']] encapsulation: Encapsulation method on physical ports. :param pulumi.Input[str] express_route_port_name: The name of the ExpressRoutePort resource. :param pulumi.Input[str] id: Resource ID. :param pulumi.Input[pulumi.InputType['ManagedServiceIdentityArgs']] identity: The identity of ExpressRoutePort, if configured. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ExpressRouteLinkArgs']]]] links: The set of physical links of the ExpressRoutePort resource. :param pulumi.Input[str] location: Resource location. :param pulumi.Input[str] peering_location: The name of the peering location that the ExpressRoutePort is mapped to physically. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags. """ ... @overload def __init__(__self__, resource_name: str, args: ExpressRoutePortArgs, opts: Optional[pulumi.ResourceOptions] = None): """ ExpressRoutePort resource definition. :param str resource_name: The name of the resource. :param ExpressRoutePortArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(ExpressRoutePortArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, bandwidth_in_gbps: Optional[pulumi.Input[int]] = None, encapsulation: Optional[pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']]] = None, express_route_port_name: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, identity: Optional[pulumi.Input[pulumi.InputType['ManagedServiceIdentityArgs']]] = None, links: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ExpressRouteLinkArgs']]]]] = None, location: Optional[pulumi.Input[str]] = None, peering_location: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = ExpressRoutePortArgs.__new__(ExpressRoutePortArgs) __props__.__dict__["bandwidth_in_gbps"] = bandwidth_in_gbps __props__.__dict__["encapsulation"] = encapsulation __props__.__dict__["express_route_port_name"] = express_route_port_name __props__.__dict__["id"] = id __props__.__dict__["identity"] = identity __props__.__dict__["links"] = links __props__.__dict__["location"] = location __props__.__dict__["peering_location"] = peering_location if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["tags"] = tags __props__.__dict__["allocation_date"] = None __props__.__dict__["circuits"] = None __props__.__dict__["etag"] = None __props__.__dict__["ether_type"] = None __props__.__dict__["mtu"] = None __props__.__dict__["name"] = None __props__.__dict__["provisioned_bandwidth_in_gbps"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["resource_guid"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network/v20200501:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20180801:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20180801:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20181001:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20181001:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20181101:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20181101:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20181201:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20181201:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190201:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190201:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190401:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190401:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190601:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190601:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190701:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190701:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190801:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190801:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190901:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190901:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20191101:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20191101:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20191201:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20191201:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20200301:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20200301:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20200401:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20200401:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20200601:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20200601:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20200701:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20200701:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20200801:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20200801:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20201101:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20201101:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20210201:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20210201:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20210301:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20210301:ExpressRoutePort")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(ExpressRoutePort, __self__).__init__( 'azure-native:network/v20200501:ExpressRoutePort', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'ExpressRoutePort': """ Get an existing ExpressRoutePort resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = ExpressRoutePortArgs.__new__(ExpressRoutePortArgs) __props__.__dict__["allocation_date"] = None __props__.__dict__["bandwidth_in_gbps"] = None __props__.__dict__["circuits"] = None __props__.__dict__["encapsulation"] = None __props__.__dict__["etag"] = None __props__.__dict__["ether_type"] = None __props__.__dict__["identity"] = None __props__.__dict__["links"] = None __props__.__dict__["location"] = None __props__.__dict__["mtu"] = None __props__.__dict__["name"] = None __props__.__dict__["peering_location"] = None __props__.__dict__["provisioned_bandwidth_in_gbps"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["resource_guid"] = None __props__.__dict__["tags"] = None __props__.__dict__["type"] = None return ExpressRoutePort(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="allocationDate") def allocation_date(self) -> pulumi.Output[str]: """ Date of the physical port allocation to be used in Letter of Authorization. """ return pulumi.get(self, "allocation_date") @property @pulumi.getter(name="bandwidthInGbps") def bandwidth_in_gbps(self) -> pulumi.Output[Optional[int]]: """ Bandwidth of procured ports in Gbps. """ return pulumi.get(self, "bandwidth_in_gbps") @property @pulumi.getter def circuits(self) -> pulumi.Output[Sequence['outputs.SubResourceResponse']]: """ Reference the ExpressRoute circuit(s) that are provisioned on this ExpressRoutePort resource. """ return pulumi.get(self, "circuits") @property @pulumi.getter def encapsulation(self) -> pulumi.Output[Optional[str]]: """ Encapsulation method on physical ports. """ return pulumi.get(self, "encapsulation") @property @pulumi.getter def etag(self) -> pulumi.Output[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="etherType") def ether_type(self) -> pulumi.Output[str]: """ Ether type of the physical port. """ return pulumi.get(self, "ether_type") @property @pulumi.getter def identity(self) -> pulumi.Output[Optional['outputs.ManagedServiceIdentityResponse']]: """ The identity of ExpressRoutePort, if configured. """ return pulumi.get(self, "identity") @property @pulumi.getter def links(self) -> pulumi.Output[Optional[Sequence['outputs.ExpressRouteLinkResponse']]]: """ The set of physical links of the ExpressRoutePort resource. """ return pulumi.get(self, "links") @property @pulumi.getter def location(self) -> pulumi.Output[Optional[str]]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter def mtu(self) -> pulumi.Output[str]: """ Maximum transmission unit of the physical port pair(s). """ return pulumi.get(self, "mtu") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="peeringLocation") def peering_location(self) -> pulumi.Output[Optional[str]]: """ The name of the peering location that the ExpressRoutePort is mapped to physically. """ return pulumi.get(self, "peering_location") @property @pulumi.getter(name="provisionedBandwidthInGbps") def provisioned_bandwidth_in_gbps(self) -> pulumi.Output[float]: """ Aggregate Gbps of associated circuit bandwidths. """ return pulumi.get(self, "provisioned_bandwidth_in_gbps") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ The provisioning state of the express route port resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="resourceGuid") def resource_guid(self) -> pulumi.Output[str]: """ The resource GUID property of the express route port resource. """ return pulumi.get(self, "resource_guid") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ Resource type. """ return pulumi.get(self, "type")
47.997835
3,108
0.670891
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__ = ['ExpressRoutePortArgs', 'ExpressRoutePort'] @pulumi.input_type class ExpressRoutePortArgs: def __init__(__self__, *, resource_group_name: pulumi.Input[str], bandwidth_in_gbps: Optional[pulumi.Input[int]] = None, encapsulation: Optional[pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']]] = None, express_route_port_name: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, identity: Optional[pulumi.Input['ManagedServiceIdentityArgs']] = None, links: Optional[pulumi.Input[Sequence[pulumi.Input['ExpressRouteLinkArgs']]]] = None, location: Optional[pulumi.Input[str]] = None, peering_location: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None): pulumi.set(__self__, "resource_group_name", resource_group_name) if bandwidth_in_gbps is not None: pulumi.set(__self__, "bandwidth_in_gbps", bandwidth_in_gbps) if encapsulation is not None: pulumi.set(__self__, "encapsulation", encapsulation) if express_route_port_name is not None: pulumi.set(__self__, "express_route_port_name", express_route_port_name) if id is not None: pulumi.set(__self__, "id", id) if identity is not None: pulumi.set(__self__, "identity", identity) if links is not None: pulumi.set(__self__, "links", links) if location is not None: pulumi.set(__self__, "location", location) if peering_location is not None: pulumi.set(__self__, "peering_location", peering_location) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="bandwidthInGbps") def bandwidth_in_gbps(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "bandwidth_in_gbps") @bandwidth_in_gbps.setter def bandwidth_in_gbps(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "bandwidth_in_gbps", value) @property @pulumi.getter def encapsulation(self) -> Optional[pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']]]: return pulumi.get(self, "encapsulation") @encapsulation.setter def encapsulation(self, value: Optional[pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']]]): pulumi.set(self, "encapsulation", value) @property @pulumi.getter(name="expressRoutePortName") def express_route_port_name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "express_route_port_name") @express_route_port_name.setter def express_route_port_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "express_route_port_name", value) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter def identity(self) -> Optional[pulumi.Input['ManagedServiceIdentityArgs']]: return pulumi.get(self, "identity") @identity.setter def identity(self, value: Optional[pulumi.Input['ManagedServiceIdentityArgs']]): pulumi.set(self, "identity", value) @property @pulumi.getter def links(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ExpressRouteLinkArgs']]]]: return pulumi.get(self, "links") @links.setter def links(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ExpressRouteLinkArgs']]]]): pulumi.set(self, "links", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "location") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "location", value) @property @pulumi.getter(name="peeringLocation") def peering_location(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "peering_location") @peering_location.setter def peering_location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "peering_location", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) class ExpressRoutePort(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, bandwidth_in_gbps: Optional[pulumi.Input[int]] = None, encapsulation: Optional[pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']]] = None, express_route_port_name: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, identity: Optional[pulumi.Input[pulumi.InputType['ManagedServiceIdentityArgs']]] = None, links: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ExpressRouteLinkArgs']]]]] = None, location: Optional[pulumi.Input[str]] = None, peering_location: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): ... @overload def __init__(__self__, resource_name: str, args: ExpressRoutePortArgs, opts: Optional[pulumi.ResourceOptions] = None): ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(ExpressRoutePortArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, bandwidth_in_gbps: Optional[pulumi.Input[int]] = None, encapsulation: Optional[pulumi.Input[Union[str, 'ExpressRoutePortsEncapsulation']]] = None, express_route_port_name: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, identity: Optional[pulumi.Input[pulumi.InputType['ManagedServiceIdentityArgs']]] = None, links: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ExpressRouteLinkArgs']]]]] = None, location: Optional[pulumi.Input[str]] = None, peering_location: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = ExpressRoutePortArgs.__new__(ExpressRoutePortArgs) __props__.__dict__["bandwidth_in_gbps"] = bandwidth_in_gbps __props__.__dict__["encapsulation"] = encapsulation __props__.__dict__["express_route_port_name"] = express_route_port_name __props__.__dict__["id"] = id __props__.__dict__["identity"] = identity __props__.__dict__["links"] = links __props__.__dict__["location"] = location __props__.__dict__["peering_location"] = peering_location if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["tags"] = tags __props__.__dict__["allocation_date"] = None __props__.__dict__["circuits"] = None __props__.__dict__["etag"] = None __props__.__dict__["ether_type"] = None __props__.__dict__["mtu"] = None __props__.__dict__["name"] = None __props__.__dict__["provisioned_bandwidth_in_gbps"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["resource_guid"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network/v20200501:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20180801:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20180801:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20181001:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20181001:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20181101:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20181101:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20181201:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20181201:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190201:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190201:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190401:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190401:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190601:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190601:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190701:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190701:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190801:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190801:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20190901:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20190901:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20191101:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20191101:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20191201:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20191201:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20200301:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20200301:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20200401:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20200401:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20200601:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20200601:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20200701:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20200701:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20200801:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20200801:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20201101:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20201101:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20210201:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20210201:ExpressRoutePort"), pulumi.Alias(type_="azure-native:network/v20210301:ExpressRoutePort"), pulumi.Alias(type_="azure-nextgen:network/v20210301:ExpressRoutePort")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(ExpressRoutePort, __self__).__init__( 'azure-native:network/v20200501:ExpressRoutePort', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'ExpressRoutePort': opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = ExpressRoutePortArgs.__new__(ExpressRoutePortArgs) __props__.__dict__["allocation_date"] = None __props__.__dict__["bandwidth_in_gbps"] = None __props__.__dict__["circuits"] = None __props__.__dict__["encapsulation"] = None __props__.__dict__["etag"] = None __props__.__dict__["ether_type"] = None __props__.__dict__["identity"] = None __props__.__dict__["links"] = None __props__.__dict__["location"] = None __props__.__dict__["mtu"] = None __props__.__dict__["name"] = None __props__.__dict__["peering_location"] = None __props__.__dict__["provisioned_bandwidth_in_gbps"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["resource_guid"] = None __props__.__dict__["tags"] = None __props__.__dict__["type"] = None return ExpressRoutePort(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="allocationDate") def allocation_date(self) -> pulumi.Output[str]: return pulumi.get(self, "allocation_date") @property @pulumi.getter(name="bandwidthInGbps") def bandwidth_in_gbps(self) -> pulumi.Output[Optional[int]]: return pulumi.get(self, "bandwidth_in_gbps") @property @pulumi.getter def circuits(self) -> pulumi.Output[Sequence['outputs.SubResourceResponse']]: return pulumi.get(self, "circuits") @property @pulumi.getter def encapsulation(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "encapsulation") @property @pulumi.getter def etag(self) -> pulumi.Output[str]: return pulumi.get(self, "etag") @property @pulumi.getter(name="etherType") def ether_type(self) -> pulumi.Output[str]: return pulumi.get(self, "ether_type") @property @pulumi.getter def identity(self) -> pulumi.Output[Optional['outputs.ManagedServiceIdentityResponse']]: return pulumi.get(self, "identity") @property @pulumi.getter def links(self) -> pulumi.Output[Optional[Sequence['outputs.ExpressRouteLinkResponse']]]: return pulumi.get(self, "links") @property @pulumi.getter def location(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "location") @property @pulumi.getter def mtu(self) -> pulumi.Output[str]: return pulumi.get(self, "mtu") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, "name") @property @pulumi.getter(name="peeringLocation") def peering_location(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "peering_location") @property @pulumi.getter(name="provisionedBandwidthInGbps") def provisioned_bandwidth_in_gbps(self) -> pulumi.Output[float]: return pulumi.get(self, "provisioned_bandwidth_in_gbps") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="resourceGuid") def resource_guid(self) -> pulumi.Output[str]: return pulumi.get(self, "resource_guid") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: return pulumi.get(self, "type")
true
true
1c442ab2c8f5c84fc82c2d5fdb56f5553c96b1cb
14,164
py
Python
reversion/revisions.py
baffolobill/django-reversion
e0e12ce00f91043ba9c828dc47cbe0e57d3cbc36
[ "BSD-3-Clause" ]
null
null
null
reversion/revisions.py
baffolobill/django-reversion
e0e12ce00f91043ba9c828dc47cbe0e57d3cbc36
[ "BSD-3-Clause" ]
null
null
null
reversion/revisions.py
baffolobill/django-reversion
e0e12ce00f91043ba9c828dc47cbe0e57d3cbc36
[ "BSD-3-Clause" ]
null
null
null
from collections import namedtuple, defaultdict from contextlib import contextmanager from functools import wraps from threading import local from django.apps import apps from django.core import serializers from django.core.exceptions import ObjectDoesNotExist from django.db import models, transaction, router from django.db.models.query import QuerySet from django.db.models.signals import post_save, m2m_changed from django.utils.encoding import force_str from django.utils import timezone from reversion.errors import RevisionManagementError, RegistrationError from reversion.signals import pre_revision_commit, post_revision_commit _VersionOptions = namedtuple("VersionOptions", ( "fields", "follow", "format", "for_concrete_model", "ignore_duplicates", "use_natural_foreign_keys", )) _StackFrame = namedtuple("StackFrame", ( "manage_manually", "user", "comment", "date_created", "db_versions", "meta", "extra_data", )) class _Local(local): def __init__(self): self.stack = () _local = _Local() def is_active(): return bool(_local.stack) def _current_frame(): if not is_active(): raise RevisionManagementError("There is no active revision for this thread") return _local.stack[-1] def _copy_db_versions(db_versions): return { db: versions.copy() for db, versions in db_versions.items() } def _push_frame(manage_manually, using): if is_active(): current_frame = _current_frame() db_versions = _copy_db_versions(current_frame.db_versions) db_versions.setdefault(using, {}) stack_frame = current_frame._replace( manage_manually=manage_manually, db_versions=db_versions, ) else: stack_frame = _StackFrame( manage_manually=manage_manually, user=None, comment="", date_created=timezone.now(), db_versions={using: {}}, meta=(), extra_data=None, ) _local.stack += (stack_frame,) def _update_frame(**kwargs): _local.stack = _local.stack[:-1] + (_current_frame()._replace(**kwargs),) def _pop_frame(): prev_frame = _current_frame() _local.stack = _local.stack[:-1] if is_active(): current_frame = _current_frame() db_versions = { db: prev_frame.db_versions[db] for db in current_frame.db_versions.keys() } _update_frame( user=prev_frame.user, comment=prev_frame.comment, date_created=prev_frame.date_created, db_versions=db_versions, meta=prev_frame.meta, extra_data=prev_frame.extra_data, ) def is_manage_manually(): return _current_frame().manage_manually def set_extra_data(extra_data): _update_frame(extra_data=extra_data) def get_extra_data(): return _current_frame().extra_data def set_user(user): _update_frame(user=user) def get_user(): return _current_frame().user def set_comment(comment): _update_frame(comment=comment) def get_comment(): return _current_frame().comment def set_date_created(date_created): _update_frame(date_created=date_created) def get_date_created(): return _current_frame().date_created def add_meta(model, **values): _update_frame(meta=_current_frame().meta + ((model, values),)) def _follow_relations(obj): version_options = _get_options(obj.__class__) for follow_name in version_options.follow: try: follow_obj = getattr(obj, follow_name) except ObjectDoesNotExist: continue if isinstance(follow_obj, models.Model): yield follow_obj elif isinstance(follow_obj, (models.Manager, QuerySet)): for follow_obj_instance in follow_obj.all(): yield follow_obj_instance elif follow_obj is not None: raise RegistrationError("{name}.{follow_name} should be a Model or QuerySet".format( name=obj.__class__.__name__, follow_name=follow_name, )) def _follow_relations_recursive(obj): def do_follow(obj): if obj not in relations: relations.add(obj) for related in _follow_relations(obj): do_follow(related) relations = set() do_follow(obj) return relations def _add_to_revision(obj, using, model_db, explicit): from reversion.models import Version # Exit early if the object is not fully-formed. if obj.pk is None: return version_options = _get_options(obj.__class__) content_type = _get_content_type(obj.__class__, using) object_id = force_str(obj.pk) version_key = (content_type, object_id) # If the obj is already in the revision, stop now. db_versions = _current_frame().db_versions versions = db_versions[using] if version_key in versions and not explicit: return # Get the version data. version = Version( content_type=content_type, object_id=object_id, db=model_db, format=version_options.format, serialized_data=serializers.serialize( version_options.format, (obj,), fields=version_options.fields, use_natural_foreign_keys=version_options.use_natural_foreign_keys, ), object_repr=force_str(obj), ) # If the version is a duplicate, stop now. if version_options.ignore_duplicates and explicit: previous_version = Version.objects.using(using).get_for_object(obj, model_db=model_db).first() if previous_version and previous_version._local_field_dict == version._local_field_dict: return # Store the version. db_versions = _copy_db_versions(db_versions) db_versions[using][version_key] = version _update_frame(db_versions=db_versions) # Follow relations. for follow_obj in _follow_relations(obj): _add_to_revision(follow_obj, using, model_db, False) def add_to_revision(obj, model_db=None): model_db = model_db or router.db_for_write(obj.__class__, instance=obj) for db in _current_frame().db_versions.keys(): _add_to_revision(obj, db, model_db, True) def _find_parent_version(version): from reversion.models import Version try: # return Version.objects.get_for_object(version.object)[0] return Version.objects\ .get_for_object_reference(version._model, version.object_id)\ .filter(reverted_at__isnull=True)[0] except IndexError: return None def _save_revision(versions, user=None, comment="", meta=(), date_created=None, using=None, extra_data=None): from reversion.models import Revision # Only save versions that exist in the database. # Use _base_manager so we don't have problems when _default_manager is overriden model_db_pks = defaultdict(lambda: defaultdict(set)) for version in versions: model_db_pks[version._model][version.db].add(version.object_id) model_db_existing_pks = { model: { db: frozenset(map( force_str, model._base_manager.using(db).filter(pk__in=pks).values_list("pk", flat=True), )) for db, pks in db_pks.items() } for model, db_pks in model_db_pks.items() } versions = [ version for version in versions if version.object_id in model_db_existing_pks[version._model][version.db] ] # Bail early if there are no objects to save. if not versions: return # Save a new revision. revision = Revision( date_created=date_created, user=user, comment=comment, extra_data=extra_data, ) # Send the pre_revision_commit signal. pre_revision_commit.send( sender=create_revision, revision=revision, versions=versions, ) # Save the revision. revision.save(using=using) # Save version models. for version in versions: version.parent = _find_parent_version(version) version.revision = revision version.save(using=using) # Save the meta information. for meta_model, meta_fields in meta: meta_model._base_manager.db_manager(using=using).create( revision=revision, **meta_fields ) # Send the post_revision_commit signal. post_revision_commit.send( sender=create_revision, revision=revision, versions=versions, ) @contextmanager def _dummy_context(): yield @contextmanager def _create_revision_context(manage_manually, using, atomic): context = transaction.atomic(using=using) if atomic else _dummy_context() with context: _push_frame(manage_manually, using) try: yield # Only save for a db if that's the last stack frame for that db. if not any(using in frame.db_versions for frame in _local.stack[:-1]): current_frame = _current_frame() _save_revision( versions=current_frame.db_versions[using].values(), user=current_frame.user, comment=current_frame.comment, meta=current_frame.meta, date_created=current_frame.date_created, using=using, extra_data=current_frame.extra_data, ) finally: _pop_frame() def create_revision(manage_manually=False, using=None, atomic=True): from reversion.models import Revision using = using or router.db_for_write(Revision) return _ContextWrapper(_create_revision_context, (manage_manually, using, atomic)) class _ContextWrapper(object): def __init__(self, func, args): self._func = func self._args = args self._context = func(*args) def __enter__(self): return self._context.__enter__() def __exit__(self, exc_type, exc_value, traceback): return self._context.__exit__(exc_type, exc_value, traceback) def __call__(self, func): @wraps(func) def do_revision_context(*args, **kwargs): with self._func(*self._args): return func(*args, **kwargs) return do_revision_context def _post_save_receiver(sender, instance, using, **kwargs): if is_registered(sender) and is_active() and not is_manage_manually(): add_to_revision(instance, model_db=using) def _m2m_changed_receiver(instance, using, action, model, reverse, **kwargs): if action.startswith("post_") and not reverse: if is_registered(instance) and is_active() and not is_manage_manually(): add_to_revision(instance, model_db=using) def _get_registration_key(model): return (model._meta.app_label, model._meta.model_name) _registered_models = {} def is_registered(model): return _get_registration_key(model) in _registered_models def get_registered_models(): return (apps.get_model(*key) for key in _registered_models.keys()) def _get_senders_and_signals(model): yield model, post_save, _post_save_receiver opts = model._meta.concrete_model._meta for field in opts.local_many_to_many: m2m_model = field.remote_field.through if isinstance(m2m_model, str): if "." not in m2m_model: m2m_model = "{app_label}.{m2m_model}".format( app_label=opts.app_label, m2m_model=m2m_model ) yield m2m_model, m2m_changed, _m2m_changed_receiver def register(model=None, fields=None, exclude=(), follow=(), format="json", for_concrete_model=True, ignore_duplicates=False, use_natural_foreign_keys=False): def register(model): # Prevent multiple registration. if is_registered(model): raise RegistrationError("{model} has already been registered with django-reversion".format( model=model, )) # Parse fields. opts = model._meta.concrete_model._meta version_options = _VersionOptions( fields=tuple( field_name for field_name in ([ field.name for field in opts.local_fields + opts.local_many_to_many ] if fields is None else fields) if field_name not in exclude ), follow=tuple(follow), format=format, for_concrete_model=for_concrete_model, ignore_duplicates=ignore_duplicates, use_natural_foreign_keys=use_natural_foreign_keys, ) # Register the model. _registered_models[_get_registration_key(model)] = version_options # Connect signals. for sender, signal, signal_receiver in _get_senders_and_signals(model): signal.connect(signal_receiver, sender=sender) # All done! return model # Return a class decorator if model is not given if model is None: return register # Register the model. return register(model) def _assert_registered(model): if not is_registered(model): raise RegistrationError("{model} has not been registered with django-reversion".format( model=model, )) def _get_options(model): _assert_registered(model) return _registered_models[_get_registration_key(model)] def unregister(model): _assert_registered(model) del _registered_models[_get_registration_key(model)] # Disconnect signals. for sender, signal, signal_receiver in _get_senders_and_signals(model): signal.disconnect(signal_receiver, sender=sender) def _get_content_type(model, using): from django.contrib.contenttypes.models import ContentType version_options = _get_options(model) return ContentType.objects.db_manager(using).get_for_model( model, for_concrete_model=version_options.for_concrete_model, )
30.724512
109
0.662666
from collections import namedtuple, defaultdict from contextlib import contextmanager from functools import wraps from threading import local from django.apps import apps from django.core import serializers from django.core.exceptions import ObjectDoesNotExist from django.db import models, transaction, router from django.db.models.query import QuerySet from django.db.models.signals import post_save, m2m_changed from django.utils.encoding import force_str from django.utils import timezone from reversion.errors import RevisionManagementError, RegistrationError from reversion.signals import pre_revision_commit, post_revision_commit _VersionOptions = namedtuple("VersionOptions", ( "fields", "follow", "format", "for_concrete_model", "ignore_duplicates", "use_natural_foreign_keys", )) _StackFrame = namedtuple("StackFrame", ( "manage_manually", "user", "comment", "date_created", "db_versions", "meta", "extra_data", )) class _Local(local): def __init__(self): self.stack = () _local = _Local() def is_active(): return bool(_local.stack) def _current_frame(): if not is_active(): raise RevisionManagementError("There is no active revision for this thread") return _local.stack[-1] def _copy_db_versions(db_versions): return { db: versions.copy() for db, versions in db_versions.items() } def _push_frame(manage_manually, using): if is_active(): current_frame = _current_frame() db_versions = _copy_db_versions(current_frame.db_versions) db_versions.setdefault(using, {}) stack_frame = current_frame._replace( manage_manually=manage_manually, db_versions=db_versions, ) else: stack_frame = _StackFrame( manage_manually=manage_manually, user=None, comment="", date_created=timezone.now(), db_versions={using: {}}, meta=(), extra_data=None, ) _local.stack += (stack_frame,) def _update_frame(**kwargs): _local.stack = _local.stack[:-1] + (_current_frame()._replace(**kwargs),) def _pop_frame(): prev_frame = _current_frame() _local.stack = _local.stack[:-1] if is_active(): current_frame = _current_frame() db_versions = { db: prev_frame.db_versions[db] for db in current_frame.db_versions.keys() } _update_frame( user=prev_frame.user, comment=prev_frame.comment, date_created=prev_frame.date_created, db_versions=db_versions, meta=prev_frame.meta, extra_data=prev_frame.extra_data, ) def is_manage_manually(): return _current_frame().manage_manually def set_extra_data(extra_data): _update_frame(extra_data=extra_data) def get_extra_data(): return _current_frame().extra_data def set_user(user): _update_frame(user=user) def get_user(): return _current_frame().user def set_comment(comment): _update_frame(comment=comment) def get_comment(): return _current_frame().comment def set_date_created(date_created): _update_frame(date_created=date_created) def get_date_created(): return _current_frame().date_created def add_meta(model, **values): _update_frame(meta=_current_frame().meta + ((model, values),)) def _follow_relations(obj): version_options = _get_options(obj.__class__) for follow_name in version_options.follow: try: follow_obj = getattr(obj, follow_name) except ObjectDoesNotExist: continue if isinstance(follow_obj, models.Model): yield follow_obj elif isinstance(follow_obj, (models.Manager, QuerySet)): for follow_obj_instance in follow_obj.all(): yield follow_obj_instance elif follow_obj is not None: raise RegistrationError("{name}.{follow_name} should be a Model or QuerySet".format( name=obj.__class__.__name__, follow_name=follow_name, )) def _follow_relations_recursive(obj): def do_follow(obj): if obj not in relations: relations.add(obj) for related in _follow_relations(obj): do_follow(related) relations = set() do_follow(obj) return relations def _add_to_revision(obj, using, model_db, explicit): from reversion.models import Version if obj.pk is None: return version_options = _get_options(obj.__class__) content_type = _get_content_type(obj.__class__, using) object_id = force_str(obj.pk) version_key = (content_type, object_id) db_versions = _current_frame().db_versions versions = db_versions[using] if version_key in versions and not explicit: return version = Version( content_type=content_type, object_id=object_id, db=model_db, format=version_options.format, serialized_data=serializers.serialize( version_options.format, (obj,), fields=version_options.fields, use_natural_foreign_keys=version_options.use_natural_foreign_keys, ), object_repr=force_str(obj), ) if version_options.ignore_duplicates and explicit: previous_version = Version.objects.using(using).get_for_object(obj, model_db=model_db).first() if previous_version and previous_version._local_field_dict == version._local_field_dict: return db_versions = _copy_db_versions(db_versions) db_versions[using][version_key] = version _update_frame(db_versions=db_versions) for follow_obj in _follow_relations(obj): _add_to_revision(follow_obj, using, model_db, False) def add_to_revision(obj, model_db=None): model_db = model_db or router.db_for_write(obj.__class__, instance=obj) for db in _current_frame().db_versions.keys(): _add_to_revision(obj, db, model_db, True) def _find_parent_version(version): from reversion.models import Version try: return Version.objects\ .get_for_object_reference(version._model, version.object_id)\ .filter(reverted_at__isnull=True)[0] except IndexError: return None def _save_revision(versions, user=None, comment="", meta=(), date_created=None, using=None, extra_data=None): from reversion.models import Revision model_db_pks = defaultdict(lambda: defaultdict(set)) for version in versions: model_db_pks[version._model][version.db].add(version.object_id) model_db_existing_pks = { model: { db: frozenset(map( force_str, model._base_manager.using(db).filter(pk__in=pks).values_list("pk", flat=True), )) for db, pks in db_pks.items() } for model, db_pks in model_db_pks.items() } versions = [ version for version in versions if version.object_id in model_db_existing_pks[version._model][version.db] ] # Bail early if there are no objects to save. if not versions: return # Save a new revision. revision = Revision( date_created=date_created, user=user, comment=comment, extra_data=extra_data, ) # Send the pre_revision_commit signal. pre_revision_commit.send( sender=create_revision, revision=revision, versions=versions, ) # Save the revision. revision.save(using=using) # Save version models. for version in versions: version.parent = _find_parent_version(version) version.revision = revision version.save(using=using) # Save the meta information. for meta_model, meta_fields in meta: meta_model._base_manager.db_manager(using=using).create( revision=revision, **meta_fields ) # Send the post_revision_commit signal. post_revision_commit.send( sender=create_revision, revision=revision, versions=versions, ) @contextmanager def _dummy_context(): yield @contextmanager def _create_revision_context(manage_manually, using, atomic): context = transaction.atomic(using=using) if atomic else _dummy_context() with context: _push_frame(manage_manually, using) try: yield # Only save for a db if that's the last stack frame for that db. if not any(using in frame.db_versions for frame in _local.stack[:-1]): current_frame = _current_frame() _save_revision( versions=current_frame.db_versions[using].values(), user=current_frame.user, comment=current_frame.comment, meta=current_frame.meta, date_created=current_frame.date_created, using=using, extra_data=current_frame.extra_data, ) finally: _pop_frame() def create_revision(manage_manually=False, using=None, atomic=True): from reversion.models import Revision using = using or router.db_for_write(Revision) return _ContextWrapper(_create_revision_context, (manage_manually, using, atomic)) class _ContextWrapper(object): def __init__(self, func, args): self._func = func self._args = args self._context = func(*args) def __enter__(self): return self._context.__enter__() def __exit__(self, exc_type, exc_value, traceback): return self._context.__exit__(exc_type, exc_value, traceback) def __call__(self, func): @wraps(func) def do_revision_context(*args, **kwargs): with self._func(*self._args): return func(*args, **kwargs) return do_revision_context def _post_save_receiver(sender, instance, using, **kwargs): if is_registered(sender) and is_active() and not is_manage_manually(): add_to_revision(instance, model_db=using) def _m2m_changed_receiver(instance, using, action, model, reverse, **kwargs): if action.startswith("post_") and not reverse: if is_registered(instance) and is_active() and not is_manage_manually(): add_to_revision(instance, model_db=using) def _get_registration_key(model): return (model._meta.app_label, model._meta.model_name) _registered_models = {} def is_registered(model): return _get_registration_key(model) in _registered_models def get_registered_models(): return (apps.get_model(*key) for key in _registered_models.keys()) def _get_senders_and_signals(model): yield model, post_save, _post_save_receiver opts = model._meta.concrete_model._meta for field in opts.local_many_to_many: m2m_model = field.remote_field.through if isinstance(m2m_model, str): if "." not in m2m_model: m2m_model = "{app_label}.{m2m_model}".format( app_label=opts.app_label, m2m_model=m2m_model ) yield m2m_model, m2m_changed, _m2m_changed_receiver def register(model=None, fields=None, exclude=(), follow=(), format="json", for_concrete_model=True, ignore_duplicates=False, use_natural_foreign_keys=False): def register(model): if is_registered(model): raise RegistrationError("{model} has already been registered with django-reversion".format( model=model, )) opts = model._meta.concrete_model._meta version_options = _VersionOptions( fields=tuple( field_name for field_name in ([ field.name for field in opts.local_fields + opts.local_many_to_many ] if fields is None else fields) if field_name not in exclude ), follow=tuple(follow), format=format, for_concrete_model=for_concrete_model, ignore_duplicates=ignore_duplicates, use_natural_foreign_keys=use_natural_foreign_keys, ) _registered_models[_get_registration_key(model)] = version_options for sender, signal, signal_receiver in _get_senders_and_signals(model): signal.connect(signal_receiver, sender=sender) return model if model is None: return register return register(model) def _assert_registered(model): if not is_registered(model): raise RegistrationError("{model} has not been registered with django-reversion".format( model=model, )) def _get_options(model): _assert_registered(model) return _registered_models[_get_registration_key(model)] def unregister(model): _assert_registered(model) del _registered_models[_get_registration_key(model)] for sender, signal, signal_receiver in _get_senders_and_signals(model): signal.disconnect(signal_receiver, sender=sender) def _get_content_type(model, using): from django.contrib.contenttypes.models import ContentType version_options = _get_options(model) return ContentType.objects.db_manager(using).get_for_model( model, for_concrete_model=version_options.for_concrete_model, )
true
true
1c442c4ca43be27ff4775ef2715d2c6c62226955
3,211
py
Python
rfxcom/protocol/lighting2.py
d0ugal-archive/python-rfxcom
2eb87f85e5f5a04d00f32f25e0f010edfefbde0d
[ "BSD-3-Clause" ]
3
2015-07-16T13:33:13.000Z
2017-09-17T13:11:42.000Z
rfxcom/protocol/lighting2.py
d0ugal/python-rfxcom
2eb87f85e5f5a04d00f32f25e0f010edfefbde0d
[ "BSD-3-Clause" ]
6
2015-07-20T21:50:36.000Z
2017-06-05T06:06:25.000Z
rfxcom/protocol/lighting2.py
d0ugal-archive/python-rfxcom
2eb87f85e5f5a04d00f32f25e0f010edfefbde0d
[ "BSD-3-Clause" ]
6
2015-07-21T07:47:25.000Z
2017-03-03T05:11:03.000Z
""" Lighting 5 ========== """ from rfxcom.protocol.base import BasePacketHandler from rfxcom.protocol.rfxpacketutils import RfxPacketUtils SUB_TYPE_COMMANDS = { 0x00: { 0x00: 'Off', 0x01: 'On', 0x02: 'Set level', 0x03: 'Group Off', 0x04: 'Group On', 0x05: 'Set Group Level', }, 0x01: { 0x00: "Off", 0x01: "On", 0x02: "Learn", }, 0x02: { 0x00: "Off", 0x01: "On", 0x02: "Group Off", 0x03: "Group On", } } DIM_LEVEL_TO_PERCENT = { 0x00: 0, 0x01: 6, 0x02: 12, 0x03: 18, 0x04: 24, 0x05: 30, 0x06: 36, 0x07: 42, 0x08: 48, 0x09: 54, 0x0A: 60, 0x0B: 66, 0x0C: 72, 0x0D: 78, 0x0E: 84, 0x0F: 100 } class Lighting2(BasePacketHandler): """The Lighting2 protocol is a 12 byte packet used by a number of lighting systems. For example Lightwave devices use this protocol. ==== ==== Byte Meaning ==== ==== 0 Packet Length, 0x0C (excludes this byte) 1 Packet Type, 0x11 2 Sub Type 3 Sequence Number 4 ID 1 5 ID 2 6 ID 3 7 ID 4 8 Unit Code 9 Command 10 Dim Level 11 RSSI and Filler ==== ==== """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.PACKET_TYPES = { 0x11: "Lighting2 sensors" } self.PACKET_SUBTYPES = { 0x00: 'AC', 0x01: 'HomeEasy EU', 0x02: 'Anslut' } def parse(self, data): """Parse a 12 bytes packet in the Lighting2 format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x111F342", 'packet_length': 10, 'packet_type': 17, 'packet_type_name': 'Humidity sensors', 'sequence_number': 19, 'packet_subtype': 0, 'packet_subtype_name': "AC", 'unit_code': 10, 'command': 1, 'command_text': "Off", 'level': 7, 'signal_level': 9, } :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict """ self.validate_packet(data) results = self.parse_header_part(data) sub_type = results['packet_subtype'] id_ = self.dump_hex(data[4:8]) unit_code = data[8] command = data[9] command_text = SUB_TYPE_COMMANDS.get(sub_type, {}).get(command) dim_level = DIM_LEVEL_TO_PERCENT.get(data[10], '--??--') sensor_specific = { 'id': id_, 'unit_code': unit_code, 'command': command, 'command_text': command_text, 'dim_level': dim_level } results.update(RfxPacketUtils.parse_signal_upper(data[11])) results.update(sensor_specific) return results
22.612676
78
0.50109
from rfxcom.protocol.base import BasePacketHandler from rfxcom.protocol.rfxpacketutils import RfxPacketUtils SUB_TYPE_COMMANDS = { 0x00: { 0x00: 'Off', 0x01: 'On', 0x02: 'Set level', 0x03: 'Group Off', 0x04: 'Group On', 0x05: 'Set Group Level', }, 0x01: { 0x00: "Off", 0x01: "On", 0x02: "Learn", }, 0x02: { 0x00: "Off", 0x01: "On", 0x02: "Group Off", 0x03: "Group On", } } DIM_LEVEL_TO_PERCENT = { 0x00: 0, 0x01: 6, 0x02: 12, 0x03: 18, 0x04: 24, 0x05: 30, 0x06: 36, 0x07: 42, 0x08: 48, 0x09: 54, 0x0A: 60, 0x0B: 66, 0x0C: 72, 0x0D: 78, 0x0E: 84, 0x0F: 100 } class Lighting2(BasePacketHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.PACKET_TYPES = { 0x11: "Lighting2 sensors" } self.PACKET_SUBTYPES = { 0x00: 'AC', 0x01: 'HomeEasy EU', 0x02: 'Anslut' } def parse(self, data): self.validate_packet(data) results = self.parse_header_part(data) sub_type = results['packet_subtype'] id_ = self.dump_hex(data[4:8]) unit_code = data[8] command = data[9] command_text = SUB_TYPE_COMMANDS.get(sub_type, {}).get(command) dim_level = DIM_LEVEL_TO_PERCENT.get(data[10], '--??--') sensor_specific = { 'id': id_, 'unit_code': unit_code, 'command': command, 'command_text': command_text, 'dim_level': dim_level } results.update(RfxPacketUtils.parse_signal_upper(data[11])) results.update(sensor_specific) return results
true
true
1c442c763412ef5363e2973cbb581f3531ffb93c
32,879
py
Python
mmdet/datasets/pipelines/transforms.py
ktw361/Local-Mid-Propagation
0a99e82cccf8c35bc5f6989af2702203def4c7a4
[ "Apache-2.0" ]
10
2020-08-13T17:51:20.000Z
2021-05-23T08:31:50.000Z
mmdet/datasets/pipelines/transforms.py
ktw361/Local-Mid-Propagation
0a99e82cccf8c35bc5f6989af2702203def4c7a4
[ "Apache-2.0" ]
null
null
null
mmdet/datasets/pipelines/transforms.py
ktw361/Local-Mid-Propagation
0a99e82cccf8c35bc5f6989af2702203def4c7a4
[ "Apache-2.0" ]
2
2020-09-07T08:33:43.000Z
2020-12-22T12:28:26.000Z
import inspect import albumentations import mmcv import numpy as np from albumentations import Compose from imagecorruptions import corrupt from numpy import random from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps from ..registry import PIPELINES @PIPELINES.register_module class Resize(object): """Resize images & bbox & mask. This transform resizes the input image to some scale. Bboxes and masks are then resized with the same scale factor. If the input dict contains the key "scale", then the scale in the input dict is used, otherwise the specified scale in the init method is used. `img_scale` can either be a tuple (single-scale) or a list of tuple (multi-scale). There are 3 multiscale modes: - `ratio_range` is not None: randomly sample a ratio from the ratio range and multiply it with the image scale. - `ratio_range` is None and `multiscale_mode` == "range": randomly sample a scale from the a range. - `ratio_range` is None and `multiscale_mode` == "value": randomly sample a scale from multiple scales. Args: img_scale (tuple or list[tuple]): Images scales for resizing. multiscale_mode (str): Either "range" or "value". ratio_range (tuple[float]): (min_ratio, max_ratio) keep_ratio (bool): Whether to keep the aspect ratio when resizing the image. """ def __init__(self, img_scale=None, multiscale_mode='range', ratio_range=None, keep_ratio=True): if img_scale is None: self.img_scale = None else: if isinstance(img_scale, list): self.img_scale = img_scale else: self.img_scale = [img_scale] assert mmcv.is_list_of(self.img_scale, tuple) if ratio_range is not None: # mode 1: given a scale and a range of image ratio assert len(self.img_scale) == 1 else: # mode 2: given multiple scales or a range of scales assert multiscale_mode in ['value', 'range'] self.multiscale_mode = multiscale_mode self.ratio_range = ratio_range self.keep_ratio = keep_ratio @staticmethod def random_select(img_scales): assert mmcv.is_list_of(img_scales, tuple) scale_idx = np.random.randint(len(img_scales)) img_scale = img_scales[scale_idx] return img_scale, scale_idx @staticmethod def random_sample(img_scales): assert mmcv.is_list_of(img_scales, tuple) and len(img_scales) == 2 img_scale_long = [max(s) for s in img_scales] img_scale_short = [min(s) for s in img_scales] long_edge = np.random.randint( min(img_scale_long), max(img_scale_long) + 1) short_edge = np.random.randint( min(img_scale_short), max(img_scale_short) + 1) img_scale = (long_edge, short_edge) return img_scale, None @staticmethod def random_sample_ratio(img_scale, ratio_range): assert isinstance(img_scale, tuple) and len(img_scale) == 2 min_ratio, max_ratio = ratio_range assert min_ratio <= max_ratio ratio = np.random.random_sample() * (max_ratio - min_ratio) + min_ratio scale = int(img_scale[0] * ratio), int(img_scale[1] * ratio) return scale, None def _random_scale(self, results): if self.ratio_range is not None: scale, scale_idx = self.random_sample_ratio( self.img_scale[0], self.ratio_range) elif len(self.img_scale) == 1: scale, scale_idx = self.img_scale[0], 0 elif self.multiscale_mode == 'range': scale, scale_idx = self.random_sample(self.img_scale) elif self.multiscale_mode == 'value': scale, scale_idx = self.random_select(self.img_scale) else: raise NotImplementedError results['scale'] = scale results['scale_idx'] = scale_idx def _resize_img(self, results): if self.keep_ratio: img, scale_factor = mmcv.imrescale( results['img'], results['scale'], return_scale=True) else: img, w_scale, h_scale = mmcv.imresize( results['img'], results['scale'], return_scale=True) scale_factor = np.array([w_scale, h_scale, w_scale, h_scale], dtype=np.float32) results['img'] = img results['img_shape'] = img.shape results['pad_shape'] = img.shape # in case that there is no padding results['scale_factor'] = scale_factor results['keep_ratio'] = self.keep_ratio def _resize_bboxes(self, results): img_shape = results['img_shape'] for key in results.get('bbox_fields', []): bboxes = results[key] * results['scale_factor'] bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1] - 1) bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0] - 1) results[key] = bboxes def _resize_masks(self, results): for key in results.get('mask_fields', []): if results[key] is None: continue if self.keep_ratio: masks = [ mmcv.imrescale( mask, results['scale_factor'], interpolation='nearest') for mask in results[key] ] else: mask_size = (results['img_shape'][1], results['img_shape'][0]) masks = [ mmcv.imresize(mask, mask_size, interpolation='nearest') for mask in results[key] ] results[key] = masks def __call__(self, results): if 'scale' not in results: self._random_scale(results) self._resize_img(results) self._resize_bboxes(results) self._resize_masks(results) return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += ('(img_scale={}, multiscale_mode={}, ratio_range={}, ' 'keep_ratio={})').format(self.img_scale, self.multiscale_mode, self.ratio_range, self.keep_ratio) return repr_str @PIPELINES.register_module class RandomFlip(object): """Flip the image & bbox & mask. If the input dict contains the key "flip", then the flag will be used, otherwise it will be randomly decided by a ratio specified in the init method. Args: flip_ratio (float, optional): The flipping probability. """ def __init__(self, flip_ratio=None): self.flip_ratio = flip_ratio if flip_ratio is not None: assert flip_ratio >= 0 and flip_ratio <= 1 def bbox_flip(self, bboxes, img_shape): """Flip bboxes horizontally. Args: bboxes(ndarray): shape (..., 4*k) img_shape(tuple): (height, width) """ assert bboxes.shape[-1] % 4 == 0 w = img_shape[1] flipped = bboxes.copy() flipped[..., 0::4] = w - bboxes[..., 2::4] - 1 flipped[..., 2::4] = w - bboxes[..., 0::4] - 1 return flipped def __call__(self, results): if 'flip' not in results: flip = True if np.random.rand() < self.flip_ratio else False results['flip'] = flip if results['flip']: # flip image results['img'] = mmcv.imflip(results['img']) # flip bboxes for key in results.get('bbox_fields', []): results[key] = self.bbox_flip(results[key], results['img_shape']) # flip masks for key in results.get('mask_fields', []): results[key] = [mask[:, ::-1] for mask in results[key]] return results def __repr__(self): return self.__class__.__name__ + '(flip_ratio={})'.format( self.flip_ratio) @PIPELINES.register_module class Pad(object): """Pad the image & mask. There are two padding modes: (1) pad to a fixed size and (2) pad to the minimum size that is divisible by some number. Args: size (tuple, optional): Fixed padding size. size_divisor (int, optional): The divisor of padded size. pad_val (float, optional): Padding value, 0 by default. """ def __init__(self, size=None, size_divisor=None, pad_val=0): self.size = size self.size_divisor = size_divisor self.pad_val = pad_val # only one of size and size_divisor should be valid assert size is not None or size_divisor is not None assert size is None or size_divisor is None def _pad_img(self, results): if self.size is not None: padded_img = mmcv.impad(results['img'], self.size) elif self.size_divisor is not None: padded_img = mmcv.impad_to_multiple( results['img'], self.size_divisor, pad_val=self.pad_val) results['img'] = padded_img results['pad_shape'] = padded_img.shape results['pad_fixed_size'] = self.size results['pad_size_divisor'] = self.size_divisor def _pad_masks(self, results): pad_shape = results['pad_shape'][:2] for key in results.get('mask_fields', []): padded_masks = [ mmcv.impad(mask, pad_shape, pad_val=self.pad_val) for mask in results[key] ] results[key] = np.stack(padded_masks, axis=0) def __call__(self, results): self._pad_img(results) self._pad_masks(results) return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(size={}, size_divisor={}, pad_val={})'.format( self.size, self.size_divisor, self.pad_val) return repr_str @PIPELINES.register_module class Normalize(object): """Normalize the image. Args: mean (sequence): Mean values of 3 channels. std (sequence): Std values of 3 channels. to_rgb (bool): Whether to convert the image from BGR to RGB, default is true. """ def __init__(self, mean, std, to_rgb=True): self.mean = np.array(mean, dtype=np.float32) self.std = np.array(std, dtype=np.float32) self.to_rgb = to_rgb def __call__(self, results): results['img'] = mmcv.imnormalize(results['img'], self.mean, self.std, self.to_rgb) results['img_norm_cfg'] = dict( mean=self.mean, std=self.std, to_rgb=self.to_rgb) return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(mean={}, std={}, to_rgb={})'.format( self.mean, self.std, self.to_rgb) return repr_str @PIPELINES.register_module class RandomCrop(object): """Random crop the image & bboxes & masks. Args: crop_size (tuple): Expected size after cropping, (h, w). """ def __init__(self, crop_size): self.crop_size = crop_size def __call__(self, results): img = results['img'] margin_h = max(img.shape[0] - self.crop_size[0], 0) margin_w = max(img.shape[1] - self.crop_size[1], 0) offset_h = np.random.randint(0, margin_h + 1) offset_w = np.random.randint(0, margin_w + 1) crop_y1, crop_y2 = offset_h, offset_h + self.crop_size[0] crop_x1, crop_x2 = offset_w, offset_w + self.crop_size[1] # crop the image img = img[crop_y1:crop_y2, crop_x1:crop_x2, :] img_shape = img.shape results['img'] = img results['img_shape'] = img_shape # crop bboxes accordingly and clip to the image boundary for key in results.get('bbox_fields', []): bbox_offset = np.array([offset_w, offset_h, offset_w, offset_h], dtype=np.float32) bboxes = results[key] - bbox_offset bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1] - 1) bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0] - 1) results[key] = bboxes # filter out the gt bboxes that are completely cropped if 'gt_bboxes' in results: gt_bboxes = results['gt_bboxes'] valid_inds = (gt_bboxes[:, 2] > gt_bboxes[:, 0]) & ( gt_bboxes[:, 3] > gt_bboxes[:, 1]) # if no gt bbox remains after cropping, just skip this image if not np.any(valid_inds): return None results['gt_bboxes'] = gt_bboxes[valid_inds, :] if 'gt_labels' in results: results['gt_labels'] = results['gt_labels'][valid_inds] # filter and crop the masks if 'gt_masks' in results: valid_gt_masks = [] for i in np.where(valid_inds)[0]: gt_mask = results['gt_masks'][i][crop_y1:crop_y2, crop_x1: crop_x2] valid_gt_masks.append(gt_mask) results['gt_masks'] = valid_gt_masks return results def __repr__(self): return self.__class__.__name__ + '(crop_size={})'.format( self.crop_size) @PIPELINES.register_module class RandomRatioCrop(object): """Random crop the image & bboxes by a ratio. Args: min_crop_ratio (tuple): Expected ratio after cropping, (h, w). max_crop_ratio (tuple of float). """ def __init__(self, min_crop_ratio, max_crop_ratio): self.min_crop_ratio = min_crop_ratio self.max_crop_ratio = max_crop_ratio def __call__(self, results): img = results['img'] crop_ratio = (random.uniform(self.min_crop_ratio[0], self.max_crop_ratio[0]), random.uniform(self.min_crop_ratio[1], self.max_crop_ratio[1])) crop_size = (int(crop_ratio[0] * img.shape[0]), int(crop_ratio[1] * img.shape[1])) margin_h = max(img.shape[0] - crop_size[0], 0) margin_w = max(img.shape[1] - crop_size[1], 0) offset_h = np.random.randint(0, margin_h + 1) offset_w = np.random.randint(0, margin_w + 1) crop_y1, crop_y2 = offset_h, offset_h + crop_size[0] crop_x1, crop_x2 = offset_w, offset_w + crop_size[1] # crop the image img = img[crop_y1:crop_y2, crop_x1:crop_x2, :] img_shape = img.shape results['img'] = img results['img_shape'] = img_shape # crop bboxes accordingly and clip to the image boundary for key in results.get('bbox_fields', []): bbox_offset = np.array([offset_w, offset_h, offset_w, offset_h], dtype=np.float32) bboxes = results[key] - bbox_offset bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1] - 1) bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0] - 1) results[key] = bboxes # filter out the gt bboxes that are completely cropped if 'gt_bboxes' in results: gt_bboxes = results['gt_bboxes'] valid_inds = (gt_bboxes[:, 2] > gt_bboxes[:, 0]) & ( gt_bboxes[:, 3] > gt_bboxes[:, 1]) # if no gt bbox remains after cropping, just skip this image if not np.any(valid_inds): return None results['gt_bboxes'] = gt_bboxes[valid_inds, :] if 'gt_labels' in results: results['gt_labels'] = results['gt_labels'][valid_inds] # filter and crop the masks if 'gt_masks' in results: valid_gt_masks = [] for i in valid_inds: gt_mask = results['gt_masks'][i][crop_y1:crop_y2, crop_x1: crop_x2] valid_gt_masks.append(gt_mask) results['gt_masks'] = valid_gt_masks return results def __repr__(self): return self.__class__.__name__ + \ f'(min_crop_ratio={self.min_crop_ratio}, max_crop_ratio={self.max_crop_ratio})' @PIPELINES.register_module class SegResizeFlipPadRescale(object): """A sequential transforms to semantic segmentation maps. The same pipeline as input images is applied to the semantic segmentation map, and finally rescale it by some scale factor. The transforms include: 1. resize 2. flip 3. pad 4. rescale (so that the final size can be different from the image size) Args: scale_factor (float): The scale factor of the final output. """ def __init__(self, scale_factor=1): self.scale_factor = scale_factor def __call__(self, results): if results['keep_ratio']: gt_seg = mmcv.imrescale( results['gt_semantic_seg'], results['scale'], interpolation='nearest') else: gt_seg = mmcv.imresize( results['gt_semantic_seg'], results['scale'], interpolation='nearest') if results['flip']: gt_seg = mmcv.imflip(gt_seg) if gt_seg.shape != results['pad_shape']: gt_seg = mmcv.impad(gt_seg, results['pad_shape'][:2]) if self.scale_factor != 1: gt_seg = mmcv.imrescale( gt_seg, self.scale_factor, interpolation='nearest') results['gt_semantic_seg'] = gt_seg return results def __repr__(self): return self.__class__.__name__ + '(scale_factor={})'.format( self.scale_factor) @PIPELINES.register_module class PhotoMetricDistortion(object): """Apply photometric distortion to image sequentially, every transformation is applied with a probability of 0.5. The position of random contrast is in second or second to last. 1. random brightness 2. random contrast (mode 0) 3. convert color from BGR to HSV 4. random saturation 5. random hue 6. convert color from HSV to BGR 7. random contrast (mode 1) 8. randomly swap channels Args: brightness_delta (int): delta of brightness. contrast_range (tuple): range of contrast. saturation_range (tuple): range of saturation. hue_delta (int): delta of hue. """ def __init__(self, brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18): self.brightness_delta = brightness_delta self.contrast_lower, self.contrast_upper = contrast_range self.saturation_lower, self.saturation_upper = saturation_range self.hue_delta = hue_delta def __call__(self, results): img = results['img'] # random brightness if random.randint(2): delta = random.uniform(-self.brightness_delta, self.brightness_delta) img += delta # mode == 0 --> do random contrast first # mode == 1 --> do random contrast last mode = random.randint(2) if mode == 1: if random.randint(2): alpha = random.uniform(self.contrast_lower, self.contrast_upper) img *= alpha # convert color from BGR to HSV img = mmcv.bgr2hsv(img) # random saturation if random.randint(2): img[..., 1] *= random.uniform(self.saturation_lower, self.saturation_upper) # random hue if random.randint(2): img[..., 0] += random.uniform(-self.hue_delta, self.hue_delta) img[..., 0][img[..., 0] > 360] -= 360 img[..., 0][img[..., 0] < 0] += 360 # convert color from HSV to BGR img = mmcv.hsv2bgr(img) # random contrast if mode == 0: if random.randint(2): alpha = random.uniform(self.contrast_lower, self.contrast_upper) img *= alpha # randomly swap channels if random.randint(2): img = img[..., random.permutation(3)] results['img'] = img return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += ('(brightness_delta={}, contrast_range={}, ' 'saturation_range={}, hue_delta={})').format( self.brightness_delta, self.contrast_range, self.saturation_range, self.hue_delta) return repr_str @PIPELINES.register_module class Expand(object): """Random expand the image & bboxes. Randomly place the original image on a canvas of 'ratio' x original image size filled with mean values. The ratio is in the range of ratio_range. Args: mean (tuple): mean value of dataset. to_rgb (bool): if need to convert the order of mean to align with RGB. ratio_range (tuple): range of expand ratio. """ def __init__(self, mean=(0, 0, 0), to_rgb=True, ratio_range=(1, 4), seg_ignore_label=None): self.to_rgb = to_rgb self.ratio_range = ratio_range if to_rgb: self.mean = mean[::-1] else: self.mean = mean self.min_ratio, self.max_ratio = ratio_range self.seg_ignore_label = seg_ignore_label def __call__(self, results): if random.randint(2): return results img, boxes = [results[k] for k in ('img', 'gt_bboxes')] h, w, c = img.shape ratio = random.uniform(self.min_ratio, self.max_ratio) expand_img = np.full((int(h * ratio), int(w * ratio), c), self.mean).astype(img.dtype) left = int(random.uniform(0, w * ratio - w)) top = int(random.uniform(0, h * ratio - h)) expand_img[top:top + h, left:left + w] = img boxes = boxes + np.tile((left, top), 2).astype(boxes.dtype) results['img'] = expand_img results['gt_bboxes'] = boxes if 'gt_masks' in results: expand_gt_masks = [] for mask in results['gt_masks']: expand_mask = np.full((int(h * ratio), int(w * ratio)), 0).astype(mask.dtype) expand_mask[top:top + h, left:left + w] = mask expand_gt_masks.append(expand_mask) results['gt_masks'] = expand_gt_masks # not tested if 'gt_semantic_seg' in results: assert self.seg_ignore_label is not None gt_seg = results['gt_semantic_seg'] expand_gt_seg = np.full((int(h * ratio), int(w * ratio)), self.seg_ignore_label).astype(gt_seg.dtype) expand_gt_seg[top:top + h, left:left + w] = gt_seg results['gt_semantic_seg'] = expand_gt_seg return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(mean={}, to_rgb={}, ratio_range={}, ' \ 'seg_ignore_label={})'.format( self.mean, self.to_rgb, self.ratio_range, self.seg_ignore_label) return repr_str @PIPELINES.register_module class MinIoURandomCrop(object): """Random crop the image & bboxes, the cropped patches have minimum IoU requirement with original image & bboxes, the IoU threshold is randomly selected from min_ious. Args: min_ious (tuple): minimum IoU threshold crop_size (tuple): Expected size after cropping, (h, w). """ def __init__(self, min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3): # 1: return ori img self.sample_mode = (1, *min_ious, 0) self.min_crop_size = min_crop_size def __call__(self, results): img, boxes, labels = [ results[k] for k in ('img', 'gt_bboxes', 'gt_labels') ] h, w, c = img.shape while True: mode = random.choice(self.sample_mode) # Force return origin for no annotation. if len(boxes) == 0: mode = 1 if mode == 1: return results min_iou = mode for i in range(50): new_w = random.uniform(self.min_crop_size * w, w) new_h = random.uniform(self.min_crop_size * h, h) # h / w in [0.5, 2] if new_h / new_w < 0.5 or new_h / new_w > 2: continue left = random.uniform(w - new_w) top = random.uniform(h - new_h) patch = np.array( (int(left), int(top), int(left + new_w), int(top + new_h))) overlaps = bbox_overlaps( patch.reshape(-1, 4), boxes.reshape(-1, 4)).reshape(-1) if overlaps.min() < min_iou: continue # center of boxes should inside the crop img center = (boxes[:, :2] + boxes[:, 2:]) / 2 mask = ((center[:, 0] > patch[0]) * (center[:, 1] > patch[1]) * (center[:, 0] < patch[2]) * (center[:, 1] < patch[3])) if not mask.any(): continue boxes = boxes[mask] labels = labels[mask] # adjust boxes img = img[patch[1]:patch[3], patch[0]:patch[2]] boxes[:, 2:] = boxes[:, 2:].clip(max=patch[2:]) boxes[:, :2] = boxes[:, :2].clip(min=patch[:2]) boxes -= np.tile(patch[:2], 2) results['img'] = img results['gt_bboxes'] = boxes results['gt_labels'] = labels if 'gt_masks' in results: valid_masks = [ results['gt_masks'][i] for i in range(len(mask)) if mask[i] ] results['gt_masks'] = [ gt_mask[patch[1]:patch[3], patch[0]:patch[2]] for gt_mask in valid_masks ] # not tested if 'gt_semantic_seg' in results: results['gt_semantic_seg'] = results['gt_semantic_seg'][ patch[1]:patch[3], patch[0]:patch[2]] return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(min_ious={}, min_crop_size={})'.format( self.min_ious, self.min_crop_size) return repr_str @PIPELINES.register_module class Corrupt(object): def __init__(self, corruption, severity=1): self.corruption = corruption self.severity = severity def __call__(self, results): results['img'] = corrupt( results['img'].astype(np.uint8), corruption_name=self.corruption, severity=self.severity) return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(corruption={}, severity={})'.format( self.corruption, self.severity) return repr_str @PIPELINES.register_module class Albu(object): def __init__(self, transforms, bbox_params=None, keymap=None, update_pad_shape=False, skip_img_without_anno=False): """ Adds custom transformations from Albumentations lib. Please, visit `https://albumentations.readthedocs.io` to get more information. transforms (list): list of albu transformations bbox_params (dict): bbox_params for albumentation `Compose` keymap (dict): contains {'input key':'albumentation-style key'} skip_img_without_anno (bool): whether to skip the image if no ann left after aug """ self.transforms = transforms self.filter_lost_elements = False self.update_pad_shape = update_pad_shape self.skip_img_without_anno = skip_img_without_anno # A simple workaround to remove masks without boxes if (isinstance(bbox_params, dict) and 'label_fields' in bbox_params and 'filter_lost_elements' in bbox_params): self.filter_lost_elements = True self.origin_label_fields = bbox_params['label_fields'] bbox_params['label_fields'] = ['idx_mapper'] del bbox_params['filter_lost_elements'] self.bbox_params = ( self.albu_builder(bbox_params) if bbox_params else None) self.aug = Compose([self.albu_builder(t) for t in self.transforms], bbox_params=self.bbox_params) if not keymap: self.keymap_to_albu = { 'img': 'image', 'gt_masks': 'masks', 'gt_bboxes': 'bboxes' } else: self.keymap_to_albu = keymap self.keymap_back = {v: k for k, v in self.keymap_to_albu.items()} def albu_builder(self, cfg): """Import a module from albumentations. Inherits some of `build_from_cfg` logic. Args: cfg (dict): Config dict. It should at least contain the key "type". Returns: obj: The constructed object. """ assert isinstance(cfg, dict) and "type" in cfg args = cfg.copy() obj_type = args.pop("type") if mmcv.is_str(obj_type): obj_cls = getattr(albumentations, obj_type) elif inspect.isclass(obj_type): obj_cls = obj_type else: raise TypeError( 'type must be a str or valid type, but got {}'.format( type(obj_type))) if 'transforms' in args: args['transforms'] = [ self.albu_builder(transform) for transform in args['transforms'] ] return obj_cls(**args) @staticmethod def mapper(d, keymap): """ Dictionary mapper. Renames keys according to keymap provided. Args: d (dict): old dict keymap (dict): {'old_key':'new_key'} Returns: dict: new dict. """ updated_dict = {} for k, v in zip(d.keys(), d.values()): new_k = keymap.get(k, k) updated_dict[new_k] = d[k] return updated_dict def __call__(self, results): # dict to albumentations format results = self.mapper(results, self.keymap_to_albu) if 'bboxes' in results: # to list of boxes if isinstance(results['bboxes'], np.ndarray): results['bboxes'] = [x for x in results['bboxes']] # add pseudo-field for filtration if self.filter_lost_elements: results['idx_mapper'] = np.arange(len(results['bboxes'])) results = self.aug(**results) if 'bboxes' in results: if isinstance(results['bboxes'], list): results['bboxes'] = np.array( results['bboxes'], dtype=np.float32) # filter label_fields if self.filter_lost_elements: results['idx_mapper'] = np.arange(len(results['bboxes'])) for label in self.origin_label_fields: results[label] = np.array( [results[label][i] for i in results['idx_mapper']]) if 'masks' in results: results['masks'] = [ results['masks'][i] for i in results['idx_mapper'] ] if (not len(results['idx_mapper']) and self.skip_img_without_anno): return None if 'gt_labels' in results: if isinstance(results['gt_labels'], list): results['gt_labels'] = np.array(results['gt_labels']) # back to the original format results = self.mapper(results, self.keymap_back) # update final shape if self.update_pad_shape: results['pad_shape'] = results['img'].shape return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(transformations={})'.format(self.transformations) return repr_str
36.370575
94
0.559962
import inspect import albumentations import mmcv import numpy as np from albumentations import Compose from imagecorruptions import corrupt from numpy import random from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps from ..registry import PIPELINES @PIPELINES.register_module class Resize(object): def __init__(self, img_scale=None, multiscale_mode='range', ratio_range=None, keep_ratio=True): if img_scale is None: self.img_scale = None else: if isinstance(img_scale, list): self.img_scale = img_scale else: self.img_scale = [img_scale] assert mmcv.is_list_of(self.img_scale, tuple) if ratio_range is not None: assert len(self.img_scale) == 1 else: assert multiscale_mode in ['value', 'range'] self.multiscale_mode = multiscale_mode self.ratio_range = ratio_range self.keep_ratio = keep_ratio @staticmethod def random_select(img_scales): assert mmcv.is_list_of(img_scales, tuple) scale_idx = np.random.randint(len(img_scales)) img_scale = img_scales[scale_idx] return img_scale, scale_idx @staticmethod def random_sample(img_scales): assert mmcv.is_list_of(img_scales, tuple) and len(img_scales) == 2 img_scale_long = [max(s) for s in img_scales] img_scale_short = [min(s) for s in img_scales] long_edge = np.random.randint( min(img_scale_long), max(img_scale_long) + 1) short_edge = np.random.randint( min(img_scale_short), max(img_scale_short) + 1) img_scale = (long_edge, short_edge) return img_scale, None @staticmethod def random_sample_ratio(img_scale, ratio_range): assert isinstance(img_scale, tuple) and len(img_scale) == 2 min_ratio, max_ratio = ratio_range assert min_ratio <= max_ratio ratio = np.random.random_sample() * (max_ratio - min_ratio) + min_ratio scale = int(img_scale[0] * ratio), int(img_scale[1] * ratio) return scale, None def _random_scale(self, results): if self.ratio_range is not None: scale, scale_idx = self.random_sample_ratio( self.img_scale[0], self.ratio_range) elif len(self.img_scale) == 1: scale, scale_idx = self.img_scale[0], 0 elif self.multiscale_mode == 'range': scale, scale_idx = self.random_sample(self.img_scale) elif self.multiscale_mode == 'value': scale, scale_idx = self.random_select(self.img_scale) else: raise NotImplementedError results['scale'] = scale results['scale_idx'] = scale_idx def _resize_img(self, results): if self.keep_ratio: img, scale_factor = mmcv.imrescale( results['img'], results['scale'], return_scale=True) else: img, w_scale, h_scale = mmcv.imresize( results['img'], results['scale'], return_scale=True) scale_factor = np.array([w_scale, h_scale, w_scale, h_scale], dtype=np.float32) results['img'] = img results['img_shape'] = img.shape results['pad_shape'] = img.shape results['scale_factor'] = scale_factor results['keep_ratio'] = self.keep_ratio def _resize_bboxes(self, results): img_shape = results['img_shape'] for key in results.get('bbox_fields', []): bboxes = results[key] * results['scale_factor'] bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1] - 1) bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0] - 1) results[key] = bboxes def _resize_masks(self, results): for key in results.get('mask_fields', []): if results[key] is None: continue if self.keep_ratio: masks = [ mmcv.imrescale( mask, results['scale_factor'], interpolation='nearest') for mask in results[key] ] else: mask_size = (results['img_shape'][1], results['img_shape'][0]) masks = [ mmcv.imresize(mask, mask_size, interpolation='nearest') for mask in results[key] ] results[key] = masks def __call__(self, results): if 'scale' not in results: self._random_scale(results) self._resize_img(results) self._resize_bboxes(results) self._resize_masks(results) return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += ('(img_scale={}, multiscale_mode={}, ratio_range={}, ' 'keep_ratio={})').format(self.img_scale, self.multiscale_mode, self.ratio_range, self.keep_ratio) return repr_str @PIPELINES.register_module class RandomFlip(object): def __init__(self, flip_ratio=None): self.flip_ratio = flip_ratio if flip_ratio is not None: assert flip_ratio >= 0 and flip_ratio <= 1 def bbox_flip(self, bboxes, img_shape): assert bboxes.shape[-1] % 4 == 0 w = img_shape[1] flipped = bboxes.copy() flipped[..., 0::4] = w - bboxes[..., 2::4] - 1 flipped[..., 2::4] = w - bboxes[..., 0::4] - 1 return flipped def __call__(self, results): if 'flip' not in results: flip = True if np.random.rand() < self.flip_ratio else False results['flip'] = flip if results['flip']: results['img'] = mmcv.imflip(results['img']) for key in results.get('bbox_fields', []): results[key] = self.bbox_flip(results[key], results['img_shape']) for key in results.get('mask_fields', []): results[key] = [mask[:, ::-1] for mask in results[key]] return results def __repr__(self): return self.__class__.__name__ + '(flip_ratio={})'.format( self.flip_ratio) @PIPELINES.register_module class Pad(object): def __init__(self, size=None, size_divisor=None, pad_val=0): self.size = size self.size_divisor = size_divisor self.pad_val = pad_val assert size is not None or size_divisor is not None assert size is None or size_divisor is None def _pad_img(self, results): if self.size is not None: padded_img = mmcv.impad(results['img'], self.size) elif self.size_divisor is not None: padded_img = mmcv.impad_to_multiple( results['img'], self.size_divisor, pad_val=self.pad_val) results['img'] = padded_img results['pad_shape'] = padded_img.shape results['pad_fixed_size'] = self.size results['pad_size_divisor'] = self.size_divisor def _pad_masks(self, results): pad_shape = results['pad_shape'][:2] for key in results.get('mask_fields', []): padded_masks = [ mmcv.impad(mask, pad_shape, pad_val=self.pad_val) for mask in results[key] ] results[key] = np.stack(padded_masks, axis=0) def __call__(self, results): self._pad_img(results) self._pad_masks(results) return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(size={}, size_divisor={}, pad_val={})'.format( self.size, self.size_divisor, self.pad_val) return repr_str @PIPELINES.register_module class Normalize(object): def __init__(self, mean, std, to_rgb=True): self.mean = np.array(mean, dtype=np.float32) self.std = np.array(std, dtype=np.float32) self.to_rgb = to_rgb def __call__(self, results): results['img'] = mmcv.imnormalize(results['img'], self.mean, self.std, self.to_rgb) results['img_norm_cfg'] = dict( mean=self.mean, std=self.std, to_rgb=self.to_rgb) return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(mean={}, std={}, to_rgb={})'.format( self.mean, self.std, self.to_rgb) return repr_str @PIPELINES.register_module class RandomCrop(object): def __init__(self, crop_size): self.crop_size = crop_size def __call__(self, results): img = results['img'] margin_h = max(img.shape[0] - self.crop_size[0], 0) margin_w = max(img.shape[1] - self.crop_size[1], 0) offset_h = np.random.randint(0, margin_h + 1) offset_w = np.random.randint(0, margin_w + 1) crop_y1, crop_y2 = offset_h, offset_h + self.crop_size[0] crop_x1, crop_x2 = offset_w, offset_w + self.crop_size[1] img = img[crop_y1:crop_y2, crop_x1:crop_x2, :] img_shape = img.shape results['img'] = img results['img_shape'] = img_shape for key in results.get('bbox_fields', []): bbox_offset = np.array([offset_w, offset_h, offset_w, offset_h], dtype=np.float32) bboxes = results[key] - bbox_offset bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1] - 1) bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0] - 1) results[key] = bboxes if 'gt_bboxes' in results: gt_bboxes = results['gt_bboxes'] valid_inds = (gt_bboxes[:, 2] > gt_bboxes[:, 0]) & ( gt_bboxes[:, 3] > gt_bboxes[:, 1]) if not np.any(valid_inds): return None results['gt_bboxes'] = gt_bboxes[valid_inds, :] if 'gt_labels' in results: results['gt_labels'] = results['gt_labels'][valid_inds] if 'gt_masks' in results: valid_gt_masks = [] for i in np.where(valid_inds)[0]: gt_mask = results['gt_masks'][i][crop_y1:crop_y2, crop_x1: crop_x2] valid_gt_masks.append(gt_mask) results['gt_masks'] = valid_gt_masks return results def __repr__(self): return self.__class__.__name__ + '(crop_size={})'.format( self.crop_size) @PIPELINES.register_module class RandomRatioCrop(object): def __init__(self, min_crop_ratio, max_crop_ratio): self.min_crop_ratio = min_crop_ratio self.max_crop_ratio = max_crop_ratio def __call__(self, results): img = results['img'] crop_ratio = (random.uniform(self.min_crop_ratio[0], self.max_crop_ratio[0]), random.uniform(self.min_crop_ratio[1], self.max_crop_ratio[1])) crop_size = (int(crop_ratio[0] * img.shape[0]), int(crop_ratio[1] * img.shape[1])) margin_h = max(img.shape[0] - crop_size[0], 0) margin_w = max(img.shape[1] - crop_size[1], 0) offset_h = np.random.randint(0, margin_h + 1) offset_w = np.random.randint(0, margin_w + 1) crop_y1, crop_y2 = offset_h, offset_h + crop_size[0] crop_x1, crop_x2 = offset_w, offset_w + crop_size[1] img = img[crop_y1:crop_y2, crop_x1:crop_x2, :] img_shape = img.shape results['img'] = img results['img_shape'] = img_shape for key in results.get('bbox_fields', []): bbox_offset = np.array([offset_w, offset_h, offset_w, offset_h], dtype=np.float32) bboxes = results[key] - bbox_offset bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1] - 1) bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0] - 1) results[key] = bboxes if 'gt_bboxes' in results: gt_bboxes = results['gt_bboxes'] valid_inds = (gt_bboxes[:, 2] > gt_bboxes[:, 0]) & ( gt_bboxes[:, 3] > gt_bboxes[:, 1]) if not np.any(valid_inds): return None results['gt_bboxes'] = gt_bboxes[valid_inds, :] if 'gt_labels' in results: results['gt_labels'] = results['gt_labels'][valid_inds] if 'gt_masks' in results: valid_gt_masks = [] for i in valid_inds: gt_mask = results['gt_masks'][i][crop_y1:crop_y2, crop_x1: crop_x2] valid_gt_masks.append(gt_mask) results['gt_masks'] = valid_gt_masks return results def __repr__(self): return self.__class__.__name__ + \ f'(min_crop_ratio={self.min_crop_ratio}, max_crop_ratio={self.max_crop_ratio})' @PIPELINES.register_module class SegResizeFlipPadRescale(object): def __init__(self, scale_factor=1): self.scale_factor = scale_factor def __call__(self, results): if results['keep_ratio']: gt_seg = mmcv.imrescale( results['gt_semantic_seg'], results['scale'], interpolation='nearest') else: gt_seg = mmcv.imresize( results['gt_semantic_seg'], results['scale'], interpolation='nearest') if results['flip']: gt_seg = mmcv.imflip(gt_seg) if gt_seg.shape != results['pad_shape']: gt_seg = mmcv.impad(gt_seg, results['pad_shape'][:2]) if self.scale_factor != 1: gt_seg = mmcv.imrescale( gt_seg, self.scale_factor, interpolation='nearest') results['gt_semantic_seg'] = gt_seg return results def __repr__(self): return self.__class__.__name__ + '(scale_factor={})'.format( self.scale_factor) @PIPELINES.register_module class PhotoMetricDistortion(object): def __init__(self, brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18): self.brightness_delta = brightness_delta self.contrast_lower, self.contrast_upper = contrast_range self.saturation_lower, self.saturation_upper = saturation_range self.hue_delta = hue_delta def __call__(self, results): img = results['img'] if random.randint(2): delta = random.uniform(-self.brightness_delta, self.brightness_delta) img += delta mode = random.randint(2) if mode == 1: if random.randint(2): alpha = random.uniform(self.contrast_lower, self.contrast_upper) img *= alpha img = mmcv.bgr2hsv(img) if random.randint(2): img[..., 1] *= random.uniform(self.saturation_lower, self.saturation_upper) if random.randint(2): img[..., 0] += random.uniform(-self.hue_delta, self.hue_delta) img[..., 0][img[..., 0] > 360] -= 360 img[..., 0][img[..., 0] < 0] += 360 img = mmcv.hsv2bgr(img) if mode == 0: if random.randint(2): alpha = random.uniform(self.contrast_lower, self.contrast_upper) img *= alpha if random.randint(2): img = img[..., random.permutation(3)] results['img'] = img return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += ('(brightness_delta={}, contrast_range={}, ' 'saturation_range={}, hue_delta={})').format( self.brightness_delta, self.contrast_range, self.saturation_range, self.hue_delta) return repr_str @PIPELINES.register_module class Expand(object): def __init__(self, mean=(0, 0, 0), to_rgb=True, ratio_range=(1, 4), seg_ignore_label=None): self.to_rgb = to_rgb self.ratio_range = ratio_range if to_rgb: self.mean = mean[::-1] else: self.mean = mean self.min_ratio, self.max_ratio = ratio_range self.seg_ignore_label = seg_ignore_label def __call__(self, results): if random.randint(2): return results img, boxes = [results[k] for k in ('img', 'gt_bboxes')] h, w, c = img.shape ratio = random.uniform(self.min_ratio, self.max_ratio) expand_img = np.full((int(h * ratio), int(w * ratio), c), self.mean).astype(img.dtype) left = int(random.uniform(0, w * ratio - w)) top = int(random.uniform(0, h * ratio - h)) expand_img[top:top + h, left:left + w] = img boxes = boxes + np.tile((left, top), 2).astype(boxes.dtype) results['img'] = expand_img results['gt_bboxes'] = boxes if 'gt_masks' in results: expand_gt_masks = [] for mask in results['gt_masks']: expand_mask = np.full((int(h * ratio), int(w * ratio)), 0).astype(mask.dtype) expand_mask[top:top + h, left:left + w] = mask expand_gt_masks.append(expand_mask) results['gt_masks'] = expand_gt_masks if 'gt_semantic_seg' in results: assert self.seg_ignore_label is not None gt_seg = results['gt_semantic_seg'] expand_gt_seg = np.full((int(h * ratio), int(w * ratio)), self.seg_ignore_label).astype(gt_seg.dtype) expand_gt_seg[top:top + h, left:left + w] = gt_seg results['gt_semantic_seg'] = expand_gt_seg return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(mean={}, to_rgb={}, ratio_range={}, ' \ 'seg_ignore_label={})'.format( self.mean, self.to_rgb, self.ratio_range, self.seg_ignore_label) return repr_str @PIPELINES.register_module class MinIoURandomCrop(object): def __init__(self, min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3): self.sample_mode = (1, *min_ious, 0) self.min_crop_size = min_crop_size def __call__(self, results): img, boxes, labels = [ results[k] for k in ('img', 'gt_bboxes', 'gt_labels') ] h, w, c = img.shape while True: mode = random.choice(self.sample_mode) if len(boxes) == 0: mode = 1 if mode == 1: return results min_iou = mode for i in range(50): new_w = random.uniform(self.min_crop_size * w, w) new_h = random.uniform(self.min_crop_size * h, h) if new_h / new_w < 0.5 or new_h / new_w > 2: continue left = random.uniform(w - new_w) top = random.uniform(h - new_h) patch = np.array( (int(left), int(top), int(left + new_w), int(top + new_h))) overlaps = bbox_overlaps( patch.reshape(-1, 4), boxes.reshape(-1, 4)).reshape(-1) if overlaps.min() < min_iou: continue center = (boxes[:, :2] + boxes[:, 2:]) / 2 mask = ((center[:, 0] > patch[0]) * (center[:, 1] > patch[1]) * (center[:, 0] < patch[2]) * (center[:, 1] < patch[3])) if not mask.any(): continue boxes = boxes[mask] labels = labels[mask] img = img[patch[1]:patch[3], patch[0]:patch[2]] boxes[:, 2:] = boxes[:, 2:].clip(max=patch[2:]) boxes[:, :2] = boxes[:, :2].clip(min=patch[:2]) boxes -= np.tile(patch[:2], 2) results['img'] = img results['gt_bboxes'] = boxes results['gt_labels'] = labels if 'gt_masks' in results: valid_masks = [ results['gt_masks'][i] for i in range(len(mask)) if mask[i] ] results['gt_masks'] = [ gt_mask[patch[1]:patch[3], patch[0]:patch[2]] for gt_mask in valid_masks ] if 'gt_semantic_seg' in results: results['gt_semantic_seg'] = results['gt_semantic_seg'][ patch[1]:patch[3], patch[0]:patch[2]] return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(min_ious={}, min_crop_size={})'.format( self.min_ious, self.min_crop_size) return repr_str @PIPELINES.register_module class Corrupt(object): def __init__(self, corruption, severity=1): self.corruption = corruption self.severity = severity def __call__(self, results): results['img'] = corrupt( results['img'].astype(np.uint8), corruption_name=self.corruption, severity=self.severity) return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(corruption={}, severity={})'.format( self.corruption, self.severity) return repr_str @PIPELINES.register_module class Albu(object): def __init__(self, transforms, bbox_params=None, keymap=None, update_pad_shape=False, skip_img_without_anno=False): self.transforms = transforms self.filter_lost_elements = False self.update_pad_shape = update_pad_shape self.skip_img_without_anno = skip_img_without_anno if (isinstance(bbox_params, dict) and 'label_fields' in bbox_params and 'filter_lost_elements' in bbox_params): self.filter_lost_elements = True self.origin_label_fields = bbox_params['label_fields'] bbox_params['label_fields'] = ['idx_mapper'] del bbox_params['filter_lost_elements'] self.bbox_params = ( self.albu_builder(bbox_params) if bbox_params else None) self.aug = Compose([self.albu_builder(t) for t in self.transforms], bbox_params=self.bbox_params) if not keymap: self.keymap_to_albu = { 'img': 'image', 'gt_masks': 'masks', 'gt_bboxes': 'bboxes' } else: self.keymap_to_albu = keymap self.keymap_back = {v: k for k, v in self.keymap_to_albu.items()} def albu_builder(self, cfg): assert isinstance(cfg, dict) and "type" in cfg args = cfg.copy() obj_type = args.pop("type") if mmcv.is_str(obj_type): obj_cls = getattr(albumentations, obj_type) elif inspect.isclass(obj_type): obj_cls = obj_type else: raise TypeError( 'type must be a str or valid type, but got {}'.format( type(obj_type))) if 'transforms' in args: args['transforms'] = [ self.albu_builder(transform) for transform in args['transforms'] ] return obj_cls(**args) @staticmethod def mapper(d, keymap): updated_dict = {} for k, v in zip(d.keys(), d.values()): new_k = keymap.get(k, k) updated_dict[new_k] = d[k] return updated_dict def __call__(self, results): results = self.mapper(results, self.keymap_to_albu) if 'bboxes' in results: if isinstance(results['bboxes'], np.ndarray): results['bboxes'] = [x for x in results['bboxes']] if self.filter_lost_elements: results['idx_mapper'] = np.arange(len(results['bboxes'])) results = self.aug(**results) if 'bboxes' in results: if isinstance(results['bboxes'], list): results['bboxes'] = np.array( results['bboxes'], dtype=np.float32) if self.filter_lost_elements: results['idx_mapper'] = np.arange(len(results['bboxes'])) for label in self.origin_label_fields: results[label] = np.array( [results[label][i] for i in results['idx_mapper']]) if 'masks' in results: results['masks'] = [ results['masks'][i] for i in results['idx_mapper'] ] if (not len(results['idx_mapper']) and self.skip_img_without_anno): return None if 'gt_labels' in results: if isinstance(results['gt_labels'], list): results['gt_labels'] = np.array(results['gt_labels']) results = self.mapper(results, self.keymap_back) if self.update_pad_shape: results['pad_shape'] = results['img'].shape return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += '(transformations={})'.format(self.transformations) return repr_str
true
true
1c442d2fada5240fc6d9343528a6ef23452beded
7,694
py
Python
nova/api/openstack/compute/contrib/baremetal_nodes.py
bopopescu/nova-39
36c7a819582b838b7bbab11d55ca3d991a587405
[ "Apache-2.0" ]
1
2021-04-08T10:13:03.000Z
2021-04-08T10:13:03.000Z
nova/api/openstack/compute/contrib/baremetal_nodes.py
bopopescu/nova-39
36c7a819582b838b7bbab11d55ca3d991a587405
[ "Apache-2.0" ]
null
null
null
nova/api/openstack/compute/contrib/baremetal_nodes.py
bopopescu/nova-39
36c7a819582b838b7bbab11d55ca3d991a587405
[ "Apache-2.0" ]
1
2020-07-24T09:39:47.000Z
2020-07-24T09:39:47.000Z
# Copyright (c) 2013 NTT DOCOMO, INC. # 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. """The bare-metal admin extension.""" import webob from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import exception from nova.virt.baremetal import db authorize = extensions.extension_authorizer('compute', 'baremetal_nodes') node_fields = ['id', 'cpus', 'local_gb', 'memory_mb', 'pm_address', 'pm_user', 'service_host', 'terminal_port', 'instance_uuid', ] interface_fields = ['id', 'address', 'datapath_id', 'port_no'] def _node_dict(node_ref): d = {} for f in node_fields: d[f] = node_ref.get(f) return d def _interface_dict(interface_ref): d = {} for f in interface_fields: d[f] = interface_ref.get(f) return d def _make_node_elem(elem): for f in node_fields: elem.set(f) def _make_interface_elem(elem): for f in interface_fields: elem.set(f) class NodeTemplate(xmlutil.TemplateBuilder): def construct(self): node_elem = xmlutil.TemplateElement('node', selector='node') _make_node_elem(node_elem) ifs_elem = xmlutil.TemplateElement('interfaces') if_elem = xmlutil.SubTemplateElement(ifs_elem, 'interface', selector='interfaces') _make_interface_elem(if_elem) node_elem.append(ifs_elem) return xmlutil.MasterTemplate(node_elem, 1) class NodesTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('nodes') node_elem = xmlutil.SubTemplateElement(root, 'node', selector='nodes') _make_node_elem(node_elem) ifs_elem = xmlutil.TemplateElement('interfaces') if_elem = xmlutil.SubTemplateElement(ifs_elem, 'interface', selector='interfaces') _make_interface_elem(if_elem) node_elem.append(ifs_elem) return xmlutil.MasterTemplate(root, 1) class InterfaceTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('interface', selector='interface') _make_interface_elem(root) return xmlutil.MasterTemplate(root, 1) class BareMetalNodeController(wsgi.Controller): """The Bare-Metal Node API controller for the OpenStack API.""" @wsgi.serializers(xml=NodesTemplate) def index(self, req): context = req.environ['nova.context'] authorize(context) nodes_from_db = db.bm_node_get_all(context) nodes = [] for node_from_db in nodes_from_db: try: ifs = db.bm_interface_get_all_by_bm_node_id( context, node_from_db['id']) except exception.NodeNotFound: ifs = [] node = _node_dict(node_from_db) node['interfaces'] = [_interface_dict(i) for i in ifs] nodes.append(node) return {'nodes': nodes} @wsgi.serializers(xml=NodeTemplate) def show(self, req, id): context = req.environ['nova.context'] authorize(context) try: node = db.bm_node_get(context, id) except exception.NodeNotFound: raise webob.exc.HTTPNotFound try: ifs = db.bm_interface_get_all_by_bm_node_id(context, id) except exception.NodeNotFound: ifs = [] node = _node_dict(node) node['interfaces'] = [_interface_dict(i) for i in ifs] return {'node': node} @wsgi.serializers(xml=NodeTemplate) def create(self, req, body): context = req.environ['nova.context'] authorize(context) values = body['node'].copy() prov_mac_address = values.pop('prov_mac_address', None) node = db.bm_node_create(context, values) node = _node_dict(node) if prov_mac_address: if_id = db.bm_interface_create(context, bm_node_id=node['id'], address=prov_mac_address, datapath_id=None, port_no=None) if_ref = db.bm_interface_get(context, if_id) node['interfaces'] = [_interface_dict(if_ref)] else: node['interfaces'] = [] return {'node': node} def delete(self, req, id): context = req.environ['nova.context'] authorize(context) try: db.bm_node_destroy(context, id) except exception.NodeNotFound: raise webob.exc.HTTPNotFound return webob.Response(status_int=202) def _check_node_exists(self, context, node_id): try: db.bm_node_get(context, node_id) except exception.NodeNotFound: raise webob.exc.HTTPNotFound @wsgi.serializers(xml=InterfaceTemplate) @wsgi.action('add_interface') def _add_interface(self, req, id, body): context = req.environ['nova.context'] authorize(context) self._check_node_exists(context, id) body = body['add_interface'] address = body['address'] datapath_id = body.get('datapath_id') port_no = body.get('port_no') if_id = db.bm_interface_create(context, bm_node_id=id, address=address, datapath_id=datapath_id, port_no=port_no) if_ref = db.bm_interface_get(context, if_id) return {'interface': _interface_dict(if_ref)} @wsgi.response(202) @wsgi.action('remove_interface') def _remove_interface(self, req, id, body): context = req.environ['nova.context'] authorize(context) self._check_node_exists(context, id) body = body['remove_interface'] if_id = body.get('id') address = body.get('address') if not if_id and not address: raise webob.exc.HTTPBadRequest( explanation=_("Must specify id or address")) ifs = db.bm_interface_get_all_by_bm_node_id(context, id) for i in ifs: if if_id and if_id != i['id']: continue if address and address != i['address']: continue db.bm_interface_destroy(context, i['id']) return webob.Response(status_int=202) raise webob.exc.HTTPNotFound class Baremetal_nodes(extensions.ExtensionDescriptor): """Admin-only bare-metal node administration.""" name = "BareMetalNodes" alias = "os-baremetal-nodes" namespace = "http://docs.openstack.org/compute/ext/baremetal_nodes/api/v2" updated = "2013-01-04T00:00:00+00:00" def get_resources(self): resources = [] res = extensions.ResourceExtension('os-baremetal-nodes', BareMetalNodeController(), member_actions={"action": "POST", }) resources.append(res) return resources
35.13242
78
0.610216
import webob from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import exception from nova.virt.baremetal import db authorize = extensions.extension_authorizer('compute', 'baremetal_nodes') node_fields = ['id', 'cpus', 'local_gb', 'memory_mb', 'pm_address', 'pm_user', 'service_host', 'terminal_port', 'instance_uuid', ] interface_fields = ['id', 'address', 'datapath_id', 'port_no'] def _node_dict(node_ref): d = {} for f in node_fields: d[f] = node_ref.get(f) return d def _interface_dict(interface_ref): d = {} for f in interface_fields: d[f] = interface_ref.get(f) return d def _make_node_elem(elem): for f in node_fields: elem.set(f) def _make_interface_elem(elem): for f in interface_fields: elem.set(f) class NodeTemplate(xmlutil.TemplateBuilder): def construct(self): node_elem = xmlutil.TemplateElement('node', selector='node') _make_node_elem(node_elem) ifs_elem = xmlutil.TemplateElement('interfaces') if_elem = xmlutil.SubTemplateElement(ifs_elem, 'interface', selector='interfaces') _make_interface_elem(if_elem) node_elem.append(ifs_elem) return xmlutil.MasterTemplate(node_elem, 1) class NodesTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('nodes') node_elem = xmlutil.SubTemplateElement(root, 'node', selector='nodes') _make_node_elem(node_elem) ifs_elem = xmlutil.TemplateElement('interfaces') if_elem = xmlutil.SubTemplateElement(ifs_elem, 'interface', selector='interfaces') _make_interface_elem(if_elem) node_elem.append(ifs_elem) return xmlutil.MasterTemplate(root, 1) class InterfaceTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('interface', selector='interface') _make_interface_elem(root) return xmlutil.MasterTemplate(root, 1) class BareMetalNodeController(wsgi.Controller): @wsgi.serializers(xml=NodesTemplate) def index(self, req): context = req.environ['nova.context'] authorize(context) nodes_from_db = db.bm_node_get_all(context) nodes = [] for node_from_db in nodes_from_db: try: ifs = db.bm_interface_get_all_by_bm_node_id( context, node_from_db['id']) except exception.NodeNotFound: ifs = [] node = _node_dict(node_from_db) node['interfaces'] = [_interface_dict(i) for i in ifs] nodes.append(node) return {'nodes': nodes} @wsgi.serializers(xml=NodeTemplate) def show(self, req, id): context = req.environ['nova.context'] authorize(context) try: node = db.bm_node_get(context, id) except exception.NodeNotFound: raise webob.exc.HTTPNotFound try: ifs = db.bm_interface_get_all_by_bm_node_id(context, id) except exception.NodeNotFound: ifs = [] node = _node_dict(node) node['interfaces'] = [_interface_dict(i) for i in ifs] return {'node': node} @wsgi.serializers(xml=NodeTemplate) def create(self, req, body): context = req.environ['nova.context'] authorize(context) values = body['node'].copy() prov_mac_address = values.pop('prov_mac_address', None) node = db.bm_node_create(context, values) node = _node_dict(node) if prov_mac_address: if_id = db.bm_interface_create(context, bm_node_id=node['id'], address=prov_mac_address, datapath_id=None, port_no=None) if_ref = db.bm_interface_get(context, if_id) node['interfaces'] = [_interface_dict(if_ref)] else: node['interfaces'] = [] return {'node': node} def delete(self, req, id): context = req.environ['nova.context'] authorize(context) try: db.bm_node_destroy(context, id) except exception.NodeNotFound: raise webob.exc.HTTPNotFound return webob.Response(status_int=202) def _check_node_exists(self, context, node_id): try: db.bm_node_get(context, node_id) except exception.NodeNotFound: raise webob.exc.HTTPNotFound @wsgi.serializers(xml=InterfaceTemplate) @wsgi.action('add_interface') def _add_interface(self, req, id, body): context = req.environ['nova.context'] authorize(context) self._check_node_exists(context, id) body = body['add_interface'] address = body['address'] datapath_id = body.get('datapath_id') port_no = body.get('port_no') if_id = db.bm_interface_create(context, bm_node_id=id, address=address, datapath_id=datapath_id, port_no=port_no) if_ref = db.bm_interface_get(context, if_id) return {'interface': _interface_dict(if_ref)} @wsgi.response(202) @wsgi.action('remove_interface') def _remove_interface(self, req, id, body): context = req.environ['nova.context'] authorize(context) self._check_node_exists(context, id) body = body['remove_interface'] if_id = body.get('id') address = body.get('address') if not if_id and not address: raise webob.exc.HTTPBadRequest( explanation=_("Must specify id or address")) ifs = db.bm_interface_get_all_by_bm_node_id(context, id) for i in ifs: if if_id and if_id != i['id']: continue if address and address != i['address']: continue db.bm_interface_destroy(context, i['id']) return webob.Response(status_int=202) raise webob.exc.HTTPNotFound class Baremetal_nodes(extensions.ExtensionDescriptor): name = "BareMetalNodes" alias = "os-baremetal-nodes" namespace = "http://docs.openstack.org/compute/ext/baremetal_nodes/api/v2" updated = "2013-01-04T00:00:00+00:00" def get_resources(self): resources = [] res = extensions.ResourceExtension('os-baremetal-nodes', BareMetalNodeController(), member_actions={"action": "POST", }) resources.append(res) return resources
true
true
1c442e3d79417cf8362146c9eef72af711a9391e
1,130
py
Python
demo/example/wsgi.py
afahounko/django-plans
089c90486ead3b8ab69b8b119f33d5ef923ca08e
[ "MIT" ]
13
2016-01-19T15:45:32.000Z
2018-06-21T22:51:56.000Z
demo/example/wsgi.py
afahounko/django-plans
089c90486ead3b8ab69b8b119f33d5ef923ca08e
[ "MIT" ]
11
2015-12-01T20:01:06.000Z
2018-07-07T05:12:17.000Z
demo/example/wsgi.py
afahounko/django-plans
089c90486ead3b8ab69b8b119f33d5ef923ca08e
[ "MIT" ]
8
2015-11-17T02:12:36.000Z
2018-08-01T22:17:12.000Z
""" WSGI config for xmpl project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xmpl.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
38.965517
79
0.806195
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xmpl.settings") # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
true
true
1c442f847b28080303990953647216aee7c6607f
11,205
py
Python
python_src/adaptive_formation/gradient_interactive.py
tkortz/motion_planning_rt
08e914642b802f7217a8ad0f6153d41ccdce8c7d
[ "MIT" ]
null
null
null
python_src/adaptive_formation/gradient_interactive.py
tkortz/motion_planning_rt
08e914642b802f7217a8ad0f6153d41ccdce8c7d
[ "MIT" ]
null
null
null
python_src/adaptive_formation/gradient_interactive.py
tkortz/motion_planning_rt
08e914642b802f7217a8ad0f6153d41ccdce8c7d
[ "MIT" ]
null
null
null
# In order to launch execute: # python3 gradient_interactive.py import numpy as np from numpy.linalg import norm import matplotlib.pyplot as plt from matplotlib import collections from scipy.ndimage.morphology import distance_transform_edt as bwdist from math import * import random from impedance_modeles import * import time from progress.bar import FillingCirclesBar from tasks import * from threading import Thread from multiprocessing import Process import os import liblitmus def poly_area(x,y): # https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates # https://en.wikipedia.org/wiki/Shoelace_formula return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def meters2grid(pose_m, nrows=500, ncols=500): # [0, 0](m) -> [250, 250] # [1, 0](m) -> [250+100, 250] # [0,-1](m) -> [250, 250-100] pose_on_grid = np.array(pose_m)*100 + np.array([ncols/2, nrows/2]) return np.array( pose_on_grid, dtype=int) def grid2meters(pose_grid, nrows=500, ncols=500): # [250, 250] -> [0, 0](m) # [250+100, 250] -> [1, 0](m) # [250, 250-100] -> [0,-1](m) pose_meters = ( np.array(pose_grid) - np.array([ncols/2, nrows/2]) ) / 100.0 return pose_meters def gradient_planner(f, current_point, ncols=500, nrows=500, movement_rate=0.06): """ GradientBasedPlanner : This function computes the next_point given current location, goal location and potential map, f. It also returns mean velocity, V, of the gradient map in current point. """ [gy, gx] = np.gradient(-f); iy, ix = np.array( meters2grid(current_point), dtype=int ) w = 30 # smoothing window size for gradient-velocity vx = np.mean(gx[ix-int(w/2) : ix+int(w/2), iy-int(w/2) : iy+int(w/2)]) vy = np.mean(gy[ix-int(w/2) : ix+int(w/2), iy-int(w/2) : iy+int(w/2)]) V = np.array([vx, vy]) dt = 0.06 / norm(V); next_point = current_point + dt*V; return next_point, V def combined_potential(obstacles_poses, R_obstacles, goal, nrows=500, ncols=500): """ Repulsive potential """ obstacles_map = map(obstacles_poses, R_obstacles) goal = meters2grid(goal) d = bwdist(obstacles_map==0); d2 = (d/100.) + 1; # Rescale and transform distances d0 = 2; nu = 200; repulsive = nu*((1./d2 - 1./d0)**2); repulsive [d2 > d0] = 0; """ Attractive potential """ [x, y] = np.meshgrid(np.arange(ncols), np.arange(nrows)) xi = 1/700.; attractive = xi * ( (x - goal[0])**2 + (y - goal[1])**2 ); """ Combine terms """ f = attractive + repulsive; return f def map(obstacles_poses, R_obstacles, nrows=500, ncols=500): """ Obstacles map """ obstacles_map = np.zeros((nrows, ncols)); [x, y] = np.meshgrid(np.arange(ncols), np.arange(nrows)) for pose in obstacles_poses: pose = meters2grid(pose) x0 = pose[0]; y0 = pose[1] # cylindrical obstacles t = ((x - x0)**2 + (y - y0)**2) < (100*R_obstacles)**2 obstacles_map[t] = 1; # rectangular obstacles obstacles_map[400:, 130:150] = 1; obstacles_map[130:150, :200] = 1; obstacles_map[330:380, 300:] = 1; return obstacles_map def move_obstacles(obstacles_poses, obstacles_goal_poses): """ All of the obstacles tend to go to the origin, (0,0) - point """ # for pose in obstacles_poses: # dx = random.uniform(0, 0.03); dy = random.uniform(0,0.03); # pose[0] -= np.sign(pose[0])*dx; pose[1] -= np.sign(pose[1])*dy; """ Each obstacles tends to go to its selected goal point with random speed """ for p in range(len(obstacles_poses)): pose = obstacles_poses[p]; goal = obstacles_goal_poses[p] dx, dy = (goal - pose) / norm(goal-pose) * 0.05#random.uniform(0,0.05) pose[0] += dx; pose[1] += dy; return obstacles_poses def formation(num_robots, leader_des, v, R_swarm): if num_robots<=1: return [] u = np.array([-v[1], v[0]]) des4 = leader_des - v*R_swarm*sqrt(3) # follower if num_robots==2: return [des4] des2 = leader_des - v*R_swarm*sqrt(3)/2 + u*R_swarm/2 # follower des3 = leader_des - v*R_swarm*sqrt(3)/2 - u*R_swarm/2 # follower if num_robots==3: return [des2, des3] return [des2, des3, des4] def gradient_interactive(): """ initialization """ animate = 1 # show 1-each frame or 0-just final configuration random_obstacles = 1 # randomly distributed obstacles on the map num_random_obstacles = 8 # number of random circular obstacles on the map num_robots = 4 # <=4, number of drones in formation moving_obstacles = 1 # 0-static or 1-dynamic obstacles impedance = 0 # impedance links between the leader and followers (leader's velocity) formation_gradient = 1 # followers are attracting to their formation position and repelling from obstacles draw_gradients = 1 # 1-gradients plot, 0-grid postprocessing = 0 # show processed data figures after the flight """ human guided swarm params """ interactive = 0 # 1-human guided swarm (requires MoCap system), 0-potential fields as a planner to goal pose human_name = 'palm' # vicon mocap object pos_coef = 3.0 # scale of the leader's movement relatively to the human operator initialized = False # is always inits with False: for relative position control max_its = 500 if interactive else 120 # max number of allowed iters for formation to reach the goal VISUALIZE = False # movie writer if VISUALIZE: progress_bar = FillingCirclesBar('Number of Iterations', max=max_its) should_write_movie = 0; movie_file_name = os.getcwd()+'/videos/output.avi' movie_writer = get_movie_writer(should_write_movie, 'Simulation Potential Fields', movie_fps=10., plot_pause_len=0.01) R_obstacles = 0.05 # [m] R_swarm = 0.3 # [m] start = np.array([-1.8, 1.8]); goal = np.array([1.8, -1.8]) V0 = (goal - start) / norm(goal-start) # initial movement direction, |V0| = 1 U0 = np.array([-V0[1], V0[0]]) / norm(V0) # perpendicular to initial movement direction, |U0|=1 imp_pose_prev = np.array([0, 0]) imp_vel_prev = np.array([0, 0]) imp_time_prev = time.time() if random_obstacles: obstacles_poses = np.random.uniform(low=-2.5, high=2.5, size=(num_random_obstacles,2)) # randomly located obstacles obstacles_goal_poses = np.random.uniform(low=-1.3, high=1.3, size=(num_random_obstacles,2)) # randomly located obstacles goal poses else: obstacles_poses = np.array([[-2, 1], [1.5, 0.5], [-1.0, 1.5], [0.1, 0.1], [1, -2], [-1.8, -1.8]]) # 2D - coordinates [m] obstacles_goal_poses = np.array([[-0, 0], [0.0, 0.0], [ 0.0, 0.0], [0.0, 0.0], [0, 0], [ 0.0, 0.0]]) """ Main loop """ # drones polygonal formation route1 = start # leader current_point1 = start robots_poses = [start] + formation(num_robots, start, V0, R_swarm) routes = [route1] + robots_poses[1:] centroid_route = [ sum([p[0] for p in robots_poses])/len(robots_poses), sum([p[1] for p in robots_poses])/len(robots_poses) ] des_poses = robots_poses vels = [] for r in range(num_robots): vels.append([]) norm_vels = [] for r in range(num_robots): norm_vels.append([]) # variables for postprocessing and performance estimation area_array = [] start_time = time.time() fig = plt.figure(figsize=(10, 10)) with get_dummy_context_mgr(): for i in range(max_its): if moving_obstacles: obstacles_poses = move_obstacles(obstacles_poses, obstacles_goal_poses) """ Leader's pose update """ f1 = combined_potential(obstacles_poses, R_obstacles, goal) des_poses[0], vels[0] = gradient_planner(f1, current_point1) direction = ( goal - des_poses[0] ) / norm(goal - des_poses[0]) norm_vels[0].append(norm(vels[0])) # drones polygonal formation # direction = ( goal - des_poses[0] ) / norm(goal - des_poses[0]) des_poses[1:] = formation(num_robots, des_poses[0], direction, R_swarm) v = direction; u = np.array([-v[1], v[0]]) if formation_gradient: # following drones are attracting to desired points - vertices of the polygonal formation for p in range(1, num_robots): """ including another robots in formation in obstacles array: """ robots_obstacles = [x for i,x in enumerate(robots_poses) if i!=p] # obstacles_poses1 = np.array(robots_obstacles + obstacles_poses.tolist()) # f = combined_potential(obstacles_poses1, des_poses[p]) f = combined_potential(obstacles_poses, R_obstacles, des_poses[p]) des_poses[p], vels[p] = gradient_planner(f, des_poses[p]) norm_vels[p].append(norm(vels[p])) for r in range(num_robots): routes[r] = np.vstack([routes[r], des_poses[r]]) current_point1 = des_poses[0] # update current point of the leader pp = des_poses centroid = [ sum([p[0] for p in pp])/len(pp), sum([p[1] for p in pp])/len(pp) ] centroid_route = np.vstack([centroid_route, centroid]) dist_to_goal = norm(centroid - goal) if dist_to_goal < 1.5*R_swarm: print('\nReached the goal') break if VISUALIZE: progress_bar.next() plt.cla() draw_map(start, goal, obstacles_poses, R_obstacles, f1, draw_gradients=draw_gradients) draw_robots(current_point1, routes, num_robots, robots_poses, centroid, vels[0]) if animate: plt.draw() plt.pause(0.01) # print('Current simulation time: ', time.time()-start_time) # Wait for the next period global jobs jobs += 1 liblitmus.call_sleep_next_period() if VISUALIZE: print('\nDone') progress_bar.finish() plt.show() end_time = time.time() print('Simulation execution time: ', round(end_time-start_time,2)) if __name__ == "__main__": wcet = 150 period = 200 deadline = 200 phase = 0 early = False numReps = 35 jobs = 0 # Make this thread a real-time task liblitmus.call_set_rt_task_param(wcet, period, deadline, phase, early) print("\nFinished setting rt params.\n") liblitmus.call_init_litmus() print("\nCalled init_litmus.\n") liblitmus.set_task_mode_litmusrt() print("\nNow a real-time task.\n") print("\nAbout to wait for synchronous release.\n") liblitmus.call_wait_for_ts_release() # Do the work for i in range(numReps): gradient_interactive() # Make it not a real-time task anymore liblitmus.set_task_mode_background() print("\nNow a background task again.\n") print("Number of jobs:", jobs)
40.745455
139
0.619188
import numpy as np from numpy.linalg import norm import matplotlib.pyplot as plt from matplotlib import collections from scipy.ndimage.morphology import distance_transform_edt as bwdist from math import * import random from impedance_modeles import * import time from progress.bar import FillingCirclesBar from tasks import * from threading import Thread from multiprocessing import Process import os import liblitmus def poly_area(x,y): return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) def meters2grid(pose_m, nrows=500, ncols=500): pose_on_grid = np.array(pose_m)*100 + np.array([ncols/2, nrows/2]) return np.array( pose_on_grid, dtype=int) def grid2meters(pose_grid, nrows=500, ncols=500): pose_meters = ( np.array(pose_grid) - np.array([ncols/2, nrows/2]) ) / 100.0 return pose_meters def gradient_planner(f, current_point, ncols=500, nrows=500, movement_rate=0.06): [gy, gx] = np.gradient(-f); iy, ix = np.array( meters2grid(current_point), dtype=int ) w = 30 vx = np.mean(gx[ix-int(w/2) : ix+int(w/2), iy-int(w/2) : iy+int(w/2)]) vy = np.mean(gy[ix-int(w/2) : ix+int(w/2), iy-int(w/2) : iy+int(w/2)]) V = np.array([vx, vy]) dt = 0.06 / norm(V); next_point = current_point + dt*V; return next_point, V def combined_potential(obstacles_poses, R_obstacles, goal, nrows=500, ncols=500): obstacles_map = map(obstacles_poses, R_obstacles) goal = meters2grid(goal) d = bwdist(obstacles_map==0); d2 = (d/100.) + 1; d0 = 2; nu = 200; repulsive = nu*((1./d2 - 1./d0)**2); repulsive [d2 > d0] = 0; [x, y] = np.meshgrid(np.arange(ncols), np.arange(nrows)) xi = 1/700.; attractive = xi * ( (x - goal[0])**2 + (y - goal[1])**2 ); f = attractive + repulsive; return f def map(obstacles_poses, R_obstacles, nrows=500, ncols=500): obstacles_map = np.zeros((nrows, ncols)); [x, y] = np.meshgrid(np.arange(ncols), np.arange(nrows)) for pose in obstacles_poses: pose = meters2grid(pose) x0 = pose[0]; y0 = pose[1] t = ((x - x0)**2 + (y - y0)**2) < (100*R_obstacles)**2 obstacles_map[t] = 1; obstacles_map[400:, 130:150] = 1; obstacles_map[130:150, :200] = 1; obstacles_map[330:380, 300:] = 1; return obstacles_map def move_obstacles(obstacles_poses, obstacles_goal_poses): for p in range(len(obstacles_poses)): pose = obstacles_poses[p]; goal = obstacles_goal_poses[p] dx, dy = (goal - pose) / norm(goal-pose) * 0.05 pose[0] += dx; pose[1] += dy; return obstacles_poses def formation(num_robots, leader_des, v, R_swarm): if num_robots<=1: return [] u = np.array([-v[1], v[0]]) des4 = leader_des - v*R_swarm*sqrt(3) if num_robots==2: return [des4] des2 = leader_des - v*R_swarm*sqrt(3)/2 + u*R_swarm/2 des3 = leader_des - v*R_swarm*sqrt(3)/2 - u*R_swarm/2 if num_robots==3: return [des2, des3] return [des2, des3, des4] def gradient_interactive(): animate = 1 random_obstacles = 1 num_random_obstacles = 8 num_robots = 4 moving_obstacles = 1 impedance = 0 formation_gradient = 1 # followers are attracting to their formation position and repelling from obstacles draw_gradients = 1 # 1-gradients plot, 0-grid postprocessing = 0 # show processed data figures after the flight interactive = 0 # 1-human guided swarm (requires MoCap system), 0-potential fields as a planner to goal pose human_name = 'palm' # vicon mocap object pos_coef = 3.0 # scale of the leader's movement relatively to the human operator initialized = False max_its = 500 if interactive else 120 VISUALIZE = False if VISUALIZE: progress_bar = FillingCirclesBar('Number of Iterations', max=max_its) should_write_movie = 0; movie_file_name = os.getcwd()+'/videos/output.avi' movie_writer = get_movie_writer(should_write_movie, 'Simulation Potential Fields', movie_fps=10., plot_pause_len=0.01) R_obstacles = 0.05 R_swarm = 0.3 start = np.array([-1.8, 1.8]); goal = np.array([1.8, -1.8]) V0 = (goal - start) / norm(goal-start) U0 = np.array([-V0[1], V0[0]]) / norm(V0) imp_pose_prev = np.array([0, 0]) imp_vel_prev = np.array([0, 0]) imp_time_prev = time.time() if random_obstacles: obstacles_poses = np.random.uniform(low=-2.5, high=2.5, size=(num_random_obstacles,2)) obstacles_goal_poses = np.random.uniform(low=-1.3, high=1.3, size=(num_random_obstacles,2)) else: obstacles_poses = np.array([[-2, 1], [1.5, 0.5], [-1.0, 1.5], [0.1, 0.1], [1, -2], [-1.8, -1.8]]) obstacles_goal_poses = np.array([[-0, 0], [0.0, 0.0], [ 0.0, 0.0], [0.0, 0.0], [0, 0], [ 0.0, 0.0]]) route1 = start current_point1 = start robots_poses = [start] + formation(num_robots, start, V0, R_swarm) routes = [route1] + robots_poses[1:] centroid_route = [ sum([p[0] for p in robots_poses])/len(robots_poses), sum([p[1] for p in robots_poses])/len(robots_poses) ] des_poses = robots_poses vels = [] for r in range(num_robots): vels.append([]) norm_vels = [] for r in range(num_robots): norm_vels.append([]) area_array = [] start_time = time.time() fig = plt.figure(figsize=(10, 10)) with get_dummy_context_mgr(): for i in range(max_its): if moving_obstacles: obstacles_poses = move_obstacles(obstacles_poses, obstacles_goal_poses) f1 = combined_potential(obstacles_poses, R_obstacles, goal) des_poses[0], vels[0] = gradient_planner(f1, current_point1) direction = ( goal - des_poses[0] ) / norm(goal - des_poses[0]) norm_vels[0].append(norm(vels[0])) des_poses[1:] = formation(num_robots, des_poses[0], direction, R_swarm) v = direction; u = np.array([-v[1], v[0]]) if formation_gradient: for p in range(1, num_robots): robots_obstacles = [x for i,x in enumerate(robots_poses) if i!=p] f = combined_potential(obstacles_poses, R_obstacles, des_poses[p]) des_poses[p], vels[p] = gradient_planner(f, des_poses[p]) norm_vels[p].append(norm(vels[p])) for r in range(num_robots): routes[r] = np.vstack([routes[r], des_poses[r]]) current_point1 = des_poses[0] pp = des_poses centroid = [ sum([p[0] for p in pp])/len(pp), sum([p[1] for p in pp])/len(pp) ] centroid_route = np.vstack([centroid_route, centroid]) dist_to_goal = norm(centroid - goal) if dist_to_goal < 1.5*R_swarm: print('\nReached the goal') break if VISUALIZE: progress_bar.next() plt.cla() draw_map(start, goal, obstacles_poses, R_obstacles, f1, draw_gradients=draw_gradients) draw_robots(current_point1, routes, num_robots, robots_poses, centroid, vels[0]) if animate: plt.draw() plt.pause(0.01) global jobs jobs += 1 liblitmus.call_sleep_next_period() if VISUALIZE: print('\nDone') progress_bar.finish() plt.show() end_time = time.time() print('Simulation execution time: ', round(end_time-start_time,2)) if __name__ == "__main__": wcet = 150 period = 200 deadline = 200 phase = 0 early = False numReps = 35 jobs = 0 liblitmus.call_set_rt_task_param(wcet, period, deadline, phase, early) print("\nFinished setting rt params.\n") liblitmus.call_init_litmus() print("\nCalled init_litmus.\n") liblitmus.set_task_mode_litmusrt() print("\nNow a real-time task.\n") print("\nAbout to wait for synchronous release.\n") liblitmus.call_wait_for_ts_release() for i in range(numReps): gradient_interactive() liblitmus.set_task_mode_background() print("\nNow a background task again.\n") print("Number of jobs:", jobs)
true
true
1c442f8e6a0dc8f5fe2a81b2f44f17d32075be5c
2,598
py
Python
openarticlegauge/plugins/hindawi.py
CottageLabs/OpenArticleGauge
58d29b4209a7b59041d61326ffe1cf03f98f3cff
[ "BSD-3-Clause" ]
1
2016-04-07T18:29:27.000Z
2016-04-07T18:29:27.000Z
openarticlegauge/plugins/hindawi.py
CottageLabs/OpenArticleGauge
58d29b4209a7b59041d61326ffe1cf03f98f3cff
[ "BSD-3-Clause" ]
11
2015-01-06T15:53:09.000Z
2022-03-01T01:46:14.000Z
openarticlegauge/plugins/hindawi.py
CottageLabs/OpenArticleGauge
58d29b4209a7b59041d61326ffe1cf03f98f3cff
[ "BSD-3-Clause" ]
null
null
null
""" This plugin handles Hindawi articles. Hindawi publish from a single domain and use a consistent format for licenses so this one should be relatively straightforward. """ from openarticlegauge import plugin class HindawiPlugin(plugin.Plugin): _short_name = __name__.split('.')[-1] __version__='0.1' # consider incrementing or at least adding a minor version # e.g. "0.1.1" if you change this plugin __desc__ = "Obtains licenses from articles published by Hindawi" # The domains that this plugin will say it can support. # Specified without the schema (protocol - e.g. "http://") part. _base_urls = ["www.hindawi.com"] # so if the http://www.hindawi.com/journals/ecam/2013/429706/ URL comes in, # it should be supported. _license_mappings = [ {'This is an open access article distributed under the <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution License</a>, which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited.': {'type': 'cc-by', # license type, see the licenses module for available ones 'version':'3.0', # version of the license if specified, can be blank # also declare some properties which override info about this license in the licenses list (see licenses module) 'url': 'http://creativecommons.org/licenses/by/3.0'} } ] def capabilities(self): return { "type_detect_verify" : False, "canonicalise" : [], "detect_provider" : [], "license_detect" : True } def supports(self, provider): """ Does this plugin support this provider """ return self.supports_by_base_url(provider) def license_detect(self, record): """ To respond to the provider identifier: http://www.hindawi.com This should determine the licence conditions of the Hindawi article and populate the record['bibjson']['license'] (note the US spelling) field. """ lic_statements = self._license_mappings # For all URL-s associated with this resource... for url in record.provider_urls: # ... run the dumb string matcher if the URL is supported. if self.supports_base_url(url): self.simple_extract(lic_statements, record, url) return (self._short_name, self.__version__)
41.238095
302
0.635104
from openarticlegauge import plugin class HindawiPlugin(plugin.Plugin): _short_name = __name__.split('.')[-1] __version__='0.1' __desc__ = "Obtains licenses from articles published by Hindawi" _base_urls = ["www.hindawi.com"] _license_mappings = [ {'This is an open access article distributed under the <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution License</a>, which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited.': {'type': 'cc-by', 'version':'3.0', 'url': 'http://creativecommons.org/licenses/by/3.0'} } ] def capabilities(self): return { "type_detect_verify" : False, "canonicalise" : [], "detect_provider" : [], "license_detect" : True } def supports(self, provider): return self.supports_by_base_url(provider) def license_detect(self, record): lic_statements = self._license_mappings for url in record.provider_urls: if self.supports_base_url(url): self.simple_extract(lic_statements, record, url) return (self._short_name, self.__version__)
true
true
1c443024fe6467b58121c2e7ba26b7dca51aeb4e
1,070
py
Python
algorithms/backtrack/subsets.py
nisaruj/algorithms
1e03cd259c2d7ada113eb99843dcada9f20adf54
[ "MIT" ]
6
2018-12-12T09:14:05.000Z
2019-04-29T22:07:28.000Z
algorithms/backtrack/subsets.py
nisaruj/algorithms
1e03cd259c2d7ada113eb99843dcada9f20adf54
[ "MIT" ]
null
null
null
algorithms/backtrack/subsets.py
nisaruj/algorithms
1e03cd259c2d7ada113eb99843dcada9f20adf54
[ "MIT" ]
7
2019-03-21T10:18:22.000Z
2021-09-22T07:34:10.000Z
""" Given a set of distinct integers, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example, If nums = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] """ def subsets(nums): """ O(2**n) """ def backtrack(res, nums, stack, pos): if pos == len(nums): res.append(list(stack)) else: # take nums[pos] stack.append(nums[pos]) backtrack(res, nums, stack, pos+1) stack.pop() # dont take nums[pos] backtrack(res, nums, stack, pos+1) res = [] backtrack(res, nums, [], 0) return res """ simplified backtrack def backtrack(res, nums, cur, pos): if pos >= len(nums): res.append(cur) else: backtrack(res, nums, cur+[nums[pos]], pos+1) backtrack(res, nums, cur, pos+1) """ # Iteratively def subsets_v2(self, nums): res = [[]] for num in sorted(nums): res += [item+[num] for item in res] return res
17.833333
68
0.526168
def subsets(nums): def backtrack(res, nums, stack, pos): if pos == len(nums): res.append(list(stack)) else: stack.append(nums[pos]) backtrack(res, nums, stack, pos+1) stack.pop() backtrack(res, nums, stack, pos+1) res = [] backtrack(res, nums, [], 0) return res def subsets_v2(self, nums): res = [[]] for num in sorted(nums): res += [item+[num] for item in res] return res
true
true
1c4430552bfe4f27d5a07dbbf8a7fb3bc4ff2e65
1,659
py
Python
tests/optimization/test_genetic_algorithm.py
iamchetry/DataChallenge-Fall2021
fa7748c9ea2f3c0f6bde8d0b094fc75463e28f33
[ "BSD-3-Clause" ]
108
2018-03-23T20:06:03.000Z
2022-01-06T19:32:46.000Z
tests/optimization/test_genetic_algorithm.py
hachmannlab/ChemML
42b152579872a57c834884596f700c76b9320280
[ "BSD-3-Clause" ]
18
2019-08-09T21:16:14.000Z
2022-02-14T21:52:06.000Z
tests/optimization/test_genetic_algorithm.py
hachmannlab/ChemML
42b152579872a57c834884596f700c76b9320280
[ "BSD-3-Clause" ]
28
2018-04-28T17:07:33.000Z
2022-02-28T07:22:56.000Z
import pytest from chemml.optimization import GeneticAlgorithm space = ({'alpha': {'uniform': [-20, 0], 'mutation': [0, 2]}}, {'neurons': {'int': [0,10]}}, {'act': {'choice':range(0,100,5)}}) def evaluate(individual): return sum(individual) def test_algorithms(): al = [3] for i in al: ga_search = GeneticAlgorithm( evaluate, space=space, pop_size=10, mutation_size=4, crossover_size=4, algorithm=i) _, best_individual = ga_search.search(n_generations=4) assert sum([best_individual[i] for i in best_individual]) <= 200 def test_sequential_min(): ga_search = GeneticAlgorithm(evaluate, fitness=("min", ), space=space, pop_size=10, mutation_size=5, crossover_size=5, algorithm=3) for _ in range(4): _, best_individual = ga_search.search(n_generations=1) assert sum([best_individual[i] for i in best_individual]) <= 200 def test_crossovers(): co = ['SinglePoint', 'DoublePoint', 'Blend'] for c in co: ga_search = GeneticAlgorithm( evaluate, space=space, crossover_type=c, pop_size=10, mutation_size=4, crossover_size=4, algorithm=3) _, best_individual = ga_search.search(n_generations=4) assert sum([best_individual[i] for i in best_individual]) <= 200
30.163636
72
0.517782
import pytest from chemml.optimization import GeneticAlgorithm space = ({'alpha': {'uniform': [-20, 0], 'mutation': [0, 2]}}, {'neurons': {'int': [0,10]}}, {'act': {'choice':range(0,100,5)}}) def evaluate(individual): return sum(individual) def test_algorithms(): al = [3] for i in al: ga_search = GeneticAlgorithm( evaluate, space=space, pop_size=10, mutation_size=4, crossover_size=4, algorithm=i) _, best_individual = ga_search.search(n_generations=4) assert sum([best_individual[i] for i in best_individual]) <= 200 def test_sequential_min(): ga_search = GeneticAlgorithm(evaluate, fitness=("min", ), space=space, pop_size=10, mutation_size=5, crossover_size=5, algorithm=3) for _ in range(4): _, best_individual = ga_search.search(n_generations=1) assert sum([best_individual[i] for i in best_individual]) <= 200 def test_crossovers(): co = ['SinglePoint', 'DoublePoint', 'Blend'] for c in co: ga_search = GeneticAlgorithm( evaluate, space=space, crossover_type=c, pop_size=10, mutation_size=4, crossover_size=4, algorithm=3) _, best_individual = ga_search.search(n_generations=4) assert sum([best_individual[i] for i in best_individual]) <= 200
true
true
1c44335e84dfb5cd043b5622e45e9e7089d0a86c
1,232
py
Python
2016/day_13.py
viddrobnic/adventofcode
8f06f4ad3ed6744d20d222b050a15b8ff0ff9c82
[ "MIT" ]
null
null
null
2016/day_13.py
viddrobnic/adventofcode
8f06f4ad3ed6744d20d222b050a15b8ff0ff9c82
[ "MIT" ]
null
null
null
2016/day_13.py
viddrobnic/adventofcode
8f06f4ad3ed6744d20d222b050a15b8ff0ff9c82
[ "MIT" ]
1
2020-12-01T16:49:12.000Z
2020-12-01T16:49:12.000Z
from queue import Queue seed = 1362 seen = set() def is_empty(x, y): n = x*x + 3*x + 2*x*y + y + y*y + seed return bin(n).count('1') % 2 == 0 def valid_moves(x, y): result = [] actions = [-1, 1] for action in actions: new_x = x + action if x > 0 and is_empty(new_x, y) and (new_x, y) not in seen: result.append((new_x, y)) new_y = y + action if y > 0 and is_empty(x, new_y) and (x, new_y) not in seen: result.append((x, new_y)) return result state = { 'coords': (1, 1), 'moves': 0 } que = Queue() que.put(state) locations = 0 solved_1 = False solved_2 = False while not solved_1 or not solved_2: current_state = que.get() moves = current_state['moves'] if current_state['coords'] in seen: continue seen.add(current_state['coords']) if current_state['coords'] == (31, 39): solved_1 = True print('#1:', moves) possible_moves = valid_moves(*current_state['coords']) for move in possible_moves: new_state = {'coords': move, 'moves': moves + 1} que.put(new_state) if moves <= 50: locations += 1 else: solved_2 = True print('#2:', locations)
20.196721
67
0.564935
from queue import Queue seed = 1362 seen = set() def is_empty(x, y): n = x*x + 3*x + 2*x*y + y + y*y + seed return bin(n).count('1') % 2 == 0 def valid_moves(x, y): result = [] actions = [-1, 1] for action in actions: new_x = x + action if x > 0 and is_empty(new_x, y) and (new_x, y) not in seen: result.append((new_x, y)) new_y = y + action if y > 0 and is_empty(x, new_y) and (x, new_y) not in seen: result.append((x, new_y)) return result state = { 'coords': (1, 1), 'moves': 0 } que = Queue() que.put(state) locations = 0 solved_1 = False solved_2 = False while not solved_1 or not solved_2: current_state = que.get() moves = current_state['moves'] if current_state['coords'] in seen: continue seen.add(current_state['coords']) if current_state['coords'] == (31, 39): solved_1 = True print('#1:', moves) possible_moves = valid_moves(*current_state['coords']) for move in possible_moves: new_state = {'coords': move, 'moves': moves + 1} que.put(new_state) if moves <= 50: locations += 1 else: solved_2 = True print('#2:', locations)
true
true
1c4433f0812e9b10a3f57fc23795522eae70a302
1,207
py
Python
tempest/services/volume/json/admin/volume_services_client.py
midokura/tempest
b0ec1d280f057d5d9c2eda081bcbda7e381ecb3b
[ "Apache-2.0" ]
null
null
null
tempest/services/volume/json/admin/volume_services_client.py
midokura/tempest
b0ec1d280f057d5d9c2eda081bcbda7e381ecb3b
[ "Apache-2.0" ]
null
null
null
tempest/services/volume/json/admin/volume_services_client.py
midokura/tempest
b0ec1d280f057d5d9c2eda081bcbda7e381ecb3b
[ "Apache-2.0" ]
null
null
null
# Copyright 2014 NEC Corporation # 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 json import urllib from tempest.common import service_client class BaseVolumesServicesClientJSON(service_client.ServiceClient): def list_services(self, params=None): url = 'os-services' if params: url += '?%s' % urllib.urlencode(params) resp, body = self.get(url) body = json.loads(body) self.expected_success(200, resp.status) return service_client.ResponseBodyList(resp, body['services']) class VolumesServicesClientJSON(BaseVolumesServicesClientJSON): """Volume V1 volume services client"""
32.621622
78
0.714996
import json import urllib from tempest.common import service_client class BaseVolumesServicesClientJSON(service_client.ServiceClient): def list_services(self, params=None): url = 'os-services' if params: url += '?%s' % urllib.urlencode(params) resp, body = self.get(url) body = json.loads(body) self.expected_success(200, resp.status) return service_client.ResponseBodyList(resp, body['services']) class VolumesServicesClientJSON(BaseVolumesServicesClientJSON):
true
true
1c4434aaeea67d038888d9e299fd5181e631f135
137
py
Python
tests/test_placeholder.py
bveeramani/sysx
ca67995d4fafb5280d16ccb3825cdd6c2a7c7e48
[ "Apache-2.0" ]
null
null
null
tests/test_placeholder.py
bveeramani/sysx
ca67995d4fafb5280d16ccb3825cdd6c2a7c7e48
[ "Apache-2.0" ]
null
null
null
tests/test_placeholder.py
bveeramani/sysx
ca67995d4fafb5280d16ccb3825cdd6c2a7c7e48
[ "Apache-2.0" ]
null
null
null
"""A placeholder test to prevent pytest from erroring.""" def test_placeholder(): """Test that 1 + 1 = 2.""" assert 1 + 1 == 2
19.571429
57
0.59854
def test_placeholder(): assert 1 + 1 == 2
true
true
1c443523f65f5f8c973e9eb58b9cf057505dc784
630
py
Python
tests/unit/db/test_users.py
jaimecruz21/lifeloopweb
ba0ffe1ea94ba3323a4e9c66c9506a338cae3212
[ "MIT" ]
null
null
null
tests/unit/db/test_users.py
jaimecruz21/lifeloopweb
ba0ffe1ea94ba3323a4e9c66c9506a338cae3212
[ "MIT" ]
null
null
null
tests/unit/db/test_users.py
jaimecruz21/lifeloopweb
ba0ffe1ea94ba3323a4e9c66c9506a338cae3212
[ "MIT" ]
null
null
null
import pytest from lifeloopweb.db.models import User from lifeloopweb import exception import tests class TestUser(tests.TestBase): def test_get_email_from_full_name_and_email(self): full_name_and_email = "Jason Meridth (jason@meridth.io)" result = User.get_email_from_full_name_and_email( full_name_and_email) assert result == 'jason@meridth.io' def test_get_email_from_full_name_and_email_with_invalid_email(self): full_name_and_email = "invalid" with pytest.raises(exception.InvalidEmail): User.get_email_from_full_name_and_email(full_name_and_email)
33.157895
73
0.757143
import pytest from lifeloopweb.db.models import User from lifeloopweb import exception import tests class TestUser(tests.TestBase): def test_get_email_from_full_name_and_email(self): full_name_and_email = "Jason Meridth (jason@meridth.io)" result = User.get_email_from_full_name_and_email( full_name_and_email) assert result == 'jason@meridth.io' def test_get_email_from_full_name_and_email_with_invalid_email(self): full_name_and_email = "invalid" with pytest.raises(exception.InvalidEmail): User.get_email_from_full_name_and_email(full_name_and_email)
true
true
1c443672071b863adb6d9fc4151f01406c3f4e08
1,165
py
Python
funcstructs/prototypes/necklace_groups.py
caleblevy/endofunction-structures
084ddeab8d12307dd95b8727190c589a1bf659df
[ "MIT" ]
5
2015-05-06T05:08:26.000Z
2017-04-21T03:32:13.000Z
funcstructs/prototypes/necklace_groups.py
caleblevy/endofunction-structures
084ddeab8d12307dd95b8727190c589a1bf659df
[ "MIT" ]
null
null
null
funcstructs/prototypes/necklace_groups.py
caleblevy/endofunction-structures
084ddeab8d12307dd95b8727190c589a1bf659df
[ "MIT" ]
null
null
null
"""Caleb Levy, 2015.""" from funcstructs.structures import necklaces from funcstructs import combinat from . import polynomials, integer_partitions def count_by_period(beads): return necklaces.FixedContentNecklaces(beads).count_by_period() def period_combos(beads, reps): """All possible combinations of periods from given counts by period""" necklace_counts = count_by_period(beads) periods = [i for i, val in enumerate(necklace_counts) if val] for part in integer_partitions.max_length_partitions(reps, len(periods)): for combo in polynomials.multisets_with_multiplicities(periods, part): yield combo def period_combo_count(necklace_counts, combo): """Number of necklaces from a combination of periods""" val = 1 for period, mult in combo.items(): val *= combinat.nCWRk(necklace_counts[period], mult) return val def necklace_groups_by_period_combo(beads, reps): """Return generator yield pairs of period groups and their counts""" necklace_counts = count_by_period(beads) for combo in period_combos(beads, reps): yield combo, period_combo_count(necklace_counts, combo)
33.285714
78
0.744206
from funcstructs.structures import necklaces from funcstructs import combinat from . import polynomials, integer_partitions def count_by_period(beads): return necklaces.FixedContentNecklaces(beads).count_by_period() def period_combos(beads, reps): necklace_counts = count_by_period(beads) periods = [i for i, val in enumerate(necklace_counts) if val] for part in integer_partitions.max_length_partitions(reps, len(periods)): for combo in polynomials.multisets_with_multiplicities(periods, part): yield combo def period_combo_count(necklace_counts, combo): val = 1 for period, mult in combo.items(): val *= combinat.nCWRk(necklace_counts[period], mult) return val def necklace_groups_by_period_combo(beads, reps): necklace_counts = count_by_period(beads) for combo in period_combos(beads, reps): yield combo, period_combo_count(necklace_counts, combo)
true
true
1c443772534ffc1c373c281238456b449eecb7ea
309
py
Python
samples/frontend/manage.py
liuyu81/datagator-contrib
813529e211f680732bd1dc9568f5b4f2bdcacdcc
[ "Apache-2.0" ]
2
2015-02-20T02:50:07.000Z
2017-05-02T19:26:42.000Z
samples/frontend/manage.py
liuyu81/datagator-contrib
813529e211f680732bd1dc9568f5b4f2bdcacdcc
[ "Apache-2.0" ]
null
null
null
samples/frontend/manage.py
liuyu81/datagator-contrib
813529e211f680732bd1dc9568f5b4f2bdcacdcc
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DATAGATOR_DEVELOP", "1") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "datagator.wsgi.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
25.75
78
0.763754
import os import sys if __name__ == "__main__": os.environ.setdefault("DATAGATOR_DEVELOP", "1") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "datagator.wsgi.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
true
true
1c4437932e33a6e182efd278f5f9d445858bdcb6
1,021
py
Python
main.py
SamAlhabash/fast-api-with-mongodb
20f5b05f37fda088ffcd6479d79847234ffc1370
[ "MIT" ]
null
null
null
main.py
SamAlhabash/fast-api-with-mongodb
20f5b05f37fda088ffcd6479d79847234ffc1370
[ "MIT" ]
null
null
null
main.py
SamAlhabash/fast-api-with-mongodb
20f5b05f37fda088ffcd6479d79847234ffc1370
[ "MIT" ]
null
null
null
from fastapi import FastAPI from config.config import settings from starlette.middleware.cors import CORSMiddleware from api.api_v1.api import api_router from api.api_v1.services.database import connect_db, close_db import uvicorn app = FastAPI( title=settings.PROJECT_NAME, description=settings.PROJECT_DESC, version=settings.PROJECT_VERSION, openapi_url="/open-api.json", docs_url="/swagger", redoc_url="/redoc" ) if settings.BACKEND_CORS_ORIGINS: app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.add_event_handler("startup", connect_db) app.add_event_handler("shutdown", close_db) app.include_router(api_router, prefix=settings.API_V1_STR) if __name__ == '__main__': uvicorn.run(app='main:app', host="0.0.0.0", port=8000, reload=True)
28.361111
68
0.688541
from fastapi import FastAPI from config.config import settings from starlette.middleware.cors import CORSMiddleware from api.api_v1.api import api_router from api.api_v1.services.database import connect_db, close_db import uvicorn app = FastAPI( title=settings.PROJECT_NAME, description=settings.PROJECT_DESC, version=settings.PROJECT_VERSION, openapi_url="/open-api.json", docs_url="/swagger", redoc_url="/redoc" ) if settings.BACKEND_CORS_ORIGINS: app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.add_event_handler("startup", connect_db) app.add_event_handler("shutdown", close_db) app.include_router(api_router, prefix=settings.API_V1_STR) if __name__ == '__main__': uvicorn.run(app='main:app', host="0.0.0.0", port=8000, reload=True)
true
true
1c4437a501f34a54f0bce2a6c39e661634304ed4
415
py
Python
api/urls.py
GomaGoma676/ScrumTaskApi_Backend
f977f6fae514ee92f3f37b94c052d953b8dcc693
[ "MIT" ]
1
2020-11-03T10:17:48.000Z
2020-11-03T10:17:48.000Z
api/urls.py
GomaGoma676/ScrumTaskApi_Backend
f977f6fae514ee92f3f37b94c052d953b8dcc693
[ "MIT" ]
null
null
null
api/urls.py
GomaGoma676/ScrumTaskApi_Backend
f977f6fae514ee92f3f37b94c052d953b8dcc693
[ "MIT" ]
1
2021-03-20T15:24:42.000Z
2021-03-20T15:24:42.000Z
from django.urls import path from django.conf.urls import include from rest_framework import routers from .views import TaskViewSet, UserViewSet, SprintViewSet, TagViewSet router = routers.DefaultRouter() router.register('users', UserViewSet) router.register('tasks', TaskViewSet) router.register('sprints', SprintViewSet) router.register('tags', TagViewSet) urlpatterns = [ path('', include(router.urls)), ]
27.666667
70
0.785542
from django.urls import path from django.conf.urls import include from rest_framework import routers from .views import TaskViewSet, UserViewSet, SprintViewSet, TagViewSet router = routers.DefaultRouter() router.register('users', UserViewSet) router.register('tasks', TaskViewSet) router.register('sprints', SprintViewSet) router.register('tags', TagViewSet) urlpatterns = [ path('', include(router.urls)), ]
true
true
1c44380bc3440a460421d22b63007e3644b1af03
587
py
Python
python_script.py
benjiyo/computer_usage_statistics
e53cd5facdbec34062b092eabeb0121f1727e36f
[ "MIT" ]
1
2016-12-08T14:10:06.000Z
2016-12-08T14:10:06.000Z
python_script.py
benjiyo/computer_usage_statistics
e53cd5facdbec34062b092eabeb0121f1727e36f
[ "MIT" ]
null
null
null
python_script.py
benjiyo/computer_usage_statistics
e53cd5facdbec34062b092eabeb0121f1727e36f
[ "MIT" ]
null
null
null
#!/usr/bin/env python # Call this script with "hour" as argument # Use the file "bash_script" to call this script import sys hour = int(sys.argv[1]) with open('PATH_TO_REPOSITORY/histogram.txt', 'r') as myfile: data = myfile.read() newdata = data.splitlines() newdata[hour] = int(newdata[hour]) + 1 tmpstr = str(newdata) tmpstr = tmpstr.replace("'","") tmpstr = tmpstr.replace(" ","") tmpstr = tmpstr.replace(",","\n") tmpstr = tmpstr.replace("[",""); tmpstr = tmpstr.replace("]",""); with open('PATH_TO_REPOSITORY/histogram.txt', 'w') as myfile: myfile.write(tmpstr)
23.48
61
0.667802
import sys hour = int(sys.argv[1]) with open('PATH_TO_REPOSITORY/histogram.txt', 'r') as myfile: data = myfile.read() newdata = data.splitlines() newdata[hour] = int(newdata[hour]) + 1 tmpstr = str(newdata) tmpstr = tmpstr.replace("'","") tmpstr = tmpstr.replace(" ","") tmpstr = tmpstr.replace(",","\n") tmpstr = tmpstr.replace("[",""); tmpstr = tmpstr.replace("]",""); with open('PATH_TO_REPOSITORY/histogram.txt', 'w') as myfile: myfile.write(tmpstr)
true
true
1c4438564c78ea33e922ec1b15a0905f72d7a386
3,669
py
Python
Tests/test_weakset_stdlib.py
pxl9588/ironpython3
3417b2d29f4116b8f44af31defb9a098686cd566
[ "Apache-2.0" ]
1
2019-06-27T13:04:33.000Z
2019-06-27T13:04:33.000Z
Tests/test_weakset_stdlib.py
pxl9588/ironpython3
3417b2d29f4116b8f44af31defb9a098686cd566
[ "Apache-2.0" ]
null
null
null
Tests/test_weakset_stdlib.py
pxl9588/ironpython3
3417b2d29f4116b8f44af31defb9a098686cd566
[ "Apache-2.0" ]
null
null
null
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. ## ## Run selected tests from test_weakset from StdLib ## import unittest import sys from iptest import run_test import test.test_weakset def load_tests(loader, standard_tests, pattern): if sys.implementation.name == 'ironpython': suite = unittest.TestSuite() suite.addTest(test.test_weakset.TestWeakSet('test_add')) suite.addTest(test.test_weakset.TestWeakSet('test_and')) suite.addTest(test.test_weakset.TestWeakSet('test_clear')) suite.addTest(test.test_weakset.TestWeakSet('test_constructor_identity')) suite.addTest(test.test_weakset.TestWeakSet('test_contains')) suite.addTest(test.test_weakset.TestWeakSet('test_copy')) suite.addTest(test.test_weakset.TestWeakSet('test_difference')) suite.addTest(test.test_weakset.TestWeakSet('test_difference_update')) suite.addTest(test.test_weakset.TestWeakSet('test_discard')) suite.addTest(test.test_weakset.TestWeakSet('test_eq')) suite.addTest(test.test_weakset.TestWeakSet('test_gc')) suite.addTest(test.test_weakset.TestWeakSet('test_gt')) suite.addTest(test.test_weakset.TestWeakSet('test_hash')) suite.addTest(test.test_weakset.TestWeakSet('test_iand')) suite.addTest(test.test_weakset.TestWeakSet('test_init')) suite.addTest(test.test_weakset.TestWeakSet('test_inplace_on_self')) suite.addTest(test.test_weakset.TestWeakSet('test_intersection')) suite.addTest(test.test_weakset.TestWeakSet('test_intersection_update')) suite.addTest(test.test_weakset.TestWeakSet('test_ior')) suite.addTest(test.test_weakset.TestWeakSet('test_isdisjoint')) suite.addTest(test.test_weakset.TestWeakSet('test_isub')) suite.addTest(test.test_weakset.TestWeakSet('test_ixor')) suite.addTest(test.test_weakset.TestWeakSet('test_len')) #suite.addTest(test.test_weakset.TestWeakSet('test_len_cycles')) suite.addTest(test.test_weakset.TestWeakSet('test_len_race')) suite.addTest(test.test_weakset.TestWeakSet('test_lt')) suite.addTest(test.test_weakset.TestWeakSet('test_methods')) suite.addTest(test.test_weakset.TestWeakSet('test_ne')) suite.addTest(test.test_weakset.TestWeakSet('test_new_or_init')) suite.addTest(test.test_weakset.TestWeakSet('test_or')) suite.addTest(test.test_weakset.TestWeakSet('test_pop')) suite.addTest(test.test_weakset.TestWeakSet('test_remove')) suite.addTest(test.test_weakset.TestWeakSet('test_sub')) suite.addTest(test.test_weakset.TestWeakSet('test_sub_and_super')) suite.addTest(test.test_weakset.TestWeakSet('test_subclass_with_custom_hash')) suite.addTest(test.test_weakset.TestWeakSet('test_symmetric_difference')) suite.addTest(test.test_weakset.TestWeakSet('test_symmetric_difference_update')) suite.addTest(test.test_weakset.TestWeakSet('test_union')) suite.addTest(test.test_weakset.TestWeakSet('test_update')) suite.addTest(test.test_weakset.TestWeakSet('test_update_set')) #suite.addTest(test.test_weakset.TestWeakSet('test_weak_destroy_and_mutate_while_iterating')) suite.addTest(test.test_weakset.TestWeakSet('test_weak_destroy_while_iterating')) suite.addTest(test.test_weakset.TestWeakSet('test_xor')) return suite else: return loader.loadTestsFromModule(test.test_weakset, pattern) run_test(__name__)
53.955882
101
0.746525
un_test import test.test_weakset def load_tests(loader, standard_tests, pattern): if sys.implementation.name == 'ironpython': suite = unittest.TestSuite() suite.addTest(test.test_weakset.TestWeakSet('test_add')) suite.addTest(test.test_weakset.TestWeakSet('test_and')) suite.addTest(test.test_weakset.TestWeakSet('test_clear')) suite.addTest(test.test_weakset.TestWeakSet('test_constructor_identity')) suite.addTest(test.test_weakset.TestWeakSet('test_contains')) suite.addTest(test.test_weakset.TestWeakSet('test_copy')) suite.addTest(test.test_weakset.TestWeakSet('test_difference')) suite.addTest(test.test_weakset.TestWeakSet('test_difference_update')) suite.addTest(test.test_weakset.TestWeakSet('test_discard')) suite.addTest(test.test_weakset.TestWeakSet('test_eq')) suite.addTest(test.test_weakset.TestWeakSet('test_gc')) suite.addTest(test.test_weakset.TestWeakSet('test_gt')) suite.addTest(test.test_weakset.TestWeakSet('test_hash')) suite.addTest(test.test_weakset.TestWeakSet('test_iand')) suite.addTest(test.test_weakset.TestWeakSet('test_init')) suite.addTest(test.test_weakset.TestWeakSet('test_inplace_on_self')) suite.addTest(test.test_weakset.TestWeakSet('test_intersection')) suite.addTest(test.test_weakset.TestWeakSet('test_intersection_update')) suite.addTest(test.test_weakset.TestWeakSet('test_ior')) suite.addTest(test.test_weakset.TestWeakSet('test_isdisjoint')) suite.addTest(test.test_weakset.TestWeakSet('test_isub')) suite.addTest(test.test_weakset.TestWeakSet('test_ixor')) suite.addTest(test.test_weakset.TestWeakSet('test_len')) suite.addTest(test.test_weakset.TestWeakSet('test_len_race')) suite.addTest(test.test_weakset.TestWeakSet('test_lt')) suite.addTest(test.test_weakset.TestWeakSet('test_methods')) suite.addTest(test.test_weakset.TestWeakSet('test_ne')) suite.addTest(test.test_weakset.TestWeakSet('test_new_or_init')) suite.addTest(test.test_weakset.TestWeakSet('test_or')) suite.addTest(test.test_weakset.TestWeakSet('test_pop')) suite.addTest(test.test_weakset.TestWeakSet('test_remove')) suite.addTest(test.test_weakset.TestWeakSet('test_sub')) suite.addTest(test.test_weakset.TestWeakSet('test_sub_and_super')) suite.addTest(test.test_weakset.TestWeakSet('test_subclass_with_custom_hash')) suite.addTest(test.test_weakset.TestWeakSet('test_symmetric_difference')) suite.addTest(test.test_weakset.TestWeakSet('test_symmetric_difference_update')) suite.addTest(test.test_weakset.TestWeakSet('test_union')) suite.addTest(test.test_weakset.TestWeakSet('test_update')) suite.addTest(test.test_weakset.TestWeakSet('test_update_set')) suite.addTest(test.test_weakset.TestWeakSet('test_weak_destroy_while_iterating')) suite.addTest(test.test_weakset.TestWeakSet('test_xor')) return suite else: return loader.loadTestsFromModule(test.test_weakset, pattern) run_test(__name__)
true
true
1c44391f7131c3bfff778a039706cd9754d9e372
890
py
Python
examples/pybullet/examples/switchConstraintSolver.py
stolk/bullet3
41a0d72759a47ef2df986b0bfe56a03e22516123
[ "Zlib" ]
158
2016-11-17T19:37:51.000Z
2022-03-21T19:57:55.000Z
examples/pybullet/examples/switchConstraintSolver.py
stolk/bullet3
41a0d72759a47ef2df986b0bfe56a03e22516123
[ "Zlib" ]
94
2016-11-18T09:55:57.000Z
2021-01-14T08:50:40.000Z
examples/pybullet/examples/switchConstraintSolver.py
stolk/bullet3
41a0d72759a47ef2df986b0bfe56a03e22516123
[ "Zlib" ]
51
2017-05-24T10:20:25.000Z
2022-03-17T15:07:02.000Z
import pybullet as p import time p.connect(p.GUI) #p.setPhysicsEngineParameter(constraintSolverType=p.CONSTRAINT_SOLVER_LCP_PGS, globalCFM = 0.0001) p.setPhysicsEngineParameter(constraintSolverType=p.CONSTRAINT_SOLVER_LCP_DANTZIG, globalCFM=0.000001) #p.setPhysicsEngineParameter(constraintSolverType=p.CONSTRAINT_SOLVER_LCP_PGS, globalCFM = 0.0001) p.loadURDF("plane.urdf") radius = 0.025 distance = 1.86 yaw = 135 pitch = -11 targetPos = [0, 0, 0] p.setPhysicsEngineParameter(solverResidualThreshold=0.001, numSolverIterations=200) p.resetDebugVisualizerCamera(distance, yaw, pitch, targetPos) objectId = -1 for i in range(10): objectId = p.loadURDF("cube_small.urdf", [1, 1, radius + i * 2 * radius]) p.changeDynamics(objectId, -1, 100) timeStep = 1. / 240. p.setGravity(0, 0, -10) while (p.isConnected()): p.stepSimulation() time.sleep(timeStep)
28.709677
98
0.748315
import pybullet as p import time p.connect(p.GUI) p.setPhysicsEngineParameter(constraintSolverType=p.CONSTRAINT_SOLVER_LCP_DANTZIG, globalCFM=0.000001) p.loadURDF("plane.urdf") radius = 0.025 distance = 1.86 yaw = 135 pitch = -11 targetPos = [0, 0, 0] p.setPhysicsEngineParameter(solverResidualThreshold=0.001, numSolverIterations=200) p.resetDebugVisualizerCamera(distance, yaw, pitch, targetPos) objectId = -1 for i in range(10): objectId = p.loadURDF("cube_small.urdf", [1, 1, radius + i * 2 * radius]) p.changeDynamics(objectId, -1, 100) timeStep = 1. / 240. p.setGravity(0, 0, -10) while (p.isConnected()): p.stepSimulation() time.sleep(timeStep)
true
true
1c4439485e85dc067e2ce19d19190057cd711a5a
13,225
py
Python
project/Python Code/implementations.py
parkjan4/HiggsBoson
1e31f9bd2c6cb03c6acc8caed573046bbc0d2c08
[ "MIT" ]
null
null
null
project/Python Code/implementations.py
parkjan4/HiggsBoson
1e31f9bd2c6cb03c6acc8caed573046bbc0d2c08
[ "MIT" ]
null
null
null
project/Python Code/implementations.py
parkjan4/HiggsBoson
1e31f9bd2c6cb03c6acc8caed573046bbc0d2c08
[ "MIT" ]
null
null
null
from proj1_helpers import * import numpy as np import random import matplotlib.pyplot as plt ######################### Loss Functions ######################### # Compute loss with Mean Squared Error def compute_loss(y, tx, w): e = y.reshape((len(y),1)) - tx.dot(w).reshape((len(y),1)) return 1/2*np.mean(e**2) # Compute gradient for gradient descent def compute_gradient(y, tx, w): e = y.reshape((len(y),1)) - tx.dot(w).reshape((len(y),1)) grad = -tx.T.dot(e) / len(e) return grad def sigmoid(x): return 1.0 / (1 + np.exp(-x)) def compute_loss_logistic(y, tx, w): # loss formula works only for y = {0,1} y[y == -1] = 0 y = y.reshape((len(y),1)) sigma = sigmoid(tx.dot(w)).reshape((len(y),1)) loss = y.T.dot(np.log(sigma)) + (1 - y).T.dot(np.log(1 - sigma)) return np.squeeze(- loss) def compute_gradient_logistic(y, tx, w): sigma = sigmoid(tx.dot(w)).reshape((len(y),1)) y = y.reshape((len(sigma),1)) grad = tx.T.dot(sigma - y) return grad ######################### Methods Implementation ######################### # Gradient Descent def least_squares_GD(y, tx, initial_w, max_iters, gamma): ws = [initial_w] losses = [] w = initial_w for n_iter in range(max_iters): gradient = compute_gradient(y, tx, w) loss = compute_loss(y, tx, w) w = w - gamma * gradient ws.append(w) losses.append(loss) return ws[-1], losses[-1] # Stochastic Gradient Descent def least_squares_SGD(y, tx, initial_w, max_iters, gamma): ws = [initial_w] losses = [] w = initial_w n_iter = 0 batch_size = 1 for batch_y, batch_tx in batch_iter(y, tx, batch_size, max_iters): grad = compute_gradient(batch_y, batch_tx, w) loss = compute_loss(batch_y, batch_tx, w) w = w - gamma * grad ws.append(w) losses.append(loss) n_iter += 1 return ws[-1], losses[-1] def least_squares(y, tx): w = np.linalg.solve(tx.T.dot(tx), tx.T.dot(y)) loss = compute_loss(y, tx ,w) return w, loss def ridge_regression(y, tx, lambda_): w = np.linalg.solve(tx.T.dot(tx) + lambda_ * np.eye(tx.shape[1]), tx.T.dot(y)) loss = compute_loss(y, tx, w) return w, loss def logistic_regression(y, tx, w, max_iters, gamma): for n_iter in range(max_iters): loss = compute_loss_logistic(y, tx, w) grad = compute_gradient_logistic(y, tx, w) w -= gamma * grad return w, loss def reg_logistic_regression(y, tx, lambda_, w, max_iters, gamma): for n_iter in range(max_iters): loss = compute_loss_logistic(y, tx, w) + lambda_ * np.squeeze(w.T.dot(w)) grad = compute_gradient_logistic(y, tx, w) + 2 * lambda_ * w w -= gamma * grad return w, loss ######################### Improvements ######################### def RR_optimal_lambda_finder(y, tx, learning_algo): k_folds = 10 lambdas = np.logspace(-4,0,30) seeds = range(10) # define an empty matrix to store cross validation errors CV_errors = np.empty((len(seeds), len(lambdas)), dtype=float) for i, seed in enumerate(seeds): for j, lambda_ in enumerate(lambdas): errors = cross_validation(y, tx, k_folds, learning_algo, lambda_, seed) CV_error = np.mean(errors) CV_errors[i, j] = CV_error best_accuracy = max(np.mean(CV_errors, axis=0)) opt_lambda = lambdas[np.argmax(np.mean(CV_errors, axis=0))] return opt_lambda, best_accuracy def build_poly(x, degree): """polynomial basis functions for input data x, for j=0 up to j=degree.""" poly = np.ones((len(x), 1)) for deg in range(1, degree+1): poly = np.c_[poly, np.power(x, deg)] return poly[:,1:] def interaction_forward_selection(y, tx): '''For every possible 2nd order interaction term, add to the original \ feature set iff its inclusion leads to higher accuracy based on 5-fold CV''' # define reference accuracy (with NO interaction terms) reference = np.mean(cross_validation(y, tx, 5, least_squares, 0, 1)) # define list to store feature indices whose interaction is useful interaction_terms = [] counter = 0 num_features = 30 # original number of features for col1 in range(num_features): for col2 in range(num_features): if col1 >= col2: continue temp_tx = np.c_[tx, tx[:,col1] * tx[:,col2]] accuracy = np.mean(cross_validation(y, temp_tx, 5, least_squares, 0, 1)) # if new accuracy is higher, add the term if accuracy > reference: reference = accuracy tx = temp_tx interaction_terms.append((col1, col2)) counter += 1 print("{p:.2f}% complete, best accuracy: {a:.9f}".format(p=100* counter / 435, a=reference)) return tx, interaction_terms def third_interaction_forward_selection(y, tx): '''For every possible 3rd order interaction term, add to the original \ feature set iff its inclusion leads to higher accuracy based on 5-fold CV''' # define reference accuracy (with NO interaction terms) reference = np.mean(cross_validation(y, tx, 5, least_squares, 0, 1)) # define list to store feature indices whose interaction is useful third_interaction_terms = [] counter = 0 # delete this line num_features = 30 # original number of features for col1 in range(num_features): for col2 in range(num_features): if col1 >= col2: continue for col3 in range(num_features): if col2 >= col3: continue temp_tx = np.c_[tx, tx[:,col1] * tx[:,col2] * tx[:,col3]] accuracy = np.mean(cross_validation(y, temp_tx, 5, least_squares, 0, 1)) # if new accuracy is higher, add the term if accuracy > reference: reference = accuracy tx = temp_tx third_interaction_terms.append((col1, col2, col3)) counter += 1 # delete this line print("{p:.2f}% complete, best accuracy: {a:.9f}".format(p=100* counter / 4060, a=reference)) return tx, third_interaction_terms def build_k_indices(y, k_fold, seed): """build k indices for k-fold.""" num_row = y.shape[0] interval = int(num_row / k_fold) np.random.seed(seed) indices = np.random.permutation(num_row) k_indices = [indices[k * interval: (k + 1) * interval] for k in range(k_fold)] return np.array(k_indices) def cross_validation(y, tx, k_folds, learning_algo, lambda_, seed): # build k_folds instances of indices k_indices = build_k_indices(y, k_folds, seed) # define list to store cross validation error errors = [] for k in range(k_folds): tx_valid = tx[k_indices[k,:]] y_valid = y[k_indices[k,:]] tx_train = tx[k_indices[list(set(range(k_indices.shape[0])) - set([k])),:].reshape((k_indices.shape[0]-1)*k_indices.shape[1]),:] y_train = y[k_indices[list(set(range(k_indices.shape[0])) - set([k])),:].reshape((k_indices.shape[0]-1)*k_indices.shape[1])] # least squares using normal equations if learning_algo == least_squares: w, loss_tr = learning_algo(y_train, tx_train) # ridge regression using normal equations elif learning_algo == ridge_regression: w, loss_tr = learning_algo(y_train, tx_train, lambda_) # least squares gradient descent elif learning_algo == least_squares_GD: initial_w = np.zeros((tx.shape[1],1)) max_iters = 1000 gamma = 0.0000001 w, loss_tr = learning_algo(y_train, tx_train, initial_w, max_iters, gamma) # least squares stochastic gradient descent elif learning_algo == least_squares_SGD: initial_w = np.zeros((tx.shape[1],1)) max_iters = 1000 gamma = 0.0000001 w, loss_tr = learning_algo(y_train, tx_train, initial_w, max_iters, gamma) # logistic regression gradient descent elif learning_algo == logistic_regression: initial_w = np.zeros((tx.shape[1],1)) max_iters = 500 gamma = 0.000000000000001 w, loss_tr = learning_algo(y_train, tx_train, initial_w, max_iters, gamma) # regularized logistic regression gradient descent elif learning_algo == reg_logistic_regression: initial_w = np.zeros((tx.shape[1],1)) max_iters = 500 gamma = 0.000000000000001 w, loss_tr = learning_algo(y_train, tx_train, lambda_, initial_w, max_iters, gamma) y_hat = predict_labels(w, tx_valid) errors.append(sum(y_valid.reshape((len(y_valid),1))==y_hat.reshape((len(y_hat),1))) / len(y_valid)) # return the average error rate across the folds return errors def data_segmentation(y, tx): ''' PRI_jet_num is a feature which only takes a value of 0, 1, 2, or 3. Many features become undefined (-999) based on which value it takes. The purpose of this function is to split the data based on the four values. Source: http://opendata.cern.ch/record/328 Input: y: reponse tx: data matrix Returns: four sets of response and data matrices segmented based on PRI_jet_num ''' # data segmentation temp_matrix = np.c_[y, tx] indices_0 = temp_matrix[:,23]==0 temp_matrix_0 = temp_matrix[indices_0,:] y_0 = temp_matrix_0[:,0] tx_0 = temp_matrix_0[:,1:] indices_1 = temp_matrix[:,23]==1 temp_matrix_1 = temp_matrix[indices_1,:] y_1 = temp_matrix_1[:,0] tx_1 = temp_matrix_1[:,1:] indices_2 = temp_matrix[:,23]==2 temp_matrix_2 = temp_matrix[indices_2,:] y_2 = temp_matrix_2[:,0] tx_2 = temp_matrix_2[:,1:] indices_3 = temp_matrix[:,23]==3 temp_matrix_3 = temp_matrix[indices_3,:] y_3 = temp_matrix_3[:,0] tx_3 = temp_matrix_3[:,1:] # when PRI_jet_num is 0, the following features are undefined and thus removed tx_0 = np.delete(tx_0, np.s_[4,5,6,12,22,23,24,25,26,27,28,29], axis=1) # when PRI_jet_num is 1, the following features are undefined and thus removed tx_1 = np.delete(tx_1, np.s_[4,5,6,12,22,26,27,28], axis=1) # at least, PRI_jet_num itself is removed tx_2 = np.delete(tx_2, np.s_[22], axis=1) tx_3 = np.delete(tx_3, np.s_[22], axis=1) # replace any remaining -999 values with the mean of that feature tx_0 = replace_with_mean(tx_0) tx_1 = replace_with_mean(tx_1) tx_2 = replace_with_mean(tx_2) tx_3 = replace_with_mean(tx_3) return y_0, tx_0, y_1, tx_1, y_2, tx_2, y_3, tx_3, indices_0, indices_1, indices_2, indices_3 def backward_selection(y, tx): '''Performs backward feature selection using least squares algorithm Input: y: response tx: data matrix Output: new data matrix with (potentially) fewer features''' cols_removed = [] temp_tx, col_removed = backward_selection_algorithm(y, tx) while tx.shape[1] != temp_tx.shape[1]: # means a feature was removed tx = temp_tx cols_removed.append(col_removed) temp_tx, col_removed = backward_selection_algorithm(y, temp_tx) return tx, cols_removed def backward_selection_algorithm(y, tx): k_folds = 10 seed = 1 index_to_remove = [] reference = np.mean(cross_validation(y, tx, k_folds, least_squares, 0.0001, seed)) for c in range(tx.shape[1]): temp_tx = tx[:,list(set(range(tx.shape[1])) - set([c]))] CV_accuracy = np.mean(cross_validation(y, temp_tx, k_folds, least_squares, 0.0001, seed)) if CV_accuracy > reference: reference = CV_accuracy index_to_remove.append(c) if len(index_to_remove) == 0: # means no features were removed return tx, -1 return tx[:,list(set(range(tx.shape[1])) - set([index_to_remove[-1]]))], index_to_remove[-1] def replace_with_mean(tx): '''replace all -999 values with mean value of each column''' for col in range(tx.shape[1]): # find indices for which the value is -999 indices = tx[:,col]==-999 # replace with mean value tx[indices,col] = np.mean(tx[~indices,col]) return tx ######################### Helpers ######################### # Creates batches for stochastic gradient descent def batch_iter(y, tx, batch_size, num_batches=1, shuffle=True): data_size = len(y) if shuffle: shuffle_indices = np.random.permutation(np.arange(data_size)) shuffled_y = y[shuffle_indices] shuffled_tx = tx[shuffle_indices] else: shuffled_y = y shuffled_tx = tx for batch_num in range(num_batches): start_index = batch_num * batch_size end_index = min((batch_num + 1) * batch_size, data_size) if start_index != end_index: yield shuffled_y[start_index:end_index], shuffled_tx[start_index:end_index]
36.035422
136
0.61603
from proj1_helpers import * import numpy as np import random import matplotlib.pyplot as plt ion_terms def build_k_indices(y, k_fold, seed): num_row = y.shape[0] interval = int(num_row / k_fold) np.random.seed(seed) indices = np.random.permutation(num_row) k_indices = [indices[k * interval: (k + 1) * interval] for k in range(k_fold)] return np.array(k_indices) def cross_validation(y, tx, k_folds, learning_algo, lambda_, seed): k_indices = build_k_indices(y, k_folds, seed) errors = [] for k in range(k_folds): tx_valid = tx[k_indices[k,:]] y_valid = y[k_indices[k,:]] tx_train = tx[k_indices[list(set(range(k_indices.shape[0])) - set([k])),:].reshape((k_indices.shape[0]-1)*k_indices.shape[1]),:] y_train = y[k_indices[list(set(range(k_indices.shape[0])) - set([k])),:].reshape((k_indices.shape[0]-1)*k_indices.shape[1])] if learning_algo == least_squares: w, loss_tr = learning_algo(y_train, tx_train) elif learning_algo == ridge_regression: w, loss_tr = learning_algo(y_train, tx_train, lambda_) elif learning_algo == least_squares_GD: initial_w = np.zeros((tx.shape[1],1)) max_iters = 1000 gamma = 0.0000001 w, loss_tr = learning_algo(y_train, tx_train, initial_w, max_iters, gamma) elif learning_algo == least_squares_SGD: initial_w = np.zeros((tx.shape[1],1)) max_iters = 1000 gamma = 0.0000001 w, loss_tr = learning_algo(y_train, tx_train, initial_w, max_iters, gamma) elif learning_algo == logistic_regression: initial_w = np.zeros((tx.shape[1],1)) max_iters = 500 gamma = 0.000000000000001 w, loss_tr = learning_algo(y_train, tx_train, initial_w, max_iters, gamma) elif learning_algo == reg_logistic_regression: initial_w = np.zeros((tx.shape[1],1)) max_iters = 500 gamma = 0.000000000000001 w, loss_tr = learning_algo(y_train, tx_train, lambda_, initial_w, max_iters, gamma) y_hat = predict_labels(w, tx_valid) errors.append(sum(y_valid.reshape((len(y_valid),1))==y_hat.reshape((len(y_hat),1))) / len(y_valid)) return errors def data_segmentation(y, tx): temp_matrix = np.c_[y, tx] indices_0 = temp_matrix[:,23]==0 temp_matrix_0 = temp_matrix[indices_0,:] y_0 = temp_matrix_0[:,0] tx_0 = temp_matrix_0[:,1:] indices_1 = temp_matrix[:,23]==1 temp_matrix_1 = temp_matrix[indices_1,:] y_1 = temp_matrix_1[:,0] tx_1 = temp_matrix_1[:,1:] indices_2 = temp_matrix[:,23]==2 temp_matrix_2 = temp_matrix[indices_2,:] y_2 = temp_matrix_2[:,0] tx_2 = temp_matrix_2[:,1:] indices_3 = temp_matrix[:,23]==3 temp_matrix_3 = temp_matrix[indices_3,:] y_3 = temp_matrix_3[:,0] tx_3 = temp_matrix_3[:,1:] tx_0 = np.delete(tx_0, np.s_[4,5,6,12,22,23,24,25,26,27,28,29], axis=1) tx_1 = np.delete(tx_1, np.s_[4,5,6,12,22,26,27,28], axis=1) tx_2 = np.delete(tx_2, np.s_[22], axis=1) tx_3 = np.delete(tx_3, np.s_[22], axis=1) tx_0 = replace_with_mean(tx_0) tx_1 = replace_with_mean(tx_1) tx_2 = replace_with_mean(tx_2) tx_3 = replace_with_mean(tx_3) return y_0, tx_0, y_1, tx_1, y_2, tx_2, y_3, tx_3, indices_0, indices_1, indices_2, indices_3 def backward_selection(y, tx): cols_removed = [] temp_tx, col_removed = backward_selection_algorithm(y, tx) while tx.shape[1] != temp_tx.shape[1]: tx = temp_tx cols_removed.append(col_removed) temp_tx, col_removed = backward_selection_algorithm(y, temp_tx) return tx, cols_removed def backward_selection_algorithm(y, tx): k_folds = 10 seed = 1 index_to_remove = [] reference = np.mean(cross_validation(y, tx, k_folds, least_squares, 0.0001, seed)) for c in range(tx.shape[1]): temp_tx = tx[:,list(set(range(tx.shape[1])) - set([c]))] CV_accuracy = np.mean(cross_validation(y, temp_tx, k_folds, least_squares, 0.0001, seed)) if CV_accuracy > reference: reference = CV_accuracy index_to_remove.append(c) if len(index_to_remove) == 0: return tx, -1 return tx[:,list(set(range(tx.shape[1])) - set([index_to_remove[-1]]))], index_to_remove[-1] def replace_with_mean(tx): for col in range(tx.shape[1]): indices = tx[:,col]==-999 tx[indices,col] = np.mean(tx[~indices,col]) return tx
true
true
1c443992ade1ebf92009bd9acefe5a6589fee159
652
py
Python
Egzersiz/efecan/FonksiyonEgzersiz.py
ibrahimediz/ornekproje
c5ebeafc43a9c6d2aa639d0d95eedbce65991576
[ "Apache-2.0" ]
null
null
null
Egzersiz/efecan/FonksiyonEgzersiz.py
ibrahimediz/ornekproje
c5ebeafc43a9c6d2aa639d0d95eedbce65991576
[ "Apache-2.0" ]
null
null
null
Egzersiz/efecan/FonksiyonEgzersiz.py
ibrahimediz/ornekproje
c5ebeafc43a9c6d2aa639d0d95eedbce65991576
[ "Apache-2.0" ]
null
null
null
from string import ascii_lowercase,ascii_uppercase,punctuation,digits import random as rnd def passwordfunc (): pwd='' liste = [ascii_lowercase,ascii_uppercase,punctuation,digits] opt=input("uzunluk belirtmek ister misiniz? (yes or no)") if opt =='Yes': lent=input("Şifre uzunluğu ne kadar olsun: ") for _ in range(len(lent)): pwd+=rnd.choice(rnd.choice(liste)) else: for _ in range(15): pwd+=rnd.choice(rnd.choice(liste)) if pwd not in ascii_lowercase and ascii_uppercase and punctuation and digits: return pwd else: passwordfunc () print(passwordfunc ())
29.636364
81
0.659509
from string import ascii_lowercase,ascii_uppercase,punctuation,digits import random as rnd def passwordfunc (): pwd='' liste = [ascii_lowercase,ascii_uppercase,punctuation,digits] opt=input("uzunluk belirtmek ister misiniz? (yes or no)") if opt =='Yes': lent=input("Şifre uzunluğu ne kadar olsun: ") for _ in range(len(lent)): pwd+=rnd.choice(rnd.choice(liste)) else: for _ in range(15): pwd+=rnd.choice(rnd.choice(liste)) if pwd not in ascii_lowercase and ascii_uppercase and punctuation and digits: return pwd else: passwordfunc () print(passwordfunc ())
true
true
1c443a79ec656385843cf4a30bde8b1696a07a76
3,116
py
Python
setup.py
cigroup-ol/metaopt
6dfd5105d3c6eaf00f96670175cae16021069514
[ "BSD-3-Clause" ]
8
2015-02-02T21:42:23.000Z
2019-06-30T18:12:43.000Z
setup.py
cigroup-ol/metaopt
6dfd5105d3c6eaf00f96670175cae16021069514
[ "BSD-3-Clause" ]
4
2015-09-24T14:12:38.000Z
2021-12-08T22:42:52.000Z
setup.py
cigroup-ol/metaopt
6dfd5105d3c6eaf00f96670175cae16021069514
[ "BSD-3-Clause" ]
6
2015-02-27T12:35:33.000Z
2020-10-15T21:04:02.000Z
# -*- coding: utf-8 -*- """setup.py script for MetaOpt.""" from __future__ import division, print_function, with_statement import os import sys try: from setuptools import setup, find_packages except ImportError: import ez_setup ez_setup.use_setuptools() from setuptools import setup, find_packages from pip.req import parse_requirements import metaopt def extract_package_name(requirement): return str(requirement.req).replace('-', '_').split('==')[0] def find_requirements(req_file='requirements.txt'): return [extract_package_name(r) for r in parse_requirements(req_file)] DESCRIPTION = 'MetaOpt is a library that optimizes black-box functions using ' + \ 'a limited amount of time and utilizing multiple processors. ' + \ 'The main focus of MetaOpt is the parameter tuning for machine ' + \ 'learning and heuristic optimization.' if os.path.isfile('README.rst'): LONG_DESCRIPTION = "\n\n".join([open('README.rst').read(), open('CHANGELOG.rst').read()]) else: LONG_DESCRIPTION = DESCRIPTION setup( author=metaopt.__author__, author_email=metaopt.__author_email__, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Environment :: Plugins', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Information Technology', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Distributed Computing' ], data_files=[("", ["README.rst", "LICENSE.rst", "requirements_examples.txt", "requirements_lint.txt", "requirements_test.txt"])], description=DESCRIPTION, ext_modules=[], install_requires=[], license=metaopt.__license__, long_description=LONG_DESCRIPTION, name='metaopt', packages=find_packages(exclude=('examples', 'docs', 'tests')), package_data={'': ['LICENSE.rst', 'README.rst', 'requirements*.txt']}, setup_requires=[], tests_require=find_requirements('requirements_test.txt'), test_suite='metaopt.tests', url=metaopt.__url__, use_2to3=(sys.version_info >= (3,)), version=metaopt.__version__, )
38
82
0.643774
from __future__ import division, print_function, with_statement import os import sys try: from setuptools import setup, find_packages except ImportError: import ez_setup ez_setup.use_setuptools() from setuptools import setup, find_packages from pip.req import parse_requirements import metaopt def extract_package_name(requirement): return str(requirement.req).replace('-', '_').split('==')[0] def find_requirements(req_file='requirements.txt'): return [extract_package_name(r) for r in parse_requirements(req_file)] DESCRIPTION = 'MetaOpt is a library that optimizes black-box functions using ' + \ 'a limited amount of time and utilizing multiple processors. ' + \ 'The main focus of MetaOpt is the parameter tuning for machine ' + \ 'learning and heuristic optimization.' if os.path.isfile('README.rst'): LONG_DESCRIPTION = "\n\n".join([open('README.rst').read(), open('CHANGELOG.rst').read()]) else: LONG_DESCRIPTION = DESCRIPTION setup( author=metaopt.__author__, author_email=metaopt.__author_email__, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Environment :: Plugins', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Information Technology', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Distributed Computing' ], data_files=[("", ["README.rst", "LICENSE.rst", "requirements_examples.txt", "requirements_lint.txt", "requirements_test.txt"])], description=DESCRIPTION, ext_modules=[], install_requires=[], license=metaopt.__license__, long_description=LONG_DESCRIPTION, name='metaopt', packages=find_packages(exclude=('examples', 'docs', 'tests')), package_data={'': ['LICENSE.rst', 'README.rst', 'requirements*.txt']}, setup_requires=[], tests_require=find_requirements('requirements_test.txt'), test_suite='metaopt.tests', url=metaopt.__url__, use_2to3=(sys.version_info >= (3,)), version=metaopt.__version__, )
true
true
1c443b008425d87a2b13f8d0a5cd54540e1eb168
4,058
py
Python
setup.py
jemilc/shap
ed284b6278813c5292d83dc2a22976a0fdedd4ec
[ "MIT" ]
1
2020-05-28T18:31:41.000Z
2020-05-28T18:31:41.000Z
setup.py
jemilc/shap
ed284b6278813c5292d83dc2a22976a0fdedd4ec
[ "MIT" ]
null
null
null
setup.py
jemilc/shap
ed284b6278813c5292d83dc2a22976a0fdedd4ec
[ "MIT" ]
2
2021-12-13T19:34:37.000Z
2021-12-13T23:45:36.000Z
from setuptools import setup, Extension from setuptools.command.build_ext import build_ext as _build_ext import os import re import codecs # to publish use: # > python setup.py sdist bdist_wheel upload # which depends on ~/.pypirc here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as fp: return fp.read() def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") # Extend the default build_ext class to bootstrap numpy installation # that are needed to build C extensions. # see https://stackoverflow.com/questions/19919905/how-to-bootstrap-numpy-installation-in-setup-py class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) if isinstance(__builtins__, dict): __builtins__["__NUMPY_SETUP__"] = False else: setattr(__builtins__, "__NUMPY_SETUP__", False) import numpy print("numpy.get_include()", numpy.get_include()) self.include_dirs.append(numpy.get_include()) def run_setup(with_binary=True, test_xgboost=True, test_lightgbm=True): ext_modules = [] if with_binary: ext_modules.append( Extension('shap._cext', sources=['shap/_cext.cc']) ) if test_xgboost and test_lightgbm: tests_require = ['nose', 'xgboost', 'lightgbm'] elif test_xgboost: tests_require = ['nose', 'xgboost'] elif test_lightgbm: tests_require = ['nose', 'lightgbm'] else: tests_require = ['nose'] setup( name='shap', version=find_version("shap", "__init__.py"), description='A unified approach to explain the output of any machine learning model.', long_description="SHAP (SHapley Additive exPlanations) is a unified approach to explain the output of " + \ "any machine learning model. SHAP connects game theory with local explanations, uniting " + \ "several previous methods and representing the only possible consistent and locally accurate " + \ "additive feature attribution method based on expectations.", long_description_content_type="text/markdown", url='http://github.com/slundberg/shap', author='Scott Lundberg', author_email='slund1@cs.washington.edu', license='MIT', packages=['shap', 'shap.explainers', 'shap.explainers.other', 'shap.plots', 'shap.benchmark'], package_data={'shap': ['plots/resources/*']}, cmdclass={'build_ext': build_ext}, setup_requires=['numpy'], install_requires=['numpy', 'scipy', 'scikit-learn', 'matplotlib', 'pandas', 'tqdm', 'ipython'], test_suite='nose.collector', tests_require=tests_require, ext_modules=ext_modules, zip_safe=False ) def try_run_setup(**kwargs): """ Fails gracefully when various install steps don't work. """ try: run_setup(**kwargs) except Exception as e: print(str(e)) if "xgboost" in str(e).lower(): kwargs["test_xgboost"] = False print("Couldn't install XGBoost for testing!") try_run_setup(**kwargs) elif "lightgbm" in str(e).lower(): kwargs["test_lightgbm"] = False print("Couldn't install LightGBM for testing!") try_run_setup(**kwargs) elif kwargs["with_binary"]: kwargs["with_binary"] = False print("WARNING: The C extension could not be compiled, sklearn tree models not supported.") try_run_setup(**kwargs) else: print("ERROR: Failed to build!") # we seem to need this import guard for appveyor if __name__ == "__main__": try_run_setup(with_binary=True, test_xgboost=True, test_lightgbm=True)
38.283019
123
0.646624
from setuptools import setup, Extension from setuptools.command.build_ext import build_ext as _build_ext import os import re import codecs here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as fp: return fp.read() def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") # Extend the default build_ext class to bootstrap numpy installation # that are needed to build C extensions. # see https://stackoverflow.com/questions/19919905/how-to-bootstrap-numpy-installation-in-setup-py class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) if isinstance(__builtins__, dict): __builtins__["__NUMPY_SETUP__"] = False else: setattr(__builtins__, "__NUMPY_SETUP__", False) import numpy print("numpy.get_include()", numpy.get_include()) self.include_dirs.append(numpy.get_include()) def run_setup(with_binary=True, test_xgboost=True, test_lightgbm=True): ext_modules = [] if with_binary: ext_modules.append( Extension('shap._cext', sources=['shap/_cext.cc']) ) if test_xgboost and test_lightgbm: tests_require = ['nose', 'xgboost', 'lightgbm'] elif test_xgboost: tests_require = ['nose', 'xgboost'] elif test_lightgbm: tests_require = ['nose', 'lightgbm'] else: tests_require = ['nose'] setup( name='shap', version=find_version("shap", "__init__.py"), description='A unified approach to explain the output of any machine learning model.', long_description="SHAP (SHapley Additive exPlanations) is a unified approach to explain the output of " + \ "any machine learning model. SHAP connects game theory with local explanations, uniting " + \ "several previous methods and representing the only possible consistent and locally accurate " + \ "additive feature attribution method based on expectations.", long_description_content_type="text/markdown", url='http://github.com/slundberg/shap', author='Scott Lundberg', author_email='slund1@cs.washington.edu', license='MIT', packages=['shap', 'shap.explainers', 'shap.explainers.other', 'shap.plots', 'shap.benchmark'], package_data={'shap': ['plots/resources/*']}, cmdclass={'build_ext': build_ext}, setup_requires=['numpy'], install_requires=['numpy', 'scipy', 'scikit-learn', 'matplotlib', 'pandas', 'tqdm', 'ipython'], test_suite='nose.collector', tests_require=tests_require, ext_modules=ext_modules, zip_safe=False ) def try_run_setup(**kwargs): try: run_setup(**kwargs) except Exception as e: print(str(e)) if "xgboost" in str(e).lower(): kwargs["test_xgboost"] = False print("Couldn't install XGBoost for testing!") try_run_setup(**kwargs) elif "lightgbm" in str(e).lower(): kwargs["test_lightgbm"] = False print("Couldn't install LightGBM for testing!") try_run_setup(**kwargs) elif kwargs["with_binary"]: kwargs["with_binary"] = False print("WARNING: The C extension could not be compiled, sklearn tree models not supported.") try_run_setup(**kwargs) else: print("ERROR: Failed to build!") # we seem to need this import guard for appveyor if __name__ == "__main__": try_run_setup(with_binary=True, test_xgboost=True, test_lightgbm=True)
true
true
1c443bbd588fb502514c1dc2517c751f29430408
478
py
Python
server/functionsfake.py
Yavonix/011-Battlebot-App
143e1990548837d81c9fcbf805e5c727e2038850
[ "MIT" ]
1
2021-07-29T03:26:29.000Z
2021-07-29T03:26:29.000Z
server/functionsfake.py
Yavonix/011-Battlebot-App
143e1990548837d81c9fcbf805e5c727e2038850
[ "MIT" ]
null
null
null
server/functionsfake.py
Yavonix/011-Battlebot-App
143e1990548837d81c9fcbf805e5c727e2038850
[ "MIT" ]
null
null
null
# Dummy program for development def jointMode(ID): print("JointModeEvent") # Move a dynamixel that has been set up as a joint. def moveJoint(ID, position, speed): print("MoveJointEvent") # === WHEEL FUNCTIONS === # # Set up a dynamixel so that it behaves like wheel. def wheelMode(ID): pass #print("WheelModeEvent") # Move a dynamixel that has been set up as a wheel. def moveWheel(ID, speed): pass #print("WheelSpeedEvent")
22.761905
51
0.656904
def jointMode(ID): print("JointModeEvent") def moveJoint(ID, position, speed): print("MoveJointEvent") def wheelMode(ID): pass def moveWheel(ID, speed): pass
true
true
1c443dbe02aa3601a4b584eb0b5bc976480a3a4d
4,034
py
Python
devine.py
noutcha/devine
3a7d6767f9032d1b988efa4104adb3a5eca97c39
[ "MIT" ]
null
null
null
devine.py
noutcha/devine
3a7d6767f9032d1b988efa4104adb3a5eca97c39
[ "MIT" ]
null
null
null
devine.py
noutcha/devine
3a7d6767f9032d1b988efa4104adb3a5eca97c39
[ "MIT" ]
null
null
null
""" Prémière version du jeu Deviner. On crée une fenêtre simple qui demande à l'utilisateur de deviner le nombre secret. Avec une possibilité de guide en indiquant si le nombre choisi est plus grand ou plus petit que le nombre secret source d'inspiration: https://pythonfaqfr.readthedocs.io/en/latest/prog_even_tkinter.html# """ # coding: utf-8 # On importe randint pour geberer les nombres aléatoire from random import randint # On importe Tkinter pour la creation de l'interface graphique import tkinter as tk #ici importation avec renommage, #from tkinter import * à éviter from tkinter.messagebox import * # On defini notre fonction de traitement def user_recup_choix(event): "fonction de rappel ou fonction de post-traitement quand le joueur a entré un nombre." nbre_choisi = int(reponse.get()) # on recupère la reponse de l'user reponse.delete(0, tk.END) # on vide le champ de saisie proposition["text"] = nbre_choisi #On recupère le choix de l'user if nombre_secret > nbre_choisi: result["text"] = "Le nombre est plus grand" # On affiche le texte pour aider l'user elif nombre_secret < nbre_choisi: result["text"] = "Le nombre est plus petit" else: # On enlève les éléments dont on n'a plus besoin lbl_reponse.destroy() reponse.destroy() # On replace les Labels `proposition` et `resultat` dans la ligne # en dessous du titre proposition.grid_forget() proposition.grid(row=1, column=0) result.grid_forget() result.grid(row=1, column=1) # On configure le label avec le texte voulu, dans le font voulu et # dans la couleur désirée. result.config(text="Tu as trouvé le nombre. Bravo!", font=("", 12), fg="green") app = tk.Tk() # creation de la fenêtre app.title("Mon premier jeu Avec Tkinter") # titre de ma fenetre # fonction qutter def Quitter(): if askyesno('Confirmation', 'Êtes-vous sûr de vouloir quitter le jeu ?'): app.quit() else: showinfo('Confirmation', 'Continuer!') # fonction a propos def Apropos(): showinfo('A propos !', 'Devine (V1.0.0) est juste un jeu banal. \n le principe est simple, j\'ai un nombre et tu dois deviner ce nombre !') # Menu de l'application menubar = tk.Menu(app) menu1 = tk.Menu(menubar, tearoff=0) menu1.add_command(label="Créer") menu1.add_command(label="Editer") menu1.add_separator() menu1.add_command(label="Quitter", command=app.quit) menubar.add_cascade(label="Fichier", menu=menu1) menu2 = tk.Menu(menubar, tearoff=0) menu2.add_command(label="Couper") menu2.add_command(label="Copier") menu2.add_command(label="Coller") menubar.add_cascade(label="Editer", menu=menu2) menu3 = tk.Menu(menubar, tearoff=0) menu3.add_command(label="A propos", command=Apropos) menubar.add_cascade(label="Aide", menu=menu3) app.config(menu=menubar) # fin menu titre = tk.Label(app, text="Devine le nombre auquel je pense", font=("", 16)) titre.grid(row=0, columnspan=2, pady=8) #Génération du nombre secret nombre_secret = randint(0, 100) + 1 lbl_reponse = tk.Label(app, text="Choisi un nombre entre 1 et 100 inclus:") lbl_reponse.grid(row=1, column=0, pady=5, padx=5) reponse = tk.Entry(app) # On demande ici la saisie dans le champ reponse.grid(row=1, column=1, pady=5, padx=5) reponse.bind("<Return>", user_recup_choix) # On affecte le resultat de la saisi dans la variable #Création d'un Rejouer bouton_rejouer = tk.Button(app, text="Rejouer") bouton_rejouer.grid(row=3, column=1, pady=10, padx=10) #Création d'un bouton Quitter bouton_quitter = tk.Button(app, text="Quitter", command=Quitter) bouton_quitter.grid(row=3, column=2, pady=15, padx=15) proposition = tk.Label(app, text="") proposition.grid(row=2, column=0, pady=5, padx=5) result = tk.Label(app, text="") result.grid(row=2, column=1, pady=5, padx=5) app.mainloop()
33.616667
143
0.683689
from random import randint import tkinter as tk #ici importation avec renommage, #from tkinter import * à éviter from tkinter.messagebox import * # On defini notre fonction de traitement def user_recup_choix(event): nbre_choisi = int(reponse.get()) # on recupère la reponse de l'user reponse.delete(0, tk.END) proposition["text"] = nbre_choisi if nombre_secret > nbre_choisi: result["text"] = "Le nombre est plus grand" # On affiche le texte pour aider l'user elif nombre_secret < nbre_choisi: result["text"] = "Le nombre est plus petit" else: lbl_reponse.destroy() reponse.destroy() # On replace les Labels `proposition` et `resultat` dans la ligne # en dessous du titre proposition.grid_forget() proposition.grid(row=1, column=0) result.grid_forget() result.grid(row=1, column=1) # On configure le label avec le texte voulu, dans le font voulu et # dans la couleur désirée. result.config(text="Tu as trouvé le nombre. Bravo!", font=("", 12), fg="green") app = tk.Tk() # creation de la fenêtre app.title("Mon premier jeu Avec Tkinter") # titre de ma fenetre # fonction qutter def Quitter(): if askyesno('Confirmation', 'Êtes-vous sûr de vouloir quitter le jeu ?'): app.quit() else: showinfo('Confirmation', 'Continuer!') # fonction a propos def Apropos(): showinfo('A propos !', 'Devine (V1.0.0) est juste un jeu banal. \n le principe est simple, j\'ai un nombre et tu dois deviner ce nombre !') menubar = tk.Menu(app) menu1 = tk.Menu(menubar, tearoff=0) menu1.add_command(label="Créer") menu1.add_command(label="Editer") menu1.add_separator() menu1.add_command(label="Quitter", command=app.quit) menubar.add_cascade(label="Fichier", menu=menu1) menu2 = tk.Menu(menubar, tearoff=0) menu2.add_command(label="Couper") menu2.add_command(label="Copier") menu2.add_command(label="Coller") menubar.add_cascade(label="Editer", menu=menu2) menu3 = tk.Menu(menubar, tearoff=0) menu3.add_command(label="A propos", command=Apropos) menubar.add_cascade(label="Aide", menu=menu3) app.config(menu=menubar) # fin menu titre = tk.Label(app, text="Devine le nombre auquel je pense", font=("", 16)) titre.grid(row=0, columnspan=2, pady=8) #Génération du nombre secret nombre_secret = randint(0, 100) + 1 lbl_reponse = tk.Label(app, text="Choisi un nombre entre 1 et 100 inclus:") lbl_reponse.grid(row=1, column=0, pady=5, padx=5) reponse = tk.Entry(app) # On demande ici la saisie dans le champ reponse.grid(row=1, column=1, pady=5, padx=5) reponse.bind("<Return>", user_recup_choix) # On affecte le resultat de la saisi dans la variable #Création d'un Rejouer bouton_rejouer = tk.Button(app, text="Rejouer") bouton_rejouer.grid(row=3, column=1, pady=10, padx=10) bouton_quitter = tk.Button(app, text="Quitter", command=Quitter) bouton_quitter.grid(row=3, column=2, pady=15, padx=15) proposition = tk.Label(app, text="") proposition.grid(row=2, column=0, pady=5, padx=5) result = tk.Label(app, text="") result.grid(row=2, column=1, pady=5, padx=5) app.mainloop()
true
true
1c443dc6a22ecc7fee90d76acd68cbc1bacd1fb9
19,705
py
Python
includes/BOLTS/freecad/extrusions/profiles.py
codysandahl/3dprinting
98d588864e5ba5826c7ed16959aa7b1040a760b3
[ "MIT" ]
null
null
null
includes/BOLTS/freecad/extrusions/profiles.py
codysandahl/3dprinting
98d588864e5ba5826c7ed16959aa7b1040a760b3
[ "MIT" ]
null
null
null
includes/BOLTS/freecad/extrusions/profiles.py
codysandahl/3dprinting
98d588864e5ba5826c7ed16959aa7b1040a760b3
[ "MIT" ]
null
null
null
# ************************************************************************************** # * * # * BOLTS - Open Library of Technical Specifications * # * * # * Copyright (C) 2014 Johannes Reinhardt <jreinhardt@ist-dein-freund.de> * # * * # * This library is free software; you can redistribute it and/or * # * modify it under the terms of the GNU Lesser General Public * # * License as published by the Free Software Foundation; either * # * version 2.1 of the License, or any later version. * # * * # * This library 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 * # * Lesser General Public License for more details. * # * * # * You should have received a copy of the GNU Lesser General Public * # * License along with this library; if not, write to the Free Software * # * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * # * * # ************************************************************************************** import math import Part from FreeCAD import Vector from DraftGeomUtils import fillet as draft_fillet # ************************************************************************************************ def vslot20x20( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 8 * [vslot_outline] fillets = [5, 17, 29, 41] corner_offset = 0 circle_offsets = [0] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # color if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) # ************************************************************************************************ def vslot20x40( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (-w, 0, True, True, False, False), (-w, 0, False, True, True, False), (-w, 0, True, False, True, False), (-w, 0, False, False, True, True), (-w, 0, True, True, True, True), (-w, 0, False, True, False, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 12 * [vslot_outline] fillets = [5, 29, 41, 65] corner_offset = -1 * w circle_offsets = [0, -w] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # color if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) # ************************************************************************************************ def vslot20x60(params, document): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (-w, 0, True, True, False, False), (-w, 0, False, True, True, False), (-2 * w, 0, True, True, False, False), (-2 * w, 0, False, True, True, False), (-2 * w, 0, True, False, True, False), (-2 * w, 0, False, False, True, True), (-2 * w, 0, True, True, True, True), (-2 * w, 0, False, True, False, True), (-w, 0, True, True, True, True), (-w, 0, False, True, False, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 16 * [vslot_outline] # add fillets in reverse order, as this inserts additional edges fillets = [5, 41, 53, 89] corner_offset = -2 * w circle_offsets = [0, -w, -2 * w] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # color if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) # ************************************************************************************************ def vslot20x80(params, document): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (-w, 0, True, True, False, False), (-w, 0, False, True, True, False), (-2 * w, 0, True, True, False, False), (-2 * w, 0, False, True, True, False), (-3 * w, 0, True, True, False, False), (-3 * w, 0, False, True, True, False), (-3 * w, 0, True, False, True, False), (-3 * w, 0, False, False, True, True), (-3 * w, 0, True, True, True, True), (-3 * w, 0, False, True, False, True), (-2 * w, 0, True, True, True, True), (-2 * w, 0, False, True, False, True), (-w, 0, True, True, True, True), (-w, 0, False, True, False, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 20 * [vslot_outline] # add fillets in reverse order, as this inserts additional edges fillets = [5, 53, 65, 113] corner_offset = -3 * w circle_offsets = [0, -w, -2 * w, -3 * w] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # color if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) # ************************************************************************************************ def tslot20x20( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 8 * [tslot_outline] fillets = [5, 17, 29, 41] corner_offset = 0 circle_offsets = [0] face = tslot(symmetry, vertices, fillets, [], [], corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # ************************************************************************************************ def tslot20x20_three_slot( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = [tslot_outline] + 2 * [tslot_closed] + 5 * [tslot_outline] fillets = [5, 7, 19, 31] closed_symmetry = [ (0, 0, False, True, False, False), ] closed_vertices = [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets, ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # ************************************************************************************************ def tslot20x20_two_slot( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = [tslot_outline] + 4 * [tslot_closed] + 3 * [tslot_outline] fillets = [5, 7, 9, 21] closed_symmetry = [ (0, 0, False, True, False, False), (0, 0, False, False, True, False), ] closed_vertices = 2 * [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets, ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # ************************************************************************************************ def tslot20x20_two_slot_opp( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = ( [tslot_outline] + 2 * [tslot_closed] + 2 * [tslot_outline] + 2 * [tslot_closed] + [tslot_outline] ) fillets = [5, 7, 19, 21] closed_symmetry = [ (0, 0, False, True, False, False), (0, 0, False, True, False, True), ] closed_vertices = 2 * [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets, ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # ************************************************************************************************ def tslot20x20_one_slot( params, document ): name = params["name"] le = params["l"] # due to symmetry this can be nicely decomposed # x offset, y offset, reverse, switch, mir_x, mir_y symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = [tslot_outline] + 6 * [tslot_closed] + [tslot_outline] fillets = [5, 7, 9, 11] closed_symmetry = [ (0, 0, False, True, False, False), (0, 0, False, False, True, False), (0, 0, False, True, False, True), ] closed_vertices = 3 * [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() # ************************************************************************************************ # helper def fillet( lines, indices, radius ): """ fillets the corner between the segments and their successors in lines indicated by indices """ lines = lines[:] # sort them in descending order, as filleting inserts additional edges indices.sort() indices.reverse() for i in indices: lines[slice(i, i + 2)] = draft_fillet(lines[slice(i, i + 2)], radius) return lines def assemble( symmetry, vertices, offset_global=(0, 0) ): """ Assemble a wire from a list of symmetry information and a list of list of vertices symmetry information is a tuple of offset x, offset y, bool reverse, bool switch_comp, bool mirror_x, bool mirror_y """ offset = Vector(offset_global[0], offset_global[1], 0) lines = [] vlast = None vcur = None for sym, verts in zip(symmetry, vertices): o_x, o_y, reverse, switch, mir_x, mir_y = sym mir_x = -1 if mir_x else 1 mir_y = -1 if mir_y else 1 if reverse: verts = verts[::-1] if vcur is None: vcur = Vector(verts[0]) if switch: vcur[0], vcur[1] = vcur[1], vcur[0] vcur[0] = mir_x * vcur[0] + o_x + offset[0] vcur[1] = mir_y * vcur[1] + o_y + offset[1] for v in verts[1:]: vlast = vcur vcur = Vector(v) if switch: vcur[0], vcur[1] = vcur[1], vcur[0] vcur[0] = mir_x * vcur[0] + o_x + offset[0] vcur[1] = mir_y * vcur[1] + o_y + offset[1] lines.append(Part.makeLine(vlast, vcur)) return lines # ************************************************************************************************ # profile size w = 20 # ************************************************************************************************ # Vslot profile: # the size of the inner square d = 5.68 + 3 / math.sqrt(2) # one eight of the outline vslot_outline = [ (0.5 * d, 0, 0), (0.5 * d, 0.5 * 5.68, 0), (0.5 * w - 1.8 - 1.64, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2), 0), (0.5 * w - 1.8, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2), 0), (0.5 * w - 1.8, 0.5 * 5.68, 0), (0.5 * w, 0.5 * 5.68 + 1.8, 0), (0.5 * w, 0.5 * w, 0) ] space_symmetry = [ (0, 0, False, False, True, False), (-w, 0, True, False, False, False), (-w, 0, False, False, False, True), (0, 0, True, False, True, True) ] # big spaces vslot_space = [ (0.5 * d, 0, 0), (0.5 * d, 0.5 * 5.68, 0), (0.5 * w - 2.7, 0.5 * w - 1.8 - 1.96, 0), (0.5 * w - 2.7, 0.5 * w - 1.8, 0), (0.5 * w, 0.5 * w - 1.8, 0), ] # corner holes vslot_cornerhole = [ (0.5 * w - 1.8, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2) + 1.07, 0), (0.5 * w - 1.8, 0.5 * w - 1.8, 0), (0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2) + 1.07, 0.5 * w - 1.8, 0), (0.5 * w - 1.8, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2) + 1.07, 0) ] def vslot( symmetry, vertices, fillets, corner_offset, circle_offsets ): outline = assemble(symmetry, vertices) outline = fillet(outline, fillets, 1.5) outline = Part.Wire(outline) holes = [] # corners # x offset, y offset, reverse, switch, mir_x, mir_y corner_symmetry = [ (0, 0, False, False, False, False), (corner_offset, 0, False, False, True, False), (corner_offset, 0, False, False, True, True), (0, 0, False, False, False, True), ] for sym in corner_symmetry: holes.append(Part.Wire(assemble([sym], [vslot_cornerhole]))) if sym[4] == sym[5]: holes[-1].reverse() # circular holes for offset in circle_offsets: holes.append(Part.Wire(Part.makeCircle(2.1, Vector(offset, 0, 0)))) holes[-1].reverse() # big spaces print("Space") for offset in circle_offsets[:-1]: print(space_symmetry, vslot_space) holes.append(Part.Wire(assemble(space_symmetry, 4 * [vslot_space], (offset, 0)))) holes[-1].reverse() print("Space") # put everything together return Part.Face([outline] + holes) # ************************************************************************************************ # T slot profile: # outline tslot_outline = [ (5.0, 0, 0), (5.0, 3.5, 0), (7.5, 6.0, 0), (9.0, 6.0, 0), (9.0, 3.0, 0), (10.0, 3.0, 0), (10.0, 10.0, 0), ] # closed slots ouline tslot_closed = [ (10.0, 0.0, 0), (10.0, 10.0, 0), ] # closed slots spaces tslot_closed_space = [ (5.0, 0, 0), (5.0, 3.5, 0), (7.5, 6.0, 0), (9.0, 6.0, 0), (9.0, -6.0, 0), (7.5, -6.0, 0), (5.0, -3.5, 0), (5.0, 0, 0), ] # big spaces tslot_space = [ (0.5 * d, 0, 0), (0.5 * d, 0.5 * 5.68, 0), (0.5 * w - 2.7, 0.5 * w - 1.8 - 1.96, 0), (0.5 * w - 2.7, 0.5 * w - 1.8, 0), (0.5 * w, 0.5 * w - 1.8, 0), ] def tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets ): outline = assemble(symmetry, vertices) outline = fillet(outline, fillets, 1.5) outline = Part.Wire(outline) holes = [] # closed holes for sym, vert in zip(closed_symmetry, closed_vertices): holes.append(Part.Wire(assemble([sym], [vert]))) if not sym[5]: holes[-1].reverse() # circular holes for offset in circle_offsets: holes.append(Part.Wire(Part.makeCircle(2.25, Vector(offset, 0, 0)))) holes[-1].reverse() # put everything together return Part.Face([outline] + holes)
29.279346
98
0.489267
import math import Part from FreeCAD import Vector from DraftGeomUtils import fillet as draft_fillet def vslot20x20( params, document ): name = params["name"] le = params["l"] symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 8 * [vslot_outline] fillets = [5, 17, 29, 41] corner_offset = 0 circle_offsets = [0] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) def vslot20x40( params, document ): name = params["name"] le = params["l"] symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (-w, 0, True, True, False, False), (-w, 0, False, True, True, False), (-w, 0, True, False, True, False), (-w, 0, False, False, True, True), (-w, 0, True, True, True, True), (-w, 0, False, True, False, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 12 * [vslot_outline] fillets = [5, 29, 41, 65] corner_offset = -1 * w circle_offsets = [0, -w] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) def vslot20x60(params, document): name = params["name"] le = params["l"] symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (-w, 0, True, True, False, False), (-w, 0, False, True, True, False), (-2 * w, 0, True, True, False, False), (-2 * w, 0, False, True, True, False), (-2 * w, 0, True, False, True, False), (-2 * w, 0, False, False, True, True), (-2 * w, 0, True, True, True, True), (-2 * w, 0, False, True, False, True), (-w, 0, True, True, True, True), (-w, 0, False, True, False, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 16 * [vslot_outline] fillets = [5, 41, 53, 89] corner_offset = -2 * w circle_offsets = [0, -w, -2 * w] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) def vslot20x80(params, document): name = params["name"] le = params["l"] symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (-w, 0, True, True, False, False), (-w, 0, False, True, True, False), (-2 * w, 0, True, True, False, False), (-2 * w, 0, False, True, True, False), (-3 * w, 0, True, True, False, False), (-3 * w, 0, False, True, True, False), (-3 * w, 0, True, False, True, False), (-3 * w, 0, False, False, True, True), (-3 * w, 0, True, True, True, True), (-3 * w, 0, False, True, False, True), (-2 * w, 0, True, True, True, True), (-2 * w, 0, False, True, False, True), (-w, 0, True, True, True, True), (-w, 0, False, True, False, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 20 * [vslot_outline] fillets = [5, 53, 65, 113] corner_offset = -3 * w circle_offsets = [0, -w, -2 * w, -3 * w] face = vslot(symmetry, vertices, fillets, corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() if params["finish"] == "Black": part.ViewObject.DiffuseColor = (0.1, 0.1, 0.1) def tslot20x20( params, document ): name = params["name"] le = params["l"] symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = 8 * [tslot_outline] fillets = [5, 17, 29, 41] corner_offset = 0 circle_offsets = [0] face = tslot(symmetry, vertices, fillets, [], [], corner_offset, circle_offsets) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() def tslot20x20_three_slot( params, document ): name = params["name"] le = params["l"] symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = [tslot_outline] + 2 * [tslot_closed] + 5 * [tslot_outline] fillets = [5, 7, 19, 31] closed_symmetry = [ (0, 0, False, True, False, False), ] closed_vertices = [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets, ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() def tslot20x20_two_slot( params, document ): name = params["name"] le = params["l"] symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = [tslot_outline] + 4 * [tslot_closed] + 3 * [tslot_outline] fillets = [5, 7, 9, 21] closed_symmetry = [ (0, 0, False, True, False, False), (0, 0, False, False, True, False), ] closed_vertices = 2 * [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets, ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() def tslot20x20_two_slot_opp( params, document ): name = params["name"] le = params["l"] symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = ( [tslot_outline] + 2 * [tslot_closed] + 2 * [tslot_outline] + 2 * [tslot_closed] + [tslot_outline] ) fillets = [5, 7, 19, 21] closed_symmetry = [ (0, 0, False, True, False, False), (0, 0, False, True, False, True), ] closed_vertices = 2 * [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets, ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() def tslot20x20_one_slot( params, document ): name = params["name"] le = params["l"] symmetry = [ (0, 0, False, False, False, False), (0, 0, True, True, False, False), (0, 0, False, True, True, False), (0, 0, True, False, True, False), (0, 0, False, False, True, True), (0, 0, True, True, True, True), (0, 0, False, True, False, True), (0, 0, True, False, False, True), ] vertices = [tslot_outline] + 6 * [tslot_closed] + [tslot_outline] fillets = [5, 7, 9, 11] closed_symmetry = [ (0, 0, False, True, False, False), (0, 0, False, False, True, False), (0, 0, False, True, False, True), ] closed_vertices = 3 * [tslot_closed_space] corner_offset = 0 circle_offsets = [0] face = tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets ) part = document.addObject("Part::Feature", "BOLTS_part") part.Label = name part.Shape = face.extrude(Vector(0, 0, le)).removeSplitter() def fillet( lines, indices, radius ): lines = lines[:] indices.sort() indices.reverse() for i in indices: lines[slice(i, i + 2)] = draft_fillet(lines[slice(i, i + 2)], radius) return lines def assemble( symmetry, vertices, offset_global=(0, 0) ): offset = Vector(offset_global[0], offset_global[1], 0) lines = [] vlast = None vcur = None for sym, verts in zip(symmetry, vertices): o_x, o_y, reverse, switch, mir_x, mir_y = sym mir_x = -1 if mir_x else 1 mir_y = -1 if mir_y else 1 if reverse: verts = verts[::-1] if vcur is None: vcur = Vector(verts[0]) if switch: vcur[0], vcur[1] = vcur[1], vcur[0] vcur[0] = mir_x * vcur[0] + o_x + offset[0] vcur[1] = mir_y * vcur[1] + o_y + offset[1] for v in verts[1:]: vlast = vcur vcur = Vector(v) if switch: vcur[0], vcur[1] = vcur[1], vcur[0] vcur[0] = mir_x * vcur[0] + o_x + offset[0] vcur[1] = mir_y * vcur[1] + o_y + offset[1] lines.append(Part.makeLine(vlast, vcur)) return lines w = 20 d = 5.68 + 3 / math.sqrt(2) vslot_outline = [ (0.5 * d, 0, 0), (0.5 * d, 0.5 * 5.68, 0), (0.5 * w - 1.8 - 1.64, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2), 0), (0.5 * w - 1.8, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2), 0), (0.5 * w - 1.8, 0.5 * 5.68, 0), (0.5 * w, 0.5 * 5.68 + 1.8, 0), (0.5 * w, 0.5 * w, 0) ] space_symmetry = [ (0, 0, False, False, True, False), (-w, 0, True, False, False, False), (-w, 0, False, False, False, True), (0, 0, True, False, True, True) ] vslot_space = [ (0.5 * d, 0, 0), (0.5 * d, 0.5 * 5.68, 0), (0.5 * w - 2.7, 0.5 * w - 1.8 - 1.96, 0), (0.5 * w - 2.7, 0.5 * w - 1.8, 0), (0.5 * w, 0.5 * w - 1.8, 0), ] vslot_cornerhole = [ (0.5 * w - 1.8, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2) + 1.07, 0), (0.5 * w - 1.8, 0.5 * w - 1.8, 0), (0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2) + 1.07, 0.5 * w - 1.8, 0), (0.5 * w - 1.8, 0.5 * w - 1.8 - 1.64 - 1.5 / math.sqrt(2) + 1.07, 0) ] def vslot( symmetry, vertices, fillets, corner_offset, circle_offsets ): outline = assemble(symmetry, vertices) outline = fillet(outline, fillets, 1.5) outline = Part.Wire(outline) holes = [] corner_symmetry = [ (0, 0, False, False, False, False), (corner_offset, 0, False, False, True, False), (corner_offset, 0, False, False, True, True), (0, 0, False, False, False, True), ] for sym in corner_symmetry: holes.append(Part.Wire(assemble([sym], [vslot_cornerhole]))) if sym[4] == sym[5]: holes[-1].reverse() for offset in circle_offsets: holes.append(Part.Wire(Part.makeCircle(2.1, Vector(offset, 0, 0)))) holes[-1].reverse() print("Space") for offset in circle_offsets[:-1]: print(space_symmetry, vslot_space) holes.append(Part.Wire(assemble(space_symmetry, 4 * [vslot_space], (offset, 0)))) holes[-1].reverse() print("Space") return Part.Face([outline] + holes) tslot_outline = [ (5.0, 0, 0), (5.0, 3.5, 0), (7.5, 6.0, 0), (9.0, 6.0, 0), (9.0, 3.0, 0), (10.0, 3.0, 0), (10.0, 10.0, 0), ] tslot_closed = [ (10.0, 0.0, 0), (10.0, 10.0, 0), ] tslot_closed_space = [ (5.0, 0, 0), (5.0, 3.5, 0), (7.5, 6.0, 0), (9.0, 6.0, 0), (9.0, -6.0, 0), (7.5, -6.0, 0), (5.0, -3.5, 0), (5.0, 0, 0), ] tslot_space = [ (0.5 * d, 0, 0), (0.5 * d, 0.5 * 5.68, 0), (0.5 * w - 2.7, 0.5 * w - 1.8 - 1.96, 0), (0.5 * w - 2.7, 0.5 * w - 1.8, 0), (0.5 * w, 0.5 * w - 1.8, 0), ] def tslot( symmetry, vertices, fillets, closed_symmetry, closed_vertices, corner_offset, circle_offsets ): outline = assemble(symmetry, vertices) outline = fillet(outline, fillets, 1.5) outline = Part.Wire(outline) holes = [] for sym, vert in zip(closed_symmetry, closed_vertices): holes.append(Part.Wire(assemble([sym], [vert]))) if not sym[5]: holes[-1].reverse() for offset in circle_offsets: holes.append(Part.Wire(Part.makeCircle(2.25, Vector(offset, 0, 0)))) holes[-1].reverse() return Part.Face([outline] + holes)
true
true
1c4441ebc66c0b0b71ab468deeaecf28874f330c
6,448
py
Python
tools/repl_test.py
zoosky/deno
020898762fa081113608504ab5012b2b27c70668
[ "MIT" ]
3
2020-07-08T11:32:22.000Z
2020-07-10T11:34:25.000Z
tools/repl_test.py
zoosky/deno
020898762fa081113608504ab5012b2b27c70668
[ "MIT" ]
null
null
null
tools/repl_test.py
zoosky/deno
020898762fa081113608504ab5012b2b27c70668
[ "MIT" ]
null
null
null
# Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import os import shutil from subprocess import CalledProcessError, PIPE, Popen import sys import time from test_util import DenoTestCase, run_tests class TestRepl(DenoTestCase): def input(self, *lines, **kwargs): exit_ = kwargs.pop("exit", True) sleep_ = kwargs.pop("sleep", 0) env_ = kwargs.pop("env", None) p = Popen([self.deno_exe], stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env_) try: # Note: The repl takes a >100ms until it's ready. time.sleep(sleep_) for line in lines: p.stdin.write(line.encode("utf-8") + b'\n') p.stdin.flush() time.sleep(sleep_) if exit_: p.stdin.write(b'Deno.exit(0)\n') else: time.sleep(1) # wait to be killed by js out, err = p.communicate() except CalledProcessError as e: p.kill() p.wait() raise e retcode = p.poll() # Ignore Windows CRLF (\r\n). return out.replace('\r\n', '\n'), err.replace('\r\n', '\n'), retcode def test_console_log(self): out, err, code = self.input("console.log('hello')", "'world'") self.assertEqual(out, 'hello\nundefined\nworld\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_eof(self): out, err, code = self.input("1 + 2", exit=False) self.assertEqual(out, '3\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_exit_command(self): out, err, code = self.input("exit", "'ignored'", exit=False) self.assertEqual(out, '') self.assertEqual(err, '') self.assertEqual(code, 0) def test_help_command(self): out, err, code = self.input("help") expectedOut = '\n'.join([ "_ Get last evaluation result", "_error Get last thrown error", "exit Exit the REPL", "help Print this help message", "", ]) self.assertEqual(out, expectedOut) self.assertEqual(err, '') self.assertEqual(code, 0) def test_function(self): out, err, code = self.input("Deno.writeFileSync") self.assertEqual(out, '[Function: writeFileSync]\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_multiline(self): out, err, code = self.input("(\n1 + 2\n)") self.assertEqual(out, '3\n') self.assertEqual(err, '') self.assertEqual(code, 0) # This should print error instead of wait for input def test_eval_unterminated(self): out, err, code = self.input("eval('{')") self.assertEqual(out, '') assert "Unexpected end of input" in err self.assertEqual(code, 0) def test_reference_error(self): out, err, code = self.input("not_a_variable") self.assertEqual(out, '') assert "not_a_variable is not defined" in err self.assertEqual(code, 0) # def test_set_timeout(self): # out, err, code = self.input( # "setTimeout(() => { console.log('b'); Deno.exit(0); }, 1)", # "'a'", # exit=False) # self.assertEqual(out, '1\na\nb\n') # self.assertEqual(err, '') # self.assertEqual(code, 0) # def test_set_timeout_interlaced(self): # out, err, code = self.input( # "setTimeout(() => console.log('a'), 1)", # "setTimeout(() => console.log('b'), 6)", # sleep=0.8) # self.assertEqual(out, '1\n2\na\nb\n') # self.assertEqual(err, '') # self.assertEqual(code, 0) # def test_async_op(self): # out, err, code = self.input( # "fetch('http://localhost:4545/tests/001_hello.js')" + # ".then(res => res.text()).then(console.log)", # sleep=1) # self.assertEqual(out, 'Promise {}\nconsole.log("Hello World");\n\n') # self.assertEqual(err, '') # self.assertEqual(code, 0) def test_syntax_error(self): out, err, code = self.input("syntax error") self.assertEqual(out, '') assert "Unexpected identifier" in err self.assertEqual(code, 0) def test_type_error(self): out, err, code = self.input("console()") self.assertEqual(out, '') assert "console is not a function" in err self.assertEqual(code, 0) def test_variable(self): out, err, code = self.input("var a = 123;", "a") self.assertEqual(out, 'undefined\n123\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_lexical_scoped_variable(self): out, err, code = self.input("let a = 123;", "a") self.assertEqual(out, 'undefined\n123\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_missing_deno_dir(self): deno_dir = "nonexistent" new_env = os.environ.copy() new_env["DENO_DIR"] = deno_dir out, err, code = self.input("1", exit=False, env=new_env) self.assertTrue(os.path.isdir(deno_dir)) shutil.rmtree(deno_dir) self.assertEqual(out, "1\n") self.assertEqual(err, "") self.assertEqual(code, 0) def test_save_last_eval(self): out, err, code = self.input("1", "_") self.assertEqual(out, '1\n1\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_save_last_thrown(self): out, err, code = self.input("throw 1", "_error") self.assertEqual(out, '1\n') self.assertEqual(err, 'Thrown: 1\n') self.assertEqual(code, 0) def test_assign_underscore(self): out, err, code = self.input("_ = 1", "2", "_") self.assertEqual( out, 'Last evaluation result is no longer saved to _.\n1\n2\n1\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_assign_underscore_error(self): out, err, code = self.input("_error = 1", "throw 2", "_error") self.assertEqual( out, 'Last thrown error is no longer saved to _error.\n1\n1\n') self.assertEqual(err, 'Thrown: 2\n') self.assertEqual(code, 0) if __name__ == "__main__": run_tests()
34.297872
78
0.559088
import os import shutil from subprocess import CalledProcessError, PIPE, Popen import sys import time from test_util import DenoTestCase, run_tests class TestRepl(DenoTestCase): def input(self, *lines, **kwargs): exit_ = kwargs.pop("exit", True) sleep_ = kwargs.pop("sleep", 0) env_ = kwargs.pop("env", None) p = Popen([self.deno_exe], stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env_) try: time.sleep(sleep_) for line in lines: p.stdin.write(line.encode("utf-8") + b'\n') p.stdin.flush() time.sleep(sleep_) if exit_: p.stdin.write(b'Deno.exit(0)\n') else: time.sleep(1) # wait to be killed by js out, err = p.communicate() except CalledProcessError as e: p.kill() p.wait() raise e retcode = p.poll() # Ignore Windows CRLF (\r\n). return out.replace('\r\n', '\n'), err.replace('\r\n', '\n'), retcode def test_console_log(self): out, err, code = self.input("console.log('hello')", "'world'") self.assertEqual(out, 'hello\nundefined\nworld\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_eof(self): out, err, code = self.input("1 + 2", exit=False) self.assertEqual(out, '3\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_exit_command(self): out, err, code = self.input("exit", "'ignored'", exit=False) self.assertEqual(out, '') self.assertEqual(err, '') self.assertEqual(code, 0) def test_help_command(self): out, err, code = self.input("help") expectedOut = '\n'.join([ "_ Get last evaluation result", "_error Get last thrown error", "exit Exit the REPL", "help Print this help message", "", ]) self.assertEqual(out, expectedOut) self.assertEqual(err, '') self.assertEqual(code, 0) def test_function(self): out, err, code = self.input("Deno.writeFileSync") self.assertEqual(out, '[Function: writeFileSync]\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_multiline(self): out, err, code = self.input("(\n1 + 2\n)") self.assertEqual(out, '3\n') self.assertEqual(err, '') self.assertEqual(code, 0) # This should print error instead of wait for input def test_eval_unterminated(self): out, err, code = self.input("eval('{')") self.assertEqual(out, '') assert "Unexpected end of input" in err self.assertEqual(code, 0) def test_reference_error(self): out, err, code = self.input("not_a_variable") self.assertEqual(out, '') assert "not_a_variable is not defined" in err self.assertEqual(code, 0) # def test_set_timeout(self): # out, err, code = self.input( # "setTimeout(() => { console.log('b'); Deno.exit(0); }, 1)", # "'a'", # exit=False) # self.assertEqual(out, '1\na\nb\n') # self.assertEqual(err, '') # self.assertEqual(code, 0) # def test_set_timeout_interlaced(self): # out, err, code = self.input( # "setTimeout(() => console.log('a'), 1)", # "setTimeout(() => console.log('b'), 6)", # sleep=0.8) # self.assertEqual(out, '1\n2\na\nb\n') # self.assertEqual(err, '') # self.assertEqual(code, 0) # def test_async_op(self): # out, err, code = self.input( # "fetch('http://localhost:4545/tests/001_hello.js')" + # ".then(res => res.text()).then(console.log)", # sleep=1) # self.assertEqual(out, 'Promise {}\nconsole.log("Hello World");\n\n') # self.assertEqual(err, '') # self.assertEqual(code, 0) def test_syntax_error(self): out, err, code = self.input("syntax error") self.assertEqual(out, '') assert "Unexpected identifier" in err self.assertEqual(code, 0) def test_type_error(self): out, err, code = self.input("console()") self.assertEqual(out, '') assert "console is not a function" in err self.assertEqual(code, 0) def test_variable(self): out, err, code = self.input("var a = 123;", "a") self.assertEqual(out, 'undefined\n123\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_lexical_scoped_variable(self): out, err, code = self.input("let a = 123;", "a") self.assertEqual(out, 'undefined\n123\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_missing_deno_dir(self): deno_dir = "nonexistent" new_env = os.environ.copy() new_env["DENO_DIR"] = deno_dir out, err, code = self.input("1", exit=False, env=new_env) self.assertTrue(os.path.isdir(deno_dir)) shutil.rmtree(deno_dir) self.assertEqual(out, "1\n") self.assertEqual(err, "") self.assertEqual(code, 0) def test_save_last_eval(self): out, err, code = self.input("1", "_") self.assertEqual(out, '1\n1\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_save_last_thrown(self): out, err, code = self.input("throw 1", "_error") self.assertEqual(out, '1\n') self.assertEqual(err, 'Thrown: 1\n') self.assertEqual(code, 0) def test_assign_underscore(self): out, err, code = self.input("_ = 1", "2", "_") self.assertEqual( out, 'Last evaluation result is no longer saved to _.\n1\n2\n1\n') self.assertEqual(err, '') self.assertEqual(code, 0) def test_assign_underscore_error(self): out, err, code = self.input("_error = 1", "throw 2", "_error") self.assertEqual( out, 'Last thrown error is no longer saved to _error.\n1\n1\n') self.assertEqual(err, 'Thrown: 2\n') self.assertEqual(code, 0) if __name__ == "__main__": run_tests()
true
true
1c4441f790e3934fdb9d9e916372990dbd0cc4c5
1,505
py
Python
src/ToolBox/SOS/tests/t_cmd_bpmd_module_function_iloffset.py
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
8
2020-01-15T11:09:15.000Z
2021-08-25T08:54:55.000Z
src/ToolBox/SOS/tests/t_cmd_bpmd_module_function_iloffset.py
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
3
2018-01-03T00:57:25.000Z
2018-10-05T16:17:52.000Z
src/ToolBox/SOS/tests/t_cmd_bpmd_module_function_iloffset.py
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
1
2020-11-17T14:55:53.000Z
2020-11-17T14:55:53.000Z
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the MIT license. # See the LICENSE file in the project root for more information. import lldb import re import testutils as test # bpmd <module name> <managed function name> [<il offset>] def runScenario(assembly, debugger, target): process = target.GetProcess() res = lldb.SBCommandReturnObject() ci = debugger.GetCommandInterpreter() # Run debugger, wait until libcoreclr is loaded, # set breakpoint at Test.Main and stop there test.stop_in_main(debugger, assembly) ci.HandleCommand("bpmd " + assembly + " Test.UnlikelyInlined 66", res) out_msg = res.GetOutput() err_msg = res.GetError() print(out_msg) print(err_msg) # Interpreter must have this command and able to run it test.assertTrue(res.Succeeded()) # Output is not empty # Should be at least 'Adding pending breakpoints...' test.assertTrue(len(out_msg) > 0) # Error message is empty test.assertTrue(len(err_msg) == 0) process.Continue() # Process must be stopped at UnlinkelyInlined test.assertEqual(process.GetState(), lldb.eStateStopped) # The reason of this stop must be a breakpoint test.assertEqual(process.GetSelectedThread().GetStopReason(), lldb.eStopReasonBreakpoint) # # Delete all breakpoints, continue current process and checks its exit code test.exit_lldb(debugger, assembly)
31.354167
79
0.710299
import lldb import re import testutils as test def runScenario(assembly, debugger, target): process = target.GetProcess() res = lldb.SBCommandReturnObject() ci = debugger.GetCommandInterpreter() test.stop_in_main(debugger, assembly) ci.HandleCommand("bpmd " + assembly + " Test.UnlikelyInlined 66", res) out_msg = res.GetOutput() err_msg = res.GetError() print(out_msg) print(err_msg) test.assertTrue(res.Succeeded()) test.assertTrue(len(out_msg) > 0) test.assertTrue(len(err_msg) == 0) process.Continue() test.assertEqual(process.GetState(), lldb.eStateStopped) test.assertEqual(process.GetSelectedThread().GetStopReason(), lldb.eStopReasonBreakpoint) test.exit_lldb(debugger, assembly)
true
true
1c44426edb5f00a1194a178579284f2e8d2aa873
1,626
py
Python
scripts/iclr_2018/rl_size.py
alcinos/dps
5467db1216e9f9089376d2c71f524ced2382e4f6
[ "Apache-2.0" ]
null
null
null
scripts/iclr_2018/rl_size.py
alcinos/dps
5467db1216e9f9089376d2c71f524ced2382e4f6
[ "Apache-2.0" ]
null
null
null
scripts/iclr_2018/rl_size.py
alcinos/dps
5467db1216e9f9089376d2c71f524ced2382e4f6
[ "Apache-2.0" ]
null
null
null
import numpy as np import os import clify import argparse from config import rl_config as config config.update( image_shape_grid=(3, 3), reductions="sum", ) grid = [dict(n_train=1, do_train=False)] + [dict(n_train=x) for x in 2**np.arange(0, 18, 2)] parser = argparse.ArgumentParser() parser.add_argument("--task", choices="A B C D E F 0".split(), default='') args, _ = parser.parse_known_args() stage_1 = dict() stage_2 = dict(min_digits=4, max_digits=4) stage_3 = dict(min_digits=5, max_digits=5) if args.task == "0": grid = dict(n_train=2**np.arange(14, 18, 2)) config.update(image_shape_grid=(2, 2)) elif args.task == "A": zero_dir = "/home/e2crawfo/rl_size_0/" config.load_path = [ os.path.join(zero_dir, d, 'weights/best_of_stage_0') for d in os.listdir(zero_dir) ] config.update(stage_1) elif args.task == "B": A_dir = "/home/e2crawfo/rl_size_A/" config.load_path = [ os.path.join(A_dir, d, 'weights/best_of_stage_0') for d in os.listdir(A_dir) ] config.update(stage_2) elif args.task == "C": B_dir = "/home/e2crawfo/rl_size_B/" config.load_path = [ os.path.join(B_dir, d, 'weights/best_of_stage_0') for d in os.listdir(B_dir) ] config.update(stage_3) elif args.task == "D": config.update(stage_1) elif args.task == "E": config.update(stage_2) elif args.task == "F": config.update(stage_3) else: raise Exception() from dps.hyper import build_and_submit, default_host_pool clify.wrap_function(build_and_submit)( config=config, distributions=grid, n_param_settings=None, host_pool=default_host_pool)
26.225806
92
0.682657
import numpy as np import os import clify import argparse from config import rl_config as config config.update( image_shape_grid=(3, 3), reductions="sum", ) grid = [dict(n_train=1, do_train=False)] + [dict(n_train=x) for x in 2**np.arange(0, 18, 2)] parser = argparse.ArgumentParser() parser.add_argument("--task", choices="A B C D E F 0".split(), default='') args, _ = parser.parse_known_args() stage_1 = dict() stage_2 = dict(min_digits=4, max_digits=4) stage_3 = dict(min_digits=5, max_digits=5) if args.task == "0": grid = dict(n_train=2**np.arange(14, 18, 2)) config.update(image_shape_grid=(2, 2)) elif args.task == "A": zero_dir = "/home/e2crawfo/rl_size_0/" config.load_path = [ os.path.join(zero_dir, d, 'weights/best_of_stage_0') for d in os.listdir(zero_dir) ] config.update(stage_1) elif args.task == "B": A_dir = "/home/e2crawfo/rl_size_A/" config.load_path = [ os.path.join(A_dir, d, 'weights/best_of_stage_0') for d in os.listdir(A_dir) ] config.update(stage_2) elif args.task == "C": B_dir = "/home/e2crawfo/rl_size_B/" config.load_path = [ os.path.join(B_dir, d, 'weights/best_of_stage_0') for d in os.listdir(B_dir) ] config.update(stage_3) elif args.task == "D": config.update(stage_1) elif args.task == "E": config.update(stage_2) elif args.task == "F": config.update(stage_3) else: raise Exception() from dps.hyper import build_and_submit, default_host_pool clify.wrap_function(build_and_submit)( config=config, distributions=grid, n_param_settings=None, host_pool=default_host_pool)
true
true
1c444325429659bd2cf13dac06eb07c96a0b5de1
2,456
py
Python
pcdet/models/model_utils/model_nms_utils.py
collector-m/ST3D
720e04aa3dc4bb95ac336171b240b6c3130144e5
[ "Apache-2.0" ]
null
null
null
pcdet/models/model_utils/model_nms_utils.py
collector-m/ST3D
720e04aa3dc4bb95ac336171b240b6c3130144e5
[ "Apache-2.0" ]
null
null
null
pcdet/models/model_utils/model_nms_utils.py
collector-m/ST3D
720e04aa3dc4bb95ac336171b240b6c3130144e5
[ "Apache-2.0" ]
null
null
null
import torch from ...ops.iou3d_nms import iou3d_nms_utils def class_agnostic_nms(box_scores, box_preds, nms_config, score_thresh=None): src_box_scores = box_scores if score_thresh is not None: scores_mask = (box_scores >= score_thresh) box_scores = box_scores[scores_mask] box_preds = box_preds[scores_mask] selected = [] if box_scores.shape[0] > 0: box_scores_nms, indices = torch.topk(box_scores, k=min(nms_config.NMS_PRE_MAXSIZE, box_scores.shape[0])) boxes_for_nms = box_preds[indices] keep_idx, selected_scores = getattr(iou3d_nms_utils, nms_config.NMS_TYPE)( boxes_for_nms[:, 0:7], box_scores_nms, nms_config.NMS_THRESH, **nms_config ) selected = indices[keep_idx[:nms_config.NMS_POST_MAXSIZE]] if score_thresh is not None: original_idxs = scores_mask.nonzero().view(-1) selected = original_idxs[selected] return selected, src_box_scores[selected] def multi_classes_nms(cls_scores, box_preds, nms_config, score_thresh=None): """ Args: cls_scores: (N, num_class) box_preds: (N, 7 + C) nms_config: score_thresh: Returns: """ pred_scores, pred_labels, pred_boxes = [], [], [] for k in range(cls_scores.shape[1]): if score_thresh is not None: scores_mask = (cls_scores[:, k] >= score_thresh) box_scores = cls_scores[scores_mask, k] cur_box_preds = box_preds[scores_mask] else: box_scores = cls_scores[:, k] cur_box_preds = box_preds selected = [] if box_scores.shape[0] > 0: box_scores_nms, indices = torch.topk(box_scores, k=min(nms_config.NMS_PRE_MAXSIZE, box_scores.shape[0])) boxes_for_nms = cur_box_preds[indices] keep_idx, selected_scores = getattr(iou3d_nms_utils, nms_config.NMS_TYPE)( boxes_for_nms[:, 0:7], box_scores_nms, nms_config.NMS_THRESH, **nms_config ) selected = indices[keep_idx[:nms_config.NMS_POST_MAXSIZE]] pred_scores.append(box_scores[selected]) pred_labels.append(box_scores.new_ones(len(selected)).long() * k) pred_boxes.append(cur_box_preds[selected]) pred_scores = torch.cat(pred_scores, dim=0) pred_labels = torch.cat(pred_labels, dim=0) pred_boxes = torch.cat(pred_boxes, dim=0) return pred_scores, pred_labels, pred_boxes
37.212121
116
0.661645
import torch from ...ops.iou3d_nms import iou3d_nms_utils def class_agnostic_nms(box_scores, box_preds, nms_config, score_thresh=None): src_box_scores = box_scores if score_thresh is not None: scores_mask = (box_scores >= score_thresh) box_scores = box_scores[scores_mask] box_preds = box_preds[scores_mask] selected = [] if box_scores.shape[0] > 0: box_scores_nms, indices = torch.topk(box_scores, k=min(nms_config.NMS_PRE_MAXSIZE, box_scores.shape[0])) boxes_for_nms = box_preds[indices] keep_idx, selected_scores = getattr(iou3d_nms_utils, nms_config.NMS_TYPE)( boxes_for_nms[:, 0:7], box_scores_nms, nms_config.NMS_THRESH, **nms_config ) selected = indices[keep_idx[:nms_config.NMS_POST_MAXSIZE]] if score_thresh is not None: original_idxs = scores_mask.nonzero().view(-1) selected = original_idxs[selected] return selected, src_box_scores[selected] def multi_classes_nms(cls_scores, box_preds, nms_config, score_thresh=None): pred_scores, pred_labels, pred_boxes = [], [], [] for k in range(cls_scores.shape[1]): if score_thresh is not None: scores_mask = (cls_scores[:, k] >= score_thresh) box_scores = cls_scores[scores_mask, k] cur_box_preds = box_preds[scores_mask] else: box_scores = cls_scores[:, k] cur_box_preds = box_preds selected = [] if box_scores.shape[0] > 0: box_scores_nms, indices = torch.topk(box_scores, k=min(nms_config.NMS_PRE_MAXSIZE, box_scores.shape[0])) boxes_for_nms = cur_box_preds[indices] keep_idx, selected_scores = getattr(iou3d_nms_utils, nms_config.NMS_TYPE)( boxes_for_nms[:, 0:7], box_scores_nms, nms_config.NMS_THRESH, **nms_config ) selected = indices[keep_idx[:nms_config.NMS_POST_MAXSIZE]] pred_scores.append(box_scores[selected]) pred_labels.append(box_scores.new_ones(len(selected)).long() * k) pred_boxes.append(cur_box_preds[selected]) pred_scores = torch.cat(pred_scores, dim=0) pred_labels = torch.cat(pred_labels, dim=0) pred_boxes = torch.cat(pred_boxes, dim=0) return pred_scores, pred_labels, pred_boxes
true
true
1c4445883af2eafcd549de66e969b087215c7666
2,335
py
Python
_matplotlibsettings.py
WillemWybo/Electrical_compartmentalization_in_neurons
1ff297be97412ff40042485479b78148fba11c27
[ "MIT" ]
null
null
null
_matplotlibsettings.py
WillemWybo/Electrical_compartmentalization_in_neurons
1ff297be97412ff40042485479b78148fba11c27
[ "MIT" ]
null
null
null
_matplotlibsettings.py
WillemWybo/Electrical_compartmentalization_in_neurons
1ff297be97412ff40042485479b78148fba11c27
[ "MIT" ]
null
null
null
import matplotlib # matplotlib.use("Agg") import matplotlib.pyplot as pl import matplotlib.animation as manimation from matplotlib.gridspec import GridSpec from matplotlib.patches import Rectangle from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib import rc, rcParams from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from mpl_toolkits.axes_grid1.inset_locator import inset_axes from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import mark_inset from matplotlib.offsetbox import AnchoredText # colours = ['DeepPink', 'Purple', 'MediumSlateBlue', 'Blue', 'Teal', # 'ForestGreen', 'DarkOliveGreen', 'DarkGoldenRod', # 'DarkOrange', 'Coral', 'Red', 'Sienna', 'Black', 'DarkGrey'] colours = list(pl.rcParams['axes.prop_cycle'].by_key()['color']) # matplotlib settings legendsize = 10 labelsize = 15 ticksize = 15 lwidth = 1.5 markersize = 6. fontsize = 16 lettersize = 20. #~ font = {'family' : 'serif', #~ 'weight' : 'normal', #~ 'size' : fontsize} #'sans-serif':'Helvetica'} #'family':'serif','serif':['Palatino']} #~ rc('font', **font) rc('font',**{'family':'serif','serif':['Palatino'], 'size': 15.0}) rc('mathtext',**{'fontset': 'stixsans'}) # rc('text', usetex=True) # rcParams['text.latex.preamble'].append(r"\usepackage{amsmath}\usepackage{xfrac}") rc('legend',**{'fontsize': 'medium'}) rc('xtick',**{'labelsize': 'small'}) rc('ytick',**{'labelsize': 'small'}) rc('axes',**{'labelsize': 'large', 'labelweight': 'normal'}) cs = ['r', 'b', 'g', 'c', 'y'] mfs = ['D', 'o', 'v', '^', 's', 'p'] mls = ['+', '*', 'x', '1', '2'] lss = ['-', '--', '-.', ':'] cmap = pl.get_cmap('jet') def myAx(ax): # customize the ax ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') return ax def myLegend(ax, add_frame=True, **kwarg): leg = ax.legend(**kwarg) if add_frame: frame = leg.get_frame() frame.set_color('white') frame.set_alpha(0.8) return leg def myColorbar(ax, im, **kwargs): divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") return pl.colorbar(im, cax=cax, **kwargs)
31.133333
83
0.65182
import matplotlib import matplotlib.pyplot as pl import matplotlib.animation as manimation from matplotlib.gridspec import GridSpec from matplotlib.patches import Rectangle from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib import rc, rcParams from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from mpl_toolkits.axes_grid1.inset_locator import inset_axes from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import mark_inset from matplotlib.offsetbox import AnchoredText colours = list(pl.rcParams['axes.prop_cycle'].by_key()['color']) legendsize = 10 labelsize = 15 ticksize = 15 lwidth = 1.5 markersize = 6. fontsize = 16 lettersize = 20. rc('font',**{'family':'serif','serif':['Palatino'], 'size': 15.0}) rc('mathtext',**{'fontset': 'stixsans'}) rc('legend',**{'fontsize': 'medium'}) rc('xtick',**{'labelsize': 'small'}) rc('ytick',**{'labelsize': 'small'}) rc('axes',**{'labelsize': 'large', 'labelweight': 'normal'}) cs = ['r', 'b', 'g', 'c', 'y'] mfs = ['D', 'o', 'v', '^', 's', 'p'] mls = ['+', '*', 'x', '1', '2'] lss = ['-', '--', '-.', ':'] cmap = pl.get_cmap('jet') def myAx(ax): ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') return ax def myLegend(ax, add_frame=True, **kwarg): leg = ax.legend(**kwarg) if add_frame: frame = leg.get_frame() frame.set_color('white') frame.set_alpha(0.8) return leg def myColorbar(ax, im, **kwargs): divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="3%") return pl.colorbar(im, cax=cax, **kwargs)
true
true
1c4445b06c65961d851d7965795b569e737f3f68
256
py
Python
image_resize.py
cristianoc20/Rebar_Detection
8a1cf22bc82c5998376cc034c9a7317401d5b2e3
[ "MIT" ]
58
2020-03-07T16:40:20.000Z
2022-03-31T08:57:05.000Z
image_resize.py
JackySnake/Rebar_Detection
8a1cf22bc82c5998376cc034c9a7317401d5b2e3
[ "MIT" ]
13
2020-03-08T11:00:58.000Z
2022-03-12T00:17:59.000Z
image_resize.py
JackySnake/Rebar_Detection
8a1cf22bc82c5998376cc034c9a7317401d5b2e3
[ "MIT" ]
17
2020-03-09T09:22:33.000Z
2022-02-23T09:20:18.000Z
import glob as gb #导入glob模块 import cv2 import os # 返回该路径下所有的 jpg 文件的路径 img_path = gb.glob("./data/test_dataset/*.jpg") for path in img_path: (filepath, tempfilename) = os.path.split(path) (filename, extension) = os.path.splitext(tempfilename)
23.272727
58
0.71875
import glob as gb import cv2 import os img_path = gb.glob("./data/test_dataset/*.jpg") for path in img_path: (filepath, tempfilename) = os.path.split(path) (filename, extension) = os.path.splitext(tempfilename)
true
true
1c44481706e54082a191a60d87d3f384cd42fec6
10,802
py
Python
vn/generator.py
Jemesson/nlp-conceptual-model
26ad7249be4ccb3863c0852738eaa8b6ddcf63f3
[ "MIT" ]
null
null
null
vn/generator.py
Jemesson/nlp-conceptual-model
26ad7249be4ccb3863c0852738eaa8b6ddcf63f3
[ "MIT" ]
null
null
null
vn/generator.py
Jemesson/nlp-conceptual-model
26ad7249be4ccb3863c0852738eaa8b6ddcf63f3
[ "MIT" ]
1
2021-11-02T03:41:17.000Z
2021-11-02T03:41:17.000Z
import os from lang.owlprefix import PREFIX_DICT from vn.utility import t, is_i, tab, is_comment, occurence_list, is_us from jinja2 import FileSystemLoader, Environment class Generator: def __init__(self, classes, relationships, onto=True, is_long=None): self.classes = classes self.relationships = relationships self.long = is_long self.onto = onto def prt(self, onto): for c in self.classes: c.stories.sort() if not self.onto: return self.gen_prolog_from_onto() if self.long is None: li = self.gen_ontology(onto) else: li = self.gen_ontology(onto) return li def gen_ontology(self, onto): ontologytext = '' rellist = [] clist = [] ontologytext += onto.gen_head(onto.get_prefixes()).prt() + "\n" if self.relationships: ontologytext += onto.gh.comment("Relationships") unique_rels = self.make_unique_relationships() for r in unique_rels: ontologytext += r.prt() + "\n" if self.classes: ontologytext += onto.gh.comment("Classes") for c in self.classes: ontologytext += c.prt() + "\n" return ontologytext def make_unique_relationships(self): rel_names = set([r.name for r in self.relationships]) new_rels = [] for rn in rel_names: rels_of_name = [] pairs = [] cnt = 1 for r in self.relationships: if r.name == rn: if [r.domain, r.range] not in pairs: rels_of_name.append(r) pairs.append([r.domain, r.range]) if len(rels_of_name) > 1: for ron in rels_of_name: new_relationship = OntProperty(ron.ontobj, "Object", ron.name + str(cnt), ron.domain, ron.range) new_relationship.stories = ron.stories new_rels.append(new_relationship) cnt += 1 else: for r in self.relationships: if r.name == rn: new_rels.append(r) return new_rels def gen_prolog_from_onto(self): prologtext = [] concept = "" for c in self.classes: concept = self.get_concept(c.name) prologtext.append(concept) for s in c.stories: if self.get_found(concept, s): prologtext.append(self.get_found(concept, s)) for r in self.relationships: d_concept = self.get_concept(r.domain) r_concept = self.get_concept(r.range) rel = "" linkrel = ['role', 'means', 'ends'] diffrel = linkrel + ['isa'] if str.lower(r.name) in diffrel: if str.lower(r.name) in linkrel: prologtext.append(str.lower(r.name) + "(" + d_concept + ",'" + r.range + "')") else: prologtext.append(str.lower(r.name) + "(" + d_concept + "," + r_concept + ")") else: rel = "rel(" + d_concept + ",'" + r.name + "'," + r_concept + ")" prologtext.append(rel) for s in r.stories: if self.get_found(rel, s): prologtext.append(self.get_found(rel, s)) prologtext.sort() return '.\n'.join(prologtext) def get_concept(self, text): return "concept('" + str(text) + "')" def get_found(self, text, story): if story >= 0: return "found(" + text + ",'US" + str(story) + "')" return False @staticmethod def gen_report(path, report_template): """Generates a report using Jinja2 :param report_dict: Dictionary containing all variables used in the report :returns: HTML page """ loader = FileSystemLoader(searchpath=path + "/templates/") env = Environment(loader=loader, trim_blocks=True, lstrip_blocks=True) env.globals['text'] = t env.globals['is_i'] = is_i env.globals['apply_tab'] = tab env.globals['is_comment'] = is_comment env.globals['occurence_list'] = occurence_list env.tests['is_us'] = is_us template = env.get_template("report.html") return template.render(report_template) class GenHelp: def __init__(self, ontology, option=None): self.ontology = ontology self.option = option def make_prefix(self, indicator, link): return "Prefix: " + indicator + ": <" + link + ">\n" def make_obj(self, name, prefix='', isname=None): if not self.option: return prefix + ":" + name + "\n" else: if prefix is '': prefix = self.ontology else: prefix = PREFIX_DICT[prefix] return "<" + prefix + name + ">\n" def make_part(self, left, right): return "\t" + left + ": " + right def space(self): return "" def comment(self, com): return "# " + com + "\n" class Ontology: def __init__(self, sysname, stories, option=None): self.sys_name = sysname self.ontology = "http://fakesite.org/" + "_".join(str(sysname).lower().split()) + ".owl#" self.ontology_name = "onto" self.option = option self.gh = GenHelp(self.ontology, option) self.stories = stories self.classes = [] self.relationships = [] def gen_head(self, parts): return Header(self, parts) def get_prefixes(self): return [str(c.prefix) for c in self.classes] def make_class(self, name, parent="Thing", prefix=''): return OntClass(self, name, parent, prefix) def make_relationship(self, name, domain, range): new_property = OntProperty(self, "Object", name, domain, range) return new_property def get_class_by_name(self, story, name, parent='', is_role=False): if self.is_empty(name): return False c_stories = [] if self.classes: for c in self.classes: if str.lower(name) == str.lower(c.name) and (str.lower(parent) == str.lower(c.parent) or ( self.is_empty(parent) and self.is_empty(c.parent))): if is_role: c.is_role = True c.stories.append(story) return c if str.lower(name) == str.lower(c.name) and not self.is_empty(c.parent) and self.is_empty(parent): if is_role: c.is_role = True c.stories.append(story) return c if str.lower(name) == str.lower(c.name) and not self.is_empty(parent): c_stories = c.stories self.classes.remove(c) new_class = self.make_class(name, parent) if is_role: new_class.is_role = True new_class.stories = c_stories new_class.stories.append(story) self.classes.append(new_class) if not self.is_empty(parent): parent_class = self.get_class_by_name(-1, parent, '') return new_class def is_empty(self, word): if word.isspace() or word == '': return True return False def new_relationship(self, story, pre, rel, post): if self.relationships: for r in self.relationships: if r.domain == pre and r.name == rel and r.range == post: r.stories.append(story) return r new_rel = self.make_relationship(rel, pre, post) new_rel.stories.append(story) self.relationships.append(new_rel) return new_rel class OntClass(object): def __init__(self, ontology, name, parent, prefix=''): self.ontobj = ontology self.name = name self.parent = parent self.prefix = prefix self.stories = [] self.is_role = False def prt(self): name = ''.join(self.name.split()) parent = ''.join(self.parent.split()) returnstr = "" returnstr += "Class: " + self.ontobj.gh.make_obj(name) if self.parent == "Thing" or self.parent == '': pass else: returnstr += self.ontobj.gh.make_part("SubClassOf", self.ontobj.gh.make_obj(parent, self.prefix)) if self.name != name or self.is_role: returnstr += "\tAnnotations:" if self.name != name: returnstr += "\n\t\trdfs:label \"%s\"" % (self.name) if self.name != name and self.is_role: returnstr += "," if self.is_role: returnstr += "\n\t\trdfs:comment \"Functional Role\"" returnstr += "\n" return returnstr def set_role(self): self.is_role = True class OntProperty(object): def __init__(self, ontology, type, name, domain, range): self.ontobj = ontology self.type = type self.name = name self.domain = domain self.range = range self.stories = [] def prt(self): name = ''.join(self.name.split()) domain = ''.join(self.domain.split()) range = ''.join(self.range.split()) returnstr = "" returnstr += self.type + "Property: " + self.ontobj.gh.make_obj(name) returnstr += self.ontobj.gh.make_part("Domain", self.ontobj.gh.make_obj(domain)) returnstr += self.ontobj.gh.make_part("Range", self.ontobj.gh.make_obj(range)) return returnstr class Header: def __init__(self, ontology, used_prefixes): self.ontobj = ontology self.standard_prefixes = ['owl', 'rdf', 'rdfs', 'xsd', 'dc'] self.used_prefixes = self.standard_prefixes + used_prefixes def prt(self): returnstr = "" returnstr += self.ontobj.gh.comment("Generated with Visual Narrator") returnstr += self.ontobj.gh.make_prefix('', self.ontobj.ontology) for prefix in self.used_prefixes: if prefix is not '': link = str(PREFIX_DICT[prefix]) returnstr += self.ontobj.gh.make_prefix(prefix, link) returnstr += self.ontobj.gh.make_prefix(self.ontobj.ontology_name, self.ontobj.ontology) returnstr += "\nOntology: <:>\n\n" returnstr += "Annotations:\n\tdc:title \"" + str( self.ontobj.sys_name) + "\",\n\tdc:creator \"Visual Narrator\",\n\trdfs:comment \"Generated with Visual Narrator\"\n\n" returnstr += "AnnotationProperty: dc:creator\n\n" returnstr += "AnnotationProperty: dc:title\n\n" return returnstr
33.339506
131
0.552861
import os from lang.owlprefix import PREFIX_DICT from vn.utility import t, is_i, tab, is_comment, occurence_list, is_us from jinja2 import FileSystemLoader, Environment class Generator: def __init__(self, classes, relationships, onto=True, is_long=None): self.classes = classes self.relationships = relationships self.long = is_long self.onto = onto def prt(self, onto): for c in self.classes: c.stories.sort() if not self.onto: return self.gen_prolog_from_onto() if self.long is None: li = self.gen_ontology(onto) else: li = self.gen_ontology(onto) return li def gen_ontology(self, onto): ontologytext = '' rellist = [] clist = [] ontologytext += onto.gen_head(onto.get_prefixes()).prt() + "\n" if self.relationships: ontologytext += onto.gh.comment("Relationships") unique_rels = self.make_unique_relationships() for r in unique_rels: ontologytext += r.prt() + "\n" if self.classes: ontologytext += onto.gh.comment("Classes") for c in self.classes: ontologytext += c.prt() + "\n" return ontologytext def make_unique_relationships(self): rel_names = set([r.name for r in self.relationships]) new_rels = [] for rn in rel_names: rels_of_name = [] pairs = [] cnt = 1 for r in self.relationships: if r.name == rn: if [r.domain, r.range] not in pairs: rels_of_name.append(r) pairs.append([r.domain, r.range]) if len(rels_of_name) > 1: for ron in rels_of_name: new_relationship = OntProperty(ron.ontobj, "Object", ron.name + str(cnt), ron.domain, ron.range) new_relationship.stories = ron.stories new_rels.append(new_relationship) cnt += 1 else: for r in self.relationships: if r.name == rn: new_rels.append(r) return new_rels def gen_prolog_from_onto(self): prologtext = [] concept = "" for c in self.classes: concept = self.get_concept(c.name) prologtext.append(concept) for s in c.stories: if self.get_found(concept, s): prologtext.append(self.get_found(concept, s)) for r in self.relationships: d_concept = self.get_concept(r.domain) r_concept = self.get_concept(r.range) rel = "" linkrel = ['role', 'means', 'ends'] diffrel = linkrel + ['isa'] if str.lower(r.name) in diffrel: if str.lower(r.name) in linkrel: prologtext.append(str.lower(r.name) + "(" + d_concept + ",'" + r.range + "')") else: prologtext.append(str.lower(r.name) + "(" + d_concept + "," + r_concept + ")") else: rel = "rel(" + d_concept + ",'" + r.name + "'," + r_concept + ")" prologtext.append(rel) for s in r.stories: if self.get_found(rel, s): prologtext.append(self.get_found(rel, s)) prologtext.sort() return '.\n'.join(prologtext) def get_concept(self, text): return "concept('" + str(text) + "')" def get_found(self, text, story): if story >= 0: return "found(" + text + ",'US" + str(story) + "')" return False @staticmethod def gen_report(path, report_template): loader = FileSystemLoader(searchpath=path + "/templates/") env = Environment(loader=loader, trim_blocks=True, lstrip_blocks=True) env.globals['text'] = t env.globals['is_i'] = is_i env.globals['apply_tab'] = tab env.globals['is_comment'] = is_comment env.globals['occurence_list'] = occurence_list env.tests['is_us'] = is_us template = env.get_template("report.html") return template.render(report_template) class GenHelp: def __init__(self, ontology, option=None): self.ontology = ontology self.option = option def make_prefix(self, indicator, link): return "Prefix: " + indicator + ": <" + link + ">\n" def make_obj(self, name, prefix='', isname=None): if not self.option: return prefix + ":" + name + "\n" else: if prefix is '': prefix = self.ontology else: prefix = PREFIX_DICT[prefix] return "<" + prefix + name + ">\n" def make_part(self, left, right): return "\t" + left + ": " + right def space(self): return "" def comment(self, com): return "# " + com + "\n" class Ontology: def __init__(self, sysname, stories, option=None): self.sys_name = sysname self.ontology = "http://fakesite.org/" + "_".join(str(sysname).lower().split()) + ".owl#" self.ontology_name = "onto" self.option = option self.gh = GenHelp(self.ontology, option) self.stories = stories self.classes = [] self.relationships = [] def gen_head(self, parts): return Header(self, parts) def get_prefixes(self): return [str(c.prefix) for c in self.classes] def make_class(self, name, parent="Thing", prefix=''): return OntClass(self, name, parent, prefix) def make_relationship(self, name, domain, range): new_property = OntProperty(self, "Object", name, domain, range) return new_property def get_class_by_name(self, story, name, parent='', is_role=False): if self.is_empty(name): return False c_stories = [] if self.classes: for c in self.classes: if str.lower(name) == str.lower(c.name) and (str.lower(parent) == str.lower(c.parent) or ( self.is_empty(parent) and self.is_empty(c.parent))): if is_role: c.is_role = True c.stories.append(story) return c if str.lower(name) == str.lower(c.name) and not self.is_empty(c.parent) and self.is_empty(parent): if is_role: c.is_role = True c.stories.append(story) return c if str.lower(name) == str.lower(c.name) and not self.is_empty(parent): c_stories = c.stories self.classes.remove(c) new_class = self.make_class(name, parent) if is_role: new_class.is_role = True new_class.stories = c_stories new_class.stories.append(story) self.classes.append(new_class) if not self.is_empty(parent): parent_class = self.get_class_by_name(-1, parent, '') return new_class def is_empty(self, word): if word.isspace() or word == '': return True return False def new_relationship(self, story, pre, rel, post): if self.relationships: for r in self.relationships: if r.domain == pre and r.name == rel and r.range == post: r.stories.append(story) return r new_rel = self.make_relationship(rel, pre, post) new_rel.stories.append(story) self.relationships.append(new_rel) return new_rel class OntClass(object): def __init__(self, ontology, name, parent, prefix=''): self.ontobj = ontology self.name = name self.parent = parent self.prefix = prefix self.stories = [] self.is_role = False def prt(self): name = ''.join(self.name.split()) parent = ''.join(self.parent.split()) returnstr = "" returnstr += "Class: " + self.ontobj.gh.make_obj(name) if self.parent == "Thing" or self.parent == '': pass else: returnstr += self.ontobj.gh.make_part("SubClassOf", self.ontobj.gh.make_obj(parent, self.prefix)) if self.name != name or self.is_role: returnstr += "\tAnnotations:" if self.name != name: returnstr += "\n\t\trdfs:label \"%s\"" % (self.name) if self.name != name and self.is_role: returnstr += "," if self.is_role: returnstr += "\n\t\trdfs:comment \"Functional Role\"" returnstr += "\n" return returnstr def set_role(self): self.is_role = True class OntProperty(object): def __init__(self, ontology, type, name, domain, range): self.ontobj = ontology self.type = type self.name = name self.domain = domain self.range = range self.stories = [] def prt(self): name = ''.join(self.name.split()) domain = ''.join(self.domain.split()) range = ''.join(self.range.split()) returnstr = "" returnstr += self.type + "Property: " + self.ontobj.gh.make_obj(name) returnstr += self.ontobj.gh.make_part("Domain", self.ontobj.gh.make_obj(domain)) returnstr += self.ontobj.gh.make_part("Range", self.ontobj.gh.make_obj(range)) return returnstr class Header: def __init__(self, ontology, used_prefixes): self.ontobj = ontology self.standard_prefixes = ['owl', 'rdf', 'rdfs', 'xsd', 'dc'] self.used_prefixes = self.standard_prefixes + used_prefixes def prt(self): returnstr = "" returnstr += self.ontobj.gh.comment("Generated with Visual Narrator") returnstr += self.ontobj.gh.make_prefix('', self.ontobj.ontology) for prefix in self.used_prefixes: if prefix is not '': link = str(PREFIX_DICT[prefix]) returnstr += self.ontobj.gh.make_prefix(prefix, link) returnstr += self.ontobj.gh.make_prefix(self.ontobj.ontology_name, self.ontobj.ontology) returnstr += "\nOntology: <:>\n\n" returnstr += "Annotations:\n\tdc:title \"" + str( self.ontobj.sys_name) + "\",\n\tdc:creator \"Visual Narrator\",\n\trdfs:comment \"Generated with Visual Narrator\"\n\n" returnstr += "AnnotationProperty: dc:creator\n\n" returnstr += "AnnotationProperty: dc:title\n\n" return returnstr
true
true
1c4449b854f1469faa313a012269b7964208ff55
1,128
py
Python
scrapy/utils/console.py
emschorsch/scrapy
acb7bad1ff4037b4a613ac94e2d3357bf92bdb8f
[ "BSD-3-Clause" ]
1
2015-04-01T20:02:08.000Z
2015-04-01T20:02:08.000Z
scrapy/utils/console.py
emschorsch/scrapy
acb7bad1ff4037b4a613ac94e2d3357bf92bdb8f
[ "BSD-3-Clause" ]
2
2021-12-13T20:51:32.000Z
2022-02-11T03:47:35.000Z
scrapy/utils/console.py
emschorsch/scrapy
acb7bad1ff4037b4a613ac94e2d3357bf92bdb8f
[ "BSD-3-Clause" ]
1
2017-11-09T20:33:59.000Z
2017-11-09T20:33:59.000Z
def start_python_console(namespace=None, noipython=False): """Start Python console binded to the given namespace. If IPython is available, an IPython console will be started instead, unless `noipython` is True. Also, tab completion will be used on Unix systems. """ if namespace is None: namespace = {} try: try: # use IPython if available if noipython: raise ImportError import IPython try: IPython.embed(user_ns=namespace) except AttributeError: shell = IPython.Shell.IPShellEmbed(argv=[], user_ns=namespace) shell() except ImportError: import code try: # readline module is only available on unix systems import readline except ImportError: pass else: import rlcompleter readline.parse_and_bind("tab:complete") code.interact(banner='', local=namespace) except SystemExit: # raised when using exit() in python code.interact pass
36.387097
78
0.585106
def start_python_console(namespace=None, noipython=False): if namespace is None: namespace = {} try: try: if noipython: raise ImportError import IPython try: IPython.embed(user_ns=namespace) except AttributeError: shell = IPython.Shell.IPShellEmbed(argv=[], user_ns=namespace) shell() except ImportError: import code try: import readline except ImportError: pass else: import rlcompleter readline.parse_and_bind("tab:complete") code.interact(banner='', local=namespace) except SystemExit: pass
true
true
1c4449dad8f315ea5b5f73b491c6a3fecb29e786
2,948
py
Python
datasets/generate_synthia_label_info.py
JDAI-CV/FADA
a1c6403963184a3427eda68cc94b03ff6143368a
[ "Apache-2.0" ]
120
2020-07-20T02:23:02.000Z
2022-03-31T02:21:31.000Z
datasets/generate_synthia_label_info.py
JDAI-CV/FADA
a1c6403963184a3427eda68cc94b03ff6143368a
[ "Apache-2.0" ]
27
2020-07-29T02:55:52.000Z
2022-03-12T08:03:42.000Z
datasets/generate_synthia_label_info.py
JDAI-CV/FADA
a1c6403963184a3427eda68cc94b03ff6143368a
[ "Apache-2.0" ]
25
2020-08-01T06:11:08.000Z
2022-02-19T07:26:57.000Z
import argparse import os import math import numpy as np import pickle from PIL import Image from tqdm import tqdm import imageio from multiprocessing import Pool parser = argparse.ArgumentParser(description="Generate label stat info") parser.add_argument("-d", "--datadir", default="", help="path to load data", type=str, ) parser.add_argument("-n", "--nprocs", default=16, help="Number of processes", type=int, ) parser.add_argument("-o", "--output_dir", default="", help="path to save label info", type=str, ) args = parser.parse_args() imgdir = os.path.join(args.datadir, 'RAND_CITYSCAPES', 'RGB') labdir = os.path.join(args.datadir, 'RAND_CITYSCAPES', 'GT', 'LABELS') labfiles = os.listdir(labdir) nprocs = args.nprocs savedir = args.output_dir ignore_label = 255 id_to_trainid = { 3: 0, 4: 1, 2: 2, 21: 3, 5: 4, 7: 5, 15: 6, 9: 7, 6: 8, 1: 9, 10: 10, 17: 11, 8: 12, 19: 13, 12: 14, 11: 15,} def generate_label_info(): label_to_file = [[] for _ in range(len(id_to_trainid.keys()))] file_to_label = {e:[] for e in os.listdir(imgdir)} for labfile in tqdm(labfiles): label = np.unique(np.asarray(imageio.imread(os.path.join(labdir, labfile), format='PNG-FI'))[:,:,0]) for lab in label: if lab in id_to_trainid.keys(): l = id_to_trainid[lab] label_to_file[l].append(labfile) file_to_label[labfile].append(l) return label_to_file, file_to_label def _foo(i): label_to_file = [[] for _ in range(len(id_to_trainid.keys()))] file_to_label = dict() labfile = labfiles[i] file_to_label[labfile] = [] label = np.unique(np.array(Image.open(os.path.join(labdir, labfile)), dtype=np.float32)) for lab in label: if lab in id_to_trainid.keys(): l = id_to_trainid[lab] label_to_file[l].append(labfile) file_to_label[labfile].append(l) return label_to_file, file_to_label def main(): label_to_file = [[] for _ in range(len(id_to_trainid.keys()))] file_to_label = {e:[] for e in os.listdir(imgdir)} if nprocs==1: label_to_file, file_to_label = generate_label_info() else: with Pool(nprocs) as p: r = list(tqdm(p.imap(_foo, range(len(labfiles))), total=len(labfiles))) for l2f, f2l in r: for lab in range(len(l2f)): label_to_file[lab].extend(l2f[lab]) for fname in f2l.keys(): file_to_label[fname].extend(f2l[fname]) with open(os.path.join(savedir, 'synthia_label_info.p'), 'wb') as f: pickle.dump((label_to_file, file_to_label), f) if __name__ == "__main__": main()
27.811321
108
0.578019
import argparse import os import math import numpy as np import pickle from PIL import Image from tqdm import tqdm import imageio from multiprocessing import Pool parser = argparse.ArgumentParser(description="Generate label stat info") parser.add_argument("-d", "--datadir", default="", help="path to load data", type=str, ) parser.add_argument("-n", "--nprocs", default=16, help="Number of processes", type=int, ) parser.add_argument("-o", "--output_dir", default="", help="path to save label info", type=str, ) args = parser.parse_args() imgdir = os.path.join(args.datadir, 'RAND_CITYSCAPES', 'RGB') labdir = os.path.join(args.datadir, 'RAND_CITYSCAPES', 'GT', 'LABELS') labfiles = os.listdir(labdir) nprocs = args.nprocs savedir = args.output_dir ignore_label = 255 id_to_trainid = { 3: 0, 4: 1, 2: 2, 21: 3, 5: 4, 7: 5, 15: 6, 9: 7, 6: 8, 1: 9, 10: 10, 17: 11, 8: 12, 19: 13, 12: 14, 11: 15,} def generate_label_info(): label_to_file = [[] for _ in range(len(id_to_trainid.keys()))] file_to_label = {e:[] for e in os.listdir(imgdir)} for labfile in tqdm(labfiles): label = np.unique(np.asarray(imageio.imread(os.path.join(labdir, labfile), format='PNG-FI'))[:,:,0]) for lab in label: if lab in id_to_trainid.keys(): l = id_to_trainid[lab] label_to_file[l].append(labfile) file_to_label[labfile].append(l) return label_to_file, file_to_label def _foo(i): label_to_file = [[] for _ in range(len(id_to_trainid.keys()))] file_to_label = dict() labfile = labfiles[i] file_to_label[labfile] = [] label = np.unique(np.array(Image.open(os.path.join(labdir, labfile)), dtype=np.float32)) for lab in label: if lab in id_to_trainid.keys(): l = id_to_trainid[lab] label_to_file[l].append(labfile) file_to_label[labfile].append(l) return label_to_file, file_to_label def main(): label_to_file = [[] for _ in range(len(id_to_trainid.keys()))] file_to_label = {e:[] for e in os.listdir(imgdir)} if nprocs==1: label_to_file, file_to_label = generate_label_info() else: with Pool(nprocs) as p: r = list(tqdm(p.imap(_foo, range(len(labfiles))), total=len(labfiles))) for l2f, f2l in r: for lab in range(len(l2f)): label_to_file[lab].extend(l2f[lab]) for fname in f2l.keys(): file_to_label[fname].extend(f2l[fname]) with open(os.path.join(savedir, 'synthia_label_info.p'), 'wb') as f: pickle.dump((label_to_file, file_to_label), f) if __name__ == "__main__": main()
true
true
1c444a39822bf470342e8467d1ba5fb4a3c7f873
1,765
py
Python
conversations/migrations/0001_initial.py
alstn2468/Django_Airbnb_Clone
eeb61e4a36320a0b269d96f47cc6755dbc4c40f8
[ "MIT" ]
5
2019-11-26T00:34:24.000Z
2021-01-04T06:04:48.000Z
conversations/migrations/0001_initial.py
alstn2468/Django_Airbnb_Clone
eeb61e4a36320a0b269d96f47cc6755dbc4c40f8
[ "MIT" ]
3
2021-06-09T19:05:40.000Z
2021-09-08T01:49:01.000Z
conversations/migrations/0001_initial.py
alstn2468/Django_Airbnb_Clone
eeb61e4a36320a0b269d96f47cc6755dbc4c40f8
[ "MIT" ]
6
2019-11-24T11:47:09.000Z
2021-08-16T20:21:35.000Z
# Generated by Django 2.2.5 on 2019-12-22 12:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Conversation", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("created_at", models.DateTimeField(auto_now_add=True)), ("updated_at", models.DateTimeField(auto_now=True)), ], options={"abstract": False,}, ), migrations.CreateModel( name="Message", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("created_at", models.DateTimeField(auto_now_add=True)), ("updated_at", models.DateTimeField(auto_now=True)), ("message", models.TextField()), ( "conversation", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="messages", to="conversations.Conversation", ), ), ], options={"abstract": False,}, ), ]
30.431034
72
0.420397
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Conversation", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("created_at", models.DateTimeField(auto_now_add=True)), ("updated_at", models.DateTimeField(auto_now=True)), ], options={"abstract": False,}, ), migrations.CreateModel( name="Message", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("created_at", models.DateTimeField(auto_now_add=True)), ("updated_at", models.DateTimeField(auto_now=True)), ("message", models.TextField()), ( "conversation", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="messages", to="conversations.Conversation", ), ), ], options={"abstract": False,}, ), ]
true
true
1c444b23a8f36b78e2011034fb20d666cb5720f3
2,548
py
Python
perfil/models.py
KleuberJacob/Ecommerce-utilizando-Python-Django-e-Bootstrap4
acf2239d408f26eb223a1fe1c03046fcf62d6733
[ "MIT" ]
41
2019-08-20T06:55:51.000Z
2022-03-23T09:59:27.000Z
perfil/models.py
KleuberJacob/Ecommerce-utilizando-Python-Django-e-Bootstrap4
acf2239d408f26eb223a1fe1c03046fcf62d6733
[ "MIT" ]
8
2021-03-18T21:29:25.000Z
2022-01-13T01:32:24.000Z
perfil/models.py
KleuberJacob/Ecommerce-utilizando-Python-Django-e-Bootstrap4
acf2239d408f26eb223a1fe1c03046fcf62d6733
[ "MIT" ]
31
2020-03-12T00:01:48.000Z
2022-03-24T23:47:10.000Z
from django.db import models from django.contrib.auth.models import User from django.forms import ValidationError import re from utils.validacpf import valida_cpf class Perfil(models.Model): usuario = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Usuário') idade = models.PositiveIntegerField() data_nascimento = models.DateField() cpf = models.CharField(max_length=11) endereco = models.CharField(max_length=50) numero = models.CharField(max_length=5) complemento = models.CharField(max_length=30) bairro = models.CharField(max_length=30) cep = models.CharField(max_length=8) cidade = models.CharField(max_length=30) estado = models.CharField( max_length=2, default='SP', choices=( ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins'), ) ) def __str__(self): return f'{self.usuario}' def clean(self): error_messages = {} cpf_enviado = self.cpf or None cpf_salvo = None perfil = Perfil.objects.filter(cpf=cpf_enviado).first() if perfil: cpf_salvo = perfil.cpf if cpf_salvo is not None and self.pk != perfil.pk: error_messages['cpf'] = 'CPF já existe.' if not valida_cpf(self.cpf): error_messages['cpf'] = 'Digite um CPF válido' if re.search(r'[^0-9]', self.cep) or len(self.cep) < 8: error_messages['cep'] = 'CEP inválido, digite os 8 digitos do CEP.' if error_messages: raise ValidationError(error_messages) class Meta: verbose_name = 'Perfil' verbose_name_plural = 'Perfis'
30.698795
79
0.522763
from django.db import models from django.contrib.auth.models import User from django.forms import ValidationError import re from utils.validacpf import valida_cpf class Perfil(models.Model): usuario = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Usuário') idade = models.PositiveIntegerField() data_nascimento = models.DateField() cpf = models.CharField(max_length=11) endereco = models.CharField(max_length=50) numero = models.CharField(max_length=5) complemento = models.CharField(max_length=30) bairro = models.CharField(max_length=30) cep = models.CharField(max_length=8) cidade = models.CharField(max_length=30) estado = models.CharField( max_length=2, default='SP', choices=( ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins'), ) ) def __str__(self): return f'{self.usuario}' def clean(self): error_messages = {} cpf_enviado = self.cpf or None cpf_salvo = None perfil = Perfil.objects.filter(cpf=cpf_enviado).first() if perfil: cpf_salvo = perfil.cpf if cpf_salvo is not None and self.pk != perfil.pk: error_messages['cpf'] = 'CPF já existe.' if not valida_cpf(self.cpf): error_messages['cpf'] = 'Digite um CPF válido' if re.search(r'[^0-9]', self.cep) or len(self.cep) < 8: error_messages['cep'] = 'CEP inválido, digite os 8 digitos do CEP.' if error_messages: raise ValidationError(error_messages) class Meta: verbose_name = 'Perfil' verbose_name_plural = 'Perfis'
true
true
1c444b8125c72d4ac5a956840cbcad32199c8ff1
1,592
py
Python
Notes/apps/users/models.py
Mi-As/Lists-RestApi
eea238f9fc5fda4b992f33dd2c7a4725a74849bb
[ "MIT" ]
1
2020-10-31T20:15:21.000Z
2020-10-31T20:15:21.000Z
Notes/apps/users/models.py
Mi-As/Note-RestApi
eea238f9fc5fda4b992f33dd2c7a4725a74849bb
[ "MIT" ]
null
null
null
Notes/apps/users/models.py
Mi-As/Note-RestApi
eea238f9fc5fda4b992f33dd2c7a4725a74849bb
[ "MIT" ]
null
null
null
from werkzeug.security import check_password_hash, generate_password_hash import uuid from ... import db # import like this bc: https://stackoverflow.com/questions/43576422/sqlalchemy-flask-class-is-not-defined from ..notes import models as notes from ...authentication import models as authenticaton from . import services class User(db.Model): id = db.Column(db.Integer, primary_key=True) public_id = db.Column(db.String(50), nullable=False, unique=True) name = db.Column(db.String, nullable=False) email = db.Column(db.String, nullable=False, unique=True) password = db.Column(db.String(255), nullable=False) # Relationships # One-to-Many role_name = db.Column(db.String, db.ForeignKey('role.name')) # Many-to-One notes = db.relationship('Note', passive_deletes='all') tokens = db.relationship('Token', passive_deletes='all') def __init__(self, name, email, password, role_name='user'): self.public_id = str(uuid.uuid4()) self.name = name self.email = email self.set_password(password) self.set_role_name(role_name) def set_role_name(self, role_name): role = services.get_role({'name':role_name}) assert role, "no such user_role!" self.role_name = role_name def set_password(self, secret): self.password = generate_password_hash(secret) def check_password(self, secret): return check_password_hash(self.password, secret) class Role(db.Model): # ['Admin', 'User'] id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, unique=True, nullable=False) has_full_access = db.Column(db.Boolean, nullable=False, default=False)
31.84
105
0.748744
from werkzeug.security import check_password_hash, generate_password_hash import uuid from ... import db from ..notes import models as notes from ...authentication import models as authenticaton from . import services class User(db.Model): id = db.Column(db.Integer, primary_key=True) public_id = db.Column(db.String(50), nullable=False, unique=True) name = db.Column(db.String, nullable=False) email = db.Column(db.String, nullable=False, unique=True) password = db.Column(db.String(255), nullable=False) role_name = db.Column(db.String, db.ForeignKey('role.name')) notes = db.relationship('Note', passive_deletes='all') tokens = db.relationship('Token', passive_deletes='all') def __init__(self, name, email, password, role_name='user'): self.public_id = str(uuid.uuid4()) self.name = name self.email = email self.set_password(password) self.set_role_name(role_name) def set_role_name(self, role_name): role = services.get_role({'name':role_name}) assert role, "no such user_role!" self.role_name = role_name def set_password(self, secret): self.password = generate_password_hash(secret) def check_password(self, secret): return check_password_hash(self.password, secret) class Role(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, unique=True, nullable=False) has_full_access = db.Column(db.Boolean, nullable=False, default=False)
true
true
1c444cea01536e9894e87342726ed2edcb74d0f2
6,369
py
Python
fitapp/south_migrations/0002_auto__add_timeseriesdatatype__add_unique_timeseriesdatatype_category_r.py
evansnj/django-fitbit-old2
87f4aa389ab9ea2f63fa41aa4d3bbb3f55cd78ac
[ "Apache-2.0" ]
null
null
null
fitapp/south_migrations/0002_auto__add_timeseriesdatatype__add_unique_timeseriesdatatype_category_r.py
evansnj/django-fitbit-old2
87f4aa389ab9ea2f63fa41aa4d3bbb3f55cd78ac
[ "Apache-2.0" ]
null
null
null
fitapp/south_migrations/0002_auto__add_timeseriesdatatype__add_unique_timeseriesdatatype_category_r.py
evansnj/django-fitbit-old2
87f4aa389ab9ea2f63fa41aa4d3bbb3f55cd78ac
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models # Safe User import for Django < 1.5 try: from django.contrib.auth import get_user_model except ImportError: from django.contrib.auth.models import User else: User = get_user_model() # With the default User model these will be 'auth.User' and 'auth.user' # so instead of using orm['auth.User'] we can use orm[user_orm_label] user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name) user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name) class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'TimeSeriesDataType' db.create_table('fitapp_timeseriesdatatype', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('category', self.gf('django.db.models.fields.IntegerField')()), ('resource', self.gf('django.db.models.fields.CharField')(max_length=128)), )) db.send_create_signal('fitapp', ['TimeSeriesDataType']) # Adding unique constraint on 'TimeSeriesDataType', fields ['category', 'resource'] db.create_unique('fitapp_timeseriesdatatype', ['category', 'resource']) # Adding model 'TimeSeriesData' db.create_table('fitapp_timeseriesdata', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[user_orm_label])), ('resource_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['fitapp.TimeSeriesDataType'])), ('date', self.gf('django.db.models.fields.DateField')()), ('value', self.gf('django.db.models.fields.CharField')(default=None, max_length=32, null=True)), )) db.send_create_signal('fitapp', ['TimeSeriesData']) # Adding unique constraint on 'TimeSeriesData', fields ['user', 'resource_type', 'date'] db.create_unique('fitapp_timeseriesdata', ['user_id', 'resource_type_id', 'date']) def backwards(self, orm): # Removing unique constraint on 'TimeSeriesData', fields ['user', 'resource_type', 'date'] db.delete_unique('fitapp_timeseriesdata', ['user_id', 'resource_type_id', 'date']) # Removing unique constraint on 'TimeSeriesDataType', fields ['category', 'resource'] db.delete_unique('fitapp_timeseriesdatatype', ['category', 'resource']) # Deleting model 'TimeSeriesDataType' db.delete_table('fitapp_timeseriesdatatype') # Deleting model 'TimeSeriesData' db.delete_table('fitapp_timeseriesdata') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, user_model_label: { 'Meta': { 'object_name': User.__name__, 'db_table': "'%s'" % User._meta.db_table }, User._meta.pk.attname: ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True', 'db_column': "'%s'" % User._meta.pk.column} ), }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'fitapp.timeseriesdata': { 'Meta': {'unique_together': "(('user', 'resource_type', 'date'),)", 'object_name': 'TimeSeriesData'}, 'date': ('django.db.models.fields.DateField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['fitapp.TimeSeriesDataType']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_orm_label}), 'value': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '32', 'null': 'True'}) }, 'fitapp.timeseriesdatatype': { 'Meta': {'unique_together': "(('category', 'resource'),)", 'object_name': 'TimeSeriesDataType'}, 'category': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'resource': ('django.db.models.fields.CharField', [], {'max_length': '128'}) }, 'fitapp.userfitbit': { 'Meta': {'object_name': 'UserFitbit'}, 'auth_secret': ('django.db.models.fields.TextField', [], {}), 'auth_token': ('django.db.models.fields.TextField', [], {}), 'fitbit_user': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['%s']" % user_orm_label, 'unique': 'True'}) } } complete_apps = ['fitapp']
52.636364
182
0.594756
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models try: from django.contrib.auth import get_user_model except ImportError: from django.contrib.auth.models import User else: User = get_user_model() user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name) user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name) class Migration(SchemaMigration): def forwards(self, orm): db.create_table('fitapp_timeseriesdatatype', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('category', self.gf('django.db.models.fields.IntegerField')()), ('resource', self.gf('django.db.models.fields.CharField')(max_length=128)), )) db.send_create_signal('fitapp', ['TimeSeriesDataType']) db.create_unique('fitapp_timeseriesdatatype', ['category', 'resource']) db.create_table('fitapp_timeseriesdata', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[user_orm_label])), ('resource_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['fitapp.TimeSeriesDataType'])), ('date', self.gf('django.db.models.fields.DateField')()), ('value', self.gf('django.db.models.fields.CharField')(default=None, max_length=32, null=True)), )) db.send_create_signal('fitapp', ['TimeSeriesData']) db.create_unique('fitapp_timeseriesdata', ['user_id', 'resource_type_id', 'date']) def backwards(self, orm): db.delete_unique('fitapp_timeseriesdata', ['user_id', 'resource_type_id', 'date']) db.delete_unique('fitapp_timeseriesdatatype', ['category', 'resource']) db.delete_table('fitapp_timeseriesdatatype') db.delete_table('fitapp_timeseriesdata') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, user_model_label: { 'Meta': { 'object_name': User.__name__, 'db_table': "'%s'" % User._meta.db_table }, User._meta.pk.attname: ( 'django.db.models.fields.AutoField', [], {'primary_key': 'True', 'db_column': "'%s'" % User._meta.pk.column} ), }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'fitapp.timeseriesdata': { 'Meta': {'unique_together': "(('user', 'resource_type', 'date'),)", 'object_name': 'TimeSeriesData'}, 'date': ('django.db.models.fields.DateField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['fitapp.TimeSeriesDataType']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_orm_label}), 'value': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '32', 'null': 'True'}) }, 'fitapp.timeseriesdatatype': { 'Meta': {'unique_together': "(('category', 'resource'),)", 'object_name': 'TimeSeriesDataType'}, 'category': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'resource': ('django.db.models.fields.CharField', [], {'max_length': '128'}) }, 'fitapp.userfitbit': { 'Meta': {'object_name': 'UserFitbit'}, 'auth_secret': ('django.db.models.fields.TextField', [], {}), 'auth_token': ('django.db.models.fields.TextField', [], {}), 'fitbit_user': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['%s']" % user_orm_label, 'unique': 'True'}) } } complete_apps = ['fitapp']
true
true
1c444d318a36178d6e5513e846e17f7a823e3ccb
931
py
Python
esphome/components/binary_sensor/homeassistant.py
pi4homez/esphome
697e9b0c28bb690719fa1d16ca8198ce5fd1d2be
[ "MIT" ]
5
2019-04-14T09:43:29.000Z
2021-07-17T06:36:44.000Z
esphome/components/binary_sensor/homeassistant.py
pi4homez/esphome
697e9b0c28bb690719fa1d16ca8198ce5fd1d2be
[ "MIT" ]
null
null
null
esphome/components/binary_sensor/homeassistant.py
pi4homez/esphome
697e9b0c28bb690719fa1d16ca8198ce5fd1d2be
[ "MIT" ]
4
2019-07-08T08:58:44.000Z
2021-12-18T21:56:22.000Z
import voluptuous as vol from esphome.components import binary_sensor import esphome.config_validation as cv from esphome.const import CONF_ENTITY_ID, CONF_ID, CONF_NAME from esphome.cpp_generator import Pvariable from esphome.cpp_types import App DEPENDENCIES = ['api'] HomeassistantBinarySensor = binary_sensor.binary_sensor_ns.class_('HomeassistantBinarySensor', binary_sensor.BinarySensor) PLATFORM_SCHEMA = cv.nameable(binary_sensor.BINARY_SENSOR_PLATFORM_SCHEMA.extend({ cv.GenerateID(): cv.declare_variable_id(HomeassistantBinarySensor), vol.Required(CONF_ENTITY_ID): cv.entity_id, })) def to_code(config): rhs = App.make_homeassistant_binary_sensor(config[CONF_NAME], config[CONF_ENTITY_ID]) subs = Pvariable(config[CONF_ID], rhs) binary_sensor.setup_binary_sensor(subs, config) BUILD_FLAGS = '-DUSE_HOMEASSISTANT_BINARY_SENSOR'
34.481481
94
0.762621
import voluptuous as vol from esphome.components import binary_sensor import esphome.config_validation as cv from esphome.const import CONF_ENTITY_ID, CONF_ID, CONF_NAME from esphome.cpp_generator import Pvariable from esphome.cpp_types import App DEPENDENCIES = ['api'] HomeassistantBinarySensor = binary_sensor.binary_sensor_ns.class_('HomeassistantBinarySensor', binary_sensor.BinarySensor) PLATFORM_SCHEMA = cv.nameable(binary_sensor.BINARY_SENSOR_PLATFORM_SCHEMA.extend({ cv.GenerateID(): cv.declare_variable_id(HomeassistantBinarySensor), vol.Required(CONF_ENTITY_ID): cv.entity_id, })) def to_code(config): rhs = App.make_homeassistant_binary_sensor(config[CONF_NAME], config[CONF_ENTITY_ID]) subs = Pvariable(config[CONF_ID], rhs) binary_sensor.setup_binary_sensor(subs, config) BUILD_FLAGS = '-DUSE_HOMEASSISTANT_BINARY_SENSOR'
true
true
1c444d5e1dda6613ae5959af1930b90d1660a982
4,000
py
Python
notebooks/parameter_tuning_ex_02.py
castorfou/scikit-learn-mooc
235748eff57409eb17d8355024579c6df44c0563
[ "CC-BY-4.0" ]
1
2021-05-25T07:29:44.000Z
2021-05-25T07:29:44.000Z
notebooks/parameter_tuning_ex_02.py
castorfou/scikit-learn-mooc
235748eff57409eb17d8355024579c6df44c0563
[ "CC-BY-4.0" ]
null
null
null
notebooks/parameter_tuning_ex_02.py
castorfou/scikit-learn-mooc
235748eff57409eb17d8355024579c6df44c0563
[ "CC-BY-4.0" ]
null
null
null
#!/usr/bin/env python # coding: utf-8 # # 📝 Exercise M3.01 # # The goal is to write an exhaustive search to find the best parameters # combination maximizing the model statistical performance. # # Here we use a small subset of the Adult Census dataset to make to code # fast to execute. Once your code works on the small subset, try to # change `train_size` to a larger value (e.g. 0.8 for 80% instead of # 20%). # In[1]: import pandas as pd from sklearn.model_selection import train_test_split adult_census = pd.read_csv("../datasets/adult-census.csv") target_name = "class" target = adult_census[target_name] data = adult_census.drop(columns=[target_name, "education-num"]) data_train, data_test, target_train, target_test = train_test_split( data, target, train_size=0.2, random_state=42) # In[2]: from sklearn.compose import ColumnTransformer from sklearn.compose import make_column_selector as selector from sklearn.preprocessing import OrdinalEncoder categorical_preprocessor = OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1) preprocessor = ColumnTransformer( [('cat-preprocessor', categorical_preprocessor, selector(dtype_include=object))], remainder='passthrough', sparse_threshold=0) # This line is currently required to import HistGradientBoostingClassifier from sklearn.experimental import enable_hist_gradient_boosting from sklearn.ensemble import HistGradientBoostingClassifier from sklearn.pipeline import Pipeline model = Pipeline([ ("preprocessor", preprocessor), ("classifier", HistGradientBoostingClassifier(random_state=42)) ]) # # Use the previously defined model (called `model`) and using two nested `for` # loops, make a search of the best combinations of the `learning_rate` and # `max_leaf_nodes` parameters. In this regard, you will need to train and test # the model by setting the parameters. The evaluation of the model should be # performed using `cross_val_score`. We will use the following parameters # search: # - `learning_rate` for the values 0.01, 0.1, 1 and 10. This parameter controls # the ability of a new tree to correct the error of the previous sequence of # trees # - `max_leaf_nodes` for the values 3, 10, 30. This parameter controls the # depth of each tree. # In[3]: for parameter in model.get_params(): print(parameter) # In[5]: # Write your code here. from sklearn.model_selection import cross_val_score learning_rate_range = [0.01, 0.1, 1, 10] max_leaf_nodes_range = [3, 10, 30] for learning_rate in learning_rate_range: for max_leaf_nodes in max_leaf_nodes_range: model.set_params(classifier__learning_rate=learning_rate) model.set_params(classifier__max_leaf_nodes=max_leaf_nodes) scores = cross_val_score(model, data_test, target_test) print(f"Accuracy score via cross-validation using learning_rate:{learning_rate}, max_leaf_nodes:{max_leaf_nodes}:\n" f"{scores.mean():.3f} +/- {scores.std():.3f}") # # correction # In[6]: from sklearn.model_selection import cross_val_score learning_rate = [0.01, 0.1, 1, 10] max_leaf_nodes = [3, 10, 30] best_score = 0 best_params = {} for lr in learning_rate: for mln in max_leaf_nodes: print(f"Evaluating model with learning rate {lr:.3f}" f" and max leaf nodes {mln}... ", end="") model.set_params( classifier__learning_rate=lr, classifier__max_leaf_nodes=mln ) scores = cross_val_score(model, data_train, target_train, cv=2) mean_score = scores.mean() print(f"score: {mean_score:.3f}") if mean_score > best_score: best_score = mean_score best_params = {'learning-rate': lr, 'max leaf nodes': mln} print(f"Found new best model with score {best_score:.3f}!") print(f"The best accuracy obtained is {best_score:.3f}") print(f"The best parameters found are:\n {best_params}") # In[ ]:
30.30303
124
0.72
t pandas as pd from sklearn.model_selection import train_test_split adult_census = pd.read_csv("../datasets/adult-census.csv") target_name = "class" target = adult_census[target_name] data = adult_census.drop(columns=[target_name, "education-num"]) data_train, data_test, target_train, target_test = train_test_split( data, target, train_size=0.2, random_state=42) from sklearn.compose import ColumnTransformer from sklearn.compose import make_column_selector as selector from sklearn.preprocessing import OrdinalEncoder categorical_preprocessor = OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1) preprocessor = ColumnTransformer( [('cat-preprocessor', categorical_preprocessor, selector(dtype_include=object))], remainder='passthrough', sparse_threshold=0) from sklearn.experimental import enable_hist_gradient_boosting from sklearn.ensemble import HistGradientBoostingClassifier from sklearn.pipeline import Pipeline model = Pipeline([ ("preprocessor", preprocessor), ("classifier", HistGradientBoostingClassifier(random_state=42)) ]) for parameter in model.get_params(): print(parameter) from sklearn.model_selection import cross_val_score learning_rate_range = [0.01, 0.1, 1, 10] max_leaf_nodes_range = [3, 10, 30] for learning_rate in learning_rate_range: for max_leaf_nodes in max_leaf_nodes_range: model.set_params(classifier__learning_rate=learning_rate) model.set_params(classifier__max_leaf_nodes=max_leaf_nodes) scores = cross_val_score(model, data_test, target_test) print(f"Accuracy score via cross-validation using learning_rate:{learning_rate}, max_leaf_nodes:{max_leaf_nodes}:\n" f"{scores.mean():.3f} +/- {scores.std():.3f}") learn.model_selection import cross_val_score learning_rate = [0.01, 0.1, 1, 10] max_leaf_nodes = [3, 10, 30] best_score = 0 best_params = {} for lr in learning_rate: for mln in max_leaf_nodes: print(f"Evaluating model with learning rate {lr:.3f}" f" and max leaf nodes {mln}... ", end="") model.set_params( classifier__learning_rate=lr, classifier__max_leaf_nodes=mln ) scores = cross_val_score(model, data_train, target_train, cv=2) mean_score = scores.mean() print(f"score: {mean_score:.3f}") if mean_score > best_score: best_score = mean_score best_params = {'learning-rate': lr, 'max leaf nodes': mln} print(f"Found new best model with score {best_score:.3f}!") print(f"The best accuracy obtained is {best_score:.3f}") print(f"The best parameters found are:\n {best_params}")
true
true
1c444d99a421ed03ab656d5c6c2d5a7c3d4e9f61
1,979
py
Python
exercises/en/test_02_07a.py
UBC-MDS/exploratory-data-viz
83b704ce10d1ff5e10bfd4cdfa872ac52993fd54
[ "CC-BY-4.0" ]
null
null
null
exercises/en/test_02_07a.py
UBC-MDS/exploratory-data-viz
83b704ce10d1ff5e10bfd4cdfa872ac52993fd54
[ "CC-BY-4.0" ]
88
2020-12-04T06:56:51.000Z
2021-05-10T22:02:45.000Z
exercises/en/test_02_07a.py
UBC-MDS/exploratory-data-viz
83b704ce10d1ff5e10bfd4cdfa872ac52993fd54
[ "CC-BY-4.0" ]
4
2021-01-13T09:30:57.000Z
2021-08-03T20:49:31.000Z
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the message will be displayed assert not fuel_efficiency is None, "Your answer does not exist. Have you passed in the correct variable?" assert type(fuel_efficiency) == type(alt.Chart()), "Your answer is not an Altair Chart object. Check to make sure that you have assigned an alt.Chart object to fuel_efficiency." assert fuel_efficiency.data.equals(data.cars()), "Make sure you are using cars() dataset from vega_datasets." assert fuel_efficiency.mark == 'area', "Make sure you are using the area mark type." assert (fuel_efficiency.encoding.x.field in {'Year', 'Year:temporal', 'Year:T'} or fuel_efficiency.encoding.x.shorthand in {'Year', 'Year:temporal', 'Year:T'}), "Make sure you are using 'Year' as the x-axis encoding." assert (fuel_efficiency.encoding.y.field in {'Miles_per_Gallon', 'Miles_per_Gallon:quantitative', 'Miles_per_Gallon:Q'} or "Miles_per_Gallon" in fuel_efficiency.encoding.y.shorthand), "Make sure you are using mean of the 'Miles_per_Gallon' as the y-axis encoding." assert ((fuel_efficiency.encoding.y.field in {'Miles_per_Gallon', 'Miles_per_Gallon:quantitative', 'Miles_per_Gallon:Q'} and fuel_efficiency.encoding.y.aggregate == 'mean') or fuel_efficiency.encoding.y.shorthand in {'mean(Miles_per_Gallon)', 'mean(Miles_per_Gallon):quantitative', 'mean(Miles_per_Gallon):Q'}), "You're very close. Make sure that you are using the mean aggregate for the y-axis encoding." assert type(fuel_efficiency.title) == str and len(fuel_efficiency.title) >= 5, "Make sure you specify a descriptive title for the fuel_efficiency plot." __msg__.good("You're correct, well done!")
98.95
241
0.738757
def test(): assert not fuel_efficiency is None, "Your answer does not exist. Have you passed in the correct variable?" assert type(fuel_efficiency) == type(alt.Chart()), "Your answer is not an Altair Chart object. Check to make sure that you have assigned an alt.Chart object to fuel_efficiency." assert fuel_efficiency.data.equals(data.cars()), "Make sure you are using cars() dataset from vega_datasets." assert fuel_efficiency.mark == 'area', "Make sure you are using the area mark type." assert (fuel_efficiency.encoding.x.field in {'Year', 'Year:temporal', 'Year:T'} or fuel_efficiency.encoding.x.shorthand in {'Year', 'Year:temporal', 'Year:T'}), "Make sure you are using 'Year' as the x-axis encoding." assert (fuel_efficiency.encoding.y.field in {'Miles_per_Gallon', 'Miles_per_Gallon:quantitative', 'Miles_per_Gallon:Q'} or "Miles_per_Gallon" in fuel_efficiency.encoding.y.shorthand), "Make sure you are using mean of the 'Miles_per_Gallon' as the y-axis encoding." assert ((fuel_efficiency.encoding.y.field in {'Miles_per_Gallon', 'Miles_per_Gallon:quantitative', 'Miles_per_Gallon:Q'} and fuel_efficiency.encoding.y.aggregate == 'mean') or fuel_efficiency.encoding.y.shorthand in {'mean(Miles_per_Gallon)', 'mean(Miles_per_Gallon):quantitative', 'mean(Miles_per_Gallon):Q'}), "You're very close. Make sure that you are using the mean aggregate for the y-axis encoding." assert type(fuel_efficiency.title) == str and len(fuel_efficiency.title) >= 5, "Make sure you specify a descriptive title for the fuel_efficiency plot." __msg__.good("You're correct, well done!")
true
true
1c444da6a8b80e2466802ae61d8ef26911df5b78
3,644
py
Python
caffe2/python/operator_test/fc_operator_test.py
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
1
2019-07-21T02:13:22.000Z
2019-07-21T02:13:22.000Z
caffe2/python/operator_test/fc_operator_test.py
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
null
null
null
caffe2/python/operator_test/fc_operator_test.py
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
null
null
null
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.proto import caffe2_pb2 from caffe2.python import core from hypothesis import assume, given, settings, HealthCheck import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestFcOperator(hu.HypothesisTestCase): def _run_test(self, n, m, k, transposed, multi_dim, dtype, engine, gc, dc): if dtype == np.float16: # fp16 only supported with CUDA assume(gc.device_type == caffe2_pb2.CUDA) dc = [d for d in dc if d.device_type == caffe2_pb2.CUDA] if engine == 'TENSORCORE': # TensorCore only makes sense with CUDA assume(gc.device_type == caffe2_pb2.CUDA) # ensures TensorCore kernels can be called m *= 8 k *= 8 n *= 8 X = np.random.rand(m, k).astype(dtype) - 0.5 if multi_dim: if transposed: W = np.random.rand(k, n, 1, 1).astype(dtype) - 0.5 else: W = np.random.rand(n, k, 1, 1).astype(dtype) - 0.5 else: if transposed: W = np.random.rand(k, n).astype(dtype) - 0.5 else: W = np.random.rand(n, k).astype(dtype) - 0.5 b = np.random.rand(n).astype(dtype) - 0.5 def fc_op(X, W, b): return [np.dot(X, W.reshape(n, k).transpose()) + b.reshape(n)] def fc_tranposed_op(X, W, b): return [np.dot(X, W.reshape(k, n)) + b.reshape(n)] op = core.CreateOperator( 'FCTransposed' if transposed else 'FC', ['X', 'W', 'b'], 'out', engine=engine, ) if dtype == np.float16 and gc.device_type == caffe2_pb2.CUDA: a = caffe2_pb2.Argument() a.i = 1 a.name = "float16_compute" op.arg.extend([a]) # Check against numpy reference self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, W, b], reference=fc_tranposed_op if transposed else fc_op, ) # Check over multiple devices self.assertDeviceChecks(dc, op, [X, W, b], [0]) # Gradient checks threshold = 0.5 if dtype == np.float16 else 0.005 stepsize = 0.5 if dtype == np.float16 else 0.05 for i in range(3): self.assertGradientChecks(gc, op, [X, W, b], i, [0], threshold=threshold, stepsize=stepsize) @settings(max_examples=50, suppress_health_check=[HealthCheck.filter_too_much]) @given(n=st.integers(1, 5), m=st.integers(0, 5), k=st.integers(1, 5), multi_dim=st.sampled_from([True, False]), dtype=st.sampled_from([np.float32, np.float16]), engine=st.sampled_from(['', 'TENSORCORE']), **hu.gcs) def test_fc(self, **kwargs): self._run_test(transposed=False, **kwargs) @settings(max_examples=50, suppress_health_check=[HealthCheck.filter_too_much]) @given(n=st.integers(1, 5), m=st.integers(0, 5), k=st.integers(1, 5), multi_dim=st.sampled_from([True, False]), dtype=st.sampled_from([np.float32, np.float16]), engine=st.sampled_from(['', 'TENSORCORE']), **hu.gcs) def test_fc_transposed(self, **kwargs): self._run_test(transposed=True, **kwargs) if __name__ == "__main__": import unittest unittest.main()
35.038462
83
0.570801
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.proto import caffe2_pb2 from caffe2.python import core from hypothesis import assume, given, settings, HealthCheck import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestFcOperator(hu.HypothesisTestCase): def _run_test(self, n, m, k, transposed, multi_dim, dtype, engine, gc, dc): if dtype == np.float16: assume(gc.device_type == caffe2_pb2.CUDA) dc = [d for d in dc if d.device_type == caffe2_pb2.CUDA] if engine == 'TENSORCORE': assume(gc.device_type == caffe2_pb2.CUDA) m *= 8 k *= 8 n *= 8 X = np.random.rand(m, k).astype(dtype) - 0.5 if multi_dim: if transposed: W = np.random.rand(k, n, 1, 1).astype(dtype) - 0.5 else: W = np.random.rand(n, k, 1, 1).astype(dtype) - 0.5 else: if transposed: W = np.random.rand(k, n).astype(dtype) - 0.5 else: W = np.random.rand(n, k).astype(dtype) - 0.5 b = np.random.rand(n).astype(dtype) - 0.5 def fc_op(X, W, b): return [np.dot(X, W.reshape(n, k).transpose()) + b.reshape(n)] def fc_tranposed_op(X, W, b): return [np.dot(X, W.reshape(k, n)) + b.reshape(n)] op = core.CreateOperator( 'FCTransposed' if transposed else 'FC', ['X', 'W', 'b'], 'out', engine=engine, ) if dtype == np.float16 and gc.device_type == caffe2_pb2.CUDA: a = caffe2_pb2.Argument() a.i = 1 a.name = "float16_compute" op.arg.extend([a]) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, W, b], reference=fc_tranposed_op if transposed else fc_op, ) self.assertDeviceChecks(dc, op, [X, W, b], [0]) threshold = 0.5 if dtype == np.float16 else 0.005 stepsize = 0.5 if dtype == np.float16 else 0.05 for i in range(3): self.assertGradientChecks(gc, op, [X, W, b], i, [0], threshold=threshold, stepsize=stepsize) @settings(max_examples=50, suppress_health_check=[HealthCheck.filter_too_much]) @given(n=st.integers(1, 5), m=st.integers(0, 5), k=st.integers(1, 5), multi_dim=st.sampled_from([True, False]), dtype=st.sampled_from([np.float32, np.float16]), engine=st.sampled_from(['', 'TENSORCORE']), **hu.gcs) def test_fc(self, **kwargs): self._run_test(transposed=False, **kwargs) @settings(max_examples=50, suppress_health_check=[HealthCheck.filter_too_much]) @given(n=st.integers(1, 5), m=st.integers(0, 5), k=st.integers(1, 5), multi_dim=st.sampled_from([True, False]), dtype=st.sampled_from([np.float32, np.float16]), engine=st.sampled_from(['', 'TENSORCORE']), **hu.gcs) def test_fc_transposed(self, **kwargs): self._run_test(transposed=True, **kwargs) if __name__ == "__main__": import unittest unittest.main()
true
true
1c444db0233ca5c275f3a1c2a5a0e92f86e9e40a
6,119
py
Python
toolkitui.py
thebirdsbeak/morse_trainer
2cc5277de066703218bc2277532a7a9b985a5b92
[ "MIT" ]
null
null
null
toolkitui.py
thebirdsbeak/morse_trainer
2cc5277de066703218bc2277532a7a9b985a5b92
[ "MIT" ]
null
null
null
toolkitui.py
thebirdsbeak/morse_trainer
2cc5277de066703218bc2277532a7a9b985a5b92
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'toolkitui.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout_2.setObjectName("gridLayout_2") self.gridLayout = QtWidgets.QGridLayout() self.gridLayout.setObjectName("gridLayout") self.toolkitBrowser = QtWidgets.QTextBrowser(self.centralwidget) self.toolkitBrowser.setObjectName("toolkitBrowser") self.gridLayout.addWidget(self.toolkitBrowser, 0, 0, 1, 1) self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.kochButton = QtWidgets.QPushButton(self.centralwidget) self.kochButton.setObjectName("kochButton") self.horizontalLayout_2.addWidget(self.kochButton) self.practiceButton = QtWidgets.QPushButton(self.centralwidget) self.practiceButton.setObjectName("practiceButton") self.horizontalLayout_2.addWidget(self.practiceButton) self.simulatedButton = QtWidgets.QPushButton(self.centralwidget) self.simulatedButton.setObjectName("simulatedButton") self.horizontalLayout_2.addWidget(self.simulatedButton) self.quizButton = QtWidgets.QPushButton(self.centralwidget) self.quizButton.setObjectName("quizButton") self.horizontalLayout_2.addWidget(self.quizButton) self.gridLayout_2.addLayout(self.horizontalLayout_2, 1, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 29)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Morse Toolkit")) self.toolkitBrowser.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Cantarell\'; font-size:11pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:14pt; text-decoration: underline;\">Welcome to the Morse Toolkit</span></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Sans Serif\'; font-size:16pt; text-decoration: underline;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\">Select one of the modes from the buttons below.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\"> </span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\">1. Koch Trainer: A classic Koch training tool for learning letters by their sounds.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\">2. Practice: Practice listening for words, callsign or individual letters. </span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\">3. Simulated QSO: Practice formal QSO exchanges. </span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\">4. Quiz Mode: Answer questions from excerpts of morse QSOs</span></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Sans Serif\'; font-size:12pt;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Sans Serif\'; font-size:16pt; text-decoration: underline;\"><br /></p></body></html>")) self.kochButton.setText(_translate("MainWindow", "Koch Trainer")) self.practiceButton.setText(_translate("MainWindow", "Practice")) self.simulatedButton.setText(_translate("MainWindow", "Simulated QSO")) self.quizButton.setText(_translate("MainWindow", "Quiz Mode")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
71.151163
280
0.708776
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout_2.setObjectName("gridLayout_2") self.gridLayout = QtWidgets.QGridLayout() self.gridLayout.setObjectName("gridLayout") self.toolkitBrowser = QtWidgets.QTextBrowser(self.centralwidget) self.toolkitBrowser.setObjectName("toolkitBrowser") self.gridLayout.addWidget(self.toolkitBrowser, 0, 0, 1, 1) self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.kochButton = QtWidgets.QPushButton(self.centralwidget) self.kochButton.setObjectName("kochButton") self.horizontalLayout_2.addWidget(self.kochButton) self.practiceButton = QtWidgets.QPushButton(self.centralwidget) self.practiceButton.setObjectName("practiceButton") self.horizontalLayout_2.addWidget(self.practiceButton) self.simulatedButton = QtWidgets.QPushButton(self.centralwidget) self.simulatedButton.setObjectName("simulatedButton") self.horizontalLayout_2.addWidget(self.simulatedButton) self.quizButton = QtWidgets.QPushButton(self.centralwidget) self.quizButton.setObjectName("quizButton") self.horizontalLayout_2.addWidget(self.quizButton) self.gridLayout_2.addLayout(self.horizontalLayout_2, 1, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 29)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Morse Toolkit")) self.toolkitBrowser.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Cantarell\'; font-size:11pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:14pt; text-decoration: underline;\">Welcome to the Morse Toolkit</span></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Sans Serif\'; font-size:16pt; text-decoration: underline;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\">Select one of the modes from the buttons below.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\"> </span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\">1. Koch Trainer: A classic Koch training tool for learning letters by their sounds.</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\">2. Practice: Practice listening for words, callsign or individual letters. </span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\">3. Simulated QSO: Practice formal QSO exchanges. </span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Sans Serif\'; font-size:10pt;\">4. Quiz Mode: Answer questions from excerpts of morse QSOs</span></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Sans Serif\'; font-size:12pt;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'Sans Serif\'; font-size:16pt; text-decoration: underline;\"><br /></p></body></html>")) self.kochButton.setText(_translate("MainWindow", "Koch Trainer")) self.practiceButton.setText(_translate("MainWindow", "Practice")) self.simulatedButton.setText(_translate("MainWindow", "Simulated QSO")) self.quizButton.setText(_translate("MainWindow", "Quiz Mode")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
true
true
1c444de510c835bf1a3b57ad6b627da2b0e5f8d3
18,760
py
Python
tensorflow/python/ops/gradients_test.py
topsun888/tensorflow
bad7c50b9dc9789ad7dd0a62daca40b7269841ed
[ "Apache-2.0" ]
2
2017-10-14T09:13:27.000Z
2017-10-26T18:34:28.000Z
tensorflow/python/ops/gradients_test.py
kiliczsh/tensorflow
f49aca4532c155597c669cf2189f211cafbebf96
[ "Apache-2.0" ]
1
2021-04-12T03:51:59.000Z
2021-04-12T03:51:59.000Z
tensorflow/python/ops/gradients_test.py
kiliczsh/tensorflow
f49aca4532c155597c669cf2189f211cafbebf96
[ "Apache-2.0" ]
5
2018-02-27T00:34:23.000Z
2022-02-28T16:38:08.000Z
# Copyright 2015 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. # ============================================================================== """Tests for tensorflow.ops.gradients.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import warnings import numpy as np import tensorflow as tf from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import function from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.framework.constant_op import constant from tensorflow.python.ops import array_grad # pylint: disable=unused-import from tensorflow.python.ops import array_ops from tensorflow.python.ops import data_flow_grad # pylint: disable=unused-import from tensorflow.python.ops import data_flow_ops # pylint: disable=unused-import from tensorflow.python.ops import gradients from tensorflow.python.ops import math_grad # pylint: disable=unused-import from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_grad # pylint: disable=unused-import from tensorflow.python.ops import state_grad # pylint: disable=unused-import from tensorflow.python.ops import functional_ops # pylint: disable=unused-import from tensorflow.python.ops.nn_ops import bias_add from tensorflow.python.platform import googletest def _OpsBetween(graph, to_ops, from_ops): """Build the list of operations between two lists of Operations. Args: graph: a Graph. to_ops: list of Operations. from_ops: list of Operations. Returns: The list of operations between "from_ops" and "to_ops", sorted by decreasing operation id. This list contains all elements of to_ops. TODO(touts): Think about returning an empty list if from_ops are not reachable from to_ops. Presently it returns to_ops in that case. """ # List of booleans, indexed by operation id, indicating if # an op is reached from the output of "input_ops". reached_ops = [False] * (graph._last_id + 1) # We only care to reach up to "output_ops" so we mark the # output ops as reached to avoid recursing past them. for op in to_ops: reached_ops[op._id] = True gradients._MarkReachedOps(from_ops, reached_ops) between_ops = gradients._GatherInputs(to_ops, reached_ops) between_ops.sort(key=lambda x: -x._id) return between_ops class GradientsTest(test_util.TensorFlowTestCase): def _OpNames(self, op_list): return ["%s/%d" % (str(op.name), op._id) for op in op_list] def _assertOpListEqual(self, ops1, ops2): self.assertEquals(self._OpNames(ops1), self._OpNames(ops2)) def testOpsBetweenSimple(self): with ops.Graph().as_default() as g: t1 = constant(1.0) t2 = constant(2.0) t3 = array_ops.pack([t1, t2]) # Full graph self._assertOpListEqual([t3.op, t2.op, t1.op], _OpsBetween(g, [t3.op], [t1.op, t2.op])) # Only t1, t3. self._assertOpListEqual([t3.op, t1.op], _OpsBetween(g, [t3.op], [t1.op])) def testOpsBetweenUnreachable(self): with ops.Graph().as_default() as g: t1 = constant(1.0) t2 = constant(2.0) _ = array_ops.pack([t1, t2]) t4 = constant(1.0) t5 = constant(2.0) t6 = array_ops.pack([t4, t5]) # Elements of to_ops are always listed. self._assertOpListEqual([t6.op], _OpsBetween(g, [t6.op], [t1.op])) def testOpsBetweenCut(self): with ops.Graph().as_default() as g: t1 = constant(1.0) t2 = constant(2.0) t3 = array_ops.pack([t1, t2]) t4 = constant([1.0]) t5 = array_ops.concat(0, [t4, t3]) t6 = constant([2.0]) t7 = array_ops.concat(0, [t5, t6]) self._assertOpListEqual([t7.op, t5.op, t4.op], _OpsBetween(g, [t7.op], [t4.op])) def testOpsBetweenCycle(self): with ops.Graph().as_default() as g: t1 = constant(1.0) t2 = constant(2.0) t3 = array_ops.pack([t1, t2]) t4 = array_ops.concat(0, [t3, t3, t3]) t5 = constant([1.0]) t6 = array_ops.concat(0, [t4, t5]) t7 = array_ops.concat(0, [t6, t3]) self._assertOpListEqual([t6.op, t4.op, t3.op], _OpsBetween(g, [t6.op], [t3.op])) self._assertOpListEqual([t7.op, t6.op, t5.op, t4.op, t3.op, t1.op], _OpsBetween(g, [t7.op], [t1.op, t5.op])) self._assertOpListEqual([t6.op, t5.op, t4.op, t3.op, t2.op], _OpsBetween(g, [t6.op], [t2.op, t5.op])) def testGradients(self): with ops.Graph().as_default(): inp = constant(1.0, shape=[32, 100], name="in") w = constant(1.0, shape=[100, 10], name="w") b = constant(1.0, shape=[10], name="b") xw = math_ops.matmul(inp, w, name="xw") h = bias_add(xw, b, name="h") w_grad = gradients.gradients(h, w)[0] self.assertEquals("MatMul", w_grad.op.type) self.assertEquals(w_grad.op._original_op, xw.op) self.assertTrue(w_grad.op.get_attr("transpose_a")) self.assertFalse(w_grad.op.get_attr("transpose_b")) def testUnusedOutput(self): with ops.Graph().as_default(): w = constant(1.0, shape=[2, 2]) x = constant(1.0, shape=[2, 2]) wx = math_ops.matmul(w, x) split_wx = array_ops.split(0, 2, wx) c = math_ops.reduce_sum(split_wx[1]) gw = gradients.gradients(c, [w])[0] self.assertEquals("MatMul", gw.op.type) def testColocateGradients(self): with ops.Graph().as_default() as g: w = constant(1.0, shape=[1, 1]) x = constant(1.0, shape=[1, 2]) with g.device("/gpu:0"): wx = math_ops.matmul(w, x) gw = gradients.gradients(wx, [w], colocate_gradients_with_ops=True)[0] self.assertEqual(gw.op.colocation_groups(), wx.op.colocation_groups()) def testColocateGradientsWithAggregation(self): with ops.Graph().as_default() as g: with g.device("/gpu:1"): w = constant(1.0, shape=[1, 1]) x = constant(1.0, shape=[1, 2]) y = constant(1.0, shape=[1, 2]) wx = math_ops.matmul(w, x) wy = math_ops.matmul(w, y) with g.device("/gpu:0"): z = wx + wy gw1 = gradients.gradients(z, [w], colocate_gradients_with_ops=True)[0] self.assertEqual(gw1.op.colocation_groups(), wx.op.colocation_groups()) gw2 = gradients.gradients(z, [w], colocate_gradients_with_ops=False)[0] self.assertTrue(wx.op.colocation_groups() != gw2.op.colocation_groups()) def testColocateGradientsWithAggregationInMultipleDevices(self): with ops.Graph().as_default() as g: with g.device("/gpu:1"): w = constant(1.0, shape=[1, 1]) x = constant(1.0, shape=[1, 2]) y = constant(1.0, shape=[1, 2]) with g.device("/task:1"): wx = math_ops.matmul(w, x) with g.device("/task:2"): wy = math_ops.matmul(w, y) with g.device("/gpu:0"): z = wx + wy gw1 = gradients.gradients(z, [w], colocate_gradients_with_ops=True)[0] self.assertEqual(gw1.op.colocation_groups(), w.op.colocation_groups()) gw2 = gradients.gradients(z, [w], colocate_gradients_with_ops=False)[0] self.assertTrue(w.op.colocation_groups() != gw2.op.colocation_groups()) def testBoundaryStop(self): # Test that we don't differentiate 'x'. The gradient function for 'x' is # set explicitly to None so we will get an exception if the gradient code # tries to differentiate 'x'. with ops.Graph().as_default() as g: c = constant(1.0) x = array_ops.identity(c) y = x + 1.0 z = y + 1 grads = gradients.gradients(z, [x]) self.assertTrue(all(x is not None for x in grads)) def testBoundaryContinue(self): # Test that we differentiate both 'x' and 'y' correctly when x is a # predecessor of y. with self.test_session(): x = constant(1.0) y = x * 2.0 z = y * 3.0 grads = gradients.gradients(z, [x, y]) self.assertTrue(all(x is not None for x in grads)) self.assertEqual(6.0, grads[0].eval()) def testAggregationMethodAccumulateN(self): with self.test_session(): x = constant(1.0) y = x * 2.0 z = y + y + y + y + y + y + y + y + y + y grads = gradients.gradients( z, [x, y], aggregation_method= gradients.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) self.assertTrue(all(x is not None for x in grads)) self.assertEqual(20.0, grads[0].eval()) self.assertEqual(10.0, grads[1].eval()) def testAggregationMethodAddN(self): with self.test_session(): x = constant(1.0) y = x * 2.0 z = y + y + y + y + y + y + y + y + y + y grads = gradients.gradients( z, [x, y], aggregation_method=gradients.AggregationMethod.ADD_N) self.assertTrue(all(x is not None for x in grads)) self.assertEqual(20.0, grads[0].eval()) self.assertEqual(10.0, grads[1].eval()) def testAggregationMethodTree(self): with self.test_session(): x = constant(1.0) y = x * 2.0 z = y + y + y + y + y + y + y + y + y + y grads = gradients.gradients( z, [x, y], aggregation_method=gradients.AggregationMethod.EXPERIMENTAL_TREE) self.assertTrue(all(x is not None for x in grads)) self.assertEqual(20.0, grads[0].eval()) self.assertEqual(10.0, grads[1].eval()) def testNoGradientForStringOutputs(self): with ops.Graph().as_default() as g: @ops.RegisterGradient("TestOp") def _TestOpGrad(op, float_grad, string_grad): """Gradient function for TestOp.""" self.assertEquals(float_grad.dtype, dtypes.float32) self.assertFalse(string_grad) return float_grad ops.RegisterShape("TestOp")(None) c = constant(1.0) x, y = g.create_op("TestOp", [c], [dtypes.float32, dtypes.string]).outputs z = x * 2.0 w = z * 3.0 grads = gradients.gradients(z, [c]) self.assertTrue(isinstance(grads[0], ops.Tensor)) def testSingletonIndexedSlices(self): with ops.Graph().as_default(): x = tf.placeholder(tf.float32) y = tf.identity(x) dy = tf.IndexedSlices(tf.placeholder(tf.float32), tf.placeholder(tf.int32)) dx, = gradients.gradients(y, x, grad_ys=dy) # The gradient of tf.identity should pass the value through unchanged. # A previous version of the code did this only for tf.Tensor, not # tf.IndexedSlices. self.assertEqual(dx, dy) class FunctionGradientsTest(test_util.TensorFlowTestCase): @classmethod def XSquarePlusB(cls, x, b): return x * x + b @classmethod def XSquarePlusBGradient(cls, x, b, g): # Perturb gradients (multiply by 2), so we can test that this was called. g *= 2.0 return g * 2.0 * x, g @classmethod def _PythonGradient(cls, op, grad): # Perturb gradients (multiply by 3), so we can test that this was called. grad *= 3.0 return grad * op.inputs[0] * 2.0, grad @classmethod def _GetFunc(cls, **kwargs): return function.Defun(tf.float32, tf.float32, **kwargs)( cls.XSquarePlusB) def _GetFuncGradients(self, f, x_value, b_value): x = tf.constant(x_value, name="x") b = tf.constant(b_value, name="b") y = f(x, b) grads = gradients.gradients(y, [x, b]) with self.test_session() as sess: return sess.run(grads) def testFunctionGradientsBasic(self): g = ops.Graph() with g.as_default(): f = self._GetFunc() # Get gradients (should add SymbolicGradient node for function). grads = self._GetFuncGradients(f, [2.0], [1.0]) self.assertAllEqual([4.0], grads[0]) self.assertAllEqual([1.0], grads[1]) def testFunctionGradientsComposition(self): with ops.Graph().as_default(): f = self._GetFunc() x = tf.constant([2.0], name="x") b1 = tf.constant([1.0], name="b1") b2 = tf.constant([1.0], name="b2") y = f(f(x, b1), b2) # Build gradient graph (should add SymbolicGradient node for function). grads = gradients.gradients(y, [x, b1]) with self.test_session() as sess: self.assertAllEqual([40.0], sess.run(grads)[0]) self.assertAllEqual([10.0], sess.run(grads)[1]) def testFunctionGradientsWithGradFunc(self): g = ops.Graph() with g.as_default(): grad_func = function.Defun(tf.float32, tf.float32, tf.float32)( self.XSquarePlusBGradient) f = self._GetFunc(grad_func=grad_func) # Get gradients (should add SymbolicGradient node for function, which # uses the grad_func above, which multiplies all gradients by 2). grads = self._GetFuncGradients(f, [2.0], [1.0]) self.assertAllEqual([4.0 * 2], grads[0]) self.assertAllEqual([1.0 * 2], grads[1]) def testFunctionGradientWithRegistration(self): g = ops.Graph() with g.as_default(): f = self._GetFunc(python_grad_func=self._PythonGradient) # Get gradients, using the python gradient function. It multiplies the # gradients by 3. grads = self._GetFuncGradients(f, [2.0], [1.0]) self.assertAllEqual([4.0 * 3], grads[0]) self.assertAllEqual([1.0 * 3], grads[1]) def testFunctionGradientWithGradFuncAndRegistration(self): g = ops.Graph() with g.as_default(): grad_func = function.Defun(tf.float32, tf.float32, tf.float32)( self.XSquarePlusBGradient) with self.assertRaisesRegexp(ValueError, "Gradient defined twice"): f = self._GetFunc(grad_func=grad_func, python_grad_func=self._PythonGradient) f.add_to_graph(tf.Graph()) class StopGradientTest(test_util.TensorFlowTestCase): def testStopGradient(self): with ops.Graph().as_default(): inp = constant(1.0, shape=[100, 32], name="in") out = array_ops.stop_gradient(inp) igrad = gradients.gradients(out, inp)[0] assert igrad is None class HessianVectorProductTest(test_util.TensorFlowTestCase): def testHessianVectorProduct(self): # Manually compute the Hessian explicitly for a low-dimensional problem # and check that HessianVectorProduct matches multiplication by the # explicit Hessian. # Specifically, the Hessian of f(x) = x^T A x is # H = A + A^T. # We expect HessianVectorProduct(f(x), x, v) to be H v. m = 4 rng = np.random.RandomState([1, 2, 3]) mat_value = rng.randn(m, m).astype("float32") v_value = rng.randn(m, 1).astype("float32") x_value = rng.randn(m, 1).astype("float32") hess_value = mat_value + mat_value.T hess_v_value = np.dot(hess_value, v_value) for use_gpu in [False, True]: with self.test_session(use_gpu=use_gpu): mat = constant_op.constant(mat_value) v = constant_op.constant(v_value) x = constant_op.constant(x_value) mat_x = math_ops.matmul(mat, x, name="Ax") x_mat_x = math_ops.matmul(array_ops.transpose(x), mat_x, name="xAx") hess_v = gradients._hessian_vector_product(x_mat_x, [x], [v])[0] hess_v_actual = hess_v.eval() self.assertAllClose(hess_v_value, hess_v_actual) class IndexedSlicesToTensorTest(test_util.TensorFlowTestCase): def testIndexedSlicesToTensor(self): with self.test_session(): np_val = np.random.rand(4, 4, 4, 4).astype(np.float32) c = constant_op.constant(np_val) c_sparse = math_ops._as_indexed_slices(c) self.assertAllEqual(np_val.shape, c_sparse.dense_shape.eval()) c_dense = math_ops.mul(c_sparse, 1.0) self.assertAllClose(np_val, c_dense.eval()) def testIndexedSlicesToTensorList(self): with self.test_session(): numpy_list = [] dense_list = [] sparse_list = [] for _ in range(3): np_val = np.random.rand(4, 4, 4, 4).astype(np.float32) c = constant_op.constant(np_val) c_sparse = math_ops._as_indexed_slices(c) numpy_list.append(np_val) dense_list.append(c) sparse_list.append(c_sparse) packed_dense = array_ops.pack(dense_list) packed_sparse = array_ops.pack(sparse_list) self.assertAllClose(packed_dense.eval(), packed_sparse.eval()) def testInt64Indices(self): with self.test_session(): np_val = np.random.rand(4, 4, 4, 4).astype(np.float32) c = constant_op.constant(np_val) c_sparse = math_ops._as_indexed_slices(c) c_sparse = ops.IndexedSlices( c_sparse.values, math_ops.cast(c_sparse.indices, dtypes.int64), c_sparse.dense_shape) self.assertAllEqual(np_val.shape, c_sparse.dense_shape.eval()) c_dense = math_ops.mul(c_sparse, 1.0) self.assertAllClose(np_val, c_dense.eval()) def testWarnings(self): # Smaller than the threshold: no warning. c_sparse = ops.IndexedSlices(array_ops.placeholder(dtypes.float32), array_ops.placeholder(dtypes.int32), constant([4, 4, 4, 4])) with warnings.catch_warnings(record=True) as w: math_ops.mul(c_sparse, 1.0) self.assertEqual(0, len(w)) # Greater than or equal to the threshold: warning. c_sparse = ops.IndexedSlices(array_ops.placeholder(dtypes.float32), array_ops.placeholder(dtypes.int32), constant([100, 100, 100, 100])) with warnings.catch_warnings(record=True) as w: math_ops.mul(c_sparse, 1.0) self.assertEqual(1, len(w)) self.assertTrue( "with 100000000 elements. This may consume a large amount of memory." in str(w[0].message)) # Unknown dense shape: warning. c_sparse = ops.IndexedSlices(array_ops.placeholder(dtypes.float32), array_ops.placeholder(dtypes.int32), array_ops.placeholder(dtypes.int32)) with warnings.catch_warnings(record=True) as w: math_ops.mul(c_sparse, 1.0) self.assertEqual(1, len(w)) self.assertTrue( "of unknown shape. This may consume a large amount of memory." in str(w[0].message)) if __name__ == "__main__": googletest.main()
37.89899
81
0.646375
from __future__ import absolute_import from __future__ import division from __future__ import print_function import warnings import numpy as np import tensorflow as tf from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import function from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.framework.constant_op import constant from tensorflow.python.ops import array_grad from tensorflow.python.ops import array_ops from tensorflow.python.ops import data_flow_grad from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import gradients from tensorflow.python.ops import math_grad from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_grad from tensorflow.python.ops import state_grad from tensorflow.python.ops import functional_ops from tensorflow.python.ops.nn_ops import bias_add from tensorflow.python.platform import googletest def _OpsBetween(graph, to_ops, from_ops): reached_ops = [False] * (graph._last_id + 1) for op in to_ops: reached_ops[op._id] = True gradients._MarkReachedOps(from_ops, reached_ops) between_ops = gradients._GatherInputs(to_ops, reached_ops) between_ops.sort(key=lambda x: -x._id) return between_ops class GradientsTest(test_util.TensorFlowTestCase): def _OpNames(self, op_list): return ["%s/%d" % (str(op.name), op._id) for op in op_list] def _assertOpListEqual(self, ops1, ops2): self.assertEquals(self._OpNames(ops1), self._OpNames(ops2)) def testOpsBetweenSimple(self): with ops.Graph().as_default() as g: t1 = constant(1.0) t2 = constant(2.0) t3 = array_ops.pack([t1, t2]) self._assertOpListEqual([t3.op, t2.op, t1.op], _OpsBetween(g, [t3.op], [t1.op, t2.op])) self._assertOpListEqual([t3.op, t1.op], _OpsBetween(g, [t3.op], [t1.op])) def testOpsBetweenUnreachable(self): with ops.Graph().as_default() as g: t1 = constant(1.0) t2 = constant(2.0) _ = array_ops.pack([t1, t2]) t4 = constant(1.0) t5 = constant(2.0) t6 = array_ops.pack([t4, t5]) self._assertOpListEqual([t6.op], _OpsBetween(g, [t6.op], [t1.op])) def testOpsBetweenCut(self): with ops.Graph().as_default() as g: t1 = constant(1.0) t2 = constant(2.0) t3 = array_ops.pack([t1, t2]) t4 = constant([1.0]) t5 = array_ops.concat(0, [t4, t3]) t6 = constant([2.0]) t7 = array_ops.concat(0, [t5, t6]) self._assertOpListEqual([t7.op, t5.op, t4.op], _OpsBetween(g, [t7.op], [t4.op])) def testOpsBetweenCycle(self): with ops.Graph().as_default() as g: t1 = constant(1.0) t2 = constant(2.0) t3 = array_ops.pack([t1, t2]) t4 = array_ops.concat(0, [t3, t3, t3]) t5 = constant([1.0]) t6 = array_ops.concat(0, [t4, t5]) t7 = array_ops.concat(0, [t6, t3]) self._assertOpListEqual([t6.op, t4.op, t3.op], _OpsBetween(g, [t6.op], [t3.op])) self._assertOpListEqual([t7.op, t6.op, t5.op, t4.op, t3.op, t1.op], _OpsBetween(g, [t7.op], [t1.op, t5.op])) self._assertOpListEqual([t6.op, t5.op, t4.op, t3.op, t2.op], _OpsBetween(g, [t6.op], [t2.op, t5.op])) def testGradients(self): with ops.Graph().as_default(): inp = constant(1.0, shape=[32, 100], name="in") w = constant(1.0, shape=[100, 10], name="w") b = constant(1.0, shape=[10], name="b") xw = math_ops.matmul(inp, w, name="xw") h = bias_add(xw, b, name="h") w_grad = gradients.gradients(h, w)[0] self.assertEquals("MatMul", w_grad.op.type) self.assertEquals(w_grad.op._original_op, xw.op) self.assertTrue(w_grad.op.get_attr("transpose_a")) self.assertFalse(w_grad.op.get_attr("transpose_b")) def testUnusedOutput(self): with ops.Graph().as_default(): w = constant(1.0, shape=[2, 2]) x = constant(1.0, shape=[2, 2]) wx = math_ops.matmul(w, x) split_wx = array_ops.split(0, 2, wx) c = math_ops.reduce_sum(split_wx[1]) gw = gradients.gradients(c, [w])[0] self.assertEquals("MatMul", gw.op.type) def testColocateGradients(self): with ops.Graph().as_default() as g: w = constant(1.0, shape=[1, 1]) x = constant(1.0, shape=[1, 2]) with g.device("/gpu:0"): wx = math_ops.matmul(w, x) gw = gradients.gradients(wx, [w], colocate_gradients_with_ops=True)[0] self.assertEqual(gw.op.colocation_groups(), wx.op.colocation_groups()) def testColocateGradientsWithAggregation(self): with ops.Graph().as_default() as g: with g.device("/gpu:1"): w = constant(1.0, shape=[1, 1]) x = constant(1.0, shape=[1, 2]) y = constant(1.0, shape=[1, 2]) wx = math_ops.matmul(w, x) wy = math_ops.matmul(w, y) with g.device("/gpu:0"): z = wx + wy gw1 = gradients.gradients(z, [w], colocate_gradients_with_ops=True)[0] self.assertEqual(gw1.op.colocation_groups(), wx.op.colocation_groups()) gw2 = gradients.gradients(z, [w], colocate_gradients_with_ops=False)[0] self.assertTrue(wx.op.colocation_groups() != gw2.op.colocation_groups()) def testColocateGradientsWithAggregationInMultipleDevices(self): with ops.Graph().as_default() as g: with g.device("/gpu:1"): w = constant(1.0, shape=[1, 1]) x = constant(1.0, shape=[1, 2]) y = constant(1.0, shape=[1, 2]) with g.device("/task:1"): wx = math_ops.matmul(w, x) with g.device("/task:2"): wy = math_ops.matmul(w, y) with g.device("/gpu:0"): z = wx + wy gw1 = gradients.gradients(z, [w], colocate_gradients_with_ops=True)[0] self.assertEqual(gw1.op.colocation_groups(), w.op.colocation_groups()) gw2 = gradients.gradients(z, [w], colocate_gradients_with_ops=False)[0] self.assertTrue(w.op.colocation_groups() != gw2.op.colocation_groups()) def testBoundaryStop(self): # set explicitly to None so we will get an exception if the gradient code # tries to differentiate 'x'. with ops.Graph().as_default() as g: c = constant(1.0) x = array_ops.identity(c) y = x + 1.0 z = y + 1 grads = gradients.gradients(z, [x]) self.assertTrue(all(x is not None for x in grads)) def testBoundaryContinue(self): # Test that we differentiate both 'x' and 'y' correctly when x is a # predecessor of y. with self.test_session(): x = constant(1.0) y = x * 2.0 z = y * 3.0 grads = gradients.gradients(z, [x, y]) self.assertTrue(all(x is not None for x in grads)) self.assertEqual(6.0, grads[0].eval()) def testAggregationMethodAccumulateN(self): with self.test_session(): x = constant(1.0) y = x * 2.0 z = y + y + y + y + y + y + y + y + y + y grads = gradients.gradients( z, [x, y], aggregation_method= gradients.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) self.assertTrue(all(x is not None for x in grads)) self.assertEqual(20.0, grads[0].eval()) self.assertEqual(10.0, grads[1].eval()) def testAggregationMethodAddN(self): with self.test_session(): x = constant(1.0) y = x * 2.0 z = y + y + y + y + y + y + y + y + y + y grads = gradients.gradients( z, [x, y], aggregation_method=gradients.AggregationMethod.ADD_N) self.assertTrue(all(x is not None for x in grads)) self.assertEqual(20.0, grads[0].eval()) self.assertEqual(10.0, grads[1].eval()) def testAggregationMethodTree(self): with self.test_session(): x = constant(1.0) y = x * 2.0 z = y + y + y + y + y + y + y + y + y + y grads = gradients.gradients( z, [x, y], aggregation_method=gradients.AggregationMethod.EXPERIMENTAL_TREE) self.assertTrue(all(x is not None for x in grads)) self.assertEqual(20.0, grads[0].eval()) self.assertEqual(10.0, grads[1].eval()) def testNoGradientForStringOutputs(self): with ops.Graph().as_default() as g: @ops.RegisterGradient("TestOp") def _TestOpGrad(op, float_grad, string_grad): self.assertEquals(float_grad.dtype, dtypes.float32) self.assertFalse(string_grad) return float_grad ops.RegisterShape("TestOp")(None) c = constant(1.0) x, y = g.create_op("TestOp", [c], [dtypes.float32, dtypes.string]).outputs z = x * 2.0 w = z * 3.0 grads = gradients.gradients(z, [c]) self.assertTrue(isinstance(grads[0], ops.Tensor)) def testSingletonIndexedSlices(self): with ops.Graph().as_default(): x = tf.placeholder(tf.float32) y = tf.identity(x) dy = tf.IndexedSlices(tf.placeholder(tf.float32), tf.placeholder(tf.int32)) dx, = gradients.gradients(y, x, grad_ys=dy) # The gradient of tf.identity should pass the value through unchanged. # A previous version of the code did this only for tf.Tensor, not # tf.IndexedSlices. self.assertEqual(dx, dy) class FunctionGradientsTest(test_util.TensorFlowTestCase): @classmethod def XSquarePlusB(cls, x, b): return x * x + b @classmethod def XSquarePlusBGradient(cls, x, b, g): # Perturb gradients (multiply by 2), so we can test that this was called. g *= 2.0 return g * 2.0 * x, g @classmethod def _PythonGradient(cls, op, grad): # Perturb gradients (multiply by 3), so we can test that this was called. grad *= 3.0 return grad * op.inputs[0] * 2.0, grad @classmethod def _GetFunc(cls, **kwargs): return function.Defun(tf.float32, tf.float32, **kwargs)( cls.XSquarePlusB) def _GetFuncGradients(self, f, x_value, b_value): x = tf.constant(x_value, name="x") b = tf.constant(b_value, name="b") y = f(x, b) grads = gradients.gradients(y, [x, b]) with self.test_session() as sess: return sess.run(grads) def testFunctionGradientsBasic(self): g = ops.Graph() with g.as_default(): f = self._GetFunc() # Get gradients (should add SymbolicGradient node for function). grads = self._GetFuncGradients(f, [2.0], [1.0]) self.assertAllEqual([4.0], grads[0]) self.assertAllEqual([1.0], grads[1]) def testFunctionGradientsComposition(self): with ops.Graph().as_default(): f = self._GetFunc() x = tf.constant([2.0], name="x") b1 = tf.constant([1.0], name="b1") b2 = tf.constant([1.0], name="b2") y = f(f(x, b1), b2) # Build gradient graph (should add SymbolicGradient node for function). grads = gradients.gradients(y, [x, b1]) with self.test_session() as sess: self.assertAllEqual([40.0], sess.run(grads)[0]) self.assertAllEqual([10.0], sess.run(grads)[1]) def testFunctionGradientsWithGradFunc(self): g = ops.Graph() with g.as_default(): grad_func = function.Defun(tf.float32, tf.float32, tf.float32)( self.XSquarePlusBGradient) f = self._GetFunc(grad_func=grad_func) # Get gradients (should add SymbolicGradient node for function, which # uses the grad_func above, which multiplies all gradients by 2). grads = self._GetFuncGradients(f, [2.0], [1.0]) self.assertAllEqual([4.0 * 2], grads[0]) self.assertAllEqual([1.0 * 2], grads[1]) def testFunctionGradientWithRegistration(self): g = ops.Graph() with g.as_default(): f = self._GetFunc(python_grad_func=self._PythonGradient) # Get gradients, using the python gradient function. It multiplies the # gradients by 3. grads = self._GetFuncGradients(f, [2.0], [1.0]) self.assertAllEqual([4.0 * 3], grads[0]) self.assertAllEqual([1.0 * 3], grads[1]) def testFunctionGradientWithGradFuncAndRegistration(self): g = ops.Graph() with g.as_default(): grad_func = function.Defun(tf.float32, tf.float32, tf.float32)( self.XSquarePlusBGradient) with self.assertRaisesRegexp(ValueError, "Gradient defined twice"): f = self._GetFunc(grad_func=grad_func, python_grad_func=self._PythonGradient) f.add_to_graph(tf.Graph()) class StopGradientTest(test_util.TensorFlowTestCase): def testStopGradient(self): with ops.Graph().as_default(): inp = constant(1.0, shape=[100, 32], name="in") out = array_ops.stop_gradient(inp) igrad = gradients.gradients(out, inp)[0] assert igrad is None class HessianVectorProductTest(test_util.TensorFlowTestCase): def testHessianVectorProduct(self): # Manually compute the Hessian explicitly for a low-dimensional problem # and check that HessianVectorProduct matches multiplication by the # explicit Hessian. # Specifically, the Hessian of f(x) = x^T A x is # H = A + A^T. # We expect HessianVectorProduct(f(x), x, v) to be H v. m = 4 rng = np.random.RandomState([1, 2, 3]) mat_value = rng.randn(m, m).astype("float32") v_value = rng.randn(m, 1).astype("float32") x_value = rng.randn(m, 1).astype("float32") hess_value = mat_value + mat_value.T hess_v_value = np.dot(hess_value, v_value) for use_gpu in [False, True]: with self.test_session(use_gpu=use_gpu): mat = constant_op.constant(mat_value) v = constant_op.constant(v_value) x = constant_op.constant(x_value) mat_x = math_ops.matmul(mat, x, name="Ax") x_mat_x = math_ops.matmul(array_ops.transpose(x), mat_x, name="xAx") hess_v = gradients._hessian_vector_product(x_mat_x, [x], [v])[0] hess_v_actual = hess_v.eval() self.assertAllClose(hess_v_value, hess_v_actual) class IndexedSlicesToTensorTest(test_util.TensorFlowTestCase): def testIndexedSlicesToTensor(self): with self.test_session(): np_val = np.random.rand(4, 4, 4, 4).astype(np.float32) c = constant_op.constant(np_val) c_sparse = math_ops._as_indexed_slices(c) self.assertAllEqual(np_val.shape, c_sparse.dense_shape.eval()) c_dense = math_ops.mul(c_sparse, 1.0) self.assertAllClose(np_val, c_dense.eval()) def testIndexedSlicesToTensorList(self): with self.test_session(): numpy_list = [] dense_list = [] sparse_list = [] for _ in range(3): np_val = np.random.rand(4, 4, 4, 4).astype(np.float32) c = constant_op.constant(np_val) c_sparse = math_ops._as_indexed_slices(c) numpy_list.append(np_val) dense_list.append(c) sparse_list.append(c_sparse) packed_dense = array_ops.pack(dense_list) packed_sparse = array_ops.pack(sparse_list) self.assertAllClose(packed_dense.eval(), packed_sparse.eval()) def testInt64Indices(self): with self.test_session(): np_val = np.random.rand(4, 4, 4, 4).astype(np.float32) c = constant_op.constant(np_val) c_sparse = math_ops._as_indexed_slices(c) c_sparse = ops.IndexedSlices( c_sparse.values, math_ops.cast(c_sparse.indices, dtypes.int64), c_sparse.dense_shape) self.assertAllEqual(np_val.shape, c_sparse.dense_shape.eval()) c_dense = math_ops.mul(c_sparse, 1.0) self.assertAllClose(np_val, c_dense.eval()) def testWarnings(self): # Smaller than the threshold: no warning. c_sparse = ops.IndexedSlices(array_ops.placeholder(dtypes.float32), array_ops.placeholder(dtypes.int32), constant([4, 4, 4, 4])) with warnings.catch_warnings(record=True) as w: math_ops.mul(c_sparse, 1.0) self.assertEqual(0, len(w)) # Greater than or equal to the threshold: warning. c_sparse = ops.IndexedSlices(array_ops.placeholder(dtypes.float32), array_ops.placeholder(dtypes.int32), constant([100, 100, 100, 100])) with warnings.catch_warnings(record=True) as w: math_ops.mul(c_sparse, 1.0) self.assertEqual(1, len(w)) self.assertTrue( "with 100000000 elements. This may consume a large amount of memory." in str(w[0].message)) # Unknown dense shape: warning. c_sparse = ops.IndexedSlices(array_ops.placeholder(dtypes.float32), array_ops.placeholder(dtypes.int32), array_ops.placeholder(dtypes.int32)) with warnings.catch_warnings(record=True) as w: math_ops.mul(c_sparse, 1.0) self.assertEqual(1, len(w)) self.assertTrue( "of unknown shape. This may consume a large amount of memory." in str(w[0].message)) if __name__ == "__main__": googletest.main()
true
true
1c444e381a5528baf355eff89d4e5396f0231430
42,894
py
Python
Lib/test/test_time.py
gdebirka/cpython
b18fd54f8c27e4b2aac222e75ac58aa85e5a7988
[ "0BSD" ]
1
2022-01-22T22:34:08.000Z
2022-01-22T22:34:08.000Z
Lib/test/test_time.py
gdebirka/cpython
b18fd54f8c27e4b2aac222e75ac58aa85e5a7988
[ "0BSD" ]
2
2022-02-06T01:15:13.000Z
2022-03-01T10:04:24.000Z
Lib/test/test_time.py
gdebirka/cpython
b18fd54f8c27e4b2aac222e75ac58aa85e5a7988
[ "0BSD" ]
2
2021-09-07T13:43:49.000Z
2021-12-19T08:34:56.000Z
from test import support from test.support import warnings_helper import decimal import enum import locale import math import platform import sys import sysconfig import time import threading import unittest try: import _testcapi except ImportError: _testcapi = None from test.support import skip_if_buggy_ucrt_strfptime # Max year is only limited by the size of C int. SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4 TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1 TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900 SEC_TO_US = 10 ** 6 US_TO_NS = 10 ** 3 MS_TO_NS = 10 ** 6 SEC_TO_NS = 10 ** 9 NS_TO_SEC = 10 ** 9 class _PyTime(enum.IntEnum): # Round towards minus infinity (-inf) ROUND_FLOOR = 0 # Round towards infinity (+inf) ROUND_CEILING = 1 # Round to nearest with ties going to nearest even integer ROUND_HALF_EVEN = 2 # Round away from zero ROUND_UP = 3 # _PyTime_t is int64_t _PyTime_MIN = -2 ** 63 _PyTime_MAX = 2 ** 63 - 1 # Rounding modes supported by PyTime ROUNDING_MODES = ( # (PyTime rounding method, decimal rounding method) (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR), (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING), (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN), (_PyTime.ROUND_UP, decimal.ROUND_UP), ) class TimeTestCase(unittest.TestCase): def setUp(self): self.t = time.time() def test_data_attributes(self): time.altzone time.daylight time.timezone time.tzname def test_time(self): time.time() info = time.get_clock_info('time') self.assertFalse(info.monotonic) self.assertTrue(info.adjustable) def test_time_ns_type(self): def check_ns(sec, ns): self.assertIsInstance(ns, int) sec_ns = int(sec * 1e9) # tolerate a difference of 50 ms self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns)) check_ns(time.time(), time.time_ns()) check_ns(time.monotonic(), time.monotonic_ns()) check_ns(time.perf_counter(), time.perf_counter_ns()) check_ns(time.process_time(), time.process_time_ns()) if hasattr(time, 'thread_time'): check_ns(time.thread_time(), time.thread_time_ns()) if hasattr(time, 'clock_gettime'): check_ns(time.clock_gettime(time.CLOCK_REALTIME), time.clock_gettime_ns(time.CLOCK_REALTIME)) @unittest.skipUnless(hasattr(time, 'clock_gettime'), 'need time.clock_gettime()') def test_clock_realtime(self): t = time.clock_gettime(time.CLOCK_REALTIME) self.assertIsInstance(t, float) @unittest.skipUnless(hasattr(time, 'clock_gettime'), 'need time.clock_gettime()') @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'), 'need time.CLOCK_MONOTONIC') def test_clock_monotonic(self): a = time.clock_gettime(time.CLOCK_MONOTONIC) b = time.clock_gettime(time.CLOCK_MONOTONIC) self.assertLessEqual(a, b) @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'), 'need time.pthread_getcpuclockid()') @unittest.skipUnless(hasattr(time, 'clock_gettime'), 'need time.clock_gettime()') def test_pthread_getcpuclockid(self): clk_id = time.pthread_getcpuclockid(threading.get_ident()) self.assertTrue(type(clk_id) is int) # when in 32-bit mode AIX only returns the predefined constant if platform.system() == "AIX" and (sys.maxsize.bit_length() <= 32): self.assertEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID) # Solaris returns CLOCK_THREAD_CPUTIME_ID when current thread is given elif sys.platform.startswith("sunos"): self.assertEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID) else: self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID) t1 = time.clock_gettime(clk_id) t2 = time.clock_gettime(clk_id) self.assertLessEqual(t1, t2) @unittest.skipUnless(hasattr(time, 'clock_getres'), 'need time.clock_getres()') def test_clock_getres(self): res = time.clock_getres(time.CLOCK_REALTIME) self.assertGreater(res, 0.0) self.assertLessEqual(res, 1.0) @unittest.skipUnless(hasattr(time, 'clock_settime'), 'need time.clock_settime()') def test_clock_settime(self): t = time.clock_gettime(time.CLOCK_REALTIME) try: time.clock_settime(time.CLOCK_REALTIME, t) except PermissionError: pass if hasattr(time, 'CLOCK_MONOTONIC'): self.assertRaises(OSError, time.clock_settime, time.CLOCK_MONOTONIC, 0) def test_conversions(self): self.assertEqual(time.ctime(self.t), time.asctime(time.localtime(self.t))) self.assertEqual(int(time.mktime(time.localtime(self.t))), int(self.t)) def test_sleep(self): self.assertRaises(ValueError, time.sleep, -2) self.assertRaises(ValueError, time.sleep, -1) time.sleep(1.2) def test_epoch(self): # bpo-43869: Make sure that Python use the same Epoch on all platforms: # January 1, 1970, 00:00:00 (UTC). epoch = time.gmtime(0) # Only test the date and time, ignore other gmtime() members self.assertEqual(tuple(epoch)[:6], (1970, 1, 1, 0, 0, 0), epoch) def test_strftime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strftime(format, tt) except ValueError: self.fail('conversion specifier: %r failed.' % format) self.assertRaises(TypeError, time.strftime, b'%S', tt) # embedded null character self.assertRaises(ValueError, time.strftime, '%S\0', tt) def _bounds_checking(self, func): # Make sure that strftime() checks the bounds of the various parts # of the time tuple (0 is valid for *all* values). # The year field is tested by other test cases above # Check month [1, 12] + zero support func((1900, 0, 1, 0, 0, 0, 0, 1, -1)) func((1900, 12, 1, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, -1, 1, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 13, 1, 0, 0, 0, 0, 1, -1)) # Check day of month [1, 31] + zero support func((1900, 1, 0, 0, 0, 0, 0, 1, -1)) func((1900, 1, 31, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, -1, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 32, 0, 0, 0, 0, 1, -1)) # Check hour [0, 23] func((1900, 1, 1, 23, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, -1, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 24, 0, 0, 0, 1, -1)) # Check minute [0, 59] func((1900, 1, 1, 0, 59, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, -1, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 60, 0, 0, 1, -1)) # Check second [0, 61] self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, -1, 0, 1, -1)) # C99 only requires allowing for one leap second, but Python's docs say # allow two leap seconds (0..61) func((1900, 1, 1, 0, 0, 60, 0, 1, -1)) func((1900, 1, 1, 0, 0, 61, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 62, 0, 1, -1)) # No check for upper-bound day of week; # value forced into range by a ``% 7`` calculation. # Start check at -2 since gettmarg() increments value before taking # modulo. self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)), func((1900, 1, 1, 0, 0, 0, +6, 1, -1))) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 0, -2, 1, -1)) # Check day of the year [1, 366] + zero support func((1900, 1, 1, 0, 0, 0, 0, 0, -1)) func((1900, 1, 1, 0, 0, 0, 0, 366, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 0, 0, -1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 0, 0, 367, -1)) def test_strftime_bounding_check(self): self._bounds_checking(lambda tup: time.strftime('', tup)) def test_strftime_format_check(self): # Test that strftime does not crash on invalid format strings # that may trigger a buffer overread. When not triggered, # strftime may succeed or raise ValueError depending on # the platform. for x in [ '', 'A', '%A', '%AA' ]: for y in range(0x0, 0x10): for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]: try: time.strftime(x * y + z) except ValueError: pass def test_default_values_for_zero(self): # Make sure that using all zeros uses the proper default # values. No test for daylight savings since strftime() does # not change output based on its value and no test for year # because systems vary in their support for year 0. expected = "2000 01 01 00 00 00 1 001" with warnings_helper.check_warnings(): result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8) self.assertEqual(expected, result) @skip_if_buggy_ucrt_strfptime def test_strptime(self): # Should be able to go round-trip from strftime to strptime without # raising an exception. tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = '%' + directive strf_output = time.strftime(format, tt) try: time.strptime(strf_output, format) except ValueError: self.fail("conversion specifier %r failed with '%s' input." % (format, strf_output)) def test_strptime_bytes(self): # Make sure only strings are accepted as arguments to strptime. self.assertRaises(TypeError, time.strptime, b'2009', "%Y") self.assertRaises(TypeError, time.strptime, '2009', b'%Y') def test_strptime_exception_context(self): # check that this doesn't chain exceptions needlessly (see #17572) with self.assertRaises(ValueError) as e: time.strptime('', '%D') self.assertIs(e.exception.__suppress_context__, True) # additional check for IndexError branch (issue #19545) with self.assertRaises(ValueError) as e: time.strptime('19', '%Y %') self.assertIs(e.exception.__suppress_context__, True) def test_asctime(self): time.asctime(time.gmtime(self.t)) # Max year is only limited by the size of C int. for bigyear in TIME_MAXYEAR, TIME_MINYEAR: asc = time.asctime((bigyear, 6, 1) + (0,) * 6) self.assertEqual(asc[-len(str(bigyear)):], str(bigyear)) self.assertRaises(OverflowError, time.asctime, (TIME_MAXYEAR + 1,) + (0,) * 8) self.assertRaises(OverflowError, time.asctime, (TIME_MINYEAR - 1,) + (0,) * 8) self.assertRaises(TypeError, time.asctime, 0) self.assertRaises(TypeError, time.asctime, ()) self.assertRaises(TypeError, time.asctime, (0,) * 10) def test_asctime_bounding_check(self): self._bounds_checking(time.asctime) def test_ctime(self): t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1)) self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973') t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1)) self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000') for year in [-100, 100, 1000, 2000, 2050, 10000]: try: testval = time.mktime((year, 1, 10) + (0,)*6) except (ValueError, OverflowError): # If mktime fails, ctime will fail too. This may happen # on some platforms. pass else: self.assertEqual(time.ctime(testval)[20:], str(year)) @unittest.skipUnless(hasattr(time, "tzset"), "time module has no attribute tzset") def test_tzset(self): from os import environ # Epoch time of midnight Dec 25th 2002. Never DST in northern # hemisphere. xmas2002 = 1040774400.0 # These formats are correct for 2002, and possibly future years # This format is the 'standard' as documented at: # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html # They are also documented in the tzset(3) man page on most Unix # systems. eastern = 'EST+05EDT,M4.1.0,M10.5.0' victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0' utc='UTC+0' org_TZ = environ.get('TZ',None) try: # Make sure we can switch to UTC time and results are correct # Note that unknown timezones default to UTC. # Note that altzone is undefined in UTC, as there is no DST environ['TZ'] = eastern time.tzset() environ['TZ'] = utc time.tzset() self.assertEqual( time.gmtime(xmas2002), time.localtime(xmas2002) ) self.assertEqual(time.daylight, 0) self.assertEqual(time.timezone, 0) self.assertEqual(time.localtime(xmas2002).tm_isdst, 0) # Make sure we can switch to US/Eastern environ['TZ'] = eastern time.tzset() self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002)) self.assertEqual(time.tzname, ('EST', 'EDT')) self.assertEqual(len(time.tzname), 2) self.assertEqual(time.daylight, 1) self.assertEqual(time.timezone, 18000) self.assertEqual(time.altzone, 14400) self.assertEqual(time.localtime(xmas2002).tm_isdst, 0) self.assertEqual(len(time.tzname), 2) # Now go to the southern hemisphere. environ['TZ'] = victoria time.tzset() self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002)) # Issue #11886: Australian Eastern Standard Time (UTC+10) is called # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST" # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone), # on some operating systems (e.g. FreeBSD), which is wrong. See for # example this bug: # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0]) self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1])) self.assertEqual(len(time.tzname), 2) self.assertEqual(time.daylight, 1) self.assertEqual(time.timezone, -36000) self.assertEqual(time.altzone, -39600) self.assertEqual(time.localtime(xmas2002).tm_isdst, 1) finally: # Repair TZ environment variable in case any other tests # rely on it. if org_TZ is not None: environ['TZ'] = org_TZ elif 'TZ' in environ: del environ['TZ'] time.tzset() def test_insane_timestamps(self): # It's possible that some platform maps time_t to double, # and that this test will fail there. This test should # exempt such platforms (provided they return reasonable # results!). for func in time.ctime, time.gmtime, time.localtime: for unreasonable in -1e200, 1e200: self.assertRaises(OverflowError, func, unreasonable) def test_ctime_without_arg(self): # Not sure how to check the values, since the clock could tick # at any time. Make sure these are at least accepted and # don't raise errors. time.ctime() time.ctime(None) def test_gmtime_without_arg(self): gt0 = time.gmtime() gt1 = time.gmtime(None) t0 = time.mktime(gt0) t1 = time.mktime(gt1) self.assertAlmostEqual(t1, t0, delta=0.2) def test_localtime_without_arg(self): lt0 = time.localtime() lt1 = time.localtime(None) t0 = time.mktime(lt0) t1 = time.mktime(lt1) self.assertAlmostEqual(t1, t0, delta=0.2) def test_mktime(self): # Issue #1726687 for t in (-2, -1, 0, 1): try: tt = time.localtime(t) except (OverflowError, OSError): pass else: self.assertEqual(time.mktime(tt), t) # Issue #13309: passing extreme values to mktime() or localtime() # borks the glibc's internal timezone data. @unittest.skipUnless(platform.libc_ver()[0] != 'glibc', "disabled because of a bug in glibc. Issue #13309") def test_mktime_error(self): # It may not be possible to reliably make mktime return an error # on all platforms. This will make sure that no other exception # than OverflowError is raised for an extreme value. tt = time.gmtime(self.t) tzname = time.strftime('%Z', tt) self.assertNotEqual(tzname, 'LMT') try: time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1)) except OverflowError: pass self.assertEqual(time.strftime('%Z', tt), tzname) def test_monotonic(self): # monotonic() should not go backward times = [time.monotonic() for n in range(100)] t1 = times[0] for t2 in times[1:]: self.assertGreaterEqual(t2, t1, "times=%s" % times) t1 = t2 # monotonic() includes time elapsed during a sleep t1 = time.monotonic() time.sleep(0.5) t2 = time.monotonic() dt = t2 - t1 self.assertGreater(t2, t1) # bpo-20101: tolerate a difference of 50 ms because of bad timer # resolution on Windows self.assertTrue(0.450 <= dt) # monotonic() is a monotonic but non adjustable clock info = time.get_clock_info('monotonic') self.assertTrue(info.monotonic) self.assertFalse(info.adjustable) def test_perf_counter(self): time.perf_counter() def test_process_time(self): # process_time() should not include time spend during a sleep start = time.process_time() time.sleep(0.100) stop = time.process_time() # use 20 ms because process_time() has usually a resolution of 15 ms # on Windows self.assertLess(stop - start, 0.020) info = time.get_clock_info('process_time') self.assertTrue(info.monotonic) self.assertFalse(info.adjustable) def test_thread_time(self): if not hasattr(time, 'thread_time'): if sys.platform.startswith(('linux', 'win')): self.fail("time.thread_time() should be available on %r" % (sys.platform,)) else: self.skipTest("need time.thread_time") # thread_time() should not include time spend during a sleep start = time.thread_time() time.sleep(0.100) stop = time.thread_time() # use 20 ms because thread_time() has usually a resolution of 15 ms # on Windows self.assertLess(stop - start, 0.020) info = time.get_clock_info('thread_time') self.assertTrue(info.monotonic) self.assertFalse(info.adjustable) @unittest.skipUnless(hasattr(time, 'clock_settime'), 'need time.clock_settime') def test_monotonic_settime(self): t1 = time.monotonic() realtime = time.clock_gettime(time.CLOCK_REALTIME) # jump backward with an offset of 1 hour try: time.clock_settime(time.CLOCK_REALTIME, realtime - 3600) except PermissionError as err: self.skipTest(err) t2 = time.monotonic() time.clock_settime(time.CLOCK_REALTIME, realtime) # monotonic must not be affected by system clock updates self.assertGreaterEqual(t2, t1) def test_localtime_failure(self): # Issue #13847: check for localtime() failure invalid_time_t = None for time_t in (-1, 2**30, 2**33, 2**60): try: time.localtime(time_t) except OverflowError: self.skipTest("need 64-bit time_t") except OSError: invalid_time_t = time_t break if invalid_time_t is None: self.skipTest("unable to find an invalid time_t value") self.assertRaises(OSError, time.localtime, invalid_time_t) self.assertRaises(OSError, time.ctime, invalid_time_t) # Issue #26669: check for localtime() failure self.assertRaises(ValueError, time.localtime, float("nan")) self.assertRaises(ValueError, time.ctime, float("nan")) def test_get_clock_info(self): clocks = ['monotonic', 'perf_counter', 'process_time', 'time'] for name in clocks: info = time.get_clock_info(name) #self.assertIsInstance(info, dict) self.assertIsInstance(info.implementation, str) self.assertNotEqual(info.implementation, '') self.assertIsInstance(info.monotonic, bool) self.assertIsInstance(info.resolution, float) # 0.0 < resolution <= 1.0 self.assertGreater(info.resolution, 0.0) self.assertLessEqual(info.resolution, 1.0) self.assertIsInstance(info.adjustable, bool) self.assertRaises(ValueError, time.get_clock_info, 'xxx') class TestLocale(unittest.TestCase): def setUp(self): self.oldloc = locale.setlocale(locale.LC_ALL) def tearDown(self): locale.setlocale(locale.LC_ALL, self.oldloc) def test_bug_3061(self): try: tmp = locale.setlocale(locale.LC_ALL, "fr_FR") except locale.Error: self.skipTest('could not set locale.LC_ALL to fr_FR') # This should not cause an exception time.strftime("%B", (2009,2,1,0,0,0,0,0,0)) class _TestAsctimeYear: _format = '%d' def yearstr(self, y): return time.asctime((y,) + (0,) * 8).split()[-1] def test_large_year(self): # Check that it doesn't crash for year > 9999 self.assertEqual(self.yearstr(12345), '12345') self.assertEqual(self.yearstr(123456789), '123456789') class _TestStrftimeYear: # Issue 13305: For years < 1000, the value is not always # padded to 4 digits across platforms. The C standard # assumes year >= 1900, so it does not specify the number # of digits. if time.strftime('%Y', (1,) + (0,) * 8) == '0001': _format = '%04d' else: _format = '%d' def yearstr(self, y): return time.strftime('%Y', (y,) + (0,) * 8) def test_4dyear(self): # Check that we can return the zero padded value. if self._format == '%04d': self.test_year('%04d') else: def year4d(y): return time.strftime('%4Y', (y,) + (0,) * 8) self.test_year('%04d', func=year4d) def skip_if_not_supported(y): msg = "strftime() is limited to [1; 9999] with Visual Studio" # Check that it doesn't crash for year > 9999 try: time.strftime('%Y', (y,) + (0,) * 8) except ValueError: cond = False else: cond = True return unittest.skipUnless(cond, msg) @skip_if_not_supported(10000) def test_large_year(self): return super().test_large_year() @skip_if_not_supported(0) def test_negative(self): return super().test_negative() del skip_if_not_supported class _Test4dYear: _format = '%d' def test_year(self, fmt=None, func=None): fmt = fmt or self._format func = func or self.yearstr self.assertEqual(func(1), fmt % 1) self.assertEqual(func(68), fmt % 68) self.assertEqual(func(69), fmt % 69) self.assertEqual(func(99), fmt % 99) self.assertEqual(func(999), fmt % 999) self.assertEqual(func(9999), fmt % 9999) def test_large_year(self): self.assertEqual(self.yearstr(12345).lstrip('+'), '12345') self.assertEqual(self.yearstr(123456789).lstrip('+'), '123456789') self.assertEqual(self.yearstr(TIME_MAXYEAR).lstrip('+'), str(TIME_MAXYEAR)) self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1) def test_negative(self): self.assertEqual(self.yearstr(-1), self._format % -1) self.assertEqual(self.yearstr(-1234), '-1234') self.assertEqual(self.yearstr(-123456), '-123456') self.assertEqual(self.yearstr(-123456789), str(-123456789)) self.assertEqual(self.yearstr(-1234567890), str(-1234567890)) self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR)) # Modules/timemodule.c checks for underflow self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1) with self.assertRaises(OverflowError): self.yearstr(-TIME_MAXYEAR - 1) class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase): pass class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase): pass class TestPytime(unittest.TestCase): @skip_if_buggy_ucrt_strfptime @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_localtime_timezone(self): # Get the localtime and examine it for the offset and zone. lt = time.localtime() self.assertTrue(hasattr(lt, "tm_gmtoff")) self.assertTrue(hasattr(lt, "tm_zone")) # See if the offset and zone are similar to the module # attributes. if lt.tm_gmtoff is None: self.assertTrue(not hasattr(time, "timezone")) else: self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst]) if lt.tm_zone is None: self.assertTrue(not hasattr(time, "tzname")) else: self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst]) # Try and make UNIX times from the localtime and a 9-tuple # created from the localtime. Test to see that the times are # the same. t = time.mktime(lt); t9 = time.mktime(lt[:9]) self.assertEqual(t, t9) # Make localtimes from the UNIX times and compare them to # the original localtime, thus making a round trip. new_lt = time.localtime(t); new_lt9 = time.localtime(t9) self.assertEqual(new_lt, lt) self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff) self.assertEqual(new_lt.tm_zone, lt.tm_zone) self.assertEqual(new_lt9, lt) self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff) self.assertEqual(new_lt9.tm_zone, lt.tm_zone) @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_strptime_timezone(self): t = time.strptime("UTC", "%Z") self.assertEqual(t.tm_zone, 'UTC') t = time.strptime("+0500", "%z") self.assertEqual(t.tm_gmtoff, 5 * 3600) @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_short_times(self): import pickle # Load a short time structure using pickle. st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n." lt = pickle.loads(st) self.assertIs(lt.tm_gmtoff, None) self.assertIs(lt.tm_zone, None) @unittest.skipIf(_testcapi is None, 'need the _testcapi module') class CPyTimeTestCase: """ Base class to test the C _PyTime_t API. """ OVERFLOW_SECONDS = None def setUp(self): from _testcapi import SIZEOF_TIME_T bits = SIZEOF_TIME_T * 8 - 1 self.time_t_min = -2 ** bits self.time_t_max = 2 ** bits - 1 def time_t_filter(self, seconds): return (self.time_t_min <= seconds <= self.time_t_max) def _rounding_values(self, use_float): "Build timestamps used to test rounding." units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS] if use_float: # picoseconds are only tested to pytime_converter accepting floats units.append(1e-3) values = ( # small values 1, 2, 5, 7, 123, 456, 1234, # 10^k - 1 9, 99, 999, 9999, 99999, 999999, # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5 499, 500, 501, 1499, 1500, 1501, 2500, 3500, 4500, ) ns_timestamps = [0] for unit in units: for value in values: ns = value * unit ns_timestamps.extend((-ns, ns)) for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33): ns = (2 ** pow2) * SEC_TO_NS ns_timestamps.extend(( -ns-1, -ns, -ns+1, ns-1, ns, ns+1 )) for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX): ns_timestamps.append(seconds * SEC_TO_NS) if use_float: # numbers with an exact representation in IEEE 754 (base 2) for pow2 in (3, 7, 10, 15): ns = 2.0 ** (-pow2) ns_timestamps.extend((-ns, ns)) # seconds close to _PyTime_t type limit ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS ns_timestamps.extend((-ns, ns)) return ns_timestamps def _check_rounding(self, pytime_converter, expected_func, use_float, unit_to_sec, value_filter=None): def convert_values(ns_timestamps): if use_float: unit_to_ns = SEC_TO_NS / float(unit_to_sec) values = [ns / unit_to_ns for ns in ns_timestamps] else: unit_to_ns = SEC_TO_NS // unit_to_sec values = [ns // unit_to_ns for ns in ns_timestamps] if value_filter: values = filter(value_filter, values) # remove duplicates and sort return sorted(set(values)) # test rounding ns_timestamps = self._rounding_values(use_float) valid_values = convert_values(ns_timestamps) for time_rnd, decimal_rnd in ROUNDING_MODES : with decimal.localcontext() as context: context.rounding = decimal_rnd for value in valid_values: debug_info = {'value': value, 'rounding': decimal_rnd} try: result = pytime_converter(value, time_rnd) expected = expected_func(value) except Exception: self.fail("Error on timestamp conversion: %s" % debug_info) self.assertEqual(result, expected, debug_info) # test overflow ns = self.OVERFLOW_SECONDS * SEC_TO_NS ns_timestamps = (-ns, ns) overflow_values = convert_values(ns_timestamps) for time_rnd, _ in ROUNDING_MODES : for value in overflow_values: debug_info = {'value': value, 'rounding': time_rnd} with self.assertRaises(OverflowError, msg=debug_info): pytime_converter(value, time_rnd) def check_int_rounding(self, pytime_converter, expected_func, unit_to_sec=1, value_filter=None): self._check_rounding(pytime_converter, expected_func, False, unit_to_sec, value_filter) def check_float_rounding(self, pytime_converter, expected_func, unit_to_sec=1, value_filter=None): self._check_rounding(pytime_converter, expected_func, True, unit_to_sec, value_filter) def decimal_round(self, x): d = decimal.Decimal(x) d = d.quantize(1) return int(d) class TestCPyTime(CPyTimeTestCase, unittest.TestCase): """ Test the C _PyTime_t API. """ # _PyTime_t is a 64-bit signed integer OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS) def test_FromSeconds(self): from _testcapi import PyTime_FromSeconds # PyTime_FromSeconds() expects a C int, reject values out of range def c_int_filter(secs): return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX) self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs), lambda secs: secs * SEC_TO_NS, value_filter=c_int_filter) # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(TypeError): PyTime_FromSeconds(float('nan')) def test_FromSecondsObject(self): from _testcapi import PyTime_FromSecondsObject self.check_int_rounding( PyTime_FromSecondsObject, lambda secs: secs * SEC_TO_NS) self.check_float_rounding( PyTime_FromSecondsObject, lambda ns: self.decimal_round(ns * SEC_TO_NS)) # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(ValueError): PyTime_FromSecondsObject(float('nan'), time_rnd) def test_AsSecondsDouble(self): from _testcapi import PyTime_AsSecondsDouble def float_converter(ns): if abs(ns) % SEC_TO_NS == 0: return float(ns // SEC_TO_NS) else: return float(ns) / SEC_TO_NS self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns), float_converter, NS_TO_SEC) # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(TypeError): PyTime_AsSecondsDouble(float('nan')) def create_decimal_converter(self, denominator): denom = decimal.Decimal(denominator) def converter(value): d = decimal.Decimal(value) / denom return self.decimal_round(d) return converter def test_AsTimeval(self): from _testcapi import PyTime_AsTimeval us_converter = self.create_decimal_converter(US_TO_NS) def timeval_converter(ns): us = us_converter(ns) return divmod(us, SEC_TO_US) if sys.platform == 'win32': from _testcapi import LONG_MIN, LONG_MAX # On Windows, timeval.tv_sec type is a C long def seconds_filter(secs): return LONG_MIN <= secs <= LONG_MAX else: seconds_filter = self.time_t_filter self.check_int_rounding(PyTime_AsTimeval, timeval_converter, NS_TO_SEC, value_filter=seconds_filter) @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'), 'need _testcapi.PyTime_AsTimespec') def test_AsTimespec(self): from _testcapi import PyTime_AsTimespec def timespec_converter(ns): return divmod(ns, SEC_TO_NS) self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns), timespec_converter, NS_TO_SEC, value_filter=self.time_t_filter) @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimeval_clamp'), 'need _testcapi.PyTime_AsTimeval_clamp') def test_AsTimeval_clamp(self): from _testcapi import PyTime_AsTimeval_clamp if sys.platform == 'win32': from _testcapi import LONG_MIN, LONG_MAX tv_sec_max = LONG_MAX tv_sec_min = LONG_MIN else: tv_sec_max = self.time_t_max tv_sec_min = self.time_t_min for t in (_PyTime_MIN, _PyTime_MAX): ts = PyTime_AsTimeval_clamp(t, _PyTime.ROUND_CEILING) with decimal.localcontext() as context: context.rounding = decimal.ROUND_CEILING us = self.decimal_round(decimal.Decimal(t) / US_TO_NS) tv_sec, tv_usec = divmod(us, SEC_TO_US) if tv_sec_max < tv_sec: tv_sec = tv_sec_max tv_usec = 0 elif tv_sec < tv_sec_min: tv_sec = tv_sec_min tv_usec = 0 self.assertEqual(ts, (tv_sec, tv_usec)) @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec_clamp'), 'need _testcapi.PyTime_AsTimespec_clamp') def test_AsTimespec_clamp(self): from _testcapi import PyTime_AsTimespec_clamp for t in (_PyTime_MIN, _PyTime_MAX): ts = PyTime_AsTimespec_clamp(t) tv_sec, tv_nsec = divmod(t, NS_TO_SEC) if self.time_t_max < tv_sec: tv_sec = self.time_t_max tv_nsec = 0 elif tv_sec < self.time_t_min: tv_sec = self.time_t_min tv_nsec = 0 self.assertEqual(ts, (tv_sec, tv_nsec)) def test_AsMilliseconds(self): from _testcapi import PyTime_AsMilliseconds self.check_int_rounding(PyTime_AsMilliseconds, self.create_decimal_converter(MS_TO_NS), NS_TO_SEC) def test_AsMicroseconds(self): from _testcapi import PyTime_AsMicroseconds self.check_int_rounding(PyTime_AsMicroseconds, self.create_decimal_converter(US_TO_NS), NS_TO_SEC) class TestOldPyTime(CPyTimeTestCase, unittest.TestCase): """ Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions. """ # time_t is a 32-bit or 64-bit signed integer OVERFLOW_SECONDS = 2 ** 64 def test_object_to_time_t(self): from _testcapi import pytime_object_to_time_t self.check_int_rounding(pytime_object_to_time_t, lambda secs: secs, value_filter=self.time_t_filter) self.check_float_rounding(pytime_object_to_time_t, self.decimal_round, value_filter=self.time_t_filter) def create_converter(self, sec_to_unit): def converter(secs): floatpart, intpart = math.modf(secs) intpart = int(intpart) floatpart *= sec_to_unit floatpart = self.decimal_round(floatpart) if floatpart < 0: floatpart += sec_to_unit intpart -= 1 elif floatpart >= sec_to_unit: floatpart -= sec_to_unit intpart += 1 return (intpart, floatpart) return converter def test_object_to_timeval(self): from _testcapi import pytime_object_to_timeval self.check_int_rounding(pytime_object_to_timeval, lambda secs: (secs, 0), value_filter=self.time_t_filter) self.check_float_rounding(pytime_object_to_timeval, self.create_converter(SEC_TO_US), value_filter=self.time_t_filter) # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(ValueError): pytime_object_to_timeval(float('nan'), time_rnd) def test_object_to_timespec(self): from _testcapi import pytime_object_to_timespec self.check_int_rounding(pytime_object_to_timespec, lambda secs: (secs, 0), value_filter=self.time_t_filter) self.check_float_rounding(pytime_object_to_timespec, self.create_converter(SEC_TO_NS), value_filter=self.time_t_filter) # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(ValueError): pytime_object_to_timespec(float('nan'), time_rnd) @unittest.skipUnless(sys.platform == "darwin", "test weak linking on macOS") class TestTimeWeaklinking(unittest.TestCase): # These test cases verify that weak linking support on macOS works # as expected. These cases only test new behaviour introduced by weak linking, # regular behaviour is tested by the normal test cases. # # See the section on Weak Linking in Mac/README.txt for more information. def test_clock_functions(self): import sysconfig import platform config_vars = sysconfig.get_config_vars() var_name = "HAVE_CLOCK_GETTIME" if var_name not in config_vars or not config_vars[var_name]: raise unittest.SkipTest(f"{var_name} is not available") mac_ver = tuple(int(x) for x in platform.mac_ver()[0].split(".")) clock_names = [ "CLOCK_MONOTONIC", "clock_gettime", "clock_gettime_ns", "clock_settime", "clock_settime_ns", "clock_getres"] if mac_ver >= (10, 12): for name in clock_names: self.assertTrue(hasattr(time, name), f"time.{name} is not available") else: for name in clock_names: self.assertFalse(hasattr(time, name), f"time.{name} is available") if __name__ == "__main__": unittest.main()
37.892226
108
0.582739
from test import support from test.support import warnings_helper import decimal import enum import locale import math import platform import sys import sysconfig import time import threading import unittest try: import _testcapi except ImportError: _testcapi = None from test.support import skip_if_buggy_ucrt_strfptime SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4 TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1 TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900 SEC_TO_US = 10 ** 6 US_TO_NS = 10 ** 3 MS_TO_NS = 10 ** 6 SEC_TO_NS = 10 ** 9 NS_TO_SEC = 10 ** 9 class _PyTime(enum.IntEnum): ROUND_FLOOR = 0 ROUND_CEILING = 1 ROUND_HALF_EVEN = 2 ROUND_UP = 3 _PyTime_MIN = -2 ** 63 _PyTime_MAX = 2 ** 63 - 1 ROUNDING_MODES = ( (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR), (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING), (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN), (_PyTime.ROUND_UP, decimal.ROUND_UP), ) class TimeTestCase(unittest.TestCase): def setUp(self): self.t = time.time() def test_data_attributes(self): time.altzone time.daylight time.timezone time.tzname def test_time(self): time.time() info = time.get_clock_info('time') self.assertFalse(info.monotonic) self.assertTrue(info.adjustable) def test_time_ns_type(self): def check_ns(sec, ns): self.assertIsInstance(ns, int) sec_ns = int(sec * 1e9) self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns)) check_ns(time.time(), time.time_ns()) check_ns(time.monotonic(), time.monotonic_ns()) check_ns(time.perf_counter(), time.perf_counter_ns()) check_ns(time.process_time(), time.process_time_ns()) if hasattr(time, 'thread_time'): check_ns(time.thread_time(), time.thread_time_ns()) if hasattr(time, 'clock_gettime'): check_ns(time.clock_gettime(time.CLOCK_REALTIME), time.clock_gettime_ns(time.CLOCK_REALTIME)) @unittest.skipUnless(hasattr(time, 'clock_gettime'), 'need time.clock_gettime()') def test_clock_realtime(self): t = time.clock_gettime(time.CLOCK_REALTIME) self.assertIsInstance(t, float) @unittest.skipUnless(hasattr(time, 'clock_gettime'), 'need time.clock_gettime()') @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'), 'need time.CLOCK_MONOTONIC') def test_clock_monotonic(self): a = time.clock_gettime(time.CLOCK_MONOTONIC) b = time.clock_gettime(time.CLOCK_MONOTONIC) self.assertLessEqual(a, b) @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'), 'need time.pthread_getcpuclockid()') @unittest.skipUnless(hasattr(time, 'clock_gettime'), 'need time.clock_gettime()') def test_pthread_getcpuclockid(self): clk_id = time.pthread_getcpuclockid(threading.get_ident()) self.assertTrue(type(clk_id) is int) if platform.system() == "AIX" and (sys.maxsize.bit_length() <= 32): self.assertEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID) elif sys.platform.startswith("sunos"): self.assertEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID) else: self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID) t1 = time.clock_gettime(clk_id) t2 = time.clock_gettime(clk_id) self.assertLessEqual(t1, t2) @unittest.skipUnless(hasattr(time, 'clock_getres'), 'need time.clock_getres()') def test_clock_getres(self): res = time.clock_getres(time.CLOCK_REALTIME) self.assertGreater(res, 0.0) self.assertLessEqual(res, 1.0) @unittest.skipUnless(hasattr(time, 'clock_settime'), 'need time.clock_settime()') def test_clock_settime(self): t = time.clock_gettime(time.CLOCK_REALTIME) try: time.clock_settime(time.CLOCK_REALTIME, t) except PermissionError: pass if hasattr(time, 'CLOCK_MONOTONIC'): self.assertRaises(OSError, time.clock_settime, time.CLOCK_MONOTONIC, 0) def test_conversions(self): self.assertEqual(time.ctime(self.t), time.asctime(time.localtime(self.t))) self.assertEqual(int(time.mktime(time.localtime(self.t))), int(self.t)) def test_sleep(self): self.assertRaises(ValueError, time.sleep, -2) self.assertRaises(ValueError, time.sleep, -1) time.sleep(1.2) def test_epoch(self): epoch = time.gmtime(0) self.assertEqual(tuple(epoch)[:6], (1970, 1, 1, 0, 0, 0), epoch) def test_strftime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strftime(format, tt) except ValueError: self.fail('conversion specifier: %r failed.' % format) self.assertRaises(TypeError, time.strftime, b'%S', tt) self.assertRaises(ValueError, time.strftime, '%S\0', tt) def _bounds_checking(self, func): func((1900, 0, 1, 0, 0, 0, 0, 1, -1)) func((1900, 12, 1, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, -1, 1, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 13, 1, 0, 0, 0, 0, 1, -1)) func((1900, 1, 0, 0, 0, 0, 0, 1, -1)) func((1900, 1, 31, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, -1, 0, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 32, 0, 0, 0, 0, 1, -1)) func((1900, 1, 1, 23, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, -1, 0, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 24, 0, 0, 0, 1, -1)) func((1900, 1, 1, 0, 59, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, -1, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 60, 0, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, -1, 0, 1, -1)) # allow two leap seconds (0..61) func((1900, 1, 1, 0, 0, 60, 0, 1, -1)) func((1900, 1, 1, 0, 0, 61, 0, 1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 62, 0, 1, -1)) # No check for upper-bound day of week; # value forced into range by a ``% 7`` calculation. # Start check at -2 since gettmarg() increments value before taking # modulo. self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)), func((1900, 1, 1, 0, 0, 0, +6, 1, -1))) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 0, -2, 1, -1)) # Check day of the year [1, 366] + zero support func((1900, 1, 1, 0, 0, 0, 0, 0, -1)) func((1900, 1, 1, 0, 0, 0, 0, 366, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 0, 0, -1, -1)) self.assertRaises(ValueError, func, (1900, 1, 1, 0, 0, 0, 0, 367, -1)) def test_strftime_bounding_check(self): self._bounds_checking(lambda tup: time.strftime('', tup)) def test_strftime_format_check(self): # Test that strftime does not crash on invalid format strings # that may trigger a buffer overread. When not triggered, # strftime may succeed or raise ValueError depending on # the platform. for x in [ '', 'A', '%A', '%AA' ]: for y in range(0x0, 0x10): for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '% try: time.strftime(x * y + z) except ValueError: pass def test_default_values_for_zero(self): # Make sure that using all zeros uses the proper default # values. No test for daylight savings since strftime() does # not change output based on its value and no test for year # because systems vary in their support for year 0. expected = "2000 01 01 00 00 00 1 001" with warnings_helper.check_warnings(): result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8) self.assertEqual(expected, result) @skip_if_buggy_ucrt_strfptime def test_strptime(self): # Should be able to go round-trip from strftime to strptime without # raising an exception. tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = '%' + directive strf_output = time.strftime(format, tt) try: time.strptime(strf_output, format) except ValueError: self.fail("conversion specifier %r failed with '%s' input." % (format, strf_output)) def test_strptime_bytes(self): # Make sure only strings are accepted as arguments to strptime. self.assertRaises(TypeError, time.strptime, b'2009', "%Y") self.assertRaises(TypeError, time.strptime, '2009', b'%Y') def test_strptime_exception_context(self): # check that this doesn't chain exceptions needlessly (see with self.assertRaises(ValueError) as e: time.strptime('', '%D') self.assertIs(e.exception.__suppress_context__, True) with self.assertRaises(ValueError) as e: time.strptime('19', '%Y %') self.assertIs(e.exception.__suppress_context__, True) def test_asctime(self): time.asctime(time.gmtime(self.t)) for bigyear in TIME_MAXYEAR, TIME_MINYEAR: asc = time.asctime((bigyear, 6, 1) + (0,) * 6) self.assertEqual(asc[-len(str(bigyear)):], str(bigyear)) self.assertRaises(OverflowError, time.asctime, (TIME_MAXYEAR + 1,) + (0,) * 8) self.assertRaises(OverflowError, time.asctime, (TIME_MINYEAR - 1,) + (0,) * 8) self.assertRaises(TypeError, time.asctime, 0) self.assertRaises(TypeError, time.asctime, ()) self.assertRaises(TypeError, time.asctime, (0,) * 10) def test_asctime_bounding_check(self): self._bounds_checking(time.asctime) def test_ctime(self): t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1)) self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973') t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1)) self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000') for year in [-100, 100, 1000, 2000, 2050, 10000]: try: testval = time.mktime((year, 1, 10) + (0,)*6) except (ValueError, OverflowError): pass else: self.assertEqual(time.ctime(testval)[20:], str(year)) @unittest.skipUnless(hasattr(time, "tzset"), "time module has no attribute tzset") def test_tzset(self): from os import environ xmas2002 = 1040774400.0 eastern = 'EST+05EDT,M4.1.0,M10.5.0' victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0' utc='UTC+0' org_TZ = environ.get('TZ',None) try: environ['TZ'] = eastern time.tzset() environ['TZ'] = utc time.tzset() self.assertEqual( time.gmtime(xmas2002), time.localtime(xmas2002) ) self.assertEqual(time.daylight, 0) self.assertEqual(time.timezone, 0) self.assertEqual(time.localtime(xmas2002).tm_isdst, 0) environ['TZ'] = eastern time.tzset() self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002)) self.assertEqual(time.tzname, ('EST', 'EDT')) self.assertEqual(len(time.tzname), 2) self.assertEqual(time.daylight, 1) self.assertEqual(time.timezone, 18000) self.assertEqual(time.altzone, 14400) self.assertEqual(time.localtime(xmas2002).tm_isdst, 0) self.assertEqual(len(time.tzname), 2) environ['TZ'] = victoria time.tzset() self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002)) self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0]) self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1])) self.assertEqual(len(time.tzname), 2) self.assertEqual(time.daylight, 1) self.assertEqual(time.timezone, -36000) self.assertEqual(time.altzone, -39600) self.assertEqual(time.localtime(xmas2002).tm_isdst, 1) finally: if org_TZ is not None: environ['TZ'] = org_TZ elif 'TZ' in environ: del environ['TZ'] time.tzset() def test_insane_timestamps(self): # and that this test will fail there. This test should # exempt such platforms (provided they return reasonable # results!). for func in time.ctime, time.gmtime, time.localtime: for unreasonable in -1e200, 1e200: self.assertRaises(OverflowError, func, unreasonable) def test_ctime_without_arg(self): # Not sure how to check the values, since the clock could tick # at any time. Make sure these are at least accepted and # don't raise errors. time.ctime() time.ctime(None) def test_gmtime_without_arg(self): gt0 = time.gmtime() gt1 = time.gmtime(None) t0 = time.mktime(gt0) t1 = time.mktime(gt1) self.assertAlmostEqual(t1, t0, delta=0.2) def test_localtime_without_arg(self): lt0 = time.localtime() lt1 = time.localtime(None) t0 = time.mktime(lt0) t1 = time.mktime(lt1) self.assertAlmostEqual(t1, t0, delta=0.2) def test_mktime(self): for t in (-2, -1, 0, 1): try: tt = time.localtime(t) except (OverflowError, OSError): pass else: self.assertEqual(time.mktime(tt), t) 'glibc', "disabled because of a bug in glibc. Issue #13309") def test_mktime_error(self): # It may not be possible to reliably make mktime return an error # on all platforms. This will make sure that no other exception # than OverflowError is raised for an extreme value. tt = time.gmtime(self.t) tzname = time.strftime('%Z', tt) self.assertNotEqual(tzname, 'LMT') try: time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1)) except OverflowError: pass self.assertEqual(time.strftime('%Z', tt), tzname) def test_monotonic(self): # monotonic() should not go backward times = [time.monotonic() for n in range(100)] t1 = times[0] for t2 in times[1:]: self.assertGreaterEqual(t2, t1, "times=%s" % times) t1 = t2 # monotonic() includes time elapsed during a sleep t1 = time.monotonic() time.sleep(0.5) t2 = time.monotonic() dt = t2 - t1 self.assertGreater(t2, t1) # bpo-20101: tolerate a difference of 50 ms because of bad timer # resolution on Windows self.assertTrue(0.450 <= dt) # monotonic() is a monotonic but non adjustable clock info = time.get_clock_info('monotonic') self.assertTrue(info.monotonic) self.assertFalse(info.adjustable) def test_perf_counter(self): time.perf_counter() def test_process_time(self): # process_time() should not include time spend during a sleep start = time.process_time() time.sleep(0.100) stop = time.process_time() # use 20 ms because process_time() has usually a resolution of 15 ms # on Windows self.assertLess(stop - start, 0.020) info = time.get_clock_info('process_time') self.assertTrue(info.monotonic) self.assertFalse(info.adjustable) def test_thread_time(self): if not hasattr(time, 'thread_time'): if sys.platform.startswith(('linux', 'win')): self.fail("time.thread_time() should be available on %r" % (sys.platform,)) else: self.skipTest("need time.thread_time") # thread_time() should not include time spend during a sleep start = time.thread_time() time.sleep(0.100) stop = time.thread_time() # use 20 ms because thread_time() has usually a resolution of 15 ms # on Windows self.assertLess(stop - start, 0.020) info = time.get_clock_info('thread_time') self.assertTrue(info.monotonic) self.assertFalse(info.adjustable) @unittest.skipUnless(hasattr(time, 'clock_settime'), 'need time.clock_settime') def test_monotonic_settime(self): t1 = time.monotonic() realtime = time.clock_gettime(time.CLOCK_REALTIME) # jump backward with an offset of 1 hour try: time.clock_settime(time.CLOCK_REALTIME, realtime - 3600) except PermissionError as err: self.skipTest(err) t2 = time.monotonic() time.clock_settime(time.CLOCK_REALTIME, realtime) # monotonic must not be affected by system clock updates self.assertGreaterEqual(t2, t1) def test_localtime_failure(self): # Issue #13847: check for localtime() failure invalid_time_t = None for time_t in (-1, 2**30, 2**33, 2**60): try: time.localtime(time_t) except OverflowError: self.skipTest("need 64-bit time_t") except OSError: invalid_time_t = time_t break if invalid_time_t is None: self.skipTest("unable to find an invalid time_t value") self.assertRaises(OSError, time.localtime, invalid_time_t) self.assertRaises(OSError, time.ctime, invalid_time_t) # Issue #26669: check for localtime() failure self.assertRaises(ValueError, time.localtime, float("nan")) self.assertRaises(ValueError, time.ctime, float("nan")) def test_get_clock_info(self): clocks = ['monotonic', 'perf_counter', 'process_time', 'time'] for name in clocks: info = time.get_clock_info(name) #self.assertIsInstance(info, dict) self.assertIsInstance(info.implementation, str) self.assertNotEqual(info.implementation, '') self.assertIsInstance(info.monotonic, bool) self.assertIsInstance(info.resolution, float) # 0.0 < resolution <= 1.0 self.assertGreater(info.resolution, 0.0) self.assertLessEqual(info.resolution, 1.0) self.assertIsInstance(info.adjustable, bool) self.assertRaises(ValueError, time.get_clock_info, 'xxx') class TestLocale(unittest.TestCase): def setUp(self): self.oldloc = locale.setlocale(locale.LC_ALL) def tearDown(self): locale.setlocale(locale.LC_ALL, self.oldloc) def test_bug_3061(self): try: tmp = locale.setlocale(locale.LC_ALL, "fr_FR") except locale.Error: self.skipTest('could not set locale.LC_ALL to fr_FR') # This should not cause an exception time.strftime("%B", (2009,2,1,0,0,0,0,0,0)) class _TestAsctimeYear: _format = '%d' def yearstr(self, y): return time.asctime((y,) + (0,) * 8).split()[-1] def test_large_year(self): # Check that it doesn't crash for year > 9999 self.assertEqual(self.yearstr(12345), '12345') self.assertEqual(self.yearstr(123456789), '123456789') class _TestStrftimeYear: if time.strftime('%Y', (1,) + (0,) * 8) == '0001': _format = '%04d' else: _format = '%d' def yearstr(self, y): return time.strftime('%Y', (y,) + (0,) * 8) def test_4dyear(self): if self._format == '%04d': self.test_year('%04d') else: def year4d(y): return time.strftime('%4Y', (y,) + (0,) * 8) self.test_year('%04d', func=year4d) def skip_if_not_supported(y): msg = "strftime() is limited to [1; 9999] with Visual Studio" try: time.strftime('%Y', (y,) + (0,) * 8) except ValueError: cond = False else: cond = True return unittest.skipUnless(cond, msg) @skip_if_not_supported(10000) def test_large_year(self): return super().test_large_year() @skip_if_not_supported(0) def test_negative(self): return super().test_negative() del skip_if_not_supported class _Test4dYear: _format = '%d' def test_year(self, fmt=None, func=None): fmt = fmt or self._format func = func or self.yearstr self.assertEqual(func(1), fmt % 1) self.assertEqual(func(68), fmt % 68) self.assertEqual(func(69), fmt % 69) self.assertEqual(func(99), fmt % 99) self.assertEqual(func(999), fmt % 999) self.assertEqual(func(9999), fmt % 9999) def test_large_year(self): self.assertEqual(self.yearstr(12345).lstrip('+'), '12345') self.assertEqual(self.yearstr(123456789).lstrip('+'), '123456789') self.assertEqual(self.yearstr(TIME_MAXYEAR).lstrip('+'), str(TIME_MAXYEAR)) self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1) def test_negative(self): self.assertEqual(self.yearstr(-1), self._format % -1) self.assertEqual(self.yearstr(-1234), '-1234') self.assertEqual(self.yearstr(-123456), '-123456') self.assertEqual(self.yearstr(-123456789), str(-123456789)) self.assertEqual(self.yearstr(-1234567890), str(-1234567890)) self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR)) # Modules/timemodule.c checks for underflow self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1) with self.assertRaises(OverflowError): self.yearstr(-TIME_MAXYEAR - 1) class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase): pass class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase): pass class TestPytime(unittest.TestCase): @skip_if_buggy_ucrt_strfptime @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_localtime_timezone(self): # Get the localtime and examine it for the offset and zone. lt = time.localtime() self.assertTrue(hasattr(lt, "tm_gmtoff")) self.assertTrue(hasattr(lt, "tm_zone")) # See if the offset and zone are similar to the module # attributes. if lt.tm_gmtoff is None: self.assertTrue(not hasattr(time, "timezone")) else: self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst]) if lt.tm_zone is None: self.assertTrue(not hasattr(time, "tzname")) else: self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst]) # Try and make UNIX times from the localtime and a 9-tuple # created from the localtime. Test to see that the times are # the same. t = time.mktime(lt); t9 = time.mktime(lt[:9]) self.assertEqual(t, t9) # Make localtimes from the UNIX times and compare them to # the original localtime, thus making a round trip. new_lt = time.localtime(t); new_lt9 = time.localtime(t9) self.assertEqual(new_lt, lt) self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff) self.assertEqual(new_lt.tm_zone, lt.tm_zone) self.assertEqual(new_lt9, lt) self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff) self.assertEqual(new_lt9.tm_zone, lt.tm_zone) @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_strptime_timezone(self): t = time.strptime("UTC", "%Z") self.assertEqual(t.tm_zone, 'UTC') t = time.strptime("+0500", "%z") self.assertEqual(t.tm_gmtoff, 5 * 3600) @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_short_times(self): import pickle # Load a short time structure using pickle. st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n." lt = pickle.loads(st) self.assertIs(lt.tm_gmtoff, None) self.assertIs(lt.tm_zone, None) @unittest.skipIf(_testcapi is None, 'need the _testcapi module') class CPyTimeTestCase: OVERFLOW_SECONDS = None def setUp(self): from _testcapi import SIZEOF_TIME_T bits = SIZEOF_TIME_T * 8 - 1 self.time_t_min = -2 ** bits self.time_t_max = 2 ** bits - 1 def time_t_filter(self, seconds): return (self.time_t_min <= seconds <= self.time_t_max) def _rounding_values(self, use_float): units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS] if use_float: # picoseconds are only tested to pytime_converter accepting floats units.append(1e-3) values = ( # small values 1, 2, 5, 7, 123, 456, 1234, # 10^k - 1 9, 99, 999, 9999, 99999, 999999, # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5 499, 500, 501, 1499, 1500, 1501, 2500, 3500, 4500, ) ns_timestamps = [0] for unit in units: for value in values: ns = value * unit ns_timestamps.extend((-ns, ns)) for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33): ns = (2 ** pow2) * SEC_TO_NS ns_timestamps.extend(( -ns-1, -ns, -ns+1, ns-1, ns, ns+1 )) for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX): ns_timestamps.append(seconds * SEC_TO_NS) if use_float: # numbers with an exact representation in IEEE 754 (base 2) for pow2 in (3, 7, 10, 15): ns = 2.0 ** (-pow2) ns_timestamps.extend((-ns, ns)) # seconds close to _PyTime_t type limit ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS ns_timestamps.extend((-ns, ns)) return ns_timestamps def _check_rounding(self, pytime_converter, expected_func, use_float, unit_to_sec, value_filter=None): def convert_values(ns_timestamps): if use_float: unit_to_ns = SEC_TO_NS / float(unit_to_sec) values = [ns / unit_to_ns for ns in ns_timestamps] else: unit_to_ns = SEC_TO_NS // unit_to_sec values = [ns // unit_to_ns for ns in ns_timestamps] if value_filter: values = filter(value_filter, values) # remove duplicates and sort return sorted(set(values)) # test rounding ns_timestamps = self._rounding_values(use_float) valid_values = convert_values(ns_timestamps) for time_rnd, decimal_rnd in ROUNDING_MODES : with decimal.localcontext() as context: context.rounding = decimal_rnd for value in valid_values: debug_info = {'value': value, 'rounding': decimal_rnd} try: result = pytime_converter(value, time_rnd) expected = expected_func(value) except Exception: self.fail("Error on timestamp conversion: %s" % debug_info) self.assertEqual(result, expected, debug_info) # test overflow ns = self.OVERFLOW_SECONDS * SEC_TO_NS ns_timestamps = (-ns, ns) overflow_values = convert_values(ns_timestamps) for time_rnd, _ in ROUNDING_MODES : for value in overflow_values: debug_info = {'value': value, 'rounding': time_rnd} with self.assertRaises(OverflowError, msg=debug_info): pytime_converter(value, time_rnd) def check_int_rounding(self, pytime_converter, expected_func, unit_to_sec=1, value_filter=None): self._check_rounding(pytime_converter, expected_func, False, unit_to_sec, value_filter) def check_float_rounding(self, pytime_converter, expected_func, unit_to_sec=1, value_filter=None): self._check_rounding(pytime_converter, expected_func, True, unit_to_sec, value_filter) def decimal_round(self, x): d = decimal.Decimal(x) d = d.quantize(1) return int(d) class TestCPyTime(CPyTimeTestCase, unittest.TestCase): # _PyTime_t is a 64-bit signed integer OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS) def test_FromSeconds(self): from _testcapi import PyTime_FromSeconds # PyTime_FromSeconds() expects a C int, reject values out of range def c_int_filter(secs): return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX) self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs), lambda secs: secs * SEC_TO_NS, value_filter=c_int_filter) # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(TypeError): PyTime_FromSeconds(float('nan')) def test_FromSecondsObject(self): from _testcapi import PyTime_FromSecondsObject self.check_int_rounding( PyTime_FromSecondsObject, lambda secs: secs * SEC_TO_NS) self.check_float_rounding( PyTime_FromSecondsObject, lambda ns: self.decimal_round(ns * SEC_TO_NS)) # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(ValueError): PyTime_FromSecondsObject(float('nan'), time_rnd) def test_AsSecondsDouble(self): from _testcapi import PyTime_AsSecondsDouble def float_converter(ns): if abs(ns) % SEC_TO_NS == 0: return float(ns // SEC_TO_NS) else: return float(ns) / SEC_TO_NS self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns), float_converter, NS_TO_SEC) # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(TypeError): PyTime_AsSecondsDouble(float('nan')) def create_decimal_converter(self, denominator): denom = decimal.Decimal(denominator) def converter(value): d = decimal.Decimal(value) / denom return self.decimal_round(d) return converter def test_AsTimeval(self): from _testcapi import PyTime_AsTimeval us_converter = self.create_decimal_converter(US_TO_NS) def timeval_converter(ns): us = us_converter(ns) return divmod(us, SEC_TO_US) if sys.platform == 'win32': from _testcapi import LONG_MIN, LONG_MAX # On Windows, timeval.tv_sec type is a C long def seconds_filter(secs): return LONG_MIN <= secs <= LONG_MAX else: seconds_filter = self.time_t_filter self.check_int_rounding(PyTime_AsTimeval, timeval_converter, NS_TO_SEC, value_filter=seconds_filter) @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'), 'need _testcapi.PyTime_AsTimespec') def test_AsTimespec(self): from _testcapi import PyTime_AsTimespec def timespec_converter(ns): return divmod(ns, SEC_TO_NS) self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns), timespec_converter, NS_TO_SEC, value_filter=self.time_t_filter) @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimeval_clamp'), 'need _testcapi.PyTime_AsTimeval_clamp') def test_AsTimeval_clamp(self): from _testcapi import PyTime_AsTimeval_clamp if sys.platform == 'win32': from _testcapi import LONG_MIN, LONG_MAX tv_sec_max = LONG_MAX tv_sec_min = LONG_MIN else: tv_sec_max = self.time_t_max tv_sec_min = self.time_t_min for t in (_PyTime_MIN, _PyTime_MAX): ts = PyTime_AsTimeval_clamp(t, _PyTime.ROUND_CEILING) with decimal.localcontext() as context: context.rounding = decimal.ROUND_CEILING us = self.decimal_round(decimal.Decimal(t) / US_TO_NS) tv_sec, tv_usec = divmod(us, SEC_TO_US) if tv_sec_max < tv_sec: tv_sec = tv_sec_max tv_usec = 0 elif tv_sec < tv_sec_min: tv_sec = tv_sec_min tv_usec = 0 self.assertEqual(ts, (tv_sec, tv_usec)) @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec_clamp'), 'need _testcapi.PyTime_AsTimespec_clamp') def test_AsTimespec_clamp(self): from _testcapi import PyTime_AsTimespec_clamp for t in (_PyTime_MIN, _PyTime_MAX): ts = PyTime_AsTimespec_clamp(t) tv_sec, tv_nsec = divmod(t, NS_TO_SEC) if self.time_t_max < tv_sec: tv_sec = self.time_t_max tv_nsec = 0 elif tv_sec < self.time_t_min: tv_sec = self.time_t_min tv_nsec = 0 self.assertEqual(ts, (tv_sec, tv_nsec)) def test_AsMilliseconds(self): from _testcapi import PyTime_AsMilliseconds self.check_int_rounding(PyTime_AsMilliseconds, self.create_decimal_converter(MS_TO_NS), NS_TO_SEC) def test_AsMicroseconds(self): from _testcapi import PyTime_AsMicroseconds self.check_int_rounding(PyTime_AsMicroseconds, self.create_decimal_converter(US_TO_NS), NS_TO_SEC) class TestOldPyTime(CPyTimeTestCase, unittest.TestCase): # time_t is a 32-bit or 64-bit signed integer OVERFLOW_SECONDS = 2 ** 64 def test_object_to_time_t(self): from _testcapi import pytime_object_to_time_t self.check_int_rounding(pytime_object_to_time_t, lambda secs: secs, value_filter=self.time_t_filter) self.check_float_rounding(pytime_object_to_time_t, self.decimal_round, value_filter=self.time_t_filter) def create_converter(self, sec_to_unit): def converter(secs): floatpart, intpart = math.modf(secs) intpart = int(intpart) floatpart *= sec_to_unit floatpart = self.decimal_round(floatpart) if floatpart < 0: floatpart += sec_to_unit intpart -= 1 elif floatpart >= sec_to_unit: floatpart -= sec_to_unit intpart += 1 return (intpart, floatpart) return converter def test_object_to_timeval(self): from _testcapi import pytime_object_to_timeval self.check_int_rounding(pytime_object_to_timeval, lambda secs: (secs, 0), value_filter=self.time_t_filter) self.check_float_rounding(pytime_object_to_timeval, self.create_converter(SEC_TO_US), value_filter=self.time_t_filter) # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(ValueError): pytime_object_to_timeval(float('nan'), time_rnd) def test_object_to_timespec(self): from _testcapi import pytime_object_to_timespec self.check_int_rounding(pytime_object_to_timespec, lambda secs: (secs, 0), value_filter=self.time_t_filter) self.check_float_rounding(pytime_object_to_timespec, self.create_converter(SEC_TO_NS), value_filter=self.time_t_filter) # test nan for time_rnd, _ in ROUNDING_MODES: with self.assertRaises(ValueError): pytime_object_to_timespec(float('nan'), time_rnd) @unittest.skipUnless(sys.platform == "darwin", "test weak linking on macOS") class TestTimeWeaklinking(unittest.TestCase): # These test cases verify that weak linking support on macOS works # as expected. These cases only test new behaviour introduced by weak linking, # regular behaviour is tested by the normal test cases. # # See the section on Weak Linking in Mac/README.txt for more information. def test_clock_functions(self): import sysconfig import platform config_vars = sysconfig.get_config_vars() var_name = "HAVE_CLOCK_GETTIME" if var_name not in config_vars or not config_vars[var_name]: raise unittest.SkipTest(f"{var_name} is not available") mac_ver = tuple(int(x) for x in platform.mac_ver()[0].split(".")) clock_names = [ "CLOCK_MONOTONIC", "clock_gettime", "clock_gettime_ns", "clock_settime", "clock_settime_ns", "clock_getres"] if mac_ver >= (10, 12): for name in clock_names: self.assertTrue(hasattr(time, name), f"time.{name} is not available") else: for name in clock_names: self.assertFalse(hasattr(time, name), f"time.{name} is available") if __name__ == "__main__": unittest.main()
true
true
1c444ef4cd29e04ad3311978e8ac577fb7bda338
629
py
Python
extras/makeDepPopulation.py
augustodn/COVID-19_Ar
4911b52cd979ab346eaf9e716883500d392bfb01
[ "MIT" ]
null
null
null
extras/makeDepPopulation.py
augustodn/COVID-19_Ar
4911b52cd979ab346eaf9e716883500d392bfb01
[ "MIT" ]
null
null
null
extras/makeDepPopulation.py
augustodn/COVID-19_Ar
4911b52cd979ab346eaf9e716883500d392bfb01
[ "MIT" ]
1
2020-09-29T11:58:12.000Z
2020-09-29T11:58:12.000Z
from openpyxl import load_workbook filename = 'poblacion_dpto.csv' csvFN = open(filename, 'w') wb = load_workbook('poblacion_dpto.xlsx') ws = wb['Sheet1'] csvFN.write('in1,nombre,pob_total\n') for row in ws.values: try: if 'AREA' in row[0]: indecCode = row[0][7:] name = row[1] newAreaFound = True if ' Total' == row[0] and newAreaFound: totPopulation = int(row[3]) print(indecCode, name, totPopulation) csvFN.write(f'{indecCode:5},{name},{totPopulation}\n') newAreaFound = False except: pass csvFN.close()
23.296296
66
0.585056
from openpyxl import load_workbook filename = 'poblacion_dpto.csv' csvFN = open(filename, 'w') wb = load_workbook('poblacion_dpto.xlsx') ws = wb['Sheet1'] csvFN.write('in1,nombre,pob_total\n') for row in ws.values: try: if 'AREA' in row[0]: indecCode = row[0][7:] name = row[1] newAreaFound = True if ' Total' == row[0] and newAreaFound: totPopulation = int(row[3]) print(indecCode, name, totPopulation) csvFN.write(f'{indecCode:5},{name},{totPopulation}\n') newAreaFound = False except: pass csvFN.close()
true
true
1c444fd9aef9620eaa7ffa85c445148e8fcc02e6
15,493
py
Python
scripts/.ipynb_checkpoints/gdal_functions-checkpoint.py
Thomas-Brd/3D_landslide_detection
95ec6fc4dd013ecc7c3c8cb22dbbbc8712467830
[ "CC-BY-3.0" ]
1
2022-02-15T09:56:34.000Z
2022-02-15T09:56:34.000Z
scripts/.ipynb_checkpoints/gdal_functions-checkpoint.py
Thomas-Brd/3D_landslide_detection
95ec6fc4dd013ecc7c3c8cb22dbbbc8712467830
[ "CC-BY-3.0" ]
null
null
null
scripts/.ipynb_checkpoints/gdal_functions-checkpoint.py
Thomas-Brd/3D_landslide_detection
95ec6fc4dd013ecc7c3c8cb22dbbbc8712467830
[ "CC-BY-3.0" ]
3
2020-09-17T13:22:07.000Z
2021-11-06T14:14:54.000Z
# coding: utf-8 # Thomas Bernard # fonctions utilisant gdal from osgeo import gdal import ogr, osr import numpy as np #import rasterio #from rasterio.plot import show import subprocess import os import matplotlib.pyplot as plt #import scripts.eros_function as eros def read_tif_file(path_to_file): ds = gdal.Open(path_to_file) gt = ds.GetGeoTransform() proj = ds.GetProjection() band= ds.GetRasterBand(1) mask = band.GetNoDataValue() array = band.ReadAsArray() return array, gt, proj, mask def ReadRasterfile(dataset): """ This function open a raster file, transform it into a numpy array and get information from it """ for x in range(1, dataset.RasterCount + 1): band = dataset.GetRasterBand(x) # Projection projection = dataset.GetProjection() # Raster extent upx, xres, xskew, upy, yskew, yres = dataset.GetGeoTransform() coordinates = [upx, xres, xskew, upy, yskew, yres] # Dimensions sizeX = dataset.RasterXSize sizeY = dataset.RasterYSize # Data as a numpy array array = band.ReadAsArray() # Get nodata value from the GDAL band object nodata = band.GetNoDataValue() #Create a masked array for making calculations without nodata values array = np.ma.masked_equal(array, nodata) type(array) return array, sizeX, sizeY, projection, band, coordinates del array, sizeX, sizeY, projection, band, coordinates # converts coordinates to index def bbox2ix(bbox,gt): xo = int(round((bbox[0] - gt[0])/gt[1])) yo = int(round((gt[3] - bbox[3])/gt[1])) xd = int(round((bbox[1] - bbox[0])/gt[1])) yd = int(round((bbox[3] - bbox[2])/gt[1])) return(xo,yo,xd,yd) def rasclip(ras,shp): ds = gdal.Open(ras) gt = ds.GetGeoTransform() driver = ogr.GetDriverByName("ESRI Shapefile") dataSource = driver.Open(shp, 0) layer = dataSource.GetLayer() for feature in layer: xo,yo,xd,yd = bbox2ix(feature.GetGeometryRef().GetEnvelope(),gt) arr = ds.ReadAsArray(xo,yo,xd,yd) yield arr layer.ResetReading() ds = None dataSource = None return arr def WriteGeoTIF(Tiffname, nb_xpixels, nb_ypixels, size_pixels, y_position, x_position, epsg, array): from osgeo import gdal, osr drv = gdal.GetDriverByName('GTiff') ds = drv.Create(Tiffname, nb_xpixels, nb_ypixels, 1, gdal.GDT_Float32) gt = [x_position, size_pixels, 0, y_position, 0,-size_pixels ] ds.SetGeoTransform(gt) srs = osr.SpatialReference() srs.ImportFromEPSG(epsg) ds.SetProjection(srs.ExportToWkt()) ds.GetRasterBand(1).WriteArray(array) ds.GetRasterBand(1).SetNoDataValue(-9999.0) return def RastertoTXTfile(path,file, output_filename): ds = gdal.Open(path+file) translate_options = gdal.TranslateOptions(format='XYZ') ds = gdal.Translate(destName = path+output_filename, srcDS = ds, options = translate_options) return def create_masks(path, filename, path_masks): """ This function create a mask from a tif file What you need: A path location of the Watersheds A file name of the watersheds tif file A path to write the resulted masks """ # Remove the previous folder if any if os.path.isdir(path_masks) == True: contenu=os.listdir(path_masks) for x in contenu: os.remove(path_masks+x)#on supprime tous les fichier dans le dossier os.rmdir(path_masks)#puis on supprime le dossier # Create topo folder dataset = gdal.Open(path +filename + '.tif', gdal.GA_ReadOnly) array,sizeX, sizeY, projection, band, coordinates = ReadRasterfile(dataset) array[array<0]=-9999 # Get origin coordinates xyzlohi = [coordinates[0],coordinates[3],coordinates[3]-sizeY,coordinates[0]+sizeX] # get id of watersheds watershed_id = np.unique(array) watershed_id = watershed_id[1:] # Create masks masks={} os.mkdir(path_masks) watersheds_filename = {} count=1 for i in watershed_id: array_copy = np.copy(array) array_copy[array!=i] = -9999 eros.write(array_copy,sizeX,sizeY,coordinates[1],xyzlohi,path_masks+'SBV'+str(i)+'_mask.alt') watersheds_filename['FN{0}'.format(count)] = 'SBV'+str(i) count=count+1 del dataset return watersheds_filename def get_outlets_coordinates(path, filename, outlet_coordinates): """ This functions get the outlets coordinates for each watershed in the tif file "*_watershed.tif" What you need: A path location of the Watersheds A file name of the watersheds tif file A panda dataframe of the coordinates of all points of the river network ('*_coord.txt') """ # Origine of the grid in the appropriate coordinate system dataset = gdal.Open(path +filename + '.tif', gdal.GA_ReadOnly) array, sizeX, sizeY, projection, band, coordinates = ReadRasterfile(dataset) outlet_coordinates['Y_origin'] = coordinates[3] outlet_coordinates['X_origin'] = coordinates[0] # Get outlet coordinates in Eros format outlet_coordinates['Xgrid_position'] = outlet_coordinates['X_coordinates'] - outlet_coordinates['X_origin'] outlet_coordinates['Ygrid_position'] = outlet_coordinates['Y_origin'] - outlet_coordinates['Y_coordinates'] outlet_coordinates['Ygrid_position']=outlet_coordinates['Ygrid_position'].astype(int) outlet_coordinates['Xgrid_position']=outlet_coordinates['Xgrid_position'].astype(int) # The coordinates are sorted by descending order of the drainage area outlet_coordinates.sort_values(by=['Contributing area'],ascending=False) outlet_coordinates.reset_index(drop=True,inplace=True) del dataset return outlet_coordinates def filename_by_Strahler_order(path, filename): """ This functions return filename in function of Strahler order What you need: A path location of the Strahler order grid and watersheds A file name of the watersheds tif file and Strahler order (same one) """ # Import Strahler grid dataset = gdal.Open(path +filename + '_ord.tif', gdal.GA_ReadOnly) array_Strahler, sizeX, sizeY, projection, band, coordinates = ReadRasterfile(dataset) # Import Watersheds grid watersheds = gdal.Open(path +filename + '_watersheds.tif', gdal.GA_ReadOnly) array_watersheds, sizeX, sizeY, projection, band, coordinates = ReadRasterfile(watersheds) # Where Strahler grid is 1 get id watersheds into list 1 first_order_array = array_watersheds[array_Strahler==1] # get id of watersheds first_order_watershed_id = np.unique(first_order_array) # ohterwise get id watersheds into list 2 bigger_order_array = array_watersheds[np.logical_and(array_Strahler!=1,array_Strahler>0)] bigger_order_watershed_id = np.unique(bigger_order_array) # save filename into dictionnary first_order_Watersheds = {} high_order_Watersheds = {} # Save first order watersheds count = 1 for i in first_order_watershed_id: first_order_Watersheds['FN{0}'.format(count)] = 'SBV' + str(i) count = count + 1 # Save higher order watersheds count = 1 for ii in bigger_order_watershed_id[1:]: high_order_Watersheds['FN{0}'.format(count)] = 'SBV' + str(ii) count = count+1 # Save last watersheds last_watershed = 'SBV2' return first_order_Watersheds, high_order_Watersheds, last_watershed def define_inputs_and_outlets(path,filename,Input_outlet_distance,outlet_coordinates,plot_option): """ This function define the inputs coordinates and the outlet coordinates located upstream and downstream What you need: Input_outlet_distance: Distance in meter where to locate the inputs from the detected outlets """ # Open watershed tif file for ploting option dataset = gdal.Open(path+filename + '_watersheds.tif', gdal.GA_ReadOnly) array, sizeX, sizeY, projection, band, coordinates = ReadRasterfile(dataset) river_network = gdal.Open(path+filename+ '_ord.tif', gdal.GA_ReadOnly) river_array, sizeX, sizeY, projection, band, coordinates = ReadRasterfile(river_network) Y_origin = coordinates[3] X_origin = coordinates[0] # Open _coord txt file import pandas as pd header = ['X_coordinates','Y_coordinates','Distance to the downstream end of a terminal link','Elevation','Contributing area'] tab_coord=pd.read_csv(path + filename+ '_coord.txt',sep='\t',names = header,index_col=False,usecols=[1, 2, 3,4, 5],na_values='-9999') # Add a line at the end of the txt file for the last outlet tab_coord =tab_coord.append({'X_coordinates' : 9999 , 'Y_coordinates' : 9999,'Distance to the downstream end of a terminal link':tab_coord.loc[len(tab_coord)-1,'Distance to the downstream end of a terminal link']+100},ignore_index=True) # chercher pour chaque Xgrid_position et Ygrid_positon si valeur après est inf alors prendre coordonnées K lignes après outlet_watershed_dico = {} input_watershed_dico = {} input_area_dico = {} count = 1 for i in outlet_coordinates['Distance to the downstream end of a terminal link']: index_list = tab_coord.index[np.around(tab_coord['Distance to the downstream end of a terminal link'],3)== np.around(i,3)].tolist() # Lists input_coord_list =[] input_area_list=[] for ii in index_list: # manage the last line of the text file if len(tab_coord) - ii > Input_outlet_distance: # Take coord k lines after if the +1 line is smaller if np.logical_and(tab_coord.loc[ii+1,'Distance to the downstream end of a terminal link'] < tab_coord.loc[ii,'Distance to the downstream end of a terminal link'],np.abs(tab_coord['Distance to the downstream end of a terminal link'][ii+1]-tab_coord['Distance to the downstream end of a terminal link'][ii])<10) : outlet_watershed_dico['Outlet{0}'.format(count)] = [tab_coord.loc[ii+Input_outlet_distance,'X_coordinates'],tab_coord.loc[ii+Input_outlet_distance,'Y_coordinates']] # get the input coordinates if np.logical_or(tab_coord.loc[ii+1,'Distance to the downstream end of a terminal link'] > tab_coord.loc[ii,'Distance to the downstream end of a terminal link'],np.abs(tab_coord['Distance to the downstream end of a terminal link'][ii+1]-tab_coord['Distance to the downstream end of a terminal link'][ii])>10): input_coord_list.append([tab_coord.loc[ii-Input_outlet_distance,'X_coordinates'],tab_coord.loc[ii-Input_outlet_distance,'Y_coordinates']]) input_area_list.append(tab_coord.loc[ii-Input_outlet_distance,'Contributing area']) input_watershed_dico['Input{0}'.format(count)] = input_coord_list input_area_dico['Area{0}'.format(count)] = input_area_list count= count + 1 # transform coordinates in grid format in each dictionnary for j in outlet_watershed_dico: outlet_watershed_dico[str(j)] = [outlet_watershed_dico[str(j)][0]-X_origin, Y_origin - outlet_watershed_dico[str(j)][1]] outlet_watershed_dico[str(j)][0] = outlet_watershed_dico[str(j)][0].astype(int) outlet_watershed_dico[str(j)][1] = outlet_watershed_dico[str(j)][1].astype(int) for g in range(1,len(input_watershed_dico)+1): for gg in range(0,len(input_watershed_dico['Input{0}'.format(g)])): input_watershed_dico['Input{0}'.format(g)][gg] = [input_watershed_dico['Input{0}'.format(g)][gg][0]-X_origin, Y_origin - input_watershed_dico['Input{0}'.format(g)][gg][1]] input_watershed_dico['Input{0}'.format(g)][gg][0] = input_watershed_dico['Input{0}'.format(g)][gg][0].astype(int) input_watershed_dico['Input{0}'.format(g)][gg][1] = input_watershed_dico['Input{0}'.format(g)][gg][1].astype(int) # plot coordinates if plot_option == 1: fig, ax = plt.subplots(1, figsize=(20, 20)) plt.imshow(array) masked_river = np.ma.masked_where(river_array < 1, river_array) plt.imshow(masked_river,cmap=plt.cm.gray) # plot all input and outlet points for y in outlet_watershed_dico: plt.plot(outlet_watershed_dico[str(y)][0],outlet_watershed_dico[str(y)][1],'k.',markersize=10) for p in range(1,len(input_watershed_dico)+1): for pp in range(0,len(input_watershed_dico['Input{0}'.format(p)])): plt.plot(input_watershed_dico['Input{0}'.format(p)][pp][0],input_watershed_dico['Input{0}'.format(p)][pp][1],'r.',markersize=10) del dataset return outlet_watershed_dico, input_watershed_dico, input_area_dico def sort_watersheds(path_masks,Watersheds_filename, outlet_watershed_dico,last_watershed): """ This function classify the watersheds by contributing area order """ list_watersheds = [] list_position = [] for i in range(1,len(Watersheds_filename)+1): grd_mask, sizeX, sizeY, cs, xyzlohi = eros.open_file(path_masks+Watersheds_filename['FN{0}'.format(i)]+'_mask.alt') if np.size(grd_mask) - np.size(grd_mask[grd_mask==-9999]) < 50: pass else: for ii in range(1,len(outlet_watershed_dico)+1): if grd_mask[outlet_watershed_dico['Outlet{0}'.format(ii)][1],outlet_watershed_dico['Outlet{0}'.format(ii)][0]] == np.max(grd_mask): list_watersheds.append(Watersheds_filename['FN{0}'.format(i)]) list_position.append(ii) watershed_classified = [x for _,x in sorted(zip(list_position,list_watersheds ))] watershed_classified_dico={} watershed_classified_dico['FN1'] = last_watershed for j in range(0,len(watershed_classified)): watershed_classified_dico['FN{0}'.format(j+2)] = watershed_classified[j] return watershed_classified_dico def merge_results(path_topo,path_simulations,path_masks,path_tif_foleder,Watershed_name,all_watersheds_filename,extension_dico, results_folders,epsg,y_position,x_position): """ This function allows to merge all the eros file results into one """ array = {} masks ={} # Open array topo array['Ar0'], sizeX, sizeY, cs, xyzlohi = eros.open_file(path+Watershed_name+'.alt') for i in range(1, len(results_extension)+1): count=1 for ii in results_folders: # Open simulation result array['Ar{0}'.format(count)], sizeX, sizeY, cs, xyzlohi = eros.open_file(path_simulations+ii+'/'+Watershed_name+'.10.'+results_extension['Ext{0}'.format(i)]) # Open simulation result Open corresponding mask masks['masks{0}'.format(count)], sizeX, sizeY, cs, xyzlohi = eros.open_file(path_masks +all_watersheds_filename['FN{0}'.format(count)]+'_mask.alt') # array['Ar0'][masks['masks{0}'.format(count)]>=0] = array['Ar{0}'.format(count)][masks['masks{0}'.format(count)]>=0] count = count + 1 eros.write(array['Ar0'],sizeX, sizeY, cs, xyzlohi,path_floodos_folder+Watershed_name+'.10.'+results_extension['Ext{0}'.format(i)]) gdalf.WriteGeoTIF(path_tif_folder+Watershed_name+'_'+results_extension['Ext{0}'.format(i)]+'.tif', sizeX, sizeY, cs, y_position, x_position, epsg, array['Ar1'])
46.525526
328
0.684825
from osgeo import gdal import ogr, osr import numpy as np import subprocess import os import matplotlib.pyplot as plt def read_tif_file(path_to_file): ds = gdal.Open(path_to_file) gt = ds.GetGeoTransform() proj = ds.GetProjection() band= ds.GetRasterBand(1) mask = band.GetNoDataValue() array = band.ReadAsArray() return array, gt, proj, mask def ReadRasterfile(dataset): for x in range(1, dataset.RasterCount + 1): band = dataset.GetRasterBand(x) projection = dataset.GetProjection() upx, xres, xskew, upy, yskew, yres = dataset.GetGeoTransform() coordinates = [upx, xres, xskew, upy, yskew, yres] sizeX = dataset.RasterXSize sizeY = dataset.RasterYSize array = band.ReadAsArray() nodata = band.GetNoDataValue() array = np.ma.masked_equal(array, nodata) type(array) return array, sizeX, sizeY, projection, band, coordinates del array, sizeX, sizeY, projection, band, coordinates def bbox2ix(bbox,gt): xo = int(round((bbox[0] - gt[0])/gt[1])) yo = int(round((gt[3] - bbox[3])/gt[1])) xd = int(round((bbox[1] - bbox[0])/gt[1])) yd = int(round((bbox[3] - bbox[2])/gt[1])) return(xo,yo,xd,yd) def rasclip(ras,shp): ds = gdal.Open(ras) gt = ds.GetGeoTransform() driver = ogr.GetDriverByName("ESRI Shapefile") dataSource = driver.Open(shp, 0) layer = dataSource.GetLayer() for feature in layer: xo,yo,xd,yd = bbox2ix(feature.GetGeometryRef().GetEnvelope(),gt) arr = ds.ReadAsArray(xo,yo,xd,yd) yield arr layer.ResetReading() ds = None dataSource = None return arr def WriteGeoTIF(Tiffname, nb_xpixels, nb_ypixels, size_pixels, y_position, x_position, epsg, array): from osgeo import gdal, osr drv = gdal.GetDriverByName('GTiff') ds = drv.Create(Tiffname, nb_xpixels, nb_ypixels, 1, gdal.GDT_Float32) gt = [x_position, size_pixels, 0, y_position, 0,-size_pixels ] ds.SetGeoTransform(gt) srs = osr.SpatialReference() srs.ImportFromEPSG(epsg) ds.SetProjection(srs.ExportToWkt()) ds.GetRasterBand(1).WriteArray(array) ds.GetRasterBand(1).SetNoDataValue(-9999.0) return def RastertoTXTfile(path,file, output_filename): ds = gdal.Open(path+file) translate_options = gdal.TranslateOptions(format='XYZ') ds = gdal.Translate(destName = path+output_filename, srcDS = ds, options = translate_options) return def create_masks(path, filename, path_masks): if os.path.isdir(path_masks) == True: contenu=os.listdir(path_masks) for x in contenu: os.remove(path_masks+x) os.rmdir(path_masks) dataset = gdal.Open(path +filename + '.tif', gdal.GA_ReadOnly) array,sizeX, sizeY, projection, band, coordinates = ReadRasterfile(dataset) array[array<0]=-9999 xyzlohi = [coordinates[0],coordinates[3],coordinates[3]-sizeY,coordinates[0]+sizeX] watershed_id = np.unique(array) watershed_id = watershed_id[1:] masks={} os.mkdir(path_masks) watersheds_filename = {} count=1 for i in watershed_id: array_copy = np.copy(array) array_copy[array!=i] = -9999 eros.write(array_copy,sizeX,sizeY,coordinates[1],xyzlohi,path_masks+'SBV'+str(i)+'_mask.alt') watersheds_filename['FN{0}'.format(count)] = 'SBV'+str(i) count=count+1 del dataset return watersheds_filename def get_outlets_coordinates(path, filename, outlet_coordinates): dataset = gdal.Open(path +filename + '.tif', gdal.GA_ReadOnly) array, sizeX, sizeY, projection, band, coordinates = ReadRasterfile(dataset) outlet_coordinates['Y_origin'] = coordinates[3] outlet_coordinates['X_origin'] = coordinates[0] outlet_coordinates['Xgrid_position'] = outlet_coordinates['X_coordinates'] - outlet_coordinates['X_origin'] outlet_coordinates['Ygrid_position'] = outlet_coordinates['Y_origin'] - outlet_coordinates['Y_coordinates'] outlet_coordinates['Ygrid_position']=outlet_coordinates['Ygrid_position'].astype(int) outlet_coordinates['Xgrid_position']=outlet_coordinates['Xgrid_position'].astype(int) outlet_coordinates.sort_values(by=['Contributing area'],ascending=False) outlet_coordinates.reset_index(drop=True,inplace=True) del dataset return outlet_coordinates def filename_by_Strahler_order(path, filename): dataset = gdal.Open(path +filename + '_ord.tif', gdal.GA_ReadOnly) array_Strahler, sizeX, sizeY, projection, band, coordinates = ReadRasterfile(dataset) watersheds = gdal.Open(path +filename + '_watersheds.tif', gdal.GA_ReadOnly) array_watersheds, sizeX, sizeY, projection, band, coordinates = ReadRasterfile(watersheds) first_order_array = array_watersheds[array_Strahler==1] first_order_watershed_id = np.unique(first_order_array) bigger_order_array = array_watersheds[np.logical_and(array_Strahler!=1,array_Strahler>0)] bigger_order_watershed_id = np.unique(bigger_order_array) first_order_Watersheds = {} high_order_Watersheds = {} count = 1 for i in first_order_watershed_id: first_order_Watersheds['FN{0}'.format(count)] = 'SBV' + str(i) count = count + 1 count = 1 for ii in bigger_order_watershed_id[1:]: high_order_Watersheds['FN{0}'.format(count)] = 'SBV' + str(ii) count = count+1 last_watershed = 'SBV2' return first_order_Watersheds, high_order_Watersheds, last_watershed def define_inputs_and_outlets(path,filename,Input_outlet_distance,outlet_coordinates,plot_option): dataset = gdal.Open(path+filename + '_watersheds.tif', gdal.GA_ReadOnly) array, sizeX, sizeY, projection, band, coordinates = ReadRasterfile(dataset) river_network = gdal.Open(path+filename+ '_ord.tif', gdal.GA_ReadOnly) river_array, sizeX, sizeY, projection, band, coordinates = ReadRasterfile(river_network) Y_origin = coordinates[3] X_origin = coordinates[0] import pandas as pd header = ['X_coordinates','Y_coordinates','Distance to the downstream end of a terminal link','Elevation','Contributing area'] tab_coord=pd.read_csv(path + filename+ '_coord.txt',sep='\t',names = header,index_col=False,usecols=[1, 2, 3,4, 5],na_values='-9999') tab_coord =tab_coord.append({'X_coordinates' : 9999 , 'Y_coordinates' : 9999,'Distance to the downstream end of a terminal link':tab_coord.loc[len(tab_coord)-1,'Distance to the downstream end of a terminal link']+100},ignore_index=True) outlet_watershed_dico = {} input_watershed_dico = {} input_area_dico = {} count = 1 for i in outlet_coordinates['Distance to the downstream end of a terminal link']: index_list = tab_coord.index[np.around(tab_coord['Distance to the downstream end of a terminal link'],3)== np.around(i,3)].tolist() input_coord_list =[] input_area_list=[] for ii in index_list: if len(tab_coord) - ii > Input_outlet_distance: if np.logical_and(tab_coord.loc[ii+1,'Distance to the downstream end of a terminal link'] < tab_coord.loc[ii,'Distance to the downstream end of a terminal link'],np.abs(tab_coord['Distance to the downstream end of a terminal link'][ii+1]-tab_coord['Distance to the downstream end of a terminal link'][ii])<10) : outlet_watershed_dico['Outlet{0}'.format(count)] = [tab_coord.loc[ii+Input_outlet_distance,'X_coordinates'],tab_coord.loc[ii+Input_outlet_distance,'Y_coordinates']] if np.logical_or(tab_coord.loc[ii+1,'Distance to the downstream end of a terminal link'] > tab_coord.loc[ii,'Distance to the downstream end of a terminal link'],np.abs(tab_coord['Distance to the downstream end of a terminal link'][ii+1]-tab_coord['Distance to the downstream end of a terminal link'][ii])>10): input_coord_list.append([tab_coord.loc[ii-Input_outlet_distance,'X_coordinates'],tab_coord.loc[ii-Input_outlet_distance,'Y_coordinates']]) input_area_list.append(tab_coord.loc[ii-Input_outlet_distance,'Contributing area']) input_watershed_dico['Input{0}'.format(count)] = input_coord_list input_area_dico['Area{0}'.format(count)] = input_area_list count= count + 1 for j in outlet_watershed_dico: outlet_watershed_dico[str(j)] = [outlet_watershed_dico[str(j)][0]-X_origin, Y_origin - outlet_watershed_dico[str(j)][1]] outlet_watershed_dico[str(j)][0] = outlet_watershed_dico[str(j)][0].astype(int) outlet_watershed_dico[str(j)][1] = outlet_watershed_dico[str(j)][1].astype(int) for g in range(1,len(input_watershed_dico)+1): for gg in range(0,len(input_watershed_dico['Input{0}'.format(g)])): input_watershed_dico['Input{0}'.format(g)][gg] = [input_watershed_dico['Input{0}'.format(g)][gg][0]-X_origin, Y_origin - input_watershed_dico['Input{0}'.format(g)][gg][1]] input_watershed_dico['Input{0}'.format(g)][gg][0] = input_watershed_dico['Input{0}'.format(g)][gg][0].astype(int) input_watershed_dico['Input{0}'.format(g)][gg][1] = input_watershed_dico['Input{0}'.format(g)][gg][1].astype(int) if plot_option == 1: fig, ax = plt.subplots(1, figsize=(20, 20)) plt.imshow(array) masked_river = np.ma.masked_where(river_array < 1, river_array) plt.imshow(masked_river,cmap=plt.cm.gray) for y in outlet_watershed_dico: plt.plot(outlet_watershed_dico[str(y)][0],outlet_watershed_dico[str(y)][1],'k.',markersize=10) for p in range(1,len(input_watershed_dico)+1): for pp in range(0,len(input_watershed_dico['Input{0}'.format(p)])): plt.plot(input_watershed_dico['Input{0}'.format(p)][pp][0],input_watershed_dico['Input{0}'.format(p)][pp][1],'r.',markersize=10) del dataset return outlet_watershed_dico, input_watershed_dico, input_area_dico def sort_watersheds(path_masks,Watersheds_filename, outlet_watershed_dico,last_watershed): list_watersheds = [] list_position = [] for i in range(1,len(Watersheds_filename)+1): grd_mask, sizeX, sizeY, cs, xyzlohi = eros.open_file(path_masks+Watersheds_filename['FN{0}'.format(i)]+'_mask.alt') if np.size(grd_mask) - np.size(grd_mask[grd_mask==-9999]) < 50: pass else: for ii in range(1,len(outlet_watershed_dico)+1): if grd_mask[outlet_watershed_dico['Outlet{0}'.format(ii)][1],outlet_watershed_dico['Outlet{0}'.format(ii)][0]] == np.max(grd_mask): list_watersheds.append(Watersheds_filename['FN{0}'.format(i)]) list_position.append(ii) watershed_classified = [x for _,x in sorted(zip(list_position,list_watersheds ))] watershed_classified_dico={} watershed_classified_dico['FN1'] = last_watershed for j in range(0,len(watershed_classified)): watershed_classified_dico['FN{0}'.format(j+2)] = watershed_classified[j] return watershed_classified_dico def merge_results(path_topo,path_simulations,path_masks,path_tif_foleder,Watershed_name,all_watersheds_filename,extension_dico, results_folders,epsg,y_position,x_position): array = {} masks ={} array['Ar0'], sizeX, sizeY, cs, xyzlohi = eros.open_file(path+Watershed_name+'.alt') for i in range(1, len(results_extension)+1): count=1 for ii in results_folders: array['Ar{0}'.format(count)], sizeX, sizeY, cs, xyzlohi = eros.open_file(path_simulations+ii+'/'+Watershed_name+'.10.'+results_extension['Ext{0}'.format(i)]) masks['masks{0}'.format(count)], sizeX, sizeY, cs, xyzlohi = eros.open_file(path_masks +all_watersheds_filename['FN{0}'.format(count)]+'_mask.alt') array['Ar0'][masks['masks{0}'.format(count)]>=0] = array['Ar{0}'.format(count)][masks['masks{0}'.format(count)]>=0] count = count + 1 eros.write(array['Ar0'],sizeX, sizeY, cs, xyzlohi,path_floodos_folder+Watershed_name+'.10.'+results_extension['Ext{0}'.format(i)]) gdalf.WriteGeoTIF(path_tif_folder+Watershed_name+'_'+results_extension['Ext{0}'.format(i)]+'.tif', sizeX, sizeY, cs, y_position, x_position, epsg, array['Ar1'])
true
true
1c444fedb8ca59daf57a90006b988852221217fd
14,700
py
Python
third_party_package/RDKit_2015_03_1/rdkit/ML/Descriptors/CompoundDescriptors.py
Ivy286/cluster_basedfps
7fc216537f570436f008ea567c137d03ba2b6d81
[ "WTFPL" ]
9
2019-04-23T01:46:12.000Z
2021-08-16T07:07:12.000Z
third_party_package/RDKit_2015_03_1/rdkit/ML/Descriptors/CompoundDescriptors.py
Ivy286/cluster_basedfps
7fc216537f570436f008ea567c137d03ba2b6d81
[ "WTFPL" ]
null
null
null
third_party_package/RDKit_2015_03_1/rdkit/ML/Descriptors/CompoundDescriptors.py
Ivy286/cluster_basedfps
7fc216537f570436f008ea567c137d03ba2b6d81
[ "WTFPL" ]
5
2016-09-21T03:47:48.000Z
2019-07-30T22:17:35.000Z
# # Copyright (C) 2001,2002 greg Landrum and Rational Discovery LLC # """ descriptor calculator for compounds defined by a composition alone (only the composition is required) """ from __future__ import print_function from rdkit import RDConfig from rdkit.utils import chemutils import os from rdkit.Dbase.DbConnection import DbConnect from rdkit.ML.Descriptors import Parser,Descriptors from rdkit.six.moves import xrange # the list of possible ways to count valence electrons that we know countOptions = [('NVAL','total number of valence electrons'), ('NVAL_NO_FULL_F','number of valence electrons neglecting filled f shells'), ('NVAL_NO_FULL_D','number of valence electrons neglecting filled d shells'), ('NVAL_NO_FULL','number of valence electrons neglecting filled f and d shells')] def GetAllDescriptorNames(db,tbl1,tbl2,user='sysdba',password='masterkey'): """ gets possible descriptor names from a database **Arguments** - db: the name of the database to use - tbl1: the name of the table to be used for reading descriptor values - tbl2: the name of the table to be used for reading notes about the descriptors (*descriptions of the descriptors if you like*) - user: the user name for DB access - password: the password for DB access **Returns** a 2-tuple containing: 1) a list of column names 2) a list of column descriptors **Notes** - this uses _Dbase.DbInfo_ and Dfunctionality for querying the database - it is assumed that tbl2 includes 'property' and 'notes' columns """ conn = DbConnect(db,user=user,password=password) colNames = conn.GetColumnNames(table=tbl1) colDesc = map(lambda x:(x[0].upper(),x[1]), conn.GetColumns('property,notes',table=tbl2)) for name,desc in countOptions: colNames.append(name) colDesc.append((name,desc)) return colNames,colDesc class CompoundDescriptorCalculator(Descriptors.DescriptorCalculator): """ used for calculating descriptors This is the central point for descriptor calculation **Notes** - There are two kinds of descriptors this cares about: 1) *Simple Descriptors* can be calculated solely using atomic descriptor values and the composition of the compound. The full list of possible simple descriptors is determined by the types of *Calculator Methods* (see below) and the contents of an atomic database. Simple Descriptors can be marked as *nonZeroDescriptors*. These are used to winnow out atom types where particular atomic descriptors are zero (usually indicating that the value is unknown) Simple Descriptors are maintained locally in the _simpleList_ 2) *Compound Descriptors* may rely upon more complicated computation schemes and descriptors for the compound as a whole (e.g. structural variables, etc.). The full list of compound descriptors is limitless. They are calculated using the _ML.Descriptors.Parser_ module. Compound Descriptors are maintained locally in the _compoundList_ - This class has a some special methods which are labelled as *Calculator Method* These are used internally to take atomic descriptors and reduce them to a single simple descriptor value for a composition. They are primarily intended for internal use. - a *composition vector* is a list of 2-tuples: '[(atom1name,atom1Num),...]' where atom1Num is the contribution of the atom to the stoichiometry of the compound. No assumption is made about the stoichiometries (i.e. they don't have to be either integral or all sum to one). """ #------------ # methods used to calculate descriptors #------------ def SUM(self,desc,compos): """ *Calculator Method* sums the descriptor values across the composition **Arguments** - desc: the name of the descriptor - compos: the composition vector **Returns** a float """ res = 0.0 for atom,num in compos: res = res + self.atomDict[atom][desc]*num return res def MEAN(self,desc,compos): """ *Calculator Method* averages the descriptor values across the composition **Arguments** - desc: the name of the descriptor - compos: the composition vector **Returns** a float """ res = 0.0 nSoFar = 0.0 for atom,num in compos: res = res + self.atomDict[atom][desc]*num nSoFar = nSoFar + num return res/nSoFar def DEV(self,desc,compos): """ *Calculator Method* average deviation of the descriptor values across the composition **Arguments** - desc: the name of the descriptor - compos: the composition vector **Returns** a float """ mean = self.MEAN(desc,compos) res = 0.0 nSoFar = 0.0 for atom,num in compos: res = res + abs(self.atomDict[atom][desc]-mean)*num nSoFar = nSoFar + num return res/nSoFar def MIN(self,desc,compos): """ *Calculator Method* minimum of the descriptor values across the composition **Arguments** - desc: the name of the descriptor - compos: the composition vector **Returns** a float """ return min(map(lambda x,y=desc,z=self:z.atomDict[x[0]][y],compos)) def MAX(self,desc,compos): """ *Calculator Method* maximum of the descriptor values across the composition **Arguments** - desc: the name of the descriptor - compos: the composition vector **Returns** a float """ return max(map(lambda x,y=desc,z=self:z.atomDict[x[0]][y],compos)) #------------ # Other methods #------------ def ProcessSimpleList(self): """ Handles the list of simple descriptors This constructs the list of _nonZeroDescriptors_ and _requiredDescriptors_. There's some other magic going on that I can't decipher at the moment. """ global countOptions self.nonZeroDescriptors = [] lCopy = self.simpleList[:] tList = map(lambda x:x[0],countOptions) for i in xrange(len(lCopy)): entry = lCopy[i] if 'NONZERO' in entry[1]: if entry[0] not in tList: self.nonZeroDescriptors.append('%s != 0'%entry[0]) if len(entry[1]) == 1: self.simpleList.remove(entry) else: self.simpleList[self.simpleList.index(entry)][1].remove('NONZERO') self.requiredDescriptors = map(lambda x:x[0],self.simpleList) for entry in tList: if entry in self.requiredDescriptors: self.requiredDescriptors.remove(entry) def ProcessCompoundList(self): """ Adds entries from the _compoundList_ to the list of _requiredDescriptors_ Each compound descriptor is surveyed. Any atomic descriptors it requires are added to the list of _requiredDescriptors_ to be pulled from the database. """ # add in the atomic descriptors we will need for entry in self.compoundList: for atomicDesc in entry[1]: if atomicDesc != '' and atomicDesc not in self.requiredDescriptors: self.requiredDescriptors.append(atomicDesc) def BuildAtomDict(self): """ builds the local atomic dict We don't want to keep around all descriptor values for all atoms, so this method takes care of only pulling out the descriptors in which we are interested. **Notes** - this uses _chemutils.GetAtomicData_ to actually pull the data """ self.ProcessSimpleList() self.ProcessCompoundList() self.atomDict = {} whereString = ' and '.join(self.nonZeroDescriptors) if whereString != '': whereString = 'where ' + whereString chemutils.GetAtomicData(self.atomDict,self.requiredDescriptors,self.dbName,self.dbTable, whereString,self.dbUser,self.dbPassword, includeElCounts=1) def CalcSimpleDescriptorsForComposition(self,compos='',composList=None): """ calculates all simple descriptors for a given composition **Arguments** - compos: a string representation of the composition - composList: a *composVect* The client must provide either _compos_ or _composList_. If both are provided, _composList_ takes priority. **Returns** the list of descriptor values **Notes** - when _compos_ is provided, this uses _chemutils.SplitComposition_ to split the composition into its individual pieces - if problems are encountered because of either an unknown descriptor or atom type, a _KeyError_ will be raised. """ if composList is None: composList = chemutils.SplitComposition(compos) try: res = [] for i in xrange(len(self.simpleList)): descName,targets = self.simpleList[i] for target in targets: try: method = getattr(self,target) except AttributeError: print('Method %s does not exist'%(target)) else: res.append(method(descName,composList)) except KeyError as msg: print('composition %s caused problems'%composList) raise KeyError(msg) return res def CalcCompoundDescriptorsForComposition(self,compos='',composList=None, propDict={}): """ calculates all simple descriptors for a given composition **Arguments** - compos: a string representation of the composition - composList: a *composVect* - propDict: a dictionary containing the properties of the composition as a whole (e.g. structural variables, etc.) The client must provide either _compos_ or _composList_. If both are provided, _composList_ takes priority. **Returns** the list of descriptor values **Notes** - when _compos_ is provided, this uses _chemutils.SplitComposition_ to split the composition into its individual pieces """ if composList is None: composList = chemutils.SplitComposition(compos) res = [] for i in xrange(len(self.compoundList)): val = Parser.CalcSingleCompoundDescriptor(composList,self.compoundList[i][1:], self.atomDict,propDict) res.append(val) return res def CalcDescriptorsForComposition(self,composVect,propDict): """ calculates all descriptors for a given composition **Arguments** - compos: a string representation of the composition - propDict: a dictionary containing the properties of the composition as a whole (e.g. structural variables, etc.). These are used to generate Compound Descriptors **Returns** the list of all descriptor values **Notes** - this uses _chemutils.SplitComposition_ to split the composition into its individual pieces """ composList = chemutils.SplitComposition(composVect[0]) try: r1 = self.CalcSimpleDescriptorsForComposition(composList=composList) except KeyError as msg: res = [] else: r2 = self.CalcCompoundDescriptorsForComposition(composList=composList, propDict=propDict) res = r1+r2 return tuple(res) CalcDescriptors = CalcDescriptorsForComposition def GetDescriptorNames(self): """ returns a list of the names of the descriptors this calculator generates """ if self.descriptorNames is not None: return self.descriptorNames else: res = [] for i in xrange(len(self.simpleList)): descName,targets = self.simpleList[i] for target in targets: try: method = getattr(self,target) except AttributeError: print('Method %s does not exist'%(target)) else: res.append('%s_%s'%(target,descName)) for entry in self.compoundList: res.append(entry[0]) self.descriptorNames = res[:] return tuple(res) def __init__(self,simpleList,compoundList=None, dbName=None, dbTable='atomic_data',dbUser='sysdba',dbPassword='masterkey'): """ Constructor **Arguments** - simpleList: list of simple descriptors to be calculated (see below for format) - compoundList: list of compound descriptors to be calculated (see below for format) - dbName: name of the atomic database to be used - dbTable: name the table in _dbName_ which has atomic data - dbUser: user name for DB access - dbPassword: password for DB access **Note** - format of simpleList: a list of 2-tuples containing: 1) name of the atomic descriptor 2) a list of operations on that descriptor (e.g. NonZero, Max, etc.) These must correspond to the *Calculator Method* names above. - format of compoundList: a list of 2-tuples containing: 1) name of the descriptor to be calculated 2) list of selected atomic descriptor names (define $1, $2, etc.) 3) list of selected compound descriptor names (define $a, $b, etc.) 4) text formula defining the calculation (see _Parser_) """ if dbName is None: dbName = RDConfig.RDDataDatabase Descriptors.DescriptorCalculator.__init__(self) #self.simpleList = map(lambda x:(string.upper(x[0]),map(string.upper,x[1])), # simpleList) self.simpleList = [(x[0].upper(), [y.upper() for y in x[1]]) for x in simpleList] self.descriptorNames = None self.compoundList = compoundList if self.compoundList is None: self.compoundList = [] self.dbName = dbName self.dbTable = dbTable self.dbUser = dbUser self.dbPassword = dbPassword if __name__ == '__main__': d = [('DED',['NonZero','Mean','Dev']), ('M_B_electroneg',['NonZero']), ('Cov_rad',['Max','Min'])] o = DescriptorCalculator(d) o.BuildAtomDict() print('len:',len(o.atomDict.keys())) for key in o.atomDict.keys()[-4:-1]: print(key,o.atomDict[key]) print('descriptors:',o.GetDescriptorNames()) composList = ['Nb','Nb3','NbPt','Nb2Pt'] for compos in composList: descs = o.CalcSimpleDescriptorsForComposition(compos) print(compos,descs)
30.625
96
0.644014
from __future__ import print_function from rdkit import RDConfig from rdkit.utils import chemutils import os from rdkit.Dbase.DbConnection import DbConnect from rdkit.ML.Descriptors import Parser,Descriptors from rdkit.six.moves import xrange countOptions = [('NVAL','total number of valence electrons'), ('NVAL_NO_FULL_F','number of valence electrons neglecting filled f shells'), ('NVAL_NO_FULL_D','number of valence electrons neglecting filled d shells'), ('NVAL_NO_FULL','number of valence electrons neglecting filled f and d shells')] def GetAllDescriptorNames(db,tbl1,tbl2,user='sysdba',password='masterkey'): conn = DbConnect(db,user=user,password=password) colNames = conn.GetColumnNames(table=tbl1) colDesc = map(lambda x:(x[0].upper(),x[1]), conn.GetColumns('property,notes',table=tbl2)) for name,desc in countOptions: colNames.append(name) colDesc.append((name,desc)) return colNames,colDesc class CompoundDescriptorCalculator(Descriptors.DescriptorCalculator): def SUM(self,desc,compos): res = 0.0 for atom,num in compos: res = res + self.atomDict[atom][desc]*num return res def MEAN(self,desc,compos): res = 0.0 nSoFar = 0.0 for atom,num in compos: res = res + self.atomDict[atom][desc]*num nSoFar = nSoFar + num return res/nSoFar def DEV(self,desc,compos): mean = self.MEAN(desc,compos) res = 0.0 nSoFar = 0.0 for atom,num in compos: res = res + abs(self.atomDict[atom][desc]-mean)*num nSoFar = nSoFar + num return res/nSoFar def MIN(self,desc,compos): return min(map(lambda x,y=desc,z=self:z.atomDict[x[0]][y],compos)) def MAX(self,desc,compos): return max(map(lambda x,y=desc,z=self:z.atomDict[x[0]][y],compos)) def ProcessSimpleList(self): global countOptions self.nonZeroDescriptors = [] lCopy = self.simpleList[:] tList = map(lambda x:x[0],countOptions) for i in xrange(len(lCopy)): entry = lCopy[i] if 'NONZERO' in entry[1]: if entry[0] not in tList: self.nonZeroDescriptors.append('%s != 0'%entry[0]) if len(entry[1]) == 1: self.simpleList.remove(entry) else: self.simpleList[self.simpleList.index(entry)][1].remove('NONZERO') self.requiredDescriptors = map(lambda x:x[0],self.simpleList) for entry in tList: if entry in self.requiredDescriptors: self.requiredDescriptors.remove(entry) def ProcessCompoundList(self): for entry in self.compoundList: for atomicDesc in entry[1]: if atomicDesc != '' and atomicDesc not in self.requiredDescriptors: self.requiredDescriptors.append(atomicDesc) def BuildAtomDict(self): self.ProcessSimpleList() self.ProcessCompoundList() self.atomDict = {} whereString = ' and '.join(self.nonZeroDescriptors) if whereString != '': whereString = 'where ' + whereString chemutils.GetAtomicData(self.atomDict,self.requiredDescriptors,self.dbName,self.dbTable, whereString,self.dbUser,self.dbPassword, includeElCounts=1) def CalcSimpleDescriptorsForComposition(self,compos='',composList=None): if composList is None: composList = chemutils.SplitComposition(compos) try: res = [] for i in xrange(len(self.simpleList)): descName,targets = self.simpleList[i] for target in targets: try: method = getattr(self,target) except AttributeError: print('Method %s does not exist'%(target)) else: res.append(method(descName,composList)) except KeyError as msg: print('composition %s caused problems'%composList) raise KeyError(msg) return res def CalcCompoundDescriptorsForComposition(self,compos='',composList=None, propDict={}): if composList is None: composList = chemutils.SplitComposition(compos) res = [] for i in xrange(len(self.compoundList)): val = Parser.CalcSingleCompoundDescriptor(composList,self.compoundList[i][1:], self.atomDict,propDict) res.append(val) return res def CalcDescriptorsForComposition(self,composVect,propDict): composList = chemutils.SplitComposition(composVect[0]) try: r1 = self.CalcSimpleDescriptorsForComposition(composList=composList) except KeyError as msg: res = [] else: r2 = self.CalcCompoundDescriptorsForComposition(composList=composList, propDict=propDict) res = r1+r2 return tuple(res) CalcDescriptors = CalcDescriptorsForComposition def GetDescriptorNames(self): if self.descriptorNames is not None: return self.descriptorNames else: res = [] for i in xrange(len(self.simpleList)): descName,targets = self.simpleList[i] for target in targets: try: method = getattr(self,target) except AttributeError: print('Method %s does not exist'%(target)) else: res.append('%s_%s'%(target,descName)) for entry in self.compoundList: res.append(entry[0]) self.descriptorNames = res[:] return tuple(res) def __init__(self,simpleList,compoundList=None, dbName=None, dbTable='atomic_data',dbUser='sysdba',dbPassword='masterkey'): if dbName is None: dbName = RDConfig.RDDataDatabase Descriptors.DescriptorCalculator.__init__(self) self.simpleList = [(x[0].upper(), [y.upper() for y in x[1]]) for x in simpleList] self.descriptorNames = None self.compoundList = compoundList if self.compoundList is None: self.compoundList = [] self.dbName = dbName self.dbTable = dbTable self.dbUser = dbUser self.dbPassword = dbPassword if __name__ == '__main__': d = [('DED',['NonZero','Mean','Dev']), ('M_B_electroneg',['NonZero']), ('Cov_rad',['Max','Min'])] o = DescriptorCalculator(d) o.BuildAtomDict() print('len:',len(o.atomDict.keys())) for key in o.atomDict.keys()[-4:-1]: print(key,o.atomDict[key]) print('descriptors:',o.GetDescriptorNames()) composList = ['Nb','Nb3','NbPt','Nb2Pt'] for compos in composList: descs = o.CalcSimpleDescriptorsForComposition(compos) print(compos,descs)
true
true
1c44505dd302e64a42b635bedc36746e9c6b4531
3,825
py
Python
dali/test/python/test_RN50_external_source_parallel_data.py
awolant/DALI
ace3e0bee44b7b10cdf7255ec02e143646c68ce1
[ "ECL-2.0", "Apache-2.0" ]
1
2019-05-31T14:00:58.000Z
2019-05-31T14:00:58.000Z
dali/test/python/test_RN50_external_source_parallel_data.py
Shruti-Raj-Vansh-Singh/DALI
e7df0b255c59a118843bfe3ecaf317d7ee1ed6bb
[ "ECL-2.0", "Apache-2.0" ]
2
2021-06-11T17:05:37.000Z
2021-06-23T03:45:04.000Z
dali/test/python/test_RN50_external_source_parallel_data.py
Shruti-Raj-Vansh-Singh/DALI
e7df0b255c59a118843bfe3ecaf317d7ee1ed6bb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#!/usr/bin/python3 # Copyright (c) 2020, NVIDIA CORPORATION. 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. from test_utils import AverageMeter import os import argparse import time import cv2 import numpy as np from nvidia.dali.plugin.base_iterator import LastBatchPolicy from test_RN50_external_source_parallel_utils import ( parse_test_arguments, external_source_parallel_pipeline, external_source_pipeline, file_reader_pipeline, get_pipe_factories) # This test requires significant amount of shared memory to be able to pass # the batches between worker processes and the main process. If running in docker # make sure that -shm-size is big enough. def iteration_test(args): test_pipe_factories = get_pipe_factories( args.test_pipes, external_source_parallel_pipeline, file_reader_pipeline, external_source_pipeline) for pipe_factory in test_pipe_factories: # TODO(klecki): We don't handle sharding in this test yet, would need to do it manually # for External Source pipelines pipes = [pipe_factory( batch_size=args.batch_size, num_threads=args.workers, device_id=gpu, data_path=args.data_path, prefetch=args.prefetch, reader_queue_depth=args.reader_queue_depth, py_start_method=args.worker_init, py_num_workers=args.py_workers ) for gpu in range(args.gpus)] # First start the Python workers, so we fork without CUDA context. for pipe in pipes: pipe.start_py_workers() for pipe in pipes: pipe.build() samples_no = pipes[0].epoch_size("Reader") if args.benchmark_iters is None: expected_iters = samples_no // args.batch_size + (samples_no % args.batch_size != 0) else: expected_iters = args.benchmark_iters print("RUN {}".format(pipe_factory.__name__)) for i in range(args.epochs): if i == 0: print("Warm up") else: print("Test run " + str(i)) data_time = AverageMeter() end = time.time() frequency = 50 for j in range(expected_iters): stop_iter = False for pipe in pipes: try: pipe.run() except StopIteration: assert j == expected_iters - 1 stop_iter = True if stop_iter: break if j % frequency == 0 and j != 0: data_time.update((time.time() - end) / frequency) end = time.time() print("{} {}/ {}, avg time: {} [s], worst time: {} [s], speed: {} [img/s]".format( pipe_factory.__name__, j, expected_iters, data_time.avg, data_time.max_val, args.batch_size * args.gpus / data_time.avg, )) for pipe in pipes: pipe.reset() print("OK {}".format(pipe_factory.__name__)) if __name__ == "__main__": args = parse_test_arguments(False) iteration_test(args)
36.778846
102
0.603399
from test_utils import AverageMeter import os import argparse import time import cv2 import numpy as np from nvidia.dali.plugin.base_iterator import LastBatchPolicy from test_RN50_external_source_parallel_utils import ( parse_test_arguments, external_source_parallel_pipeline, external_source_pipeline, file_reader_pipeline, get_pipe_factories) def iteration_test(args): test_pipe_factories = get_pipe_factories( args.test_pipes, external_source_parallel_pipeline, file_reader_pipeline, external_source_pipeline) for pipe_factory in test_pipe_factories: # for External Source pipelines pipes = [pipe_factory( batch_size=args.batch_size, num_threads=args.workers, device_id=gpu, data_path=args.data_path, prefetch=args.prefetch, reader_queue_depth=args.reader_queue_depth, py_start_method=args.worker_init, py_num_workers=args.py_workers ) for gpu in range(args.gpus)] # First start the Python workers, so we fork without CUDA context. for pipe in pipes: pipe.start_py_workers() for pipe in pipes: pipe.build() samples_no = pipes[0].epoch_size("Reader") if args.benchmark_iters is None: expected_iters = samples_no // args.batch_size + (samples_no % args.batch_size != 0) else: expected_iters = args.benchmark_iters print("RUN {}".format(pipe_factory.__name__)) for i in range(args.epochs): if i == 0: print("Warm up") else: print("Test run " + str(i)) data_time = AverageMeter() end = time.time() frequency = 50 for j in range(expected_iters): stop_iter = False for pipe in pipes: try: pipe.run() except StopIteration: assert j == expected_iters - 1 stop_iter = True if stop_iter: break if j % frequency == 0 and j != 0: data_time.update((time.time() - end) / frequency) end = time.time() print("{} {}/ {}, avg time: {} [s], worst time: {} [s], speed: {} [img/s]".format( pipe_factory.__name__, j, expected_iters, data_time.avg, data_time.max_val, args.batch_size * args.gpus / data_time.avg, )) for pipe in pipes: pipe.reset() print("OK {}".format(pipe_factory.__name__)) if __name__ == "__main__": args = parse_test_arguments(False) iteration_test(args)
true
true
1c44516c6c2cb62d2ea46dd638986291034ed6e1
367
py
Python
payeezy_python/example/Dependancy/requests-master/requests/packages/urllib3/util/response.py
Dylfin/payeezy_direct_API
d0ec010dd265421ddc002e665221312178e2b0fe
[ "MIT" ]
76
2015-04-28T18:50:16.000Z
2022-03-21T18:52:44.000Z
payeezy_python/example/Dependancy/requests-master/requests/packages/urllib3/util/response.py
Dylfin/payeezy_direct_API
d0ec010dd265421ddc002e665221312178e2b0fe
[ "MIT" ]
17
2015-07-15T17:46:41.000Z
2022-03-01T19:14:48.000Z
payeezy_python/example/Dependancy/requests-master/requests/packages/urllib3/util/response.py
Dylfin/payeezy_direct_API
d0ec010dd265421ddc002e665221312178e2b0fe
[ "MIT" ]
149
2015-04-13T04:51:09.000Z
2021-07-06T14:16:20.000Z
def is_fp_closed(obj): """ Checks whether a given file-like object is closed. :param obj: The file-like object to check. """ if hasattr(obj, 'fp'): # Object is a container for another file-like object that gets released # on exhaustion (e.g. HTTPResponse) return obj.fp is None return obj.closed
26.214286
80
0.60218
def is_fp_closed(obj): if hasattr(obj, 'fp'): return obj.fp is None return obj.closed
true
true
1c4452faf589fe4cf63d1a0d78c548ac6bdf060e
11,373
py
Python
train_plain_bert_dot4_con.py
playing-code/fairseq2
ac97b18c0aecca9eb36146492a1e95e521cb345a
[ "MIT" ]
null
null
null
train_plain_bert_dot4_con.py
playing-code/fairseq2
ac97b18c0aecca9eb36146492a1e95e521cb345a
[ "MIT" ]
null
null
null
train_plain_bert_dot4_con.py
playing-code/fairseq2
ac97b18c0aecca9eb36146492a1e95e521cb345a
[ "MIT" ]
null
null
null
import json import pickle import numpy as np import random # from fairseq.data import Dictionary import sys import torch import argparse import os from model_plain_bert_dot4 import Plain_bert from fairseq.models.roberta import RobertaModel from utils_sample import NewsIterator from utils_sample import cal_metric import utils_sample as utils # import dgl # import dgl.function as fn #from gpu_mem_track import MemTracker #import inspect #from multiprocessing import Pool import torch.nn as nn import math from fairseq.data import ( data_utils, Dictionary, IdDataset, MaskTokensDataset, NestedDictionaryDataset, NumelDataset, NumSamplesDataset, PadDataset, PrependTokenDataset, SortDataset, TokenBlockDataset, ) import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter import apex random.seed(1) np.random.seed(1) torch.manual_seed(1) torch.cuda.manual_seed(1) cudaid=0 metrics=['group_auc','mean_mrr','ndcg@5;10'] lr=1e-4 T_warm=5000 all_iteration=33040 # def init_process(rank,local_rank,args,minutes=720): # """ Initialize the distributed environment. """ # # os.environ['MASTER_ADDR'] = '127.0.0.1' # # os.environ['MASTER_PORT'] = '1234' # # torch.distributed.init_process_group(backend, rank=rank, world_size=size) # dist_init_method = 'tcp://{master_ip}:{master_port}'.format( # master_ip='localhost', master_port='12345') # dist.init_process_group(backend='nccl', # init_method=dist_init_method, # # If you have a larger dataset, you will need to increase it. # timeout=timedelta(minutes=minutes), # world_size=args.size, # rank=rank) # num_gpus = torch.cuda.device_count() # torch.cuda.set_device(local_rank) # assert torch.distributed.is_initialized() def parse_args(): parser = argparse.ArgumentParser("Transformer-XH") parser.add_argument("--data_dir", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--save_dir", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--data_file", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--test_data_file", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--feature_file", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--test_feature_file", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--size", type=int, default=1, help="local_rank for distributed training on gpus") parser.add_argument("--gpu_size", type=int, default=1, help="local_rank for distributed training on gpus") parser.add_argument("--gpu_size_test", type=int, default=1, help="local_rank for distributed training on gpus") parser.add_argument("--batch_size", type=int, default=1, help="local_rank for distributed training on gpus") parser.add_argument("--log_file", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--field", type=str, help="local_rank for distributed training on gpus") return parser.parse_args() def adjust_learning_rate(optimizer,iteration,lr=lr, T_warm=T_warm, all_iteration=all_iteration ):#得看一些一共有多少个iteration再确定 if iteration<=T_warm: lr=lr*float(iteration)/T_warm elif iteration<all_iteration: lr = lr * (1 - (iteration - T_warm) / (all_iteration - T_warm)) else: lr=0 for param_group in optimizer.param_groups: param_group['lr'] = lr def group_labels_func(labels, preds, group_keys): """Devide labels and preds into several group according to values in group keys. Args: labels (list): ground truth label list. preds (list): prediction score list. group_keys (list): group key list. Returns: all_labels: labels after group. all_preds: preds after group. """ all_keys = list(set(group_keys)) group_labels = {k: [] for k in all_keys} group_preds = {k: [] for k in all_keys} for l, p, k in zip(labels, preds, group_keys): group_labels[k].append(l) group_preds[k].append(p) all_labels = [] all_preds = [] for k in all_keys: all_labels.append(group_labels[k]) all_preds.append(group_preds[k]) return all_labels, all_preds def test(model,args): preds = [] labels = [] imp_indexes = [] metrics=['group_auc'] test_file=os.path.join(args.data_dir, args.test_data_file) preds = [] labels = [] imp_indexes = [] feature_file=os.path.join(args.data_dir,args.feature_file) iterator=NewsIterator(batch_size=args.gpu_size_test, npratio=-1,feature_file=feature_file,field=args.field) print('test...') with torch.no_grad(): data_batch=iterator.load_data_from_file(test_file) batch_t=0 for imp_index , user_index, his_id, candidate_id , label in data_batch: batch_t+=len(candidate_id) his_id=his_id.cuda(cudaid) candidate_id= candidate_id.cuda(cudaid) logit=model(his_id,candidate_id,None,mode='validation') # print('???',label_t,label) # assert 1==0 logit=list(np.reshape(np.array(logit.cpu()), -1)) label=list(np.reshape(np.array(label), -1)) imp_index=list(np.reshape(np.array(imp_index), -1)) assert len(logit)==len(label) assert len(logit)==len(imp_index) labels.extend(label) preds.extend(logit) imp_indexes.extend(imp_index) print('all data: ',len(labels)) group_labels, group_preds = group_labels_func(labels, preds, imp_indexes) res = cal_metric(group_labels, group_preds, metrics) return res['group_auc'] def train(model,optimizer, args): print('params: '," T_warm: ",T_warm," all_iteration: ",all_iteration," lr: ",lr) cuda_list=range(args.size) accumulation_steps=int(args.batch_size/args.size/args.gpu_size) #model = nn.DataParallel(model, device_ids=cuda_list) # torch.cuda.set_device(cudaid) # torch.distributed.init_process_group(backend='nccl', init_method='tcp://localhost:23456', rank=0, world_size=1) # model=torch.nn.parallel.DistributedDataParallel(model, device_ids=cuda_list,output_device=0,find_unused_parameters=True) model = torch.nn.DataParallel(model,device_ids=cuda_list) accum_batch_loss=0 iterator=NewsIterator(batch_size=args.gpu_size*args.size, npratio=4,feature_file=os.path.join(args.data_dir,args.feature_file),field=args.field) train_file=os.path.join(args.data_dir, args.data_file) #for epoch in range(0,100): batch_t=0 iteration=0 print('train...',cuda_list) #w=open(os.path.join(args.data_dir,args.log_file),'w') writer = SummaryWriter(os.path.join(args.data_dir, args.log_file) ) epoch=0 model.train() # batch_t=52880-1 # iteration=3305-1 batch_t=0 iteration=0 step=0 best_score=-1 #w=open(os.path.join(args.data_dir,args.log_file),'w') # model.eval() # auc=test(model,args) # model.eval() # auc=test(model,args) # print(auc) for epoch in range(0,10): #while True: all_loss=0 all_batch=0 data_batch=iterator.load_data_from_file(train_file) for imp_index , user_index, his_id, candidate_id , label in data_batch: batch_t+=1 assert candidate_id.shape[1]==2 his_id=his_id.cuda(cudaid) candidate_id= candidate_id.cuda(cudaid) label = label.cuda(cudaid) loss=model(his_id,candidate_id, label) sample_size=candidate_id.shape[0] loss=loss.sum()/sample_size/math.log(2) accum_batch_loss+=float(loss) all_loss+=float(loss) all_batch+=1 loss = loss/accumulation_steps loss.backward() if (batch_t)%accumulation_steps==0: iteration+=1 adjust_learning_rate(optimizer,iteration) optimizer.step() optimizer.zero_grad() print(' batch_t: ',batch_t, ' iteration: ', iteration, ' epoch: ',epoch,' accum_batch_loss: ',accum_batch_loss/accumulation_steps,' lr: ', optimizer.param_groups[0]['lr']) writer.add_scalar('Loss/train', accum_batch_loss/accumulation_steps, iteration) writer.add_scalar('Ltr/train', optimizer.param_groups[0]['lr'], iteration) accum_batch_loss=0 if iteration%2==0: torch.cuda.empty_cache() model.eval() auc=test(model,args) print(auc) writer.add_scalar('auc/valid', auc, step) step+=1 if auc>best_score: torch.save(model.state_dict(), os.path.join(args.save_dir,'Plain_robert_dot_best.pkl')) best_score=auc print('best score: ',best_score) torch.cuda.empty_cache() model.train() torch.save(model.state_dict(), os.path.join(args.save_dir,'Plain_robert_dot'+str(epoch)+'.pkl')) #w.close() if __name__ == '__main__': # cuda_num=int(sys.argv[1]) random.seed(1) np.random.seed(1) torch.manual_seed(1) torch.cuda.manual_seed(1) #main() args = parse_args() model=Plain_bert(args) #optimizer = torch.optim.Adam(model.parameters(), lr=lr,betas=(0.9,0.98),eps=1e-6,weight_decay=0.0) optimizer = apex.optimizers.FusedLAMB(model.parameters(), lr=lr,betas=(0.9,0.98),eps=1e-6,weight_decay=0.0,max_grad_norm=1.0) # for name, param in model.named_parameters(): # print(name,param.shape,param.requires_grad) roberta = RobertaModel.from_pretrained(os.path.join(args.data_dir,'roberta.base'), checkpoint_file='checkpoint_best.pt') #roberta = RobertaModel.from_pretrained(args.save_dir, checkpoint_file='checkpoint_best.pt') # for name, param in roberta.named_parameters(): # print(name,param.shape,param.requires_grad) model_dict = model.state_dict() pretrained_dict={} for name,parameters in roberta.named_parameters(): if 'lm_head' not in name: pretrained_dict['encoder.'+name[31:]]=parameters print(pretrained_dict.keys()) model_dict.update(pretrained_dict) model.load_state_dict(model_dict) # for item in model.parameters(): # print(item.requires_grad) model.cuda(cudaid) train(model,optimizer,args)
32.401709
187
0.62578
import json import pickle import numpy as np import random import sys import torch import argparse import os from model_plain_bert_dot4 import Plain_bert from fairseq.models.roberta import RobertaModel from utils_sample import NewsIterator from utils_sample import cal_metric import utils_sample as utils import torch.nn as nn import math from fairseq.data import ( data_utils, Dictionary, IdDataset, MaskTokensDataset, NestedDictionaryDataset, NumelDataset, NumSamplesDataset, PadDataset, PrependTokenDataset, SortDataset, TokenBlockDataset, ) import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter import apex random.seed(1) np.random.seed(1) torch.manual_seed(1) torch.cuda.manual_seed(1) cudaid=0 metrics=['group_auc','mean_mrr','ndcg@5;10'] lr=1e-4 T_warm=5000 all_iteration=33040 ining on gpus") parser.add_argument("--save_dir", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--data_file", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--test_data_file", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--feature_file", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--test_feature_file", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--size", type=int, default=1, help="local_rank for distributed training on gpus") parser.add_argument("--gpu_size", type=int, default=1, help="local_rank for distributed training on gpus") parser.add_argument("--gpu_size_test", type=int, default=1, help="local_rank for distributed training on gpus") parser.add_argument("--batch_size", type=int, default=1, help="local_rank for distributed training on gpus") parser.add_argument("--log_file", type=str, help="local_rank for distributed training on gpus") parser.add_argument("--field", type=str, help="local_rank for distributed training on gpus") return parser.parse_args() def adjust_learning_rate(optimizer,iteration,lr=lr, T_warm=T_warm, all_iteration=all_iteration ): if iteration<=T_warm: lr=lr*float(iteration)/T_warm elif iteration<all_iteration: lr = lr * (1 - (iteration - T_warm) / (all_iteration - T_warm)) else: lr=0 for param_group in optimizer.param_groups: param_group['lr'] = lr def group_labels_func(labels, preds, group_keys): all_keys = list(set(group_keys)) group_labels = {k: [] for k in all_keys} group_preds = {k: [] for k in all_keys} for l, p, k in zip(labels, preds, group_keys): group_labels[k].append(l) group_preds[k].append(p) all_labels = [] all_preds = [] for k in all_keys: all_labels.append(group_labels[k]) all_preds.append(group_preds[k]) return all_labels, all_preds def test(model,args): preds = [] labels = [] imp_indexes = [] metrics=['group_auc'] test_file=os.path.join(args.data_dir, args.test_data_file) preds = [] labels = [] imp_indexes = [] feature_file=os.path.join(args.data_dir,args.feature_file) iterator=NewsIterator(batch_size=args.gpu_size_test, npratio=-1,feature_file=feature_file,field=args.field) print('test...') with torch.no_grad(): data_batch=iterator.load_data_from_file(test_file) batch_t=0 for imp_index , user_index, his_id, candidate_id , label in data_batch: batch_t+=len(candidate_id) his_id=his_id.cuda(cudaid) candidate_id= candidate_id.cuda(cudaid) logit=model(his_id,candidate_id,None,mode='validation') logit=list(np.reshape(np.array(logit.cpu()), -1)) label=list(np.reshape(np.array(label), -1)) imp_index=list(np.reshape(np.array(imp_index), -1)) assert len(logit)==len(label) assert len(logit)==len(imp_index) labels.extend(label) preds.extend(logit) imp_indexes.extend(imp_index) print('all data: ',len(labels)) group_labels, group_preds = group_labels_func(labels, preds, imp_indexes) res = cal_metric(group_labels, group_preds, metrics) return res['group_auc'] def train(model,optimizer, args): print('params: '," T_warm: ",T_warm," all_iteration: ",all_iteration," lr: ",lr) cuda_list=range(args.size) accumulation_steps=int(args.batch_size/args.size/args.gpu_size) model = torch.nn.DataParallel(model,device_ids=cuda_list) accum_batch_loss=0 iterator=NewsIterator(batch_size=args.gpu_size*args.size, npratio=4,feature_file=os.path.join(args.data_dir,args.feature_file),field=args.field) train_file=os.path.join(args.data_dir, args.data_file) batch_t=0 iteration=0 print('train...',cuda_list) writer = SummaryWriter(os.path.join(args.data_dir, args.log_file) ) epoch=0 model.train() batch_t=0 iteration=0 step=0 best_score=-1 for epoch in range(0,10): all_loss=0 all_batch=0 data_batch=iterator.load_data_from_file(train_file) for imp_index , user_index, his_id, candidate_id , label in data_batch: batch_t+=1 assert candidate_id.shape[1]==2 his_id=his_id.cuda(cudaid) candidate_id= candidate_id.cuda(cudaid) label = label.cuda(cudaid) loss=model(his_id,candidate_id, label) sample_size=candidate_id.shape[0] loss=loss.sum()/sample_size/math.log(2) accum_batch_loss+=float(loss) all_loss+=float(loss) all_batch+=1 loss = loss/accumulation_steps loss.backward() if (batch_t)%accumulation_steps==0: iteration+=1 adjust_learning_rate(optimizer,iteration) optimizer.step() optimizer.zero_grad() print(' batch_t: ',batch_t, ' iteration: ', iteration, ' epoch: ',epoch,' accum_batch_loss: ',accum_batch_loss/accumulation_steps,' lr: ', optimizer.param_groups[0]['lr']) writer.add_scalar('Loss/train', accum_batch_loss/accumulation_steps, iteration) writer.add_scalar('Ltr/train', optimizer.param_groups[0]['lr'], iteration) accum_batch_loss=0 if iteration%2==0: torch.cuda.empty_cache() model.eval() auc=test(model,args) print(auc) writer.add_scalar('auc/valid', auc, step) step+=1 if auc>best_score: torch.save(model.state_dict(), os.path.join(args.save_dir,'Plain_robert_dot_best.pkl')) best_score=auc print('best score: ',best_score) torch.cuda.empty_cache() model.train() torch.save(model.state_dict(), os.path.join(args.save_dir,'Plain_robert_dot'+str(epoch)+'.pkl')) if __name__ == '__main__': random.seed(1) np.random.seed(1) torch.manual_seed(1) torch.cuda.manual_seed(1) args = parse_args() model=Plain_bert(args) optimizer = apex.optimizers.FusedLAMB(model.parameters(), lr=lr,betas=(0.9,0.98),eps=1e-6,weight_decay=0.0,max_grad_norm=1.0) roberta = RobertaModel.from_pretrained(os.path.join(args.data_dir,'roberta.base'), checkpoint_file='checkpoint_best.pt') model_dict = model.state_dict() pretrained_dict={} for name,parameters in roberta.named_parameters(): if 'lm_head' not in name: pretrained_dict['encoder.'+name[31:]]=parameters print(pretrained_dict.keys()) model_dict.update(pretrained_dict) model.load_state_dict(model_dict) model.cuda(cudaid) train(model,optimizer,args)
true
true
1c44534ae52d49a685a8b666effb3e998f3d5f6a
667
py
Python
survey_api/reports/serializers/__init__.py
OpenStackweb/openstack-survey-api
6ede5d0521d9055cff0adb939db2d11a216336f5
[ "Apache-2.0" ]
null
null
null
survey_api/reports/serializers/__init__.py
OpenStackweb/openstack-survey-api
6ede5d0521d9055cff0adb939db2d11a216336f5
[ "Apache-2.0" ]
3
2020-02-11T23:49:55.000Z
2021-06-10T21:13:14.000Z
survey_api/reports/serializers/__init__.py
OpenStackweb/openstack-survey-api
6ede5d0521d9055cff0adb939db2d11a216336f5
[ "Apache-2.0" ]
null
null
null
""" * Copyright 2019 OpenStack Foundation * 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 .survey_serializer import SurveySerializer, SurveyTemplateSerializer
44.466667
75
0.772114
from .survey_serializer import SurveySerializer, SurveyTemplateSerializer
true
true
1c445417358840223a835234f4a381e0ad420f0e
1,217
py
Python
facebook_business/adobjects/serverside/http_service_interface.py
MyrikLD/facebook-python-business-sdk
a53c8ba0e8f7d0b41b385c60089f6ba00fa5c814
[ "CNRI-Python" ]
576
2018-05-01T19:09:32.000Z
2022-03-31T11:45:11.000Z
facebook_business/adobjects/serverside/http_service_interface.py
MyrikLD/facebook-python-business-sdk
a53c8ba0e8f7d0b41b385c60089f6ba00fa5c814
[ "CNRI-Python" ]
217
2018-05-03T07:31:59.000Z
2022-03-29T14:19:52.000Z
facebook_business/adobjects/serverside/http_service_interface.py
MyrikLD/facebook-python-business-sdk
a53c8ba0e8f7d0b41b385c60089f6ba00fa5c814
[ "CNRI-Python" ]
323
2018-05-01T20:32:26.000Z
2022-03-29T07:05:12.000Z
# Copyright 2014 Facebook, Inc. # You are hereby granted a non-exclusive, worldwide, royalty-free license to # use, copy, modify, and distribute this software in source code or binary # form for use in connection with the web services and APIs provided by # Facebook. # As with any software that integrates with the Facebook platform, your use # of this software is subject to the Facebook Developer Principles and # Policies [http://developers.facebook.com/policy/]. This copyright 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 MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS 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. from abc import ABC, abstractmethod class HttpServiceInterface(ABC): @abstractmethod def execute(self, url, method, request_options, headers, params): pass
45.074074
76
0.775678
from abc import ABC, abstractmethod class HttpServiceInterface(ABC): @abstractmethod def execute(self, url, method, request_options, headers, params): pass
true
true